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): settle the Cowork migration past permanent failures

Akarshan Biswas0189b6550c3e
diff --git a/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts b/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts
index b3cdbcd64..d9920afbb 100644
--- a/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts
+++ b/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts
@@ -3,6 +3,7 @@ import {
migrateCoworkSessionsToThreads,
CODE_SESSIONS_KEY,
COWORK_MIGRATION_FLAG_KEY,
+ COWORK_MIGRATION_ABANDONED_KEY,
type Invoke,
} from '../migrateCoworkSessions'
import type { CoworkSession } from '@/hooks/useCoworkSessions'
@@ -230,15 +231,83 @@ describe('migrateCoworkSessionsToThreads', () => {
expect(b.threads.has('s1')).toBe(false)
})
- it('an id collision with a chat thread is reported, not overwritten', async () => {
+ it('an id collision with a chat thread is reported, never overwritten, and settles the marker', async () => {
b.threads.set('s1', { id: 's1', title: 'My chat', metadata: {} })
b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))
const r = await migrateCoworkSessionsToThreads(b.invoke)
- expect(r.status).toBe('partial')
- expect(r.failed[0].id).toBe('s1')
+ // A collision cannot fix itself, so it must not keep the marker unset
+ // (and the migration redoing work) on every launch.
+ expect(r.status).toBe('complete')
+ expect(r.failed).toEqual([])
+ expect(r.abandoned.map((a) => a.id)).toEqual(['s1'])
expect(b.threads.get('s1')!.title).toBe('My chat')
expect(b.extras.has('s1/cowork')).toBe(false)
+ 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' }),
+ ])
+ })
+
+ it('a permanent failure is remembered while a transient one keeps the marker unset and is retried', async () => {
+ b = makeBackend({ failCreateFor: 's2' })
+ b.threads.set('s1', { id: 's1', title: 'My chat', metadata: {} })
+ b.settings.set(
+ CODE_SESSIONS_KEY,
+ envelope([session('s1'), session('s2'), session('s3')])
+ )
+ const first = await migrateCoworkSessionsToThreads(b.invoke)
+ expect(first.status).toBe('partial')
+ expect(first.failed.map((f) => f.id)).toEqual(['s2'])
+ expect(first.abandoned.map((a) => a.id)).toEqual(['s1'])
expect(b.settings.has(COWORK_MIGRATION_FLAG_KEY)).toBe(false)
+
+ // Next launch (same stored state, the transient fault gone): only the
+ // transient failure is retried; the abandoned session is not examined.
+ const heal = makeBackend()
+ for (const [k, v] of b.settings) heal.settings.set(k, v)
+ for (const [k, v] of b.threads) heal.threads.set(k, v)
+ for (const [k, v] of b.extras) heal.extras.set(k, v)
+ for (const [k, v] of b.logs) heal.logs.set(k, v)
+ const second = await migrateCoworkSessionsToThreads(heal.invoke)
+ expect(second.status).toBe('complete')
+ expect(second.migrated).toEqual(['s2'])
+ expect(second.abandoned.map((a) => a.id)).toEqual(['s1'])
+ expect(heal.settings.get(COWORK_MIGRATION_FLAG_KEY)).toBe('true')
+ // s1 was not even examined again: no write was attempted for it.
+ expect(heal.extras.has('s1/cowork')).toBe(false)
+ })
+
+ it('a session id the backend would refuse is abandoned before any write', async () => {
+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('../escape')]))
+ const r = await migrateCoworkSessionsToThreads(b.invoke)
+ expect(r.abandoned.map((a) => a.id)).toEqual(['../escape'])
+ expect(r.status).toBe('complete')
+ expect(b.calls).not.toContain('write_thread_extra')
+ expect(b.calls).not.toContain('create_thread')
+ })
+
+ it('a refusal to overwrite a foreign messages log is permanent too', async () => {
+ 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"
+ )
+ return b.invoke<T>(cmd, args)
+ }
+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))
+ const r = await migrateCoworkSessionsToThreads(invoke)
+ expect(r.abandoned.map((a) => a.id)).toEqual(['s1'])
+ expect(b.settings.get(COWORK_MIGRATION_FLAG_KEY)).toBe('true')
+ })
+
+ it('transient write errors keep being retried and never settle the marker', async () => {
+ b = makeBackend({ failWriteFor: 's1' })
+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))
+ const r = await migrateCoworkSessionsToThreads(b.invoke)
+ expect(r.status).toBe('partial')
+ expect(r.abandoned).toEqual([])
+ expect(b.settings.has(COWORK_MIGRATION_FLAG_KEY)).toBe(false)
+ expect(b.settings.has(COWORK_MIGRATION_ABANDONED_KEY)).toBe(false)
})
it('fails a session when the backend assigns a different thread id', async () => {
@@ -248,9 +317,9 @@ describe('migrateCoworkSessionsToThreads', () => {
: b.invoke<T>(cmd, args)
b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))
const r = await migrateCoworkSessionsToThreads(invoke)
- expect(r.status).toBe('partial')
- expect(r.failed[0].id).toBe('s1')
- expect(b.settings.has(COWORK_MIGRATION_FLAG_KEY)).toBe(false)
+ // The backend would answer the same way every launch.
+ expect(r.abandoned.map((x) => x.id)).toEqual(['s1'])
+ expect(r.status).toBe('complete')
})
it('rebuilds messages for version-0 sessions that have none', async () => {
diff --git a/web-app/src/lib/migrateCoworkSessions.ts b/web-app/src/lib/migrateCoworkSessions.ts
index 4e94b9ccc..4c2ea3189 100644
--- a/web-app/src/lib/migrateCoworkSessions.ts
+++ b/web-app/src/lib/migrateCoworkSessions.ts
@@ -22,9 +22,11 @@ import {
* commit. The conversion is a pure function of the session, so a retry after
* 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, never overwritten, and keeps the marker unset.
- * - The completion marker is set only when every session migrated. Failures
- * never throw into app startup; they are returned.
+ * collision: it is reported and never overwritten. Such permanent failures
+ * are recorded under COWORK_MIGRATION_ABANDONED_KEY and not retried.
+ * - 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.
* - 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
@@ -35,6 +37,14 @@ import {
export const CODE_SESSIONS_KEY = 'code-sessions'
export const COWORK_MIGRATION_FLAG_KEY = 'cowork_threads_migrated_v1'
export const COWORK_SIDECAR = 'cowork'
+/**
+ * Sessions that can never migrate (an id taken by another conversation, an id
+ * the backend refuses). Remembering them lets the completion marker settle
+ * instead of redoing the same work on every launch. Transient errors (disk,
+ * backend not ready) are never recorded here and are retried.
+ */
+export const COWORK_MIGRATION_ABANDONED_KEY =
+ 'cowork_threads_migration_abandoned_v1'
export type Invoke = <T = unknown>(
cmd: string,
@@ -45,9 +55,15 @@ export type CoworkMigrationResult = {
status: 'already-migrated' | 'nothing-to-migrate' | 'complete' | 'partial'
migrated: string[]
skipped: string[]
+ /** Permanent failures: reported, remembered, never retried. */
+ abandoned: { id: string; error: string }[]
+ /** Transient failures: the marker stays unset and the next launch retries. */
failed: { id: string; error: string }[]
}
+/** A failure retrying cannot fix. */
+class PermanentMigrationError extends Error {}
+
/** The transcript payload stored beside thread.json, losslessly. */
export type CoworkSidecar = {
version: 1
@@ -77,9 +93,40 @@ function canonical(v: unknown): string {
)
}
+// Mirrors validate_thread_id in src-tauri/src/core/threads/utils.rs.
+const WINDOWS_DEVICE = /^(con|prn|aux|nul|(com|lpt)\d)$/i
+export function isValidThreadId(id: unknown): id is string {
+ return (
+ typeof id === 'string' &&
+ id.length > 0 &&
+ id.length <= 128 &&
+ /^[A-Za-z0-9_-]+$/.test(id) &&
+ !WINDOWS_DEVICE.test(id.split('.')[0])
+ )
+}
+
+// Backend refusals that will repeat on every launch.
+const isPermanentBackendError = (e: unknown) =>
+ /refusing to overwrite its messages|Invalid thread id/.test(toErrorMessage(e))
+
const toErrorMessage = (e: unknown) =>
e instanceof Error ? e.message : String(e)
+function readAbandoned(raw: string | null): { id: string; error: string }[] {
+ if (!raw) return []
+ try {
+ const parsed: unknown = JSON.parse(raw)
+ return Array.isArray(parsed)
+ ? parsed.filter(
+ (a): a is { id: string; error: string } =>
+ typeof a?.id === 'string' && typeof a?.error === 'string'
+ )
+ : []
+ } 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
@@ -149,6 +196,7 @@ export async function migrateCoworkSessionsToThreads(
status: 'complete',
migrated: [],
skipped: [],
+ abandoned: [],
failed: [],
}
const markDone = () =>
@@ -163,6 +211,11 @@ export async function migrateCoworkSessionsToThreads(
const sessions = readCoworkSessions(
await invoke<string | null>('settings_get', { key: CODE_SESSIONS_KEY })
)
+ const previouslyAbandoned = readAbandoned(
+ await invoke<string | null>('settings_get', {
+ key: COWORK_MIGRATION_ABANDONED_KEY,
+ })
+ )
const nonEmpty = sessions.filter((s) => !isEmptySession(s))
result.skipped = sessions.filter(isEmptySession).map((s) => s.id)
@@ -179,8 +232,19 @@ export async function migrateCoworkSessionsToThreads(
if (typeof t?.id === 'string') existing.set(t.id, t)
}
+ const newlyAbandoned: { id: string; error: string }[] = []
for (const session of nonEmpty) {
+ const before = previouslyAbandoned.find((a) => a.id === session.id)
+ if (before) {
+ result.abandoned.push(before)
+ continue
+ }
try {
+ if (!isValidThreadId(session.id)) {
+ throw new PermanentMigrationError(
+ `session id ${JSON.stringify(session.id)} is not a valid thread id`
+ )
+ }
const committed = existing.get(session.id)
if (committed) {
// A cowork thread with this id is already ours (copied by an earlier
@@ -189,7 +253,9 @@ export async function migrateCoworkSessionsToThreads(
result.skipped.push(session.id)
continue
}
- throw new Error('a different conversation already uses this id')
+ throw new PermanentMigrationError(
+ 'a different conversation already uses this id'
+ )
}
const sidecar = sessionToSidecar(session)
@@ -228,14 +294,33 @@ export async function migrateCoworkSessionsToThreads(
thread: sessionToThread(session),
})
if (created?.id !== session.id) {
- throw new Error('backend assigned a different thread id')
+ throw new PermanentMigrationError(
+ 'backend assigned a different thread id'
+ )
}
result.migrated.push(session.id)
} catch (e) {
- result.failed.push({ id: session.id, error: toErrorMessage(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)
+ }
}
}
+ if (newlyAbandoned.length > 0) {
+ console.warn(
+ '[cowork-migration] sessions that cannot be migrated; not retrying',
+ newlyAbandoned
+ )
+ await invoke('settings_set', {
+ key: COWORK_MIGRATION_ABANDONED_KEY,
+ value: JSON.stringify([...previouslyAbandoned, ...newlyAbandoned]),
+ })
+ }
+
if (result.failed.length > 0) {
console.warn(
'[cowork-migration] some sessions failed; will retry next launch',