Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(web-app): copy the Cowork sandbox into the thread workspace on migration
Akarshan Biswas9e1872c20cec
diff --git a/src-tauri/src/core/threads/commands.rs b/src-tauri/src/core/threads/commands.rsindex 237611bb0..94c4a148e 100644--- a/src-tauri/src/core/threads/commands.rs+++ b/src-tauri/src/core/threads/commands.rs@@ -64,11 +64,24 @@ pub async fn list_threads<R: Runtime>(/// Creates a new thread and persists its metadata./// Ensures the thread directory exists and writes thread.json.///-/// A caller-supplied `id` is kept when it is a valid thread id (a migrated-/// Cowork session keeps its id so its sandbox stays linked). A missing or+/// A caller-supplied `id` is kept when it is a valid thread id; a missing or/// invalid id gets a fresh UUID. Creation is idempotent: when thread.json/// already exists for the id, that record is returned untouched. thread.json/// is written atomically because it is the commit marker of a thread.+///+/// Two consequences of keeping the id:+/// - A migrated Cowork session keeps its session id as its thread id. Its+/// sandbox files under `agent-workspace/sessions/<id>` are NOT linked to the+/// thread: the thread uses the normal thread workspace+/// (`agent-workspace/threads/<id>`), and the migration COPIES the session's+/// files there (`session_workspace_copy_to_thread`). `sessions/<id>` is left+/// behind untouched as the rollback source.+/// - Every normal chat now keeps the ULID the web app mints (`ulid()` in+/// useThreads / ChatInput / conversations) instead of getting a backend UUID,+/// so thread directory names are ULIDs for new chats and UUIDs for old ones+/// (F6). Nothing in jan-cli or core/cli parses a thread id as a UUID: they+/// only mint UUIDs and treat ids as opaque `[A-Za-z0-9_-]` names+/// (`validate_thread_id`).#[tauri::command]pub async fn create_thread<R: Runtime>(app_handle: tauri::AppHandle<R>,diff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.tsindex c1890272c..c983bb871 100644--- a/web-app/src/lib/__tests__/agentTools.test.ts+++ b/web-app/src/lib/__tests__/agentTools.test.ts@@ -4,6 +4,7 @@ const toolSchemas = vi.fn()const executeTool = vi.fn()const threadWorkspaceDelete = vi.fn()const threadWorkspaceSweep = vi.fn()+const sessionWorkspaceCopyToThread = vi.fn()const sandboxStatus = vi.fn()const memoryCatalog = vi.fn()const memoryRead = vi.fn()@@ -16,6 +17,8 @@ vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({executeTool: (...args: unknown[]) => executeTool(...args),threadWorkspaceDelete: (...args: unknown[]) => threadWorkspaceDelete(...args),threadWorkspaceSweep: (...args: unknown[]) => threadWorkspaceSweep(...args),+ sessionWorkspaceCopyToThread: (...args: unknown[]) =>+ sessionWorkspaceCopyToThread(...args),sandboxStatus: () => sandboxStatus(),memoryCatalog: (...args: unknown[]) => memoryCatalog(...args),memoryRead: (...args: unknown[]) => memoryRead(...args),@@ -40,6 +43,9 @@ describe('agentTools', () => {executeTool.mockReset()threadWorkspaceDelete.mockReset().mockResolvedValue(undefined)threadWorkspaceSweep.mockReset().mockResolvedValue(0)+ sessionWorkspaceCopyToThread+ .mockReset()+ .mockResolvedValue({ copied: true, files: 2, skipped: 0 })sandboxStatus.mockReset().mockResolvedValue({ backend: 'bubblewrap', enforces: true })@@ -494,6 +500,32 @@ describe('agentTools', () => {expect(threadWorkspaceSweep).toHaveBeenCalledWith('/data', ['a', 'b'])})+ it('copies a session sandbox into the thread workspace of the same id', async () => {+ const { copySessionWorkspaceToThread } = await import('../agentTools')+ await expect(copySessionWorkspaceToThread('s1')).resolves.toMatchObject({+ copied: true,+ })+ expect(sessionWorkspaceCopyToThread).toHaveBeenCalledWith('/data', 's1')+ })++ // The migration must not commit a thread whose files did not arrive.+ it('lets a failed sandbox copy reject instead of swallowing it', async () => {+ sessionWorkspaceCopyToThread.mockRejectedValue({ message: 'disk full' })+ const { copySessionWorkspaceToThread } = await import('../agentTools')+ await expect(copySessionWorkspaceToThread('s1')).rejects.toEqual({+ message: 'disk full',+ })+ })++ it('copies nothing when there is no data folder', async () => {+ getJanDataFolder.mockResolvedValue('')+ const { copySessionWorkspaceToThread } = await import('../agentTools')+ await expect(copySessionWorkspaceToThread('s1')).resolves.toEqual({+ copied: false,+ })+ expect(sessionWorkspaceCopyToThread).not.toHaveBeenCalled()+ })+it('reports zero swept when the sweep fails', async () => {threadWorkspaceSweep.mockRejectedValue(new Error('nope'))const { sweepThreadWorkspaces } = await import('../agentTools')diff --git a/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts b/web-app/src/lib/__tests__/migrateCoworkSessions.test.tsindex 54e6c9fe8..cc41c44e5 100644--- a/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts+++ b/web-app/src/lib/__tests__/migrateCoworkSessions.test.ts@@ -471,6 +471,112 @@ describe('migrateCoworkSessionsToThreads', () => {})})+describe('sandbox workspace copy', () => {+ type Copy = (id: string) => Promise<{ copied: boolean }>+ const run = (b: ReturnType<typeof makeBackend>, copyWorkspace: Copy) =>+ migrateCoworkSessionsToThreads(b.invoke, { copyWorkspace })++ it('copies the sandbox into the thread workspace before thread.json commits', async () => {+ const b = makeBackend()+ const order: string[] = []+ const invoke: Invoke = async <T = unknown>(cmd: string, args?: Args) => {+ order.push(cmd)+ return b.invoke<T>(cmd, args)+ }+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ const copyWorkspace = vi.fn(async (id: string) => {+ order.push(`copy:${id}`)+ return { copied: true }+ })+ const r = await migrateCoworkSessionsToThreads(invoke, { copyWorkspace })+ expect(r.status).toBe('complete')+ expect(copyWorkspace).toHaveBeenCalledWith('s1')+ expect(order.indexOf('copy:s1')).toBeGreaterThan(-1)+ expect(order.indexOf('copy:s1')).toBeLessThan(order.indexOf('create_thread'))+ })++ it('leaves the thread on Thread scope: no session scope marker in its metadata', async () => {+ const b = makeBackend()+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ await run(b, async () => ({ copied: true }))+ const meta = (b.threads.get('s1') as { metadata: Json }).metadata+ expect(meta).not.toHaveProperty('sandboxScope')+ expect(JSON.stringify(meta)).not.toContain('"session"')+ })++ 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')]))+ const copyWorkspace = vi.fn(async () => ({ copied: true }))+ await run(b, copyWorkspace)+ expect(b.threads.has('s1')).toBe(false)+ await run(b, copyWorkspace)+ expect(copyWorkspace).toHaveBeenCalledTimes(2)+ expect(b.threads.has('s1')).toBe(true)+ })++ it('does not copy again for a thread that is already committed', async () => {+ const b = makeBackend()+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ const copyWorkspace = vi.fn(async () => ({ copied: true }))+ await run(b, copyWorkspace)+ b.settings.delete(COWORK_MIGRATION_FLAG_KEY)+ await run(b, copyWorkspace)+ expect(copyWorkspace).toHaveBeenCalledTimes(1)+ })++ it('a transient copy failure never commits the thread and is retried', async () => {+ const b = makeBackend()+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ const r = await run(b, async () => {+ throw new Error('ERROR: disk full')+ })+ expect(r.status).toBe('partial')+ expect(r.failed.map((f) => f.id)).toEqual(['s1'])+ expect(b.threads.has('s1')).toBe(false)+ 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 () => {+ 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')+ })+ 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 () => {+ 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',+ }+ })+ expect(r.abandoned).toEqual([+ expect.objectContaining({ error: expect.stringContaining('refusing to merge') }),+ ])+ })++ it('sessions without a sandbox migrate normally', async () => {+ const b = makeBackend()+ b.settings.set(CODE_SESSIONS_KEY, envelope([session('s1')]))+ const r = await run(b, async () => ({ copied: false }))+ expect(r.migrated).toEqual(['s1'])+ })++ it('without a copy function (no sandbox backend) the migration still runs', async () => {+ const b = makeBackend()+ 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 aa765c48e..2c55ca641 100644--- a/web-app/src/lib/__tests__/migrateCoworkSessionsStartup.test.ts+++ b/web-app/src/lib/__tests__/migrateCoworkSessionsStartup.test.ts@@ -6,6 +6,9 @@ const h = vi.hoisted(() => ({isAndroid: false,invoke: vi.fn(),getServiceHub: vi.fn(),+ copyWorkspace: vi.fn(),+ lastExtra: undefined as unknown,+ lastMessages: [] as unknown[],}))vi.mock('@/lib/platform/utils', () => ({@@ -16,6 +19,9 @@ vi.mock('@/lib/platform/utils', () => ({vi.mock('@/hooks/useServiceHub', () => ({getServiceHub: h.getServiceHub,}))+vi.mock('@/lib/agentTools', () => ({+ copySessionWorkspaceToThread: h.copyWorkspace,+}))import {migrateCoworkSessionsOnStartup,@@ -29,6 +35,7 @@ describe('migrateCoworkSessionsOnStartup', () => {h.isIOS = falseh.isAndroid = falseh.invoke.mockReset()+ h.copyWorkspace.mockReset().mockResolvedValue({ copied: true })h.getServiceHub.mockReset()h.getServiceHub.mockReturnValue({ core: () => ({ invoke: h.invoke }) })})@@ -77,4 +84,46 @@ describe('migrateCoworkSessionsOnStartup', () => {const r = await migrateCoworkSessionsOnStartup()expect(r?.status).toBe('partial')})++ it('wires the sandbox copy through the agent-tools helper, not a raw invoke', async () => {+ const envelope = JSON.stringify({+ state: {+ sessions: [+ {+ id: 's1',+ title: 'T',+ turns: [{ role: 'user', content: 'hi' }],+ messages: [+ { id: 'm', role: 'user', parts: [{ type: 'text', text: 'hi' }] },+ ],+ updated: 1_700_000_000_000,+ },+ ],+ },+ version: 1,+ })+ h.invoke.mockImplementation(async (cmd: string, args?: { key?: string }) => {+ if (cmd === 'settings_get')+ return args?.key === CODE_SESSIONS_KEY ? envelope : null+ if (cmd === 'list_threads') return []+ if (cmd === 'read_thread_extra') return h.lastExtra+ if (cmd === 'write_thread_extra') {+ h.lastExtra = (args as unknown as { value: unknown }).value+ return undefined+ }+ if (cmd === 'replace_thread_messages') {+ h.lastMessages = (args as unknown as { messages: unknown[] }).messages+ return undefined+ }+ if (cmd === 'list_messages') return h.lastMessages+ if (cmd === 'create_thread') return (args as unknown as { thread: unknown }).thread+ return undefined+ })+ const r = await migrateCoworkSessionsOnStartup()+ expect(r?.migrated).toEqual(['s1'])+ expect(h.copyWorkspace).toHaveBeenCalledWith('s1')+ expect(h.invoke.mock.calls.map((c) => c[0])).not.toContain(+ 'plugin:agent-tools|session_workspace_copy_to_thread'+ )+ })})diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex a23cae27b..a400c7805 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -3,6 +3,7 @@ import {executeTool,sandboxStatus,threadWorkspaceDelete,+ sessionWorkspaceCopyToThread,threadWorkspaceSweep,memoryCatalog,memoryRead,@@ -509,6 +510,20 @@ export async function cleanupThreadWorkspace(threadId: string): Promise<void> {}}+/**+ * Copy a Cowork session's sandbox into the thread workspace of the same id+ * (Cowork migration). Unlike the cleanup helpers this THROWS: the migration+ * must not commit a thread whose files did not arrive. With no data folder+ * there is nothing to copy.+ */+export async function copySessionWorkspaceToThread(+ sessionId: string+): Promise<{ copied: boolean }> {+ const dataFolder = await getServiceHub().app().getJanDataFolder()+ if (!dataFolder) return { copied: false }+ return await sessionWorkspaceCopyToThread(dataFolder, sessionId)+}+/*** Delete sandboxes left behind by threads that no longer exist, returning how* many were removed. Best-effort, same reasoning as above.diff --git a/web-app/src/lib/migrateCoworkSessions.ts b/web-app/src/lib/migrateCoworkSessions.tsindex d7e278954..1cb865bcb 100644--- a/web-app/src/lib/migrateCoworkSessions.ts+++ b/web-app/src/lib/migrateCoworkSessions.ts@@ -2,6 +2,7 @@ import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'import { coworkSessionToThreadMessages } from '@/lib/coworkThreadMessages'import type { CoworkSession } from '@/hooks/useCoworkSessions'import { getServiceHub } from '@/hooks/useServiceHub'+import { copySessionWorkspaceToThread } from '@/lib/agentTools'import {isPlatformAndroid,isPlatformIOS,@@ -27,6 +28,11 @@ import {* - 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.+ * - The session's sandbox files (agent-workspace/sessions/<id>) are COPIED+ * into the thread's own workspace (agent-workspace/threads/<id>) before the+ * commit. The thread uses the normal Thread scope; it is not linked to the+ * session directory, which is left in place as the rollback source and is+ * 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@@ -51,6 +57,15 @@ export type Invoke = <T = unknown>(args?: Record<string, unknown>) => Promise<T>+/**+ * Copies a session's sandbox into the thread workspace of the same id. Injected+ * so the migration stays a pure sequence of backend calls; the startup entry+ * point wires it to the agent-tools plugin.+ */+export type CopyWorkspace = (id: string) => Promise<{ copied: boolean }>++export type MigrationDeps = { copyWorkspace?: CopyWorkspace }+export type CoworkMigrationResult = {status: 'already-migrated' | 'nothing-to-migrate' | 'complete' | 'partial'migrated: string[]@@ -118,10 +133,19 @@ export function isValidThreadId(id: unknown): id is string {// Backend refusals that will repeat on every launch.const isPermanentBackendError = (e: unknown) =>- /refusing to overwrite its messages|Invalid thread id/.test(toErrorMessage(e))+ /refusing to overwrite its messages|refusing to merge into|Invalid thread id/.test(+ toErrorMessage(e)+ )-const toErrorMessage = (e: unknown) =>- e instanceof Error ? e.message : String(e)+function toErrorMessage(e: unknown): string {+ if (e instanceof Error) return e.message+ // Tauri plugin commands reject with `{ message }`, not an Error.+ if (typeof e === 'object' && e !== null && 'message' in e) {+ const { message } = e as { message: unknown }+ if (typeof message === 'string') return message+ }+ return String(e)+}function readAbandoned(raw: string | null): { id: string; error: string }[] {if (!raw) return []@@ -201,7 +225,8 @@ const isEmptySession = (s: CoworkSession) =>(s.turns?.length ?? 0) === 0 && (s.messages?.length ?? 0) === 0export async function migrateCoworkSessionsToThreads(- invoke: Invoke+ invoke: Invoke,+ deps: MigrationDeps = {}): Promise<CoworkMigrationResult> {const result: CoworkMigrationResult = {status: 'complete',@@ -300,6 +325,13 @@ export async function migrateCoworkSessionsToThreads(throw new Error('messages did not read back identically')}+ // The sandbox files move into the thread's own workspace+ // (agent-workspace/threads/<id>, main chat's Thread scope), before the+ // 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)+// Commit: thread.json last.const created = await invoke<StoredThread>('create_thread', {thread: sessionToThread(session),@@ -366,7 +398,9 @@ export async function migrateCoworkSessionsOnStartup(): Promise<CoworkMigrationRif (isPlatformIOS() || isPlatformAndroid()) return nulltry {const core = getServiceHub().core()- return await migrateCoworkSessionsToThreads(core.invoke.bind(core) as Invoke)+ return await migrateCoworkSessionsToThreads(core.invoke.bind(core) as Invoke, {+ copyWorkspace: copySessionWorkspaceToThread,+ })} catch (e) {console.warn('[cowork-migration] could not start; will retry next launch:', e)return null