Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(web-app): copy Cowork sessions into threads once
Akarshan Biswas49d682a51013
diff --git a/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts b/web-app/src/lib/__tests__/migrateCoworkSessions.test.tsnew file mode 100644index 000000000..1504151aa--- /dev/null+++ b/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts@@ -0,0 +1,258 @@+import { describe, it, expect, beforeEach } from 'vitest'+import {+ migrateCoworkSessionsToThreads,+ CODE_SESSIONS_KEY,+ COWORK_MIGRATION_FLAG_KEY,+ type Invoke,+} from '../migrateCoworkSessions'+import type { CoworkSession } from '@/hooks/useCoworkSessions'++type Json = Record<string, unknown>+type Args = Record<string, unknown>++type BackendOptions = { failCreateFor?: string; failWriteFor?: string }++// In-memory backend with the same command surface the migration uses.+function makeBackend(opts: BackendOptions = {}) {+ const settings = new Map<string, string>()+ const threads = new Map<string, Json>()+ const extras = new Map<string, unknown>()+ const calls: string[] = []+ const invoke: Invoke = async <T = unknown>(cmd: string, args: Args = {}) => {+ calls.push(cmd)+ const threadId = args.threadId as string+ const key = args.key as string+ switch (cmd) {+ case 'settings_get':+ return (settings.get(key) ?? null) as T+ case 'settings_set':+ settings.set(key, args.value as string)+ return undefined as T+ case 'list_threads':+ return [...threads.values()] as T+ case 'write_thread_extra':+ if (threadId === opts.failWriteFor) throw new Error('disk full')+ if (!args.create && !threads.has(threadId))+ throw new Error('no thread.json')+ // Mimic serde_json by round-tripping through JSON.+ extras.set(+ `${threadId}/${args.name}`,+ JSON.parse(JSON.stringify(args.value))+ )+ return undefined as T+ case 'read_thread_extra':+ return (extras.get(`${threadId}/${args.name}`) ?? null) as T+ case 'create_thread': {+ const thread = args.thread as Json & { id: string }+ if (thread.id === opts.failCreateFor) throw new Error('boom')+ threads.set(thread.id, thread)+ return thread as T+ }+ default:+ throw new Error(`unexpected command ${cmd}`)+ }+ }+ return { invoke, settings, threads, extras, calls }+}++const session = (id: string, extra: Partial<CoworkSession> = {}) =>+ ({+ id,+ title: `Session ${id}`,+ model: { id: 'gpt', provider: 'openai' },+ folder: '/work/proj',+ turns: [{ role: 'user', content: 'hi' }],+ messages: [{ id: 'm1', role: 'user', parts: [{ type: 'text', text: 'hi' }] }],+ updated: 1_700_000_000_000,+ ...extra,+ }) as unknown as CoworkSession++const envelope = (sessions: unknown[], version = 1) =>+ JSON.stringify({ state: { sessions, currentId: null }, version })++describe('migrateCoworkSessionsToThreads', () => {+ let b: ReturnType<typeof makeBackend>+ beforeEach(() => {+ b = makeBackend()+ })++ it('sets the marker and writes nothing when there is no blob (stable path)', async () => {+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.status).toBe('nothing-to-migrate')+ expect(b.settings.get(COWORK_MIGRATION_FLAG_KEY)).toBe('true')+ expect(b.threads.size).toBe(0)+ expect(b.calls).not.toContain('create_thread')+ })++ it('maps a session to a cowork thread and a lossless sidecar', async () => {+ const s = session('s1', {+ planMode: true,+ goal: { condition: 'done', turns: 1, status: 'active', lastReason: '' },+ todos: { phases: [] },+ subagents: [{ runId: 'r1' }],+ history: [{ role: 'user', content: 'old' }],+ } as unknown as Partial<CoworkSession>)+ b.settings.set(CODE_SESSIONS_KEY, envelope([s]))+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.status).toBe('complete')+ expect(r.migrated).toEqual(['s1'])++ const t = b.threads.get('s1') as {+ metadata: Json+ assistants: { id: string; model: unknown }[]+ updated: number+ created: number+ }+ expect(t.metadata.mode).toBe('cowork')+ expect(t.metadata.folder).toBe('/work/proj')+ expect(t.metadata.planMode).toBe(true)+ expect(t.metadata.migratedFrom).toEqual({+ store: CODE_SESSIONS_KEY,+ updated: s.updated,+ })+ // Same assistant shape main's thread service writes for a model-only chat.+ expect(t.assistants[0].id).toBe('model-only')+ expect(t.assistants[0].model).toEqual({ id: 'gpt', engine: 'openai' })+ // ms -> seconds+ expect(t.updated).toBe(1_700_000_000)+ expect(t.created).toBe(1_700_000_000)++ const side = b.extras.get('s1/cowork') as Json+ expect(side.turns).toEqual(s.turns)+ expect(side.messages).toEqual(s.messages)+ expect(side.history).toEqual(s.history)+ expect(side.subagents).toEqual(s.subagents)+ expect(side.todos).toEqual(s.todos)+ })++ it('never touches the source blob', async () => {+ const raw = envelope([session('s1')])+ b.settings.set(CODE_SESSIONS_KEY, raw)+ await migrateCoworkSessionsToThreads(b.invoke)+ expect(b.settings.get(CODE_SESSIONS_KEY)).toBe(raw)+ })++ it('is a no-op once the marker is set', async () => {+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ await migrateCoworkSessionsToThreads(b.invoke)+ b.calls.length = 0+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.status).toBe('already-migrated')+ expect(b.calls).toEqual(['settings_get'])+ })++ it('is idempotent when the marker is lost: committed sessions are skipped, not rewritten', async () => {+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ await migrateCoworkSessionsToThreads(b.invoke)+ b.settings.delete(COWORK_MIGRATION_FLAG_KEY)+ b.calls.length = 0+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.status).toBe('complete')+ expect(r.skipped).toContain('s1')+ expect(b.calls).not.toContain('write_thread_extra')+ expect(b.calls).not.toContain('create_thread')+ expect(b.settings.get(COWORK_MIGRATION_FLAG_KEY)).toBe('true')+ })++ it('skips empty sessions', async () => {+ b.settings.set(+ CODE_SESSIONS_KEY,+ envelope([session('full'), session('empty', { turns: [], messages: [] })])+ )+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.migrated).toEqual(['full'])+ expect(r.skipped).toContain('empty')+ expect(b.threads.has('empty')).toBe(false)+ })++ it('crash recovery: a sidecar without thread.json is redone, not skipped', async () => {+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ // Simulate a crash after the sidecar write: sidecar exists, no thread.json.+ b.extras.set('s1/cowork', { version: 1, turns: [], messages: [] })+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.migrated).toEqual(['s1'])+ expect(b.threads.has('s1')).toBe(true)+ expect((b.extras.get('s1/cowork') as { turns: unknown[] }).turns).toHaveLength(1)+ })++ it('writes the sidecar before thread.json, which is the commit marker', async () => {+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ await migrateCoworkSessionsToThreads(b.invoke)+ expect(b.calls.indexOf('write_thread_extra')).toBeGreaterThan(-1)+ expect(b.calls.indexOf('write_thread_extra')).toBeLessThan(+ b.calls.indexOf('create_thread')+ )+ })++ it('partial failure leaves the marker unset and migrates the rest', async () => {+ b = makeBackend({ failCreateFor: 's2' })+ b.settings.set(+ CODE_SESSIONS_KEY,+ envelope([session('s1'), session('s2'), session('s3')])+ )+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.status).toBe('partial')+ expect(r.migrated).toEqual(['s1', 's3'])+ expect(r.failed).toEqual([{ id: 's2', error: 'boom' }])+ expect(b.settings.has(COWORK_MIGRATION_FLAG_KEY)).toBe(false)+ })++ it('a failed sidecar write never commits thread.json', 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(b.threads.has('s1')).toBe(false)+ })++ it('an id collision with a chat thread is reported, not overwritten', 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')+ expect(b.threads.get('s1')!.title).toBe('My chat')+ expect(b.extras.has('s1/cowork')).toBe(false)+ expect(b.settings.has(COWORK_MIGRATION_FLAG_KEY)).toBe(false)+ })++ it('fails a session when the backend assigns a different thread id', async () => {+ const invoke: Invoke = async <T = unknown>(cmd: string, args?: Args) =>+ cmd === 'create_thread'+ ? ({ ...(args!.thread as Json), id: 'other' } as T)+ : 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)+ })++ it('rebuilds messages for version-0 sessions that have none', async () => {+ const v0: Partial<CoworkSession> = {+ ...session('old', { turns: [{ role: 'user', content: 'hello' }] as never }),+ }+ delete v0.messages+ b.settings.set(CODE_SESSIONS_KEY, envelope([v0], 0))+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.migrated).toEqual(['old'])+ const side = b.extras.get('old/cowork') as { messages: unknown[] }+ expect(side.messages.length).toBeGreaterThan(0)+ })++ it('a corrupt blob does not throw into startup and leaves the marker unset', async () => {+ b.settings.set(CODE_SESSIONS_KEY, '{not json')+ const r = await migrateCoworkSessionsToThreads(b.invoke)+ expect(r.status).toBe('partial')+ expect(b.settings.has(COWORK_MIGRATION_FLAG_KEY)).toBe(false)+ })++ it('a rejected settings read does not throw into startup', async () => {+ const invoke: Invoke = async () => {+ throw new Error('backend not ready')+ }+ const r = await migrateCoworkSessionsToThreads(invoke)+ expect(r.status).toBe('partial')+ expect(r.failed[0].error).toContain('backend not ready')+ })+})diff --git a/web-app/src/lib/__tests__/migrateCoworkSessionsStartup.test.ts b/web-app/src/lib/__tests__/migrateCoworkSessionsStartup.test.tsnew file mode 100644index 000000000..a553da2d6--- /dev/null+++ b/web-app/src/lib/__tests__/migrateCoworkSessionsStartup.test.ts@@ -0,0 +1,63 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++const h = vi.hoisted(() => ({+ isTauri: true,+ invoke: vi.fn(),+ getServiceHub: vi.fn(),+}))++vi.mock('@/lib/platform/utils', () => ({+ isPlatformTauri: () => h.isTauri,+}))+vi.mock('@/hooks/useServiceHub', () => ({+ getServiceHub: h.getServiceHub,+}))++import {+ migrateCoworkSessionsOnStartup,+ CODE_SESSIONS_KEY,+ COWORK_MIGRATION_FLAG_KEY,+} from '../migrateCoworkSessions'++describe('migrateCoworkSessionsOnStartup', () => {+ beforeEach(() => {+ h.isTauri = true+ h.invoke.mockReset()+ h.getServiceHub.mockReset()+ h.getServiceHub.mockReturnValue({ core: () => ({ invoke: h.invoke }) })+ })++ it('does nothing outside Tauri (no backend to migrate)', async () => {+ h.isTauri = false+ await migrateCoworkSessionsOnStartup()+ expect(h.getServiceHub).not.toHaveBeenCalled()+ expect(h.invoke).not.toHaveBeenCalled()+ })++ it('runs the migration through the service hub invoke', async () => {+ h.invoke.mockImplementation(async (_cmd: string, args?: { key?: string }) =>+ args?.key === COWORK_MIGRATION_FLAG_KEY ? 'true' : null+ )+ const r = await migrateCoworkSessionsOnStartup()+ expect(r?.status).toBe('already-migrated')+ expect(h.invoke).toHaveBeenCalledWith('settings_get', {+ key: COWORK_MIGRATION_FLAG_KEY,+ })+ expect(h.invoke).not.toHaveBeenCalledWith('settings_get', {+ key: CODE_SESSIONS_KEY,+ })+ })++ it('never throws into startup when the service hub is unavailable', async () => {+ h.getServiceHub.mockImplementation(() => {+ throw new Error('hub not ready')+ })+ await expect(migrateCoworkSessionsOnStartup()).resolves.toBeNull()+ })++ it('never throws into startup when the backend rejects', async () => {+ h.invoke.mockRejectedValue(new Error('boom'))+ const r = await migrateCoworkSessionsOnStartup()+ expect(r?.status).toBe('partial')+ })+})diff --git a/web-app/src/lib/migrateCoworkSessions.ts b/web-app/src/lib/migrateCoworkSessions.tsnew file mode 100644index 000000000..8888b2394--- /dev/null+++ b/web-app/src/lib/migrateCoworkSessions.ts@@ -0,0 +1,249 @@+import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'+import type { CoworkSession } from '@/hooks/useCoworkSessions'+import { getServiceHub } from '@/hooks/useServiceHub'+import { isPlatformTauri } from '@/lib/platform/utils'++/**+ * One-time copy of Cowork sessions (`code-sessions` in settings.json) into+ * threads with `metadata.mode = "cowork"`.+ *+ * Rules:+ * - Copy, never move: `code-sessions` is left untouched as the rollback source.+ * - Idempotent and resumable. `thread.json` is the commit marker and is written+ * LAST; a directory holding only the sidecar is not committed and is redone.+ * - 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.+ * - 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.+ */++export const CODE_SESSIONS_KEY = 'code-sessions'+export const COWORK_MIGRATION_FLAG_KEY = 'cowork_threads_migrated_v1'+export const COWORK_SIDECAR = 'cowork'++export type Invoke = <T = unknown>(+ cmd: string,+ args?: Record<string, unknown>+) => Promise<T>++export type CoworkMigrationResult = {+ status: 'already-migrated' | 'nothing-to-migrate' | 'complete' | 'partial'+ migrated: string[]+ skipped: string[]+ failed: { id: string; error: string }[]+}++/** The transcript payload stored beside thread.json, losslessly. */+export type CoworkSidecar = {+ version: 1+ turns: CoworkSession['turns']+ messages: CoworkSession['messages']+ history?: CoworkSession['history']+ subagents?: CoworkSession['subagents']+ lastUsage?: CoworkSession['lastUsage']+ todos?: CoworkSession['todos']+}++type StoredThread = {+ id?: unknown+ metadata?: { mode?: unknown } | null+}++// Key-order-insensitive serialization: the backend may reorder object keys.+function canonical(v: unknown): string {+ return JSON.stringify(v, (_k, val) =>+ val && typeof val === 'object' && !Array.isArray(val)+ ? Object.fromEntries(+ Object.entries(val as Record<string, unknown>).sort(([a], [b]) =>+ a < b ? -1 : a > b ? 1 : 0+ )+ )+ : val+ )+}++const toErrorMessage = (e: unknown) =>+ e instanceof Error ? e.message : String(e)++/**+ * Parse the zustand-persist envelope `{state:{sessions}, version}`. Version-0+ * sessions have no `messages`; rebuild them from `turns` as the store's own+ * `migrate` does, leaving `history` as it was.+ */+export function readCoworkSessions(raw: string | null): CoworkSession[] {+ if (!raw) return []+ const parsed = JSON.parse(raw) as { state?: { sessions?: CoworkSession[] } }+ const sessions = parsed?.state?.sessions+ if (!Array.isArray(sessions)) return []+ return sessions.map((s) =>+ s.messages+ ? s+ : { ...s, messages: coworkTurnsToUIMessages(s.turns ?? [], s.id) }+ )+}++export function sessionToSidecar(s: CoworkSession): CoworkSidecar {+ return {+ version: 1,+ turns: s.turns ?? [],+ messages: s.messages ?? [],+ ...(s.history !== undefined && { history: s.history }),+ ...(s.subagents !== undefined && { subagents: s.subagents }),+ ...(s.lastUsage !== undefined && { lastUsage: s.lastUsage }),+ ...(s.todos !== undefined && { todos: s.todos }),+ }+}++export function sessionToThread(s: CoworkSession) {+ // 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+ return {+ id: s.id,+ object: 'thread',+ title: s.title,+ assistants: [+ {+ id: 'model-only',+ name: 'Model',+ model: {+ id: s.model?.id ?? '*',+ engine: s.model?.provider ?? 'llamacpp',+ },+ },+ ],+ created: seconds,+ updated: seconds,+ metadata: {+ mode: 'cowork',+ folder: s.folder ?? null,+ ...(s.planMode !== undefined && { planMode: s.planMode }),+ ...(s.goal !== undefined && { goal: s.goal }),+ migratedFrom: { store: CODE_SESSIONS_KEY, updated: s.updated },+ },+ }+}++const isEmptySession = (s: CoworkSession) =>+ (s.turns?.length ?? 0) === 0 && (s.messages?.length ?? 0) === 0++export async function migrateCoworkSessionsToThreads(+ invoke: Invoke+): Promise<CoworkMigrationResult> {+ const result: CoworkMigrationResult = {+ status: 'complete',+ migrated: [],+ skipped: [],+ failed: [],+ }+ const markDone = () =>+ invoke('settings_set', { key: COWORK_MIGRATION_FLAG_KEY, value: 'true' })++ try {+ const flag = await invoke<string | null>('settings_get', {+ key: COWORK_MIGRATION_FLAG_KEY,+ })+ if (flag === 'true') return { ...result, status: 'already-migrated' }++ const sessions = readCoworkSessions(+ await invoke<string | null>('settings_get', { key: CODE_SESSIONS_KEY })+ )+ const nonEmpty = sessions.filter((s) => !isEmptySession(s))+ result.skipped = sessions.filter(isEmptySession).map((s) => s.id)++ if (nonEmpty.length === 0) {+ // Nothing was ever written (stable never enabled Cowork): just record it.+ await markDone()+ return { ...result, status: 'nothing-to-migrate' }+ }++ // 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>()+ for (const t of await invoke<StoredThread[]>('list_threads')) {+ if (typeof t?.id === 'string') existing.set(t.id, t)+ }++ for (const session of nonEmpty) {+ try {+ const committed = existing.get(session.id)+ if (committed) {+ // A cowork thread with this id is already ours (copied by an earlier+ // run). Anything else is a different conversation.+ if (committed.metadata?.mode === 'cowork') {+ result.skipped.push(session.id)+ continue+ }+ throw new Error('a different conversation already uses this id')+ }++ const sidecar = sessionToSidecar(session)+ await invoke('write_thread_extra', {+ threadId: session.id,+ name: COWORK_SIDECAR,+ value: sidecar,+ // The thread directory does not exist yet; creating it is allowed here.+ create: true,+ })+ const back = await invoke<unknown>('read_thread_extra', {+ threadId: session.id,+ name: COWORK_SIDECAR,+ })+ if (canonical(back) !== canonical(sidecar)) {+ throw new Error('sidecar did not read back identically')+ }++ // Commit: thread.json last.+ const created = await invoke<StoredThread>('create_thread', {+ thread: sessionToThread(session),+ })+ if (created?.id !== session.id) {+ throw new Error('backend assigned a different thread id')+ }+ result.migrated.push(session.id)+ } catch (e) {+ result.failed.push({ id: session.id, error: toErrorMessage(e) })+ }+ }++ if (result.failed.length > 0) {+ console.warn(+ '[cowork-migration] some sessions failed; will retry next launch',+ result.failed+ )+ return { ...result, status: 'partial' }+ }+ await markDone()+ return result+ } catch (e) {+ console.warn('[cowork-migration] failed; will retry next launch:', e)+ return {+ ...result,+ status: 'partial',+ failed: [...result.failed, { id: '*', error: toErrorMessage(e) }],+ }+ }+}++/**+ * Startup entry point: runs the migration through the service hub's backend+ * `invoke`, the same seam `migrateLocalStorageToBackend` uses. On web there is+ * no backend and no `code-sessions` blob in it, so nothing runs. It never+ * 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> {+ if (!isPlatformTauri()) return null+ try {+ const core = getServiceHub().core()+ return await migrateCoworkSessionsToThreads(core.invoke.bind(core) as Invoke)+ } catch (e) {+ console.warn('[cowork-migration] could not start; will retry next launch:', e)+ return null+ }+}