Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(web-app): back up settings.json before migrating Cowork sessions and record what the copy left out

thinhlpg897d82148362
diff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.ts
index 3dfe3dd2b..c42309c6a 100644
--- a/web-app/src/lib/__tests__/agentTools.test.ts
+++ b/web-app/src/lib/__tests__/agentTools.test.ts
@@ -551,6 +551,8 @@ describe('agentTools', () => {
const { copySessionWorkspaceToThread } = await import('../agentTools')
await expect(copySessionWorkspaceToThread('s1')).resolves.toEqual({
copied: false,
+ files: 0,
+ skipped: 0,
})
expect(sessionWorkspaceCopyToThread).not.toHaveBeenCalled()
})
diff --git a/web-app/src/lib/__tests__/coworkSync.test.ts b/web-app/src/lib/__tests__/coworkSync.test.ts
index 2c70318a3..322a97b1d 100644
--- a/web-app/src/lib/__tests__/coworkSync.test.ts
+++ b/web-app/src/lib/__tests__/coworkSync.test.ts
@@ -25,6 +25,8 @@ const backend = vi.hoisted(() => {
return
case 'settings_flush':
return
+ case 'settings_backup_once':
+ return true
case 'settings_remove':
settings.delete(args.key)
return
diff --git a/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts b/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts
index 00717b7ec..2f32981ee 100644
--- a/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts
+++ b/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts
@@ -19,6 +19,7 @@ type Json = Record<string, unknown>
type Args = Record<string, unknown>
type BackendOptions = {
+ failBackup?: boolean
failCreateFor?: string
failWriteFor?: string
// Fails the first create_thread only, like a crash before the commit.
@@ -34,6 +35,7 @@ function makeBackend(opts: BackendOptions = {}) {
const logs = new Map<string, string>()
let crashPending = opts.crashFirstCreate ?? false
const calls: string[] = []
+ const backups = new Map<string, Map<string, string>>()
const invoke: Invoke = async <T = unknown>(cmd: string, args: Args = {}) => {
calls.push(cmd)
const threadId = args.threadId as string
@@ -44,6 +46,13 @@ function makeBackend(opts: BackendOptions = {}) {
case 'settings_set':
settings.set(key, args.value as string)
return undefined as T
+ case 'settings_backup_once': {
+ if (opts.failBackup) throw new Error('backup: disk full')
+ const name = `settings.${args.label}.json`
+ if (backups.has(name)) return false as T
+ backups.set(name, new Map(settings))
+ return true as T
+ }
case 'list_threads':
return [...threads.values()] as T
case 'write_thread_extra':
@@ -85,7 +94,7 @@ function makeBackend(opts: BackendOptions = {}) {
throw new Error(`unexpected command ${cmd}`)
}
}
- return { invoke, settings, threads, extras, logs, calls }
+ return { invoke, settings, threads, extras, logs, calls, backups }
}
const session = (id: string, extra: Partial<CoworkSession> = {}) =>
@@ -477,8 +486,40 @@ describe('migrateCoworkSessionsToThreads', () => {
})
})
+describe('settings backup before the first migration', () => {
+ it('backs up the old sessions once, before anything is written', async () => {
+ const b = makeBackend()
+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))
+ await migrateCoworkSessionsToThreads(b.invoke)
+ const backup = b.backups.get('settings.pre-cowork-migration.json')
+ expect(backup?.get(CODE_SESSIONS_KEY)).toBe(envelope([session('s1')]))
+ expect(b.calls.indexOf('settings_backup_once')).toBeLessThan(
+ b.calls.indexOf('write_thread_extra')
+ )
+ })
+
+ it('writes nothing and retries next launch when the backup fails', async () => {
+ const b = makeBackend({ failBackup: true })
+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))
+ const r = await migrateCoworkSessionsToThreads(b.invoke)
+ expect(r.status).toBe('partial')
+ expect(b.calls).not.toContain('write_thread_extra')
+ expect(b.settings.has(COWORK_MIGRATION_FLAG_KEY)).toBe(false)
+ // Not the session's fault: no attempt is counted against it.
+ expect(b.settings.has(COWORK_MIGRATION_ATTEMPTS_KEY)).toBe(false)
+ })
+
+ it('needs no backup when there is nothing to migrate', async () => {
+ const b = makeBackend()
+ await migrateCoworkSessionsToThreads(b.invoke)
+ expect(b.calls).not.toContain('settings_backup_once')
+ })
+})
+
describe('sandbox workspace copy', () => {
- type Copy = (id: string) => Promise<{ copied: boolean }>
+ type Copy = (
+ id: string
+ ) => Promise<{ copied: boolean; skipped?: number; unreadable?: number }>
const run = (b: ReturnType<typeof makeBackend>, copyWorkspace: Copy) =>
migrateCoworkSessionsToThreads(b.invoke, { copyWorkspace })
@@ -510,6 +551,20 @@ describe('sandbox workspace copy', () => {
expect(JSON.stringify(meta)).not.toContain('"session"')
})
+ it('records on the thread what the copy left out, and nothing when it left nothing', async () => {
+ const b = makeBackend()
+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1'), session('s2')]))
+ await run(b, async (id) =>
+ id === 's1'
+ ? { copied: true, skipped: 2, unreadable: 1 }
+ : { copied: true, skipped: 0, unreadable: 0 }
+ )
+ const meta = (id: string) =>
+ (b.threads.get(id) as { metadata: { migratedFrom: Json } }).metadata.migratedFrom
+ expect(meta('s1').leftOut).toEqual({ skipped: 2, unreadable: 1 })
+ expect(meta('s2')).not.toHaveProperty('leftOut')
+ })
+
it('an interrupted run redoes the copy: it is not skipped before the commit', async () => {
const b = makeBackend({ crashFirstCreate: true })
b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))
diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.ts
index 6142fe6d2..f26bc1da5 100644
--- a/web-app/src/lib/agentTools.ts
+++ b/web-app/src/lib/agentTools.ts
@@ -23,6 +23,7 @@ import {
type ToolImage,
type ToolSchema,
type WorkspaceScope,
+ type WorkspaceCopy,
} from '@janhq/tauri-plugin-agent-tools-api'
import { getServiceHub } from '@/hooks/useServiceHub'
@@ -526,9 +527,9 @@ export async function cleanupThreadWorkspace(threadId: string): Promise<void> {
*/
export async function copySessionWorkspaceToThread(
sessionId: string
-): Promise<{ copied: boolean }> {
+): Promise<WorkspaceCopy> {
const dataFolder = await getServiceHub().app().getJanDataFolder()
- if (!dataFolder) return { copied: false }
+ if (!dataFolder) return { copied: false, files: 0, skipped: 0 }
return await sessionWorkspaceCopyToThread(dataFolder, sessionId)
}
diff --git a/web-app/src/lib/coworkPersistence.ts b/web-app/src/lib/coworkPersistence.ts
index 2648e40cb..40a5a18e3 100644
--- a/web-app/src/lib/coworkPersistence.ts
+++ b/web-app/src/lib/coworkPersistence.ts
@@ -58,7 +58,11 @@ type ThreadMetadata = {
planMode?: boolean
goal?: CoworkSession['goal']
cleared?: boolean
- migratedFrom?: { store: string; updated?: number }
+ migratedFrom?: {
+ store: string
+ updated?: number
+ leftOut?: { skipped: number; unreadable: number }
+ }
messagesAnchorMs?: number
titleSetManually?: boolean
is_favorite?: boolean
diff --git a/web-app/src/lib/migrateCoworkSessions.ts b/web-app/src/lib/migrateCoworkSessions.ts
index b8dc91a57..e23158540 100644
--- a/web-app/src/lib/migrateCoworkSessions.ts
+++ b/web-app/src/lib/migrateCoworkSessions.ts
@@ -91,7 +91,23 @@ export type Invoke = <T = unknown>(
* so the migration stays a pure sequence of backend calls; the startup entry
* point wires it to the agent-tools plugin.
*/
-type CopyWorkspace = (id: string) => Promise<{ copied: boolean }>
+type CopyWorkspace = (
+ id: string
+) => Promise<{ copied: boolean; skipped?: number; unreadable?: number }>
+
+/**
+ * What a sandbox copy left behind in `sessions/<id>`: symlinks and special
+ * files (never recreated) and entries it was not allowed to read. Recorded on
+ * the thread so the conversation can say so; the originals stay in place.
+ */
+export type CopyLeftOut = { skipped: number; unreadable: number }
+
+/**
+ * `settings.json` is copied once to `settings.<label>.json` before the first
+ * migration writes anything: it holds the only copy of the old sessions, and
+ * the file is rewritten whole on every settings change.
+ */
+export const COWORK_SETTINGS_BACKUP_LABEL = 'pre-cowork-migration'
type MigrationDeps = { copyWorkspace?: CopyWorkspace }
@@ -286,7 +302,7 @@ export function sessionToSidecar(s: CoworkSession): CoworkSidecar {
}
}
-export function sessionToThread(s: CoworkSession) {
+export function sessionToThread(s: CoworkSession, leftOut?: CopyLeftOut) {
// Cowork stores `updated` in ms, threads in seconds. Sessions carry no
// creation time, so `created` is the last update.
const seconds = s.updated > 1e12 ? Math.floor(s.updated / 1000) : s.updated
@@ -311,7 +327,11 @@ export function sessionToThread(s: CoworkSession) {
folder: s.folder ?? null,
...(s.planMode !== undefined && { planMode: s.planMode }),
...(s.goal !== undefined && { goal: s.goal }),
- migratedFrom: { store: CODE_SESSIONS_KEY, updated: s.updated },
+ migratedFrom: {
+ store: CODE_SESSIONS_KEY,
+ updated: s.updated,
+ ...(leftOut && { leftOut }),
+ },
},
}
}
@@ -382,6 +402,11 @@ export async function migrateCoworkSessionsToThreads(
return { ...result, status: 'nothing-to-migrate' }
}
+ // Before the first write: a backup of the file holding the old sessions.
+ // It is written once and never replaced. A failure stops this run (outer
+ // catch -> partial, no attempt counted) rather than migrate without it.
+ await invoke('settings_backup_once', { label: COWORK_SETTINGS_BACKUP_LABEL })
+
// thread.json is the commit marker, so "already migrated" is decided from
// the committed threads, never from a directory that may hold a lone sidecar.
const existing = new Map<string, StoredThread>()
@@ -473,11 +498,15 @@ export async function migrateCoworkSessionsToThreads(
// commit so an interrupted run redoes it. It is a copy done in Rust:
// sessions/<id> is intentionally left behind as the rollback source,
// and the two scopes never share a directory.
- await deps.copyWorkspace?.(session.id)
+ const copy = await deps.copyWorkspace?.(session.id)
+ const skipped = copy?.skipped ?? 0
+ const unreadable = copy?.unreadable ?? 0
+ const leftOut =
+ skipped > 0 || unreadable > 0 ? { skipped, unreadable } : undefined
// Commit: thread.json last.
const created = await invoke<StoredThread>('create_thread', {
- thread: sessionToThread(session),
+ thread: sessionToThread(session, leftOut),
})
if (created?.id !== session.id) {
throw new PermanentMigrationError(