Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(web-app): classify Cowork migration errors by code, cap retries, remember migrated ids
Akarshan Biswasd50e28bf5562
diff --git a/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts b/web-app/src/lib/__tests__/migrateCoworkSessions.test.tsindex cc41c44e5..5b0411706 100644--- a/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts+++ b/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts@@ -4,6 +4,9 @@ import {CODE_SESSIONS_KEY,COWORK_MIGRATION_FLAG_KEY,COWORK_MIGRATION_ABANDONED_KEY,+ COWORK_MIGRATED_IDS_KEY,+ COWORK_MIGRATION_ATTEMPTS_KEY,+ COWORK_MAX_ATTEMPTS,sameJson,type Invoke,} from '../migrateCoworkSessions'@@ -291,7 +294,7 @@ describe('migrateCoworkSessionsToThreads', () => {const invoke: Invoke = async <T = unknown>(cmd: string, args?: Args) => {if (cmd === 'write_thread_extra')throw new Error(- "Thread 's1' has messages but no thread.json; refusing to overwrite its messages"+ "PERMANENT: Thread 's1' has messages but no thread.json; refusing to overwrite its messages")return b.invoke<T>(cmd, args)}@@ -537,24 +540,24 @@ describe('sandbox workspace copy', () => {expect(b.settings.has(COWORK_MIGRATION_FLAG_KEY)).toBe(false)})- it('a refusal to merge into a thread workspace with its own files is permanent', async () => {+ it('a PERMANENT: copy refusal is permanent', async () => {const b = makeBackend()b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))const r = await run(b, async () => {- throw new Error('already holds files of its own; refusing to merge into it')+ throw new Error('PERMANENT: x already holds files of its own; refusing to merge into it')})expect(r.abandoned.map((a) => a.id)).toEqual(['s1'])expect(b.threads.has('s1')).toBe(false)expect(b.settings.get(COWORK_MIGRATION_FLAG_KEY)).toBe('true')})- it('reads the message of a plugin error object, so a merge refusal is still permanent', async () => {+ it('reads the message of a plugin error object, so a PERMANENT: code is still seen', async () => {const b = makeBackend()b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))const r = await run(b, async () => {// The plugin rejects with { message }, not an Error.throw {- message: 'x already holds files of its own; refusing to merge into it',+ message: 'PERMANENT: x already holds files of its own; refusing to merge into it',}})expect(r.abandoned).toEqual([@@ -577,6 +580,123 @@ describe('sandbox workspace copy', () => {})})+describe('classification by stable code', () => {+ const run = (copy: () => Promise<{ copied: boolean }>) => {+ const b = makeBackend()+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ return migrateCoworkSessionsToThreads(b.invoke, { copyWorkspace: copy })+ }++ it('does not classify by message wording: the old phrases without the code are transient', async () => {+ for (const text of [+ 'already holds files of its own; refusing to merge into it',+ 'Invalid thread id: "x"',+ 'x is a symlink; refusing to follow it',+ 'x is not a directory',+ ]) {+ const r = await run(async () => {+ throw new Error(text)+ })+ expect(r.failed.map((f) => f.id), text).toEqual(['s1'])+ expect(r.abandoned, text).toEqual([])+ }+ })++ it('every PERMANENT: error is abandoned, whatever its text', async () => {+ for (const text of [+ 'PERMANENT: x is a symlink; refusing to follow it',+ 'PERMANENT: x is not a directory',+ 'PERMANENT: invalid thread id',+ ]) {+ const r = await run(async () => {+ throw { message: text }+ })+ expect(r.abandoned.map((a) => a.id), text).toEqual(['s1'])+ }+ })++ it('a PERMANENT: error from a threads command is abandoned too', async () => {+ const b = makeBackend()+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ const invoke: Invoke = async <T = unknown>(cmd: string, args?: Args) => {+ if (cmd === 'replace_thread_messages')+ throw 'PERMANENT: Duplicate message id "m"'+ return b.invoke<T>(cmd, args)+ }+ const r = await migrateCoworkSessionsToThreads(invoke)+ expect(r.abandoned.map((a) => a.id)).toEqual(['s1'])+ })+})++describe('retry cap', () => {+ it('abandons a session that keeps failing transiently after N launches', async () => {+ const b = makeBackend({ failWriteFor: 's1' })+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1'), session('s2')]))+ for (let launch = 1; launch < COWORK_MAX_ATTEMPTS; launch++) {+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.status, `launch ${launch}`).toBe('partial')+ expect(r.failed.map((f) => f.id)).toEqual(['s1'])+ expect(b.settings.has(COWORK_MIGRATION_FLAG_KEY)).toBe(false)+ }+ const last = await migrateCoworkSessionsToThreads(b.invoke)+ expect(last.failed).toEqual([])+ expect(last.abandoned.map((a) => a.id)).toEqual(['s1'])+ expect(last.status).toBe('complete')+ expect(b.settings.get(COWORK_MIGRATION_FLAG_KEY)).toBe('true')+ expect(JSON.parse(b.settings.get(COWORK_MIGRATION_ABANDONED_KEY)!)).toEqual([+ expect.objectContaining({ id: 's1' }),+ ])+ expect(b.threads.has('s2')).toBe(true)+ expect(b.settings.has(COWORK_MIGRATION_ATTEMPTS_KEY)).toBe(true)+ })++ it('counts launches, not sessions: a session that succeeds is never abandoned', async () => {+ const b = makeBackend({ crashFirstCreate: true })+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ await migrateCoworkSessionsToThreads(b.invoke)+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.migrated).toEqual(['s1'])+ expect(r.abandoned).toEqual([])+ })+})++describe('migrated ids survive a user deleting the thread', () => {+ it('a migrated thread deleted in main chat is not recreated while the flag is unset', async () => {+ const b = makeBackend({ failWriteFor: 's2' })+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1'), session('s2')]))+ const first = await migrateCoworkSessionsToThreads(b.invoke)+ expect(first.migrated).toEqual(['s1'])+ expect(b.settings.has(COWORK_MIGRATION_FLAG_KEY)).toBe(false)+ expect(JSON.parse(b.settings.get(COWORK_MIGRATED_IDS_KEY)!)).toEqual(['s1'])++ // The user deletes the migrated thread; s2 still fails, so the flag stays unset.+ b.threads.delete('s1')+ b.extras.delete('s1/cowork')+ b.logs.delete('s1')+ const second = await migrateCoworkSessionsToThreads(b.invoke)+ expect(second.migrated).toEqual([])+ expect(second.skipped).toContain('s1')+ expect(b.threads.has('s1')).toBe(false)+ expect(b.extras.has('s1/cowork')).toBe(false)+ })++ it('an id found committed (crash before it was recorded) is recorded on the next run', async () => {+ const b = makeBackend()+ b.threads.set('s1', { id: 's1', title: 'x', metadata: { mode: 'cowork' } })+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ await migrateCoworkSessionsToThreads(b.invoke)+ expect(JSON.parse(b.settings.get(COWORK_MIGRATED_IDS_KEY)!)).toEqual(['s1'])+ })++ it('an unreadable ids record is treated as empty, not as a failure', async () => {+ const b = makeBackend()+ b.settings.set(COWORK_MIGRATED_IDS_KEY, '{not json')+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.migrated).toEqual(['s1'])+ })+})+describe('sameJson', () => {it('compares without re-sorting keys on the happy path', () => {const entries = vi.spyOn(Object, 'entries')diff --git a/web-app/src/lib/__tests__/migrateCoworkSessionsStartup.test.ts b/web-app/src/lib/__tests__/migrateCoworkSessionsStartup.test.tsindex 2c55ca641..63a5c82b3 100644--- a/web-app/src/lib/__tests__/migrateCoworkSessionsStartup.test.ts+++ b/web-app/src/lib/__tests__/migrateCoworkSessionsStartup.test.ts@@ -85,6 +85,40 @@ describe('migrateCoworkSessionsOnStartup', () => {expect(r?.status).toBe('partial')})+ it('runs one migration at a time: a second start (StrictMode, reload) shares the in-flight one', async () => {+ let release!: () => void+ const gate = new Promise<void>((r) => (release = r))+ h.invoke.mockImplementation(async (_cmd: string, args?: { key?: string }) => {+ await gate+ return args?.key === COWORK_MIGRATION_FLAG_KEY ? 'true' : null+ })+ const first = migrateCoworkSessionsOnStartup()+ const second = migrateCoworkSessionsOnStartup()+ release()+ const [a, b] = await Promise.all([first, second])+ expect(b).toBe(a)+ expect(+ h.invoke.mock.calls.filter(+ (c) => c[0] === 'settings_get' && c[1]?.key === COWORK_MIGRATION_FLAG_KEY+ )+ ).toHaveLength(1)++ // Once it has finished, the next start runs afresh (and is a cheap no-op).+ h.invoke.mockClear()+ await migrateCoworkSessionsOnStartup()+ expect(h.invoke).toHaveBeenCalled()+ })++ it('forgets a migration that returned null, so the next start can run', async () => {+ h.getServiceHub.mockImplementationOnce(() => {+ throw new Error('hub not ready')+ })+ await expect(migrateCoworkSessionsOnStartup()).resolves.toBeNull()+ h.invoke.mockResolvedValue('true')+ const r = await migrateCoworkSessionsOnStartup()+ expect(r?.status).toBe('already-migrated')+ })+it('wires the sandbox copy through the agent-tools helper, not a raw invoke', async () => {const envelope = JSON.stringify({state: {diff --git a/web-app/src/lib/migrateCoworkSessions.ts b/web-app/src/lib/migrateCoworkSessions.tsindex 1cb865bcb..a541f7cbb 100644--- a/web-app/src/lib/migrateCoworkSessions.ts+++ b/web-app/src/lib/migrateCoworkSessions.ts@@ -24,7 +24,16 @@ import {* a crash rewrites identical bytes and the prompt prefix stays stable.* - A thread id that already exists and is not a migrated Cowork thread is a* collision: it is reported and never overwritten. Such permanent failures- * are recorded under COWORK_MIGRATION_ABANDONED_KEY and not retried.+ * are recorded under COWORK_MIGRATION_ABANDONED_KEY and not retried. Backend+ * errors are classified by their stable `PERMANENT: ` prefix, never by text.+ * - A session that keeps failing transiently is abandoned after+ * COWORK_MAX_ATTEMPTS launches (counted under COWORK_MIGRATION_ATTEMPTS_KEY),+ * so one bad session cannot repeat a full copy on every launch forever.+ * - Every id is recorded under COWORK_MIGRATED_IDS_KEY when its thread+ * commits. A recorded id is never migrated again, so a thread the user+ * deletes in main chat does not come back while the completion marker is+ * still unset (some other session failing). Deleting a thread in the Cowork+ * UI is covered by the same record.* - The completion marker is set once every session has either migrated or been* abandoned. Transient failures keep it unset so the next launch retries.* Failures never throw into app startup; they are returned.@@ -35,9 +44,8 @@ import {* not touched when the migrated thread is deleted.* - Talks to the backend commands directly. `DefaultThreadsService.createThread`* swallows errors and would hide a failed write.- * - No deletion journal: on this build the Cowork store removes a deleted- * session from `code-sessions` itself, so a deleted session is never in the- * blob this reads and nothing can be resurrected from it.+ * - A session deleted in the Cowork UI is removed from `code-sessions` itself,+ * so it is never in the blob this reads.*/export const CODE_SESSIONS_KEY = 'code-sessions'@@ -52,6 +60,19 @@ export const COWORK_SIDECAR = 'cowork'export const COWORK_MIGRATION_ABANDONED_KEY ='cowork_threads_migration_abandoned_v1'+/** Ids whose thread this migration has committed (JSON array of strings). */+export const COWORK_MIGRATED_IDS_KEY = 'cowork_threads_migrated_ids_v1'+/** Launches in which a session failed transiently: JSON `{ [id]: count }`. */+export const COWORK_MIGRATION_ATTEMPTS_KEY = 'cowork_threads_migration_attempts_v1'+/** A session failing transiently on this many launches is abandoned. */+export const COWORK_MAX_ATTEMPTS = 5+/**+ * Stable prefix of a backend/plugin error that retrying cannot fix. Set by the+ * Rust side (`PERMANENT_PREFIX` in core::threads::utils and the agent-tools+ * workspace module); the migration matches it, not the message wording.+ */+export const PERMANENT_ERROR_PREFIX = 'PERMANENT: '+export type Invoke = <T = unknown>(cmd: string,args?: Record<string, unknown>@@ -131,11 +152,9 @@ export function isValidThreadId(id: unknown): id is string {)}-// Backend refusals that will repeat on every launch.+// Backend refusals that will repeat on every launch, by stable code.const isPermanentBackendError = (e: unknown) =>- /refusing to overwrite its messages|refusing to merge into|Invalid thread id/.test(- toErrorMessage(e)- )+ toErrorMessage(e).trimStart().startsWith(PERMANENT_ERROR_PREFIX)function toErrorMessage(e: unknown): string {if (e instanceof Error) return e.message@@ -162,6 +181,34 @@ function readAbandoned(raw: string | null): { id: string; error: string }[] {}}+function readIds(raw: string | null): string[] {+ if (!raw) return []+ try {+ const parsed: unknown = JSON.parse(raw)+ return Array.isArray(parsed)+ ? parsed.filter((id): id is string => typeof id === 'string')+ : []+ } catch {+ return []+ }+}++function readAttempts(raw: string | null): Record<string, number> {+ if (!raw) return {}+ try {+ const parsed: unknown = JSON.parse(raw)+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))+ return {}+ return Object.fromEntries(+ Object.entries(parsed).filter(+ (e): e is [string, number] => typeof e[1] === 'number'+ )+ )+ } catch {+ return {}+ }+}+/*** Parse the zustand-persist envelope `{state:{sessions}, version}`. Version-0* sessions have no `messages`; rebuild them from `turns` as the store's own@@ -252,6 +299,32 @@ export async function migrateCoworkSessionsToThreads(key: COWORK_MIGRATION_ABANDONED_KEY,}))+ const migratedIds = new Set(+ readIds(+ await invoke<string | null>('settings_get', {+ key: COWORK_MIGRATED_IDS_KEY,+ })+ )+ )+ const attempts = readAttempts(+ await invoke<string | null>('settings_get', {+ key: COWORK_MIGRATION_ATTEMPTS_KEY,+ })+ )+ let attemptsChanged = false+ // Best effort: a failed write must not turn a committed thread into a+ // failure. The next run finds the committed thread and records it then.+ const persistIds = async () => {+ try {+ await invoke('settings_set', {+ key: COWORK_MIGRATED_IDS_KEY,+ value: JSON.stringify([...migratedIds]),+ })+ } catch (e) {+ console.warn('[cowork-migration] could not record migrated ids:', e)+ }+ }+ let idsChanged = falseconst nonEmpty = sessions.filter((s) => !isEmptySession(s))result.skipped = sessions.filter(isEmptySession).map((s) => s.id)@@ -275,6 +348,12 @@ export async function migrateCoworkSessionsToThreads(result.abandoned.push(before)continue}+ if (migratedIds.has(session.id)) {+ // Committed by an earlier launch. If the user has deleted the thread+ // since, it stays deleted.+ result.skipped.push(session.id)+ continue+ }try {if (!isValidThreadId(session.id)) {throw new PermanentMigrationError(@@ -287,6 +366,8 @@ export async function migrateCoworkSessionsToThreads(// run). Anything else is a different conversation.if (committed.metadata?.mode === 'cowork') {result.skipped.push(session.id)+ migratedIds.add(session.id)+ idsChanged = truecontinue}throw new PermanentMigrationError(@@ -342,17 +423,50 @@ export async function migrateCoworkSessionsToThreads()}result.migrated.push(session.id)+ migratedIds.add(session.id)+ await persistIds()+ idsChanged = false+ if (session.id in attempts) {+ delete attempts[session.id]+ attemptsChanged = true+ }} catch (e) {const entry = { id: String(session.id), error: toErrorMessage(e) }if (e instanceof PermanentMigrationError || isPermanentBackendError(e)) {result.abandoned.push(entry)newlyAbandoned.push(entry)} else {- result.failed.push(entry)+ // Transient: count the launch, and give up on a session that has+ // failed on too many of them.+ const count = (attempts[entry.id] ?? 0) + 1+ attempts[entry.id] = count+ attemptsChanged = true+ if (count >= COWORK_MAX_ATTEMPTS) {+ const capped = {+ id: entry.id,+ error: `gave up after ${count} launches: ${entry.error}`,+ }+ result.abandoned.push(capped)+ newlyAbandoned.push(capped)+ } else {+ result.failed.push(entry)+ }}}}+ if (idsChanged) await persistIds()+ if (attemptsChanged) {+ try {+ await invoke('settings_set', {+ key: COWORK_MIGRATION_ATTEMPTS_KEY,+ value: JSON.stringify(attempts),+ })+ } catch (e) {+ console.warn('[cowork-migration] could not record attempts:', e)+ }+ }+if (newlyAbandoned.length > 0) {console.warn('[cowork-migration] sessions that cannot be migrated; not retrying',@@ -391,7 +505,24 @@ export async function migrateCoworkSessionsToThreads(* throws: a failed migration stays unflagged and is retried next launch, and* must not stop the app from rendering. Returns `null` when it did not run.*/-export async function migrateCoworkSessionsOnStartup(): Promise<CoworkMigrationResult | null> {+let inFlight: Promise<CoworkMigrationResult | null> | null = null++export function migrateCoworkSessionsOnStartup(): Promise<CoworkMigrationResult | null> {+ // One migration at a time: React StrictMode runs effects twice in dev and a+ // webview reload starts another while the first's backend work goes on, and+ // two overlapping runs would redo the same copies. Later callers share the+ // running one; it is forgotten once it settles, so a later start (a retry)+ // runs afresh.+ if (!inFlight) {+ const run = runCoworkMigrationOnStartup().finally(() => {+ if (inFlight === run) inFlight = null+ })+ inFlight = run+ }+ return inFlight+}++async function runCoworkMigrationOnStartup(): Promise<CoworkMigrationResult | null> {if (!isPlatformTauri()) return null// Sidecars and message replacement are file-backed and desktop-only; mobile// stores threads in SQLite and Cowork does not exist there.