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.

feat(web-app): persist live Cowork sessions as threads (write-through)

Akarshan Biswase876cfbbb51a
diff --git a/web-app/src/hooks/__tests__/useCoworkSessions.autoTitle.test.ts b/web-app/src/hooks/__tests__/useCoworkSessions.autoTitle.test.ts
new file mode 100644
index 000000000..1a8f9a941
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useCoworkSessions.autoTitle.test.ts
@@ -0,0 +1,28 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+import { useCoworkSessions } from '../useCoworkSessions'
+
+const seed = (title: string) =>
+ useCoworkSessions.setState({
+ sessions: [{ id: 's', title, folder: null, turns: [], messages: [], updated: 0 }],
+ currentId: 's',
+ })
+const title = () => useCoworkSessions.getState().sessions[0].title
+
+beforeEach(() => seed('New session'))
+
+describe('setTitleIfDefault', () => {
+ it('titles a session that still has the default title', () => {
+ useCoworkSessions.getState().setTitleIfDefault('s', 'First prompt')
+ expect(title()).toBe('First prompt')
+ })
+
+ // The first-run path captures the session, awaits skill expansion, then
+ // titles it: a rename made during that await must survive.
+ it('keeps a title the user set while preparation was pending', async () => {
+ const pending = new Promise<void>((r) => setTimeout(r, 0))
+ useCoworkSessions.getState().setTitle('s', 'My name')
+ await pending
+ useCoworkSessions.getState().setTitleIfDefault('s', 'First prompt')
+ expect(title()).toBe('My name')
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
index f1ff02863..3bc23f8e9 100644
--- a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
+++ b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
@@ -349,50 +349,3 @@ describe('useCoworkSessions pruneEmptySessions', () => {
expect(useCoworkSessions.getState().sessions).toBe(before)
})
})
-
-describe('useCoworkSessions persist migration', () => {
- // v0 sessions carry `turns` but no `messages`. Losing the tool turns on
- // upgrade would leave the agent replaying a conversation with holes in it.
- it('rebuilds messages from turns for a v0 session', () => {
- const migrate = useCoworkSessions.persist.getOptions().migrate!
- const out = migrate(
- {
- sessions: [
- {
- id: 's1',
- turns: [
- { role: 'user', content: 'build it' },
- {
- role: 'tool',
- content: '',
- name: 'write',
- callId: 'c1',
- args: { path: 'a.txt' },
- result: 'Created a.txt (3 bytes)',
- status: 'done',
- },
- ],
- },
- ],
- },
- 0
- ) as { sessions: Array<{ messages: unknown[] }> }
-
- const parts = (out.sessions[0].messages as never[]).flatMap(
- (m: { parts?: unknown[] }) => m.parts ?? []
- )
- expect(out.sessions[0].messages.length).toBeGreaterThan(0)
- expect(parts.some((p: { type?: string }) => p.type === 'tool-write')).toBe(
- true
- )
- })
-
- it('leaves an already-migrated session alone', () => {
- const migrate = useCoworkSessions.persist.getOptions().migrate!
- const existing = [{ id: 's1', turns: [], messages: [{ id: 'keep' }] }]
- const out = migrate({ sessions: existing }, 1) as {
- sessions: Array<{ messages: Array<{ id: string }> }>
- }
- expect(out.sessions[0].messages[0].id).toBe('keep')
- })
-})
diff --git a/web-app/src/hooks/__tests__/useCoworkSessions.writeThrough.test.ts b/web-app/src/hooks/__tests__/useCoworkSessions.writeThrough.test.ts
new file mode 100644
index 000000000..e851a0232
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useCoworkSessions.writeThrough.test.ts
@@ -0,0 +1,184 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useCoworkSessions } from '../useCoworkSessions'
+import {
+ isCoworkClosing,
+ quiesceCoworkRuns,
+ registerCoworkRunForClose,
+ resumeCoworkAfterPreventedClose,
+ __resetCoworkRunCloseForTests,
+} from '../useCoworkRun'
+import { todosFromTurns } from '@/lib/coworkTodo'
+import type { CoworkTurn } from '@/types/coworkSession'
+
+const todoTurn = (list: unknown, over: Partial<CoworkTurn> = {}): CoworkTurn => ({
+ role: 'tool',
+ name: 'todo',
+ content: '',
+ result: JSON.stringify(list),
+ status: 'done',
+ ...over,
+})
+const list = (content: string) => ({
+ phases: [{ name: 'p', tasks: [{ content, status: 'pending' }] }],
+})
+const user = (content: string): CoworkTurn => ({ role: 'user', content })
+const msg = (id: string, role: 'user' | 'assistant', text = id) =>
+ ({ id, role, parts: [{ type: 'text', text }] }) as never
+
+const seed = (turns: CoworkTurn[], messages: never[]) => {
+ useCoworkSessions.setState({
+ sessions: [{ id: 's', title: 'T', folder: null, turns, messages, updated: 0 }],
+ currentId: 's',
+ })
+}
+const get = () => useCoworkSessions.getState().sessions[0]
+
+describe('the in-memory store is no longer persisted', () => {
+ it('has no persist middleware (write-through lives in coworkSync)', () => {
+ expect('persist' in useCoworkSessions).toBe(false)
+ })
+})
+
+describe('todosFromTurns', () => {
+ it('returns the latest valid finished snapshot and ignores running, failed and malformed results', () => {
+ expect(todosFromTurns([])).toBeUndefined()
+ expect(
+ todosFromTurns([
+ todoTurn(list('first')),
+ todoTurn(list('second')),
+ todoTurn(list('running'), { status: 'running' }),
+ todoTurn(list('failed'), { isError: true }),
+ todoTurn('not a list'),
+ { ...todoTurn(list('other tool')), name: 'write' },
+ ])
+ ).toEqual(list('second'))
+ })
+})
+
+describe('rewind, drop and clear keep the todo list in step with the transcript', () => {
+ beforeEach(() => seed([], []))
+
+ it('rewindToLastUser restores the todos the kept turns produced', () => {
+ seed(
+ [user('q1'), todoTurn(list('kept')), user('q2'), todoTurn(list('dropped'))],
+ [msg('1', 'user'), msg('2', 'user')]
+ )
+ useCoworkSessions.setState((s) => ({
+ sessions: s.sessions.map((x) => ({ ...x, todos: list('dropped') as never })),
+ }))
+ useCoworkSessions.getState().rewindToLastUser('s')
+ expect(get().todos).toEqual(list('kept'))
+ })
+
+ it('dropFromTurn to the very first question empties the session and marks it cleared (stays listed)', () => {
+ seed([user('q1'), todoTurn(list('x'))], [msg('1', 'user')])
+ useCoworkSessions.getState().dropFromTurn('s', 0)
+ expect(get().turns).toEqual([])
+ expect(get().todos).toEqual({ phases: [] })
+ expect(get().cleared).toBe(true)
+ // A cleared session is a used one: it survives the empty-session sweep.
+ useCoworkSessions.setState({ currentId: null })
+ useCoworkSessions.getState().pruneEmptySessions([])
+ expect(useCoworkSessions.getState().sessions).toHaveLength(1)
+ })
+
+ it('clearSession keeps the empty session and createSession does not reuse it', () => {
+ seed([user('q1')], [msg('1', 'user')])
+ useCoworkSessions.getState().clearSession('s')
+ expect(get().cleared).toBe(true)
+ expect(get().todos).toEqual({ phases: [] })
+ const fresh = useCoworkSessions.getState().createSession()
+ expect(fresh).not.toBe('s')
+ })
+
+ it('an unavailable session is never reused as the blank placeholder', () => {
+ useCoworkSessions.setState({
+ sessions: [
+ {
+ id: 'u',
+ title: 'T',
+ folder: null,
+ turns: [],
+ messages: [],
+ updated: 0,
+ unavailable: 'missing-thread',
+ },
+ ],
+ currentId: 'u',
+ })
+ expect(useCoworkSessions.getState().createSession()).not.toBe('u')
+ })
+
+ it('goal, todo and title edits bump `updated` so write-through sees them as changes', () => {
+ seed([user('q')], [msg('1', 'user')])
+ useCoworkSessions.getState().setTitle('s', 'x')
+ expect(get().updated).toBeGreaterThan(0)
+ useCoworkSessions.setState((s) => ({
+ sessions: s.sessions.map((x) => ({ ...x, updated: 0 })),
+ }))
+ useCoworkSessions.getState().setTodos('s', list('a') as never)
+ expect(get().updated).toBeGreaterThan(0)
+ useCoworkSessions.setState((s) => ({
+ sessions: s.sessions.map((x) => ({ ...x, updated: 0 })),
+ }))
+ useCoworkSessions.getState().setGoal('s', null)
+ expect(get().updated).toBeGreaterThan(0)
+ })
+
+ it('setProject records the project on the session', () => {
+ seed([user('q')], [msg('1', 'user')])
+ useCoworkSessions.getState().setProject('s', { id: 'p', name: 'P', updated_at: 1 })
+ expect(get().project?.id).toBe('p')
+ })
+})
+
+describe('close registry', () => {
+ beforeEach(() => __resetCoworkRunCloseForTests())
+
+ it('stops every registered run, waits for all of them even when one fails, and rejects with the failure', async () => {
+ const order: string[] = []
+ let finish!: () => void
+ const slow = new Promise<void>((r) => (finish = r))
+ registerCoworkRunForClose(async () => {
+ order.push('bad')
+ throw new Error('commit failed')
+ })
+ registerCoworkRunForClose(async () => {
+ order.push('slow-start')
+ await slow
+ order.push('slow-done')
+ })
+ const closing = quiesceCoworkRuns()
+ expect(isCoworkClosing()).toBe(true)
+ let settled = false
+ closing.catch(() => {}).finally(() => (settled = true))
+ await Promise.resolve()
+ expect(settled).toBe(false) // waits for the slow run
+ finish()
+ await expect(closing).rejects.toThrow('commit failed')
+ expect(order).toEqual(['bad', 'slow-start', 'slow-done'])
+ })
+
+ it('a prevented close reopens the app and the next close retries the runs', async () => {
+ let calls = 0
+ registerCoworkRunForClose(async () => {
+ calls += 1
+ if (calls === 1) throw new Error('first fails')
+ })
+ await expect(quiesceCoworkRuns()).rejects.toThrow()
+ resumeCoworkAfterPreventedClose()
+ expect(isCoworkClosing()).toBe(false)
+ await expect(quiesceCoworkRuns()).resolves.toBeUndefined()
+ expect(calls).toBe(2)
+ })
+
+ it('an unregistered run is no longer awaited', async () => {
+ let ran = false
+ const off = registerCoworkRunForClose(async () => {
+ ran = true
+ })
+ off()
+ await quiesceCoworkRuns()
+ expect(ran).toBe(false)
+ })
+})
diff --git a/web-app/src/hooks/useCoworkRun.ts b/web-app/src/hooks/useCoworkRun.ts
index a655d6165..d25620003 100644
--- a/web-app/src/hooks/useCoworkRun.ts
+++ b/web-app/src/hooks/useCoworkRun.ts
@@ -703,3 +703,48 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({
// changes, not on every other session's.
export const useIsSessionActive = (sid: string | undefined) =>
useCoworkRun((s) => (sid ? s.runId[sid] != null : false))
+
+// Run closures own their transcript and wire history until their finally block
+// commits them. Keep this registry outside React so background/unmounted runs
+// participate in close just like the session currently on screen.
+const closeParticipants = new Set<() => Promise<void>>()
+let closing = false
+let quiescePromise: Promise<void> | null = null
+
+export function isCoworkClosing(): boolean {
+ return closing
+}
+
+/** Register synchronously when a run is claimed; unregister AFTER its commit. */
+export function registerCoworkRunForClose(stopAndCommit: () => Promise<void>): () => void {
+ closeParticipants.add(stopAndCommit)
+ return () => { closeParticipants.delete(stopAndCommit) }
+}
+
+/** Stop every run before waiting, then await all final commits (even on error). */
+export function quiesceCoworkRuns(): Promise<void> {
+ closing = true
+ quiescePromise ??= (async () => {
+ const settled = await Promise.allSettled(
+ [...closeParticipants].map(async (stopAndCommit) => stopAndCommit())
+ )
+ const failed = settled.find((result) => result.status === 'rejected')
+ if (failed?.status === 'rejected') {
+ quiescePromise = null
+ throw failed.reason
+ }
+ })()
+ return quiescePromise
+}
+
+/** A prevented close leaves the application usable and the next close retries. */
+export function resumeCoworkAfterPreventedClose(): void {
+ closing = false
+ quiescePromise = null
+}
+
+export function __resetCoworkRunCloseForTests(): void {
+ closeParticipants.clear()
+ closing = false
+ quiescePromise = null
+}
diff --git a/web-app/src/hooks/useCoworkSessions.ts b/web-app/src/hooks/useCoworkSessions.ts
index 0d91b4f59..a40f71aa9 100644
--- a/web-app/src/hooks/useCoworkSessions.ts
+++ b/web-app/src/hooks/useCoworkSessions.ts
@@ -1,9 +1,6 @@
import type { UIMessage } from 'ai'
import { create } from 'zustand'
-import { persist, createJSONStorage } from 'zustand/middleware'
-import { localStorageKey } from '@/constants/localStorage'
-import { backendStorage } from '@/lib/backendStorage'
-import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'
+import { todosFromTurns } from '@/lib/coworkTodo'
import { isPingOnly } from '@/lib/coworkPing'
import type {
CoworkTurn,
@@ -46,6 +43,14 @@ export type CoworkSession = {
/** An attached project folder, mounted read-only. Writes always land in the
* session's own sandbox, never here. */
folder: string | null
+ /**
+ * How the attached folder may be used. Absent means write, which is what
+ * every session had before this field existed. This is a UI-level setting
+ * (persisted in `metadata.folderAccess`), not host-enforced consent.
+ */
+ folderAccess?: 'read' | 'write'
+ /** Optional Jan project associated with this conversation. */
+ project?: { id: string; name: string; updated_at: number; assistantId?: string }
turns: CoworkTurn[]
/** The authoritative conversation, sent to the model each turn. */
messages: UIMessage[]
@@ -61,6 +66,19 @@ export type CoworkSession = {
todos?: TodoList
/** Plan mode: the agent reads and proposes, without writing. Absent means off. */
planMode?: boolean
+ /** The user had a conversation here and cleared it (/clear). Unlike a
+ * never-used blank placeholder, the empty session stays listed, reachable and
+ * persisted, so the record does not become a hidden thread on disk. */
+ cleared?: true
+ /** Set when the session's stored data cannot be used (missing/corrupt
+ * transcript, an id that cannot be a thread, or a thread that was deleted
+ * underneath it). It is shown but never written back, so the files on disk
+ * are preserved for recovery. */
+ unavailable?:
+ | 'missing-sidecar'
+ | 'unreadable-sidecar'
+ | 'id-collision'
+ | 'missing-thread'
updated: number
}
@@ -71,9 +89,13 @@ type CoworkSessionsState = {
selectSession: (id: string) => void
deleteSession: (id: string) => void
setFolder: (id: string, folder: string | null) => void
+ setProject: (id: string, project: CoworkSession['project']) => void
setModel: (id: string, model: ThreadModel) => void
setPlanMode: (id: string, planMode: boolean) => void
setTitle: (id: string, title: string) => void
+ /** Auto-title: applies only while the stored title is still the default, so a
+ * rename made in the meantime wins. */
+ setTitleIfDefault: (id: string, title: string) => void
setMessages: (id: string, messages: UIMessage[]) => void
setGoal: (id: string, goal: CoworkGoal | null) => void
setTodos: (id: string, todos: TodoList) => void
@@ -140,219 +162,230 @@ function lastQuestionIndex(items: RoleLike[]): number {
return -1
}
-export const useCoworkSessions = create<CoworkSessionsState>()(
- persist(
- (set, get) => ({
- sessions: [],
- currentId: null,
+/**
+ * In-memory store. Persistence is NOT here: `lib/coworkSync` subscribes to it
+ * and writes sessions through to thread storage (thread.json + the `cowork`
+ * sidecar + messages.jsonl), and hydrates it at startup. The legacy
+ * `code-sessions` settings blob is no longer written by this store; it is left
+ * untouched as the rollback source.
+ */
+export const useCoworkSessions = create<CoworkSessionsState>()((set, get) => ({
+ sessions: [],
+ currentId: null,
- createSession: () => {
- // Already viewing an untouched session — reuse it instead of piling
- // up empty ones (e.g. from repeated clicks on "New session").
- const { currentId, sessions } = get()
- const current = sessions.find((s) => s.id === currentId)
- if (current && current.turns.length === 0) return current.id
+ createSession: () => {
+ // Already viewing an untouched session, reuse it instead of piling
+ // up empty ones (e.g. from repeated clicks on "New session").
+ const { currentId, sessions } = get()
+ const current = sessions.find((s) => s.id === currentId)
+ if (
+ current &&
+ !current.unavailable &&
+ !current.cleared &&
+ current.turns.length === 0
+ )
+ return current.id
- const id = crypto.randomUUID()
- const session: CoworkSession = {
- id,
- title: 'New session',
- folder: null,
- turns: [],
- messages: [],
- updated: now(),
- }
- set((s) => ({ sessions: [session, ...s.sessions], currentId: id }))
- return id
- },
+ const id = crypto.randomUUID()
+ const session: CoworkSession = {
+ id,
+ title: 'New session',
+ folder: null,
+ turns: [],
+ messages: [],
+ updated: now(),
+ }
+ set((s) => ({ sessions: [session, ...s.sessions], currentId: id }))
+ return id
+ },
- selectSession: (id) => set({ currentId: id }),
+ selectSession: (id) => set({ currentId: id }),
- setModel: (id, model) =>
- set((s) => ({
- sessions: s.sessions.map((session) =>
- session.id === id ? { ...session, model, updated: now() } : session
- ),
- })),
+ setModel: (id, model) =>
+ set((s) => ({
+ sessions: s.sessions.map((session) =>
+ session.id === id ? { ...session, model, updated: now() } : session
+ ),
+ })),
- deleteSession: (id) =>
- set((s) => {
- const sessions = s.sessions.filter((x) => x.id !== id)
- const currentId =
- s.currentId === id ? (sessions[0]?.id ?? null) : s.currentId
- return { sessions, currentId }
- }),
+ deleteSession: (id) =>
+ set((s) => {
+ const sessions = s.sessions.filter((x) => x.id !== id)
+ const currentId =
+ s.currentId === id ? (sessions[0]?.id ?? null) : s.currentId
+ return { sessions, currentId }
+ }),
- setFolder: (id, folder) =>
- set((s) => ({
- sessions: s.sessions.map((x) =>
- x.id === id ? { ...x, folder, updated: now() } : x
- ),
- })),
+ setProject: (id, project) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id ? { ...x, project, updated: now() } : x
+ ),
+ })),
- setMessages: (id, messages) =>
- set((s) => ({
- sessions: s.sessions.map((x) =>
- x.id === id ? { ...x, messages, updated: now() } : x
- ),
- })),
+ setFolder: (id, folder) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id ? { ...x, folder, updated: now() } : x
+ ),
+ })),
- setGoal: (id, goal) =>
- set((s) => ({
- sessions: s.sessions.map((x) =>
- x.id === id ? { ...x, goal: goal ?? undefined } : x
- ),
- })),
+ setMessages: (id, messages) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id ? { ...x, messages, updated: now() } : x
+ ),
+ })),
- setTodos: (id, todos) =>
- set((s) => ({
- sessions: s.sessions.map((x) => (x.id === id ? { ...x, todos } : x)),
- })),
+ setGoal: (id, goal) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id ? { ...x, goal: goal ?? undefined, updated: now() } : x
+ ),
+ })),
- setPlanMode: (id, planMode) =>
- set((s) => ({
- sessions: s.sessions.map((x) =>
- x.id === id ? { ...x, planMode, updated: now() } : x
- ),
- })),
+ setTodos: (id, todos) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id ? { ...x, todos, updated: now() } : x
+ ),
+ })),
- setTitle: (id, title) =>
- set((s) => ({
- sessions: s.sessions.map((x) => (x.id === id ? { ...x, title } : x)),
- })),
+ setPlanMode: (id, planMode) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id ? { ...x, planMode, updated: now() } : x
+ ),
+ })),
- commitLegacyTurns: (id, turns, history) =>
- set((s) => ({
- sessions: s.sessions.map((x) =>
- x.id === id
- ? { ...x, turns: [...x.turns, ...turns], history, updated: now() }
- : x
- ),
- })),
+ setTitle: (id, title) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id ? { ...x, title, updated: now() } : x
+ ),
+ })),
- commitTurns: (id, turns, messages, subagents, usage) =>
- set((s) => ({
- sessions: s.sessions.map((x) => {
- if (x.id !== id) return x
- // Accumulate across this session's runs, keyed by runId — a later
- // run that dispatches no subagents of its own must not erase what
- // an earlier run in the same session already finished.
- const incoming = new Set(subagents.map((r) => r.runId))
- return {
- ...x,
- turns: [...x.turns, ...turns],
- messages,
- subagents: [
- ...(x.subagents ?? []).filter((r) => !incoming.has(r.runId)),
- ...subagents,
- ],
- lastUsage: usage ?? x.lastUsage,
- updated: now(),
- }
- }),
- })),
+ setTitleIfDefault: (id, title) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id && x.title === 'New session'
+ ? { ...x, title, updated: now() }
+ : x
+ ),
+ })),
- rewindToLastUser: (id) =>
- set((s) => ({
- sessions: s.sessions.map((x) => {
- if (x.id !== id) return x
- const lastTurn = lastQuestionIndex(x.turns)
- const lastMessage = lastQuestionIndex(x.messages)
- if (lastTurn < 0 || lastMessage < 0) return x
- return {
- ...x,
- // The question survives; the run it produced does not.
- turns: x.turns.slice(0, lastTurn + 1),
- messages: x.messages.slice(0, lastMessage + 1),
- updated: now(),
- }
- }),
- })),
+ commitLegacyTurns: (id, turns, history) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id
+ ? { ...x, turns: [...x.turns, ...turns], history, updated: now() }
+ : x
+ ),
+ })),
- dropFromTurn: (id, turnIndex) =>
- set((s) => ({
- sessions: s.sessions.map((x) => {
- if (x.id !== id) return x
- if (x.turns[turnIndex]?.role !== 'user') return x
- // The wire history holds messages the transcript has no row for
- // (and vice versa), so the cut is made at the same *question*,
- // counted, rather than at the same index.
- const ordinal = x.turns
- .slice(0, turnIndex)
- .filter((t) => t.role === 'user').length
- const cut = questionIndex(x.messages, ordinal)
- // Out of step (a session saved before the two were kept aligned):
- // truncating the transcript alone would leave the model answering
- // questions the user can no longer see.
- if (cut < 0) return x
- return {
- ...x,
- turns: x.turns.slice(0, turnIndex),
- messages: x.messages.slice(0, cut),
- updated: now(),
- }
- }),
- })),
+ commitTurns: (id, turns, messages, subagents, usage) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) => {
+ if (x.id !== id) return x
+ // Accumulate across this session's runs, keyed by runId, a later
+ // run that dispatches no subagents of its own must not erase what
+ // an earlier run in the same session already finished.
+ const incoming = new Set(subagents.map((r) => r.runId))
+ return {
+ ...x,
+ turns: [...x.turns, ...turns],
+ messages,
+ subagents: [
+ ...(x.subagents ?? []).filter((r) => !incoming.has(r.runId)),
+ ...subagents,
+ ],
+ lastUsage: usage ?? x.lastUsage,
+ updated: now(),
+ }
+ }),
+ })),
- clearSession: (id) =>
- set((s) => ({
- sessions: s.sessions.map((x) =>
- x.id === id
- ? {
- ...x,
- turns: [],
- messages: [],
- subagents: [],
- lastUsage: undefined,
- updated: now(),
- }
- : x
- ),
- })),
+ rewindToLastUser: (id) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) => {
+ if (x.id !== id) return x
+ const lastTurn = lastQuestionIndex(x.turns)
+ const lastMessage = lastQuestionIndex(x.messages)
+ if (lastTurn < 0 || lastMessage < 0) return x
+ return {
+ ...x,
+ // The question survives; the run it produced does not.
+ turns: x.turns.slice(0, lastTurn + 1),
+ messages: x.messages.slice(0, lastMessage + 1),
+ todos: todosFromTurns(x.turns.slice(0, lastTurn + 1)) ?? {
+ phases: [],
+ },
+ updated: now(),
+ }
+ }),
+ })),
- pruneEmptySessions: (keepIds) =>
- set((s) => {
- const keep = new Set(keepIds)
- const sessions = s.sessions.filter(
- (x) => x.turns.length > 0 || x.id === s.currentId || keep.has(x.id)
- )
- return sessions.length === s.sessions.length ? {} : { sessions }
+ dropFromTurn: (id, turnIndex) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) => {
+ if (x.id !== id) return x
+ if (x.turns[turnIndex]?.role !== 'user') return x
+ // The wire history holds messages the transcript has no row for
+ // (and vice versa), so the cut is made at the same *question*,
+ // counted, rather than at the same index.
+ const ordinal = x.turns
+ .slice(0, turnIndex)
+ .filter((t) => t.role === 'user').length
+ const cut = questionIndex(x.messages, ordinal)
+ // Out of step (a session saved before the two were kept aligned):
+ // truncating the transcript alone would leave the model answering
+ // questions the user can no longer see.
+ if (cut < 0) return x
+ return {
+ ...x,
+ turns: x.turns.slice(0, turnIndex),
+ messages: x.messages.slice(0, cut),
+ todos: todosFromTurns(x.turns.slice(0, turnIndex)) ?? { phases: [] },
+ // Emptying a used session is the same end state as /clear: keep it
+ // listed, reachable and persisted. (A valid cut means the session
+ // had a turn, so it is never a blank placeholder.)
+ ...(turnIndex === 0 ? { cleared: true as const } : {}),
+ updated: now(),
+ }
}),
- }),
- {
- name: localStorageKey.coworkSessions,
- // Persist through the Rust settings store (see backendStorage) so sessions
- // live in <jan_data>/settings.json instead of webview localStorage.
- // Async storage requires skipHydration + explicit rehydrate in
- // hydrateBackendStores() once the ServiceHub is ready.
- storage: createJSONStorage(() => backendStorage),
- skipHydration: true,
- version: 1,
- // v0 persisted an OpenAI-shaped `history` that could not represent tool
- // calls, so replaying it dropped every tool turn. Rebuild the message
- // list from `turns`, which did record them, and leave `history` in place
- // untouched rather than mutating a blob a rollback would still read.
- migrate: (persisted, version) => {
- const state = persisted as { sessions?: CoworkSession[] } | undefined
- if (version >= 1 || !state?.sessions) return persisted
- return {
- ...state,
- sessions: state.sessions.map((session) =>
- session.messages
- ? session
- : {
- ...session,
- messages: coworkTurnsToUIMessages(
- session.turns ?? [],
- session.id
- ),
- }
- ),
- }
- },
- }
- )
-)
+ })),
+
+ clearSession: (id) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id
+ ? {
+ ...x,
+ turns: [],
+ messages: [],
+ subagents: [],
+ lastUsage: undefined,
+ todos: { phases: [] },
+ cleared: true as const,
+ updated: now(),
+ }
+ : x
+ ),
+ })),
+
+ pruneEmptySessions: (keepIds) =>
+ set((s) => {
+ const keep = new Set(keepIds)
+ const sessions = s.sessions.filter(
+ (x) =>
+ x.turns.length > 0 ||
+ x.cleared ||
+ x.id === s.currentId ||
+ keep.has(x.id)
+ )
+ return sessions.length === s.sessions.length ? {} : { sessions }
+ }),
+}))
/**
* Open the start page: a fresh session (or the untouched current one), with the
diff --git a/web-app/src/hooks/useThreads.ts b/web-app/src/hooks/useThreads.ts
index ef85086e0..46b0414b5 100644
--- a/web-app/src/hooks/useThreads.ts
+++ b/web-app/src/hooks/useThreads.ts
@@ -9,11 +9,21 @@ import { ServiceKeys } from '@janhq/core'
import { useChatSessions } from '@/stores/chat-session-store'
import { useAppState } from '@/hooks/useAppState'
import { cleanupThreadWorkspace } from '@/lib/agentTools'
+import { isCoworkThread } from '@/lib/threadMode'
+import {
+ deleteCoworkConversation,
+ hasCoworkSession,
+} from '@/lib/coworkDelete'
type ThreadState = {
threads: Record<string, Thread>
isLoadingThreads: boolean
setThreadsLoading: (loading: boolean) => void
+ /** Set once a thread listing succeeded (an empty one counts). Unlike
+ * `isLoadingThreads` it is never set by the retry-exhaustion path, so it
+ * means "the list is real", not "we stopped waiting". */
+ threadsHydrated: boolean
+ markThreadsHydrated: () => void
currentThreadId?: string
getCurrentThread: () => Thread | undefined
setThreads: (threads: Thread[]) => void
@@ -88,10 +98,36 @@ const cleanupThreadArtifacts = (threadId: string) => {
cleanupThreadWorkspace(threadId)
}
+/**
+ * What the sidebar's Delete All removes: plain chats only. Favorites, anything
+ * with project metadata (even a project that no longer exists, so no data is
+ * lost to a dangling reference) and Cowork threads are kept.
+ */
+export const isDeletedByDeleteAll = (thread: Thread): boolean =>
+ !thread.isFavorite && !thread.metadata?.project && !isCoworkThread(thread)
+
+/**
+ * The deletion of one thread plus its out-of-store artifacts. A Cowork thread
+ * that is live in the session store is deleted through that store (see
+ * `deleteCoworkConversation`), which journals it, removes the thread and
+ * reclaims the sandbox itself; everything else goes straight to the thread
+ * service.
+ */
+const deleteThreadEverywhere = (threadId: string, thread: Thread | undefined) => {
+ if (isCoworkThread(thread) && hasCoworkSession(threadId)) {
+ deleteCoworkConversation(threadId)
+ return
+ }
+ cleanupThreadArtifacts(threadId)
+ getServiceHub().threads().deleteThread(threadId)
+}
+
export const useThreads = create<ThreadState>()((set, get) => ({
threads: {},
isLoadingThreads: true,
setThreadsLoading: (loading) => set({ isLoadingThreads: loading }),
+ threadsHydrated: false,
+ markThreadsHydrated: () => set({ threadsHydrated: true }),
searchIndex: null,
setThreads: (threads) => {
const threadMap = threads.reduce(
@@ -194,8 +230,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({
useAgentMode.getState().removeThread(threadId)
useChatSessions.getState().removeSession(threadId)
useAppState.getState().clearThreadState(threadId)
- cleanupThreadArtifacts(threadId)
- getServiceHub().threads().deleteThread(threadId)
+ deleteThreadEverywhere(threadId, state.threads[threadId])
return {
threads: remainingThreads,
@@ -214,18 +249,13 @@ export const useThreads = create<ThreadState>()((set, get) => ({
set((state) => {
const allThreadIds = Object.keys(state.threads)
- // Identify threads to keep (favorites OR have project metadata)
+ // Threads to keep: everything Delete All does not delete (favorites,
+ // project threads and Cowork conversations).
const threadsToKeepIds = allThreadIds.filter(
- (threadId) =>
- state.threads[threadId].isFavorite ||
- state.threads[threadId].metadata?.project
+ (threadId) => !isDeletedByDeleteAll(state.threads[threadId])
)
-
- // Identify threads to delete (non-favorites AND no project metadata)
- const threadsToDeleteIds = allThreadIds.filter(
- (threadId) =>
- !state.threads[threadId].isFavorite &&
- !state.threads[threadId].metadata?.project
+ const threadsToDeleteIds = allThreadIds.filter((threadId) =>
+ isDeletedByDeleteAll(state.threads[threadId])
)
// Delete threads and clean up their out-of-store artifacts. As in
@@ -235,8 +265,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({
useAgentMode.getState().removeThread(threadId)
useChatSessions.getState().removeSession(threadId)
useAppState.getState().clearThreadState(threadId)
- cleanupThreadArtifacts(threadId)
- getServiceHub().threads().deleteThread(threadId)
+ deleteThreadEverywhere(threadId, state.threads[threadId])
})
// Keep favorite threads and threads with project metadata
@@ -269,8 +298,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({
useAgentMode.getState().removeThread(threadId)
useChatSessions.getState().removeSession(threadId)
useAppState.getState().clearThreadState(threadId)
- cleanupThreadArtifacts(threadId)
- getServiceHub().threads().deleteThread(threadId)
+ deleteThreadEverywhere(threadId, state.threads[threadId])
})
return {
@@ -295,8 +323,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({
threadsToDeleteIds.forEach((threadId) => {
useChatSessions.getState().removeSession(threadId)
useAppState.getState().clearThreadState(threadId)
- cleanupThreadArtifacts(threadId)
- getServiceHub().threads().deleteThread(threadId)
+ deleteThreadEverywhere(threadId, state.threads[threadId])
})
// Keep threads that don't belong to this project
diff --git a/web-app/src/lib/__tests__/coworkClose.test.ts b/web-app/src/lib/__tests__/coworkClose.test.ts
new file mode 100644
index 000000000..d008e849d
--- /dev/null
+++ b/web-app/src/lib/__tests__/coworkClose.test.ts
@@ -0,0 +1,198 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import capability from '../../../../src-tauri/capabilities/default.json'
+import config from '../../../../src-tauri/tauri.conf.json'
+
+// Keep the installed Tauri window/event/core API real. Only IPC and storage are
+// doubles: this is a JS dispatch + configuration regression, NOT native ACL QA.
+const storage = vi.hoisted(() => ({
+ create: vi.fn(),
+ invoke: vi.fn(),
+ flush: vi.fn(),
+ remove: vi.fn(),
+ schedule: vi.fn(),
+ adopt: vi.fn(),
+ setCurrentId: vi.fn(),
+}))
+vi.mock('@/lib/platform/utils', () => ({
+ isPlatformTauri: () => true,
+ isPlatformIOS: () => false,
+ isPlatformAndroid: () => false,
+}))
+vi.mock('@/lib/agentTools', () => ({
+ cleanupThreadWorkspace: vi.fn(),
+}))
+vi.mock('@/lib/migrateCoworkSessions', async (importOriginal) => ({
+ ...await importOriginal<typeof import('@/lib/migrateCoworkSessions')>(),
+ migrateCoworkSessionsOnStartup: async () => ({ status: 'complete' }),
+ isCoworkMigrationSettled: async () => true,
+}))
+vi.mock('@/lib/coworkPersistence', async (importOriginal) => ({
+ // Keep the unmocked exports (record mapping, error classification) real.
+ ...await importOriginal<typeof import('@/lib/coworkPersistence')>(),
+ createCoworkPersistence: (...args: unknown[]) => storage.create(...args),
+ loadCoworkSessions: async () => ({
+ threads: [], sessions: [], currentId: null, legacyIds: new Set(),
+ }),
+}))
+vi.mock('@/hooks/useServiceHub', () => ({
+ getServiceHub: () => ({ core: () => ({ invoke: storage.invoke }) }),
+}))
+
+import { isCoworkClosing, registerCoworkRunForClose } from '@/hooks/useCoworkRun'
+import { useCoworkSessions } from '@/hooks/useCoworkSessions'
+import { startCoworkSync, __resetCoworkSyncForTests } from '../coworkSync'
+
+type CloseEvent = { event: string; id: number; payload: null }
+let dispatchClose: (event: CloseEvent) => Promise<void>
+const invoke = vi.fn()
+const closeEvent: CloseEvent = { event: 'tauri://close-requested', id: 1, payload: null }
+
+function deferred() {
+ let resolve!: () => void
+ const promise = new Promise<void>((done) => { resolve = done })
+ return { promise, resolve }
+}
+
+describe('Cowork close with the installed Tauri API', () => {
+ beforeEach(() => {
+ __resetCoworkSyncForTests()
+ useCoworkSessions.setState({ sessions: [], currentId: null })
+ vi.clearAllMocks()
+ storage.create.mockImplementation(() => storage)
+ storage.flush.mockResolvedValue(undefined)
+ storage.remove.mockResolvedValue(undefined)
+ vi.stubGlobal('__TAURI_INTERNALS__', {
+ metadata: { currentWindow: { label: 'main' } },
+ transformCallback: (callback: typeof dispatchClose) => {
+ dispatchClose = callback
+ return 42
+ },
+ invoke: invoke.mockImplementation(async (command, args) => {
+ if (command === 'plugin:event|listen') return 1
+ if (command === 'plugin:window|destroy') {
+ // Deliberately only an assertion of file/API alignment, not an ACL
+ // emulator. Rust is responsible for enforcing the actual permission.
+ expect(args).toEqual({ label: 'main' })
+ expect(capability.permissions).toContain('core:window:allow-destroy')
+ return
+ }
+ throw new Error(`Unexpected IPC: ${command}`)
+ }),
+ })
+ })
+
+ afterEach(() => {
+ __resetCoworkSyncForTests()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it('enables destroy only for the main-window caller in an active local capability', () => {
+ expect(config.app.security.capabilities).toContain(capability.identifier)
+ expect(capability.windows).toEqual(['main'])
+ expect('webviews' in capability ? capability.webviews : undefined).toBeUndefined()
+ expect('remote' in capability ? capability.remote : undefined).toBeUndefined()
+ expect('local' in capability ? capability.local : true).toBe(true)
+ expect(capability.permissions).toContain('core:window:allow-close')
+ expect(capability.permissions).toContain('core:window:allow-destroy')
+ })
+
+ it('dispatches destroy only after queued writes AND pending deletes settle', async () => {
+ await startCoworkSync()
+ expect(invoke).toHaveBeenCalledWith('plugin:event|listen', {
+ event: closeEvent.event, target: { kind: 'Window', label: 'main' }, handler: 42,
+ }, undefined)
+ const writes = deferred()
+ const deletes = deferred()
+ storage.flush.mockReturnValueOnce(writes.promise)
+ storage.remove.mockReturnValueOnce(deletes.promise)
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().deleteSession(id)
+ expect(storage.remove).toHaveBeenCalled()
+
+ const closing = dispatchClose(closeEvent)
+ expect(invoke).not.toHaveBeenCalledWith('plugin:window|destroy', expect.anything(), undefined)
+ writes.resolve()
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(invoke).not.toHaveBeenCalledWith('plugin:window|destroy', expect.anything(), undefined)
+ deletes.resolve()
+ await closing
+ expect(invoke).toHaveBeenCalledWith('plugin:window|destroy', { label: 'main' }, undefined)
+ })
+
+ it('waits for every run even if one fails, flushes commits, and retries a prevented close', async () => {
+ await startCoworkSync()
+ const completion = deferred()
+ const failure = new Error('commit failed')
+ const badRun = vi.fn().mockRejectedValueOnce(failure).mockResolvedValue(undefined)
+ const otherRun = vi.fn(() => completion.promise)
+ registerCoworkRunForClose(badRun)
+ registerCoworkRunForClose(otherRun)
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const closing = dispatchClose(closeEvent)
+ expect(badRun).toHaveBeenCalledOnce()
+ expect(otherRun).toHaveBeenCalledOnce()
+ await Promise.resolve()
+ expect(storage.flush).not.toHaveBeenCalled()
+ expect(invoke).not.toHaveBeenCalledWith('plugin:window|destroy', expect.anything(), undefined)
+ completion.resolve()
+ await closing
+ expect(storage.flush).toHaveBeenCalledOnce()
+ expect(isCoworkClosing()).toBe(false)
+ expect(invoke).not.toHaveBeenCalledWith('plugin:window|destroy', expect.anything(), undefined)
+ await dispatchClose(closeEvent)
+ expect(badRun).toHaveBeenCalledTimes(2)
+ expect(invoke).toHaveBeenCalledWith('plugin:window|destroy', { label: 'main' }, undefined)
+ })
+
+ it.each(['write_thread_extra', 'settings_set'])(
+ 'prevents destroy on real persistence %s failure and closes after recovery',
+ async (failingCommand) => {
+ const { createCoworkPersistence } = await vi.importActual<typeof import('@/lib/coworkPersistence')>('@/lib/coworkPersistence')
+ storage.create.mockImplementation(createCoworkPersistence)
+ let failing = true
+ const disk = new Map<string, unknown>()
+ storage.invoke.mockImplementation(async (command, args) => {
+ if (failing && command === failingCommand) throw new Error('disk full')
+ if (command === 'write_thread_extra') disk.set('sidecar', args.value)
+ if (command === 'create_thread') {
+ disk.set('thread', args.thread)
+ return args.thread
+ }
+ if (command === 'settings_set') disk.set(args.key, args.value)
+ })
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ const messages = [{ id: 'question', role: 'user' as const, parts: [{ type: 'text' as const, text: 'Keep this question' }] }]
+ useCoworkSessions.getState().setMessages(id, messages)
+
+ await dispatchClose(closeEvent)
+ expect(isCoworkClosing()).toBe(false)
+ expect(invoke).not.toHaveBeenCalledWith('plugin:window|destroy', expect.anything(), undefined)
+ expect(useCoworkSessions.getState().sessions.find((s) => s.id === id)?.messages).toEqual(messages)
+ expect(storage.invoke.mock.calls.filter(([command]) => command === failingCommand)).toHaveLength(3)
+
+ failing = false
+ await dispatchClose(closeEvent)
+ expect(disk.get('sidecar')).toMatchObject({ messages })
+ expect(disk.get('thread')).toMatchObject({ id })
+ expect(disk.get('cowork_current_id')).toBe(id)
+ expect(invoke).toHaveBeenCalledWith('plugin:window|destroy', { label: 'main' }, undefined)
+ }
+ )
+
+ it('keeps unsaved state alive on flush failure and allows a later close retry', async () => {
+ await startCoworkSync()
+ const failure = new Error('disk full')
+ storage.flush.mockRejectedValueOnce(failure)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ await dispatchClose(closeEvent)
+ expect(warn).toHaveBeenCalledWith('[cowork] flush on close failed:', failure)
+ expect(isCoworkClosing()).toBe(false)
+ expect(invoke).not.toHaveBeenCalledWith('plugin:window|destroy', expect.anything(), undefined)
+ await dispatchClose(closeEvent)
+ expect(invoke).toHaveBeenCalledWith('plugin:window|destroy', { label: 'main' }, undefined)
+ })
+})
diff --git a/web-app/src/lib/__tests__/coworkPersistence.test.ts b/web-app/src/lib/__tests__/coworkPersistence.test.ts
new file mode 100644
index 000000000..4c00a37dc
--- /dev/null
+++ b/web-app/src/lib/__tests__/coworkPersistence.test.ts
@@ -0,0 +1,1119 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import {
+ createCoworkPersistence,
+ isMissingThreadError,
+ loadCoworkSessions,
+ sessionFromThread,
+ sessionToThreadRecord,
+ COWORK_CURRENT_ID_KEY,
+} from '../coworkPersistence'
+import {
+ CODE_SESSIONS_KEY,
+ COWORK_DELETED_IDS_KEY,
+} from '../migrateCoworkSessions'
+
+type Json = Record<string, any>
+
+// In-memory backend with the same semantics as the Rust commands: the sidecar
+// write refuses a thread with no thread.json unless `create` is set.
+function makeBackend(opts: { failNext?: { cmd: string; times: number } } = {}) {
+ const settings = new Map<string, string>()
+ const threads = new Map<string, Json>()
+ const extras = new Map<string, any>()
+ const log: string[] = []
+ // The derived messages.jsonl per thread, and a switch to fail its writes.
+ const logs = new Map<string, any[]>()
+ const messageFailure: { error: unknown } = { error: null }
+ let failure = opts.failNext
+ const invoke = async (cmd: string, args: Record<string, any> = {}) => {
+ log.push(cmd === 'write_thread_extra' ? `${cmd}:${args.threadId}` : cmd)
+ if (failure && failure.cmd === cmd && failure.times > 0) {
+ failure.times -= 1
+ throw new Error(`${cmd} failed`)
+ }
+ switch (cmd) {
+ case 'settings_get':
+ return settings.get(args.key) ?? null
+ case 'settings_set':
+ settings.set(args.key, args.value)
+ return
+ case 'settings_remove':
+ settings.delete(args.key)
+ return
+ case 'list_threads':
+ return [...threads.values()].map((t) => JSON.parse(JSON.stringify(t)))
+ case 'write_thread_extra':
+ if (!args.create && !threads.has(args.threadId)) {
+ throw new Error("thread_missing: Thread has no thread.json")
+ }
+ extras.set(args.threadId, JSON.parse(JSON.stringify(args.value)))
+ return
+ case 'replace_thread_messages': {
+ if (!args.create && !threads.has(args.threadId)) {
+ throw new Error('thread_missing: Thread has no thread.json')
+ }
+ if (messageFailure.error) throw messageFailure.error
+ logs.set(args.threadId, JSON.parse(JSON.stringify(args.messages)))
+ return
+ }
+ case 'read_thread_extra':
+ return extras.get(args.threadId) ?? null
+ case 'create_thread': {
+ const existing = threads.get(args.thread.id)
+ if (existing) return existing
+ threads.set(args.thread.id, JSON.parse(JSON.stringify(args.thread)))
+ return args.thread
+ }
+ case 'modify_thread':
+ threads.set(args.thread.id, JSON.parse(JSON.stringify(args.thread)))
+ return
+ case 'delete_thread':
+ threads.delete(args.threadId)
+ extras.delete(args.threadId)
+ logs.delete(args.threadId)
+ return
+ default:
+ throw new Error(`unexpected ${cmd}`)
+ }
+ }
+ return { invoke: invoke as any, settings, threads, extras, log, logs, messageFailure }
+}
+
+const session = (id: string, extra: Json = {}): any => ({
+ id,
+ title: 'T ' + id,
+ model: { id: 'gpt', provider: 'openai' },
+ folder: '/proj',
+ turns: [{ role: 'user', content: 'hi' }],
+ messages: [{ id: 'm', role: 'user', parts: [{ type: 'text', text: 'hi' }] }],
+ updated: 1_700_000_000_000,
+ ...extra,
+})
+
+describe('coworkPersistence write protocol', () => {
+ let b: ReturnType<typeof makeBackend>
+ beforeEach(() => {
+ vi.useFakeTimers()
+ b = makeBackend()
+ })
+ afterEach(() => vi.useRealTimers())
+
+ it('debounces: many schedules for a session produce one write of the latest snapshot', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 100 })
+ p.schedule(session('a', { title: 'one' }))
+ p.schedule(session('a', { title: 'two' }))
+ p.schedule(session('a', { title: 'three' }))
+ await vi.advanceTimersByTimeAsync(150)
+ await p.flush()
+ expect(b.log.filter((c) => c === 'create_thread')).toHaveLength(1)
+ expect(b.threads.get('a')!.title).toBe('three')
+ })
+
+ it('first commit is sidecar first, thread.json last', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ p.schedule(session('a'))
+ await p.flush()
+ expect(b.log.indexOf('write_thread_extra:a')).toBeLessThan(b.log.indexOf('create_thread'))
+ expect(b.threads.get('a')!.metadata.mode).toBe('cowork')
+ })
+
+ it('writes only the changed session', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ p.schedule(session('a'))
+ p.schedule(session('b'))
+ await p.flush()
+ b.log.length = 0
+ p.schedule(session('a', { title: 'changed' }))
+ await p.flush()
+ expect(b.log).not.toContain('write_thread_extra:b')
+ expect(b.log).toContain('write_thread_extra:a')
+ })
+
+ it('never writes a new empty session, but does write a persisted one that became empty', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ p.schedule(session('a', { turns: [], messages: [] }))
+ await p.flush()
+ expect(b.threads.has('a')).toBe(false)
+
+ p.schedule(session('a'))
+ await p.flush()
+ expect(b.extras.get('a').turns).toHaveLength(1)
+
+ p.schedule(session('a', { turns: [], messages: [] })) // /clear
+ await p.flush()
+ expect(b.extras.get('a').turns).toHaveLength(0)
+ })
+
+ it('a cleared session is a used session: written even if never persisted, and it rehydrates as cleared and listed', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ // Used then cleared inside the debounce window: no prior write exists.
+ p.schedule(session('a', { title: 'Kept title', turns: [], messages: [], cleared: true }))
+ await p.flush()
+ expect(p.isPersisted('a')).toBe(true)
+ expect(b.threads.get('a')!.title).toBe('Kept title')
+ expect(b.threads.get('a')!.metadata.cleared).toBe(true)
+ const back = sessionFromThread(b.threads.get('a'), b.extras.get('a'))
+ expect(back).toMatchObject({ id: 'a', title: 'Kept title', cleared: true, turns: [], messages: [] })
+ // A blank placeholder carries no marker and is still not written.
+ p.schedule(session('blank', { turns: [], messages: [] }))
+ await p.flush()
+ expect(b.threads.has('blank')).toBe(false)
+ })
+
+ it('explicitly writes an empty new session only when allowEmpty is set', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ p.schedule(session('a', { turns: [], messages: [] }), { allowEmpty: false })
+ await p.flush()
+ expect(p.isPersisted('a')).toBe(false)
+
+ p.schedule(session('a', { turns: [], messages: [] }), { allowEmpty: true })
+ await p.flush()
+ expect(p.isPersisted('a')).toBe(true)
+ expect(b.threads.get('a')!.metadata.mode).toBe('cowork')
+ expect(b.extras.get('a').turns).toHaveLength(0)
+ })
+
+ it('a failed write keeps the session dirty and retries', async () => {
+ b = makeBackend({ failNext: { cmd: 'create_thread', times: 1 } })
+ const onError = vi.fn()
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10, retryMs: 50, onError })
+ p.schedule(session('a'))
+ await vi.advanceTimersByTimeAsync(20)
+ await Promise.resolve()
+ expect(onError).toHaveBeenCalled()
+ expect(b.threads.has('a')).toBe(false)
+ await vi.advanceTimersByTimeAsync(100)
+ await p.flush()
+ expect(b.threads.has('a')).toBe(true)
+ })
+
+ it.each(['write_thread_extra', 'create_thread', 'modify_thread'])(
+ 'rejects flush after bounded %s failures and recovers the latest snapshot',
+ async (cmd) => {
+ const failure = { cmd, times: 0 }
+ b = makeBackend({ failNext: failure })
+ const onError = vi.fn()
+ const p = createCoworkPersistence(b.invoke, { onError, retryMs: 50 })
+ if (cmd === 'modify_thread') {
+ p.schedule(session('a'))
+ await p.flush()
+ }
+ failure.times = 6
+ p.schedule(session('a', { title: 'unsaved' }))
+ await expect(p.flush()).rejects.toThrow('pending writes: a')
+ expect(onError).toHaveBeenCalledTimes(3)
+ await expect(p.flush()).rejects.toThrow('pending writes: a')
+ expect(onError).toHaveBeenCalledTimes(6)
+ p.schedule(session('a', { title: 'latest' }))
+ await p.flush()
+ expect(b.threads.get('a')!.title).toBe('latest')
+ expect(b.extras.get('a').messages).toEqual(session('a').messages)
+ await vi.advanceTimersByTimeAsync(100)
+ expect(onError).toHaveBeenCalledTimes(6)
+ }
+ )
+
+ it('counts failures from an already in-flight write and rejects instead of losing dirty work', async () => {
+ let release!: () => void
+ const gate = new Promise<void>((resolve) => { release = resolve })
+ const onError = vi.fn()
+ let failing = true
+ const p = createCoworkPersistence(async (cmd, args) => {
+ if (cmd === 'write_thread_extra' && failing) {
+ await gate
+ throw new Error('disk full')
+ }
+ return b.invoke(cmd, args)
+ }, { debounceMs: 10, onError })
+ p.schedule(session('a'))
+ await vi.advanceTimersByTimeAsync(10)
+ const flushed = expect(p.flush()).rejects.toThrow('pending writes: a')
+ release()
+ await flushed
+ expect(onError).toHaveBeenCalledTimes(3)
+ failing = false
+ await p.flush()
+ expect(b.threads.get('a')!.title).toBe('T a')
+ })
+
+ it('retains a failed snapshot for automatic background recovery after rejected flush', async () => {
+ b = makeBackend({ failNext: { cmd: 'write_thread_extra', times: 3 } })
+ const p = createCoworkPersistence(b.invoke, { retryMs: 50 })
+ p.schedule(session('a'))
+ await expect(p.flush()).rejects.toThrow('pending writes: a')
+ await vi.advanceTimersByTimeAsync(50)
+ expect(b.threads.get('a')!.title).toBe('T a')
+ await p.flush()
+ })
+
+ it.each(['settings_set', 'settings_remove'])(
+ 'rejects flush after bounded current-id %s failures and retries without a new selection',
+ async (cmd) => {
+ b = makeBackend({ failNext: { cmd, times: 3 } })
+ b.settings.set(COWORK_CURRENT_ID_KEY, 'old')
+ const onError = vi.fn()
+ const p = createCoworkPersistence(b.invoke, { onError })
+ p.setCurrentId(cmd === 'settings_set' ? 'new' : null)
+ await expect(p.flush()).rejects.toThrow('pending writes: current-id')
+ expect(onError).toHaveBeenCalledTimes(3)
+ expect(onError).toHaveBeenLastCalledWith('current-id', expect.any(Error))
+ expect(b.settings.get(COWORK_CURRENT_ID_KEY)).toBe('old')
+ await p.flush()
+ expect(b.settings.get(COWORK_CURRENT_ID_KEY)).toBe(cmd === 'settings_set' ? 'new' : undefined)
+ }
+ )
+
+ it('flush writes pending work immediately without waiting for the debounce', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 60_000 })
+ p.schedule(session('a'))
+ expect(b.threads.has('a')).toBe(false)
+ await p.flush()
+ expect(b.threads.has('a')).toBe(true)
+ })
+
+ it('a mutation during an in-flight write is written after it, in order', async () => {
+ const order: string[] = []
+ const slow = async (cmd: string, args: any) => {
+ if (cmd === 'write_thread_extra') {
+ await new Promise((r) => setTimeout(r, 50))
+ order.push(`extra:${args.value.turns.length}`)
+ }
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(slow as any, { debounceMs: 5 })
+ p.schedule(session('a'))
+ await vi.advanceTimersByTimeAsync(10) // first write now in flight
+ p.schedule(session('a', { turns: [{ role: 'user', content: 'a' }, { role: 'assistant', content: 'b' }] }))
+ const done = p.flush()
+ await vi.advanceTimersByTimeAsync(500)
+ await done
+ expect(order).toEqual(['extra:1', 'extra:2'])
+ expect(b.extras.get('a').turns).toHaveLength(2)
+ })
+
+ it('delete cancels a pending write and drops late writes (no resurrection)', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 100 })
+ p.schedule(session('a'))
+ await p.flush()
+ p.schedule(session('a', { title: 'pending edit' }))
+ await p.remove('a')
+ p.schedule(session('a', { title: 'late edit' }))
+ await vi.advanceTimersByTimeAsync(500)
+ await p.flush()
+ expect(b.threads.has('a')).toBe(false)
+ expect(b.extras.has('a')).toBe(false)
+ })
+
+ it('delete during an in-flight write drains it first, then removes the thread', async () => {
+ let release!: () => void
+ const gate = new Promise<void>((r) => (release = r))
+ const gated = async (cmd: string, args: any) => {
+ if (cmd === 'write_thread_extra') await gate
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(gated as any, { debounceMs: 5 })
+ p.schedule(session('a'))
+ await vi.advanceTimersByTimeAsync(10)
+ const removed = p.remove('a')
+ release()
+ await vi.advanceTimersByTimeAsync(10)
+ await removed
+ expect(b.threads.has('a')).toBe(false)
+ expect(b.extras.has('a')).toBe(false)
+ })
+
+ it('records a deleted id when asked, so the legacy blob cannot resurrect it', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 5 })
+ p.schedule(session('a'))
+ await p.flush()
+ await p.remove('a', { recordDeleted: true })
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toEqual(['a'])
+ })
+
+ it('serializes the shared deletion journal for concurrent removals', async () => {
+ const p = createCoworkPersistence(b.invoke)
+ await Promise.all([p.remove('a', { recordDeleted: true }), p.remove('b', { recordDeleted: true })])
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!).sort()).toEqual(['a', 'b'])
+ })
+
+ it('rolls back failed deletion intent so a legacy-only session survives rehydration', async () => {
+ b = makeBackend({ failNext: { cmd: 'delete_thread', times: 1 } })
+ b.settings.set(CODE_SESSIONS_KEY, JSON.stringify({
+ state: { sessions: [session('a')] }, version: 1,
+ }))
+ const p = createCoworkPersistence(b.invoke)
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('delete_thread failed')
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toEqual([])
+ // No retry write has persisted a thread before this simulated restart.
+ expect(b.threads.has('a')).toBe(false)
+ const loaded = await loadCoworkSessions(b.invoke, { migrationSettled: false })
+ expect(loaded.sessions.map((s) => s.id)).toEqual(['a'])
+ expect([...loaded.legacyIds]).toEqual(['a'])
+ p.schedule(session('a', { title: 'still editable' }), { legacy: true })
+ await p.flush()
+ expect(b.threads.get('a')!.title).toBe('still editable')
+ })
+
+ it('retries transient rollback failure before rejecting so immediate legacy hydration recovers', async () => {
+ b.settings.set(CODE_SESSIONS_KEY, JSON.stringify({
+ state: { sessions: [session('a')] }, version: 1,
+ }))
+ let rollbackAttempts = 0
+ const invoke = async (cmd: string, args: any) => {
+ if (cmd === 'delete_thread') throw new Error('delete failed')
+ if (cmd === 'settings_set' && args.key === COWORK_DELETED_IDS_KEY && args.value === '[]') {
+ if (++rollbackAttempts === 1) throw new Error('rollback failed')
+ }
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(invoke as any)
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('delete failed')
+ expect(rollbackAttempts).toBe(2)
+ expect(b.threads.has('a')).toBe(false)
+ const loaded = await loadCoworkSessions(b.invoke, { migrationSettled: false })
+ expect(loaded.sessions.map((s) => s.id)).toEqual(['a'])
+ expect([...loaded.legacyIds]).toEqual(['a'])
+ })
+
+ it('retries a failed rollback read without erasing unrelated deletion markers', async () => {
+ b.settings.set(COWORK_DELETED_IDS_KEY, JSON.stringify(['other']))
+ let rollbackReads = 0
+ let deleting = false
+ const invoke = async (cmd: string, args: any) => {
+ if (cmd === 'delete_thread') {
+ deleting = true
+ throw new Error('delete failed')
+ }
+ if (deleting && cmd === 'settings_get' && args.key === COWORK_DELETED_IDS_KEY) {
+ if (++rollbackReads === 1) throw new Error('read failed')
+ }
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(invoke as any)
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('delete failed')
+ expect(rollbackReads).toBe(2)
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toEqual(['other'])
+ expect(b.log.filter((cmd) => cmd === 'settings_set')).toHaveLength(2)
+ })
+
+ it.each(['{invalid', '{}', 'null', '["other", 42]', ''])(
+ 'does not overwrite invalid journal %j during rollback and reports pending recovery',
+ async (raw) => {
+ b.settings.set(COWORK_DELETED_IDS_KEY, JSON.stringify(['other']))
+ const invoke = async (cmd: string, args: any) => {
+ if (cmd === 'delete_thread') {
+ b.settings.set(COWORK_DELETED_IDS_KEY, raw)
+ throw new Error('delete failed')
+ }
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(invoke as any)
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('deletion recovery pending')
+ await expect(p.flush()).rejects.toThrow()
+ expect(b.settings.get(COWORK_DELETED_IDS_KEY)).toBe(raw)
+ expect(b.log.filter((cmd) => cmd === 'settings_set')).toHaveLength(1)
+ b.settings.set(COWORK_DELETED_IDS_KEY, JSON.stringify(['other', 'a']))
+ await p.flush()
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toEqual(['other'])
+ }
+ )
+
+ it('does not erase existing markers or delete files when the intent read fails', async () => {
+ b = makeBackend({ failNext: { cmd: 'settings_get', times: 1 } })
+ b.settings.set(COWORK_DELETED_IDS_KEY, JSON.stringify(['other']))
+ const p = createCoworkPersistence(b.invoke)
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('settings_get failed')
+ expect(b.settings.get(COWORK_DELETED_IDS_KEY)).toBe('["other"]')
+ expect(b.log).not.toContain('settings_set')
+ expect(b.log).not.toContain('delete_thread')
+ await p.remove('a', { recordDeleted: true })
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toEqual(['other', 'a'])
+ })
+
+ it.each(['{invalid', '{}', 'null', '["other", 42]', ''])(
+ 'rejects invalid journal %j before recording intent or deleting files',
+ async (raw) => {
+ b.settings.set(COWORK_DELETED_IDS_KEY, raw)
+ const p = createCoworkPersistence(b.invoke)
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow()
+ expect(b.settings.get(COWORK_DELETED_IDS_KEY)).toBe(raw)
+ expect(b.log).not.toContain('settings_set')
+ expect(b.log).not.toContain('delete_thread')
+ }
+ )
+
+ it('surfaces persistent rollback failure, retains compensation for bounded flush retry and queued edits', async () => {
+ b.settings.set(CODE_SESSIONS_KEY, JSON.stringify({
+ state: { sessions: [session('a')] }, version: 1,
+ }))
+ let broken = true
+ let rollbackAttempts = 0
+ const invoke = async (cmd: string, args: any) => {
+ if (cmd === 'delete_thread') throw new Error('delete failed')
+ if (cmd === 'settings_set' && args.key === COWORK_DELETED_IDS_KEY && args.value === '[]') {
+ rollbackAttempts++
+ if (broken) throw new Error('rollback failed')
+ }
+ return b.invoke(cmd, args)
+ }
+ const onError = vi.fn()
+ const p = createCoworkPersistence(invoke as any, { onError })
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('deletion recovery pending')
+ expect(onError).toHaveBeenCalledWith('a', expect.objectContaining({ message: expect.stringContaining('rollback failed') }))
+ expect(rollbackAttempts).toBe(3)
+ // The sync catch restores this snapshot; it must not be silently discarded.
+ p.schedule(session('a', { title: 'restored edit' }), { legacy: true })
+ await expect(p.flush()).rejects.toThrow('rollback failed')
+ expect(rollbackAttempts).toBe(6)
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(rollbackAttempts).toBe(6)
+ expect(b.threads.has('a')).toBe(false)
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toEqual(['a'])
+ // Disk is still broken: do not pretend this is restart-safe recovery.
+ expect((await loadCoworkSessions(b.invoke, { migrationSettled: false })).sessions).toEqual([])
+ broken = false
+ await p.flush()
+ expect(rollbackAttempts).toBe(7)
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toEqual([])
+ expect(b.threads.get('a')!.title).toBe('restored edit')
+ expect((await loadCoworkSessions(b.invoke, { migrationSettled: false })).sessions.map((s) => s.id)).toEqual(['a'])
+ await p.flush()
+ expect(rollbackAttempts).toBe(7)
+ })
+
+ it('flushSession drains only the target: unrelated dirty failures and current-id never block or run', async () => {
+ let brokenOther = true
+ const invoke = async (cmd: string, args: any) => {
+ if (cmd === 'write_thread_extra' && args.threadId === 'other' && brokenOther) throw new Error('other failed')
+ if (cmd === 'settings_set' && args.key === COWORK_CURRENT_ID_KEY) throw new Error('current-id failed')
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(invoke as any, { debounceMs: 10, retryMs: 1_000_000 })
+ p.setCurrentId('other')
+ p.schedule(session('other'))
+ p.schedule(session('target', { turns: [], messages: [] }), { allowEmpty: true })
+ b.log.length = 0
+ await expect(p.flushSession('target')).resolves.toBeUndefined()
+ expect(p.isPersisted('target')).toBe(true)
+ expect(p.isPersisted('other')).toBe(false)
+ expect(b.log).not.toContain('write_thread_extra:other')
+ expect(b.log).not.toContain('settings_set')
+ // The unrelated failure is still pending for a full flush.
+ await expect(p.flush()).rejects.toThrow()
+ brokenOther = false
+ })
+
+ it('flushSession fails closed when the target write fails, keeping it dirty for retry', async () => {
+ let broken = true
+ const invoke = async (cmd: string, args: any) => {
+ if (cmd === 'write_thread_extra' && args.threadId === 'target' && broken) throw new Error('target failed')
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(invoke as any, { debounceMs: 10, retryMs: 1_000_000 })
+ p.schedule(session('target'))
+ await expect(p.flushSession('target')).rejects.toThrow('pending writes: target')
+ expect(p.isPersisted('target')).toBe(false)
+ broken = false
+ await expect(p.flushSession('target')).resolves.toBeUndefined()
+ expect(p.isPersisted('target')).toBe(true)
+ })
+
+ it('flushSession respects a pending rollback of the same id and ignores other ids', async () => {
+ b.settings.set(CODE_SESSIONS_KEY, JSON.stringify({ state: { sessions: [session('a')] }, version: 1 }))
+ let broken = true
+ const invoke = async (cmd: string, args: any) => {
+ if (cmd === 'delete_thread') throw new Error('delete failed')
+ if (cmd === 'settings_set' && args.key === COWORK_DELETED_IDS_KEY && args.value === '[]' && broken) throw new Error('rollback failed')
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(invoke as any, { debounceMs: 10 })
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('deletion recovery pending')
+ p.schedule(session('a', { title: 'restored' }), { legacy: true })
+ await expect(p.flushSession('a')).rejects.toThrow('rollback failed')
+ expect(b.threads.has('a')).toBe(false)
+ // An unrelated id does not retry the pending rollback of 'a'.
+ await expect(p.flushSession('zzz')).resolves.toBeUndefined()
+ broken = false
+ await expect(p.flushSession('a')).resolves.toBeUndefined()
+ expect(b.threads.get('a')!.title).toBe('restored')
+ })
+
+ it('flushSession on an already durable clean id makes no storage call and schedules no write', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ p.adopt([{ id: 'a' }])
+ b.log.length = 0
+ await expect(p.flushSession('a')).resolves.toBeUndefined()
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(b.log).toEqual([])
+ })
+
+ it('flushSession denies the same id while its deletion is in flight and after it completes', async () => {
+ let releaseDelete!: () => void
+ const gate = new Promise<void>((resolve) => (releaseDelete = resolve))
+ const invoke = async (cmd: string, args: any) => {
+ if (cmd === 'delete_thread') await gate
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(invoke as any, { debounceMs: 10 })
+ p.schedule(session('a'))
+ await p.flushSession('a')
+ expect(p.isPersisted('a')).toBe(true)
+ const removal = p.remove('a')
+ await expect(p.flushSession('a')).rejects.toThrow('being deleted')
+ // Another session is unaffected.
+ await expect(p.flushSession('other')).resolves.toBeUndefined()
+ releaseDelete()
+ await removal
+ await expect(p.flushSession('a')).rejects.toThrow('being deleted')
+ expect(b.threads.has('a')).toBe(false)
+ })
+
+ it('flushSession rejects a target whose thread the host confirmed missing', async () => {
+ const onThreadMissing = vi.fn()
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10, onThreadMissing })
+ p.adopt([{ id: 'gone' }]) // adopted, but no thread.json on disk
+ p.schedule(session('gone'))
+ await expect(p.flushSession('gone')).rejects.toThrow('thread is missing')
+ expect(onThreadMissing).toHaveBeenCalledOnce()
+ expect(b.threads.has('gone')).toBe(false)
+ })
+
+ it('a failed deletion with failed rollback still blocks flushSession of a durable id until rollback settles', async () => {
+ let broken = true
+ const invoke = async (cmd: string, args: any) => {
+ if (cmd === 'delete_thread') throw new Error('delete failed')
+ if (cmd === 'settings_set' && args.key === COWORK_DELETED_IDS_KEY && args.value === '[]' && broken) throw new Error('rollback failed')
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(invoke as any, { debounceMs: 10 })
+ p.schedule(session('a'))
+ await p.flushSession('a')
+ expect(p.isPersisted('a')).toBe(true) // durable and clean
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('deletion recovery pending')
+ expect(p.isPersisted('a')).toBe(true) // still durable, deletion intent still journaled
+ await expect(p.flushSession('a')).rejects.toThrow('rollback failed')
+ broken = false
+ await expect(p.flushSession('a')).resolves.toBeUndefined()
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toEqual([])
+ })
+
+ it('rollback preserves concurrent deletion intent and successful deletes cannot resurrect', async () => {
+ b.settings.set(COWORK_DELETED_IDS_KEY, JSON.stringify(['already-deleted']))
+ b.settings.set(CODE_SESSIONS_KEY, JSON.stringify({
+ state: { sessions: ['a', 'b', 'already-deleted'].map((id) => session(id)) }, version: 1,
+ }))
+ let rejectDelete!: (e: Error) => void
+ let started!: () => void
+ const deleting = new Promise<void>((resolve) => (started = resolve))
+ const gate = new Promise<void>((_resolve, reject) => (rejectDelete = reject))
+ const invoke = async (cmd: string, args: any) => {
+ if (cmd === 'delete_thread' && args.threadId === 'a') {
+ started()
+ await gate
+ }
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(invoke as any)
+ const failed = expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('delete failed')
+ await deleting
+ await p.remove('b', { recordDeleted: true })
+ rejectDelete(new Error('delete failed'))
+ await failed
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!).sort()).toEqual(['already-deleted', 'b'])
+ p.schedule(session('b', { title: 'late edit' }))
+ await p.flush()
+ expect(b.threads.has('b')).toBe(false)
+ const loaded = await loadCoworkSessions(b.invoke, { migrationSettled: false })
+ expect(loaded.sessions.map((s) => s.id)).toEqual(['a'])
+ })
+
+ it('does not roll back a pre-existing legitimate deletion marker', async () => {
+ b = makeBackend({ failNext: { cmd: 'delete_thread', times: 1 } })
+ b.settings.set(COWORK_DELETED_IDS_KEY, JSON.stringify(['a', 'other']))
+ const p = createCoworkPersistence(b.invoke)
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('delete_thread failed')
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toEqual(['a', 'other'])
+ })
+
+ it('keeps deletion intent if notification fails after the backend has deleted the thread', async () => {
+ const p = createCoworkPersistence(b.invoke, {
+ onThreadRemoved: () => { throw new Error('notification failed') },
+ })
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('notification failed')
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toEqual(['a'])
+ })
+
+ it('does not delete files when journaling fails and the journal queue remains usable', async () => {
+ b = makeBackend({ failNext: { cmd: 'settings_set', times: 1 } })
+ const p = createCoworkPersistence(b.invoke)
+ await expect(p.remove('a', { recordDeleted: true })).rejects.toThrow('settings_set failed')
+ expect(b.log).not.toContain('delete_thread')
+ await p.remove('b', { recordDeleted: true })
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toEqual(['b'])
+ })
+
+ it('a failed deletion is surfaced and does not permanently block session writes', async () => {
+ b = makeBackend({ failNext: { cmd: 'delete_thread', times: 1 } })
+ const p = createCoworkPersistence(b.invoke)
+ p.schedule(session('a'))
+ await p.flush()
+ await expect(p.remove('a')).rejects.toThrow('delete_thread failed')
+ p.schedule(session('a', { title: 'still editable' }))
+ await p.flush()
+ expect(b.threads.get('a')!.title).toBe('still editable')
+ })
+
+ it('deleting a collision placeholder never deletes or unlists the unrelated chat', async () => {
+ b.threads.set('collision', { id: 'collision', title: 'Original chat' })
+ const onRemoved = vi.fn()
+ const p = createCoworkPersistence(b.invoke, { onThreadRemoved: onRemoved })
+ await p.remove('collision', { preserveThread: true, recordDeleted: true })
+ expect(b.threads.get('collision')!.title).toBe('Original chat')
+ expect(onRemoved).not.toHaveBeenCalled()
+ expect(JSON.parse(b.settings.get(COWORK_DELETED_IDS_KEY)!)).toContain('collision')
+ })
+
+ it('settles without endless retry when the thread directory is permanently missing', async () => {
+ const onThreadMissing = vi.fn()
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 5, retryMs: 50, onThreadMissing })
+ p.schedule(session('a'))
+ await p.flush()
+ expect(b.threads.has('a')).toBe(true)
+ // Out-of-band deletion of the thread directory.
+ b.threads.delete('a')
+ b.extras.delete('a')
+ p.schedule(session('a', { title: 'edited' }))
+ await expect(p.flush()).resolves.toBeUndefined()
+ expect(onThreadMissing).toHaveBeenCalledTimes(1)
+ expect(onThreadMissing.mock.calls[0][0]).toBe('a')
+ expect(onThreadMissing.mock.calls[0][1].title).toBe('edited')
+ const writes = () => b.log.filter((l) => l === 'write_thread_extra:a').length
+ const before = writes()
+ await vi.advanceTimersByTimeAsync(1000)
+ await p.flush()
+ expect(writes()).toBe(before)
+ // Never resurrected by the failed write or later retries.
+ expect(b.threads.has('a')).toBe(false)
+ expect(b.extras.has('a')).toBe(false)
+ })
+
+ it('does not treat a transient disk failure as a missing thread', async () => {
+ const onThreadMissing = vi.fn()
+ b = makeBackend({ failNext: { cmd: 'write_thread_extra', times: 3 } })
+ const q = createCoworkPersistence(b.invoke, { debounceMs: 5, retryMs: 50, onThreadMissing })
+ q.schedule(session('t'))
+ await expect(q.flush()).rejects.toThrow(/pending writes: t/)
+ expect(onThreadMissing).not.toHaveBeenCalled()
+ await q.flush()
+ expect(b.threads.has('t')).toBe(true)
+ expect(b.extras.has('t')).toBe(true)
+ })
+
+ it('a missing-thread error from an in-flight write while a deletion is pending keeps tombstone semantics (no unavailable, no recreate)', async () => {
+ const onThreadMissing = vi.fn()
+ let entered!: () => void
+ const enteredP = new Promise<void>((r) => (entered = r))
+ let release!: () => void
+ const gate = new Promise<void>((r) => (release = r))
+ let gatingArmed = false
+ let gatedOnce = false
+ // Real Tauri rejection shape: a plain string, not an Error.
+ const gated = (async (cmd: string, args: Record<string, any> = {}) => {
+ if (cmd === 'write_thread_extra' && args.threadId === 'a' && gatingArmed && !gatedOnce) {
+ gatedOnce = true
+ entered()
+ await gate
+ b.threads.delete('a')
+ b.extras.delete('a')
+ throw 'thread_missing: Thread has no thread.json'
+ }
+ return b.invoke(cmd, args)
+ }) as any
+ const onThreadRemoved = vi.fn()
+ const p = createCoworkPersistence(gated, { debounceMs: 5, retryMs: 50, onThreadMissing, onThreadRemoved })
+ p.schedule(session('a'))
+ await p.flush()
+ gatingArmed = true // arm only after the initial persist
+ p.schedule(session('a', { title: 'late' }))
+ await vi.advanceTimersByTimeAsync(10)
+ await enteredP // the write is now genuinely in flight
+ const removal = p.remove('a')
+ release()
+ await removal
+ await p.flush()
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(onThreadMissing).not.toHaveBeenCalled()
+ expect(onThreadRemoved).toHaveBeenCalledWith('a')
+ expect(b.log).toContain('delete_thread')
+ expect(b.threads.has('a')).toBe(false)
+ expect(b.extras.has('a')).toBe(false)
+ // No write after the in-flight one failed (no retry, no recreate).
+ expect(b.log.filter((l) => l === 'write_thread_extra:a')).toHaveLength(1)
+ // And the tombstone still blocks a stale snapshot.
+ p.schedule(session('a', { title: 'stale' }))
+ await p.flush()
+ expect(b.threads.has('a')).toBe(false)
+ })
+
+ it('a late flush after delete never recreates the sidecar or thread', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 5, retryMs: 50 })
+ p.schedule(session('a'))
+ await p.flush()
+ p.schedule(session('a', { title: 'late' }))
+ await p.remove('a')
+ b.log.length = 0
+ await p.flush()
+ await vi.advanceTimersByTimeAsync(1000)
+ p.schedule(session('a', { title: 'later' }), { allowEmpty: true })
+ await p.flush()
+ expect(b.log.filter((l) => l.startsWith('write_thread_extra'))).toEqual([])
+ expect(b.extras.has('a')).toBe(false)
+ expect(b.threads.has('a')).toBe(false)
+ })
+
+ it('a first write queued behind the tombstone does not create the sidecar (create: true)', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 5, retryMs: 50 })
+ p.schedule(session('n'))
+ await vi.advanceTimersByTimeAsync(10) // write dispatched, never persisted before remove
+ await p.remove('n')
+ await p.flush()
+ expect(b.extras.has('n')).toBe(false)
+ expect(b.threads.has('n')).toBe(false)
+ })
+
+ it('isMissingThreadError accepts only the host code, as a string, Error or {message}', () => {
+ expect(isMissingThreadError('thread_missing: x')).toBe(true)
+ expect(isMissingThreadError(new Error('thread_missing: x'))).toBe(true)
+ expect(isMissingThreadError({ message: 'thread_missing: x' })).toBe(true)
+ // Not the typed code: stays on the retry path.
+ expect(isMissingThreadError('Error: thread_missing: x')).toBe(false)
+ expect(isMissingThreadError('thread_missing')).toBe(false)
+ expect(isMissingThreadError('write failed: thread_missing: x')).toBe(false)
+ expect(isMissingThreadError('disk full')).toBe(false)
+ expect(isMissingThreadError({ message: 42 })).toBe(false)
+ expect(isMissingThreadError({ code: 'thread_missing' })).toBe(false)
+ expect(isMissingThreadError(null)).toBe(false)
+ expect(isMissingThreadError(undefined)).toBe(false)
+ expect(isMissingThreadError(42)).toBe(false)
+ })
+
+ it.each([
+ ['a plain string (real Tauri rejection)', () => 'thread_missing: gone'],
+ ['an {message} object', () => ({ message: 'thread_missing: gone' })],
+ ['an Error', () => new Error('thread_missing: gone')],
+ ])('settles as missing when the host rejects with %s', async (_label, make) => {
+ const onThreadMissing = vi.fn()
+ let failing = false
+ const inv = (async (cmd: string, args: Record<string, any> = {}) => {
+ if (failing && cmd === 'write_thread_extra') throw make()
+ return b.invoke(cmd, args)
+ }) as any
+ const p = createCoworkPersistence(inv, { debounceMs: 5, retryMs: 50, onThreadMissing })
+ p.schedule(session('a'))
+ await p.flush()
+ failing = true
+ p.schedule(session('a', { title: 'edited' }))
+ await expect(p.flush()).resolves.toBeUndefined()
+ expect(onThreadMissing).toHaveBeenCalledTimes(1)
+ const before = b.log.filter((l) => l === 'write_thread_extra:a').length
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(b.log.filter((l) => l === 'write_thread_extra:a').length).toBe(before)
+ })
+
+ it('a non-prefixed string rejection stays on the retry path', async () => {
+ const onThreadMissing = vi.fn()
+ let failing = true
+ const inv = (async (cmd: string, args: Record<string, any> = {}) => {
+ if (failing && cmd === 'write_thread_extra') throw 'disk full'
+ return b.invoke(cmd, args)
+ }) as any
+ const p = createCoworkPersistence(inv, { debounceMs: 5, retryMs: 50, onThreadMissing })
+ p.schedule(session('t'))
+ await expect(p.flush()).rejects.toThrow(/pending writes: t/)
+ expect(onThreadMissing).not.toHaveBeenCalled()
+ failing = false
+ await p.flush()
+ expect(b.threads.has('t')).toBe(true)
+ })
+
+ it('a session flagged missing can still be deleted: remove resolves and notifies', async () => {
+ const onThreadMissing = vi.fn()
+ const onThreadRemoved = vi.fn()
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 5, retryMs: 50, onThreadMissing, onThreadRemoved })
+ p.schedule(session('a'))
+ await p.flush()
+ b.threads.delete('a')
+ b.extras.delete('a')
+ p.schedule(session('a', { title: 'edited' }))
+ await p.flush()
+ expect(onThreadMissing).toHaveBeenCalledTimes(1)
+ await expect(p.remove('a')).resolves.toBeUndefined()
+ expect(onThreadRemoved).toHaveBeenCalledWith('a')
+ expect(b.log).toContain('delete_thread')
+ expect(p.isPersisted('a')).toBe(false)
+ // No resurrection after the removal.
+ p.schedule(session('a', { title: 'stale' }))
+ await p.flush()
+ expect(b.threads.has('a')).toBe(false)
+ })
+
+ it('never writes sessions flagged unavailable (files are preserved)', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 5 })
+ p.schedule(session('a', { unavailable: 'unreadable-sidecar' }))
+ await p.flush()
+ expect(b.log).not.toContain('create_thread')
+ expect(b.log).not.toContain('write_thread_extra:a')
+ })
+
+ it('stamps migratedFrom on legacy-sourced first writes', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 5 })
+ p.schedule(session('a'), { legacy: true })
+ await p.flush()
+ expect(b.threads.get('a')!.metadata.migratedFrom.store).toBe(CODE_SESSIONS_KEY)
+ })
+
+ it('a thread that already exists on disk is updated, not duplicated, and keeps its metadata', async () => {
+ b.threads.set('a', {
+ id: 'a',
+ created: 5,
+ assistants: [{ id: 'model-only', name: 'Model', model: { id: 'x', engine: 'y' } }],
+ metadata: { mode: 'cowork', is_favorite: true, order: 3 },
+ })
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 5 })
+ p.schedule(session('a', { title: 'renamed' }))
+ await p.flush()
+ const t = b.threads.get('a')!
+ expect(t.title).toBe('renamed')
+ expect(t.created).toBe(5)
+ expect(t.metadata.is_favorite).toBe(true)
+ expect(t.metadata.order).toBe(3)
+ })
+
+ it('persists the current id and clears it with null', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 5 })
+ p.setCurrentId('a')
+ await p.flush()
+ expect(b.settings.get(COWORK_CURRENT_ID_KEY)).toBe('a')
+ p.setCurrentId(null)
+ await p.flush()
+ expect(b.settings.has(COWORK_CURRENT_ID_KEY)).toBe(false)
+ })
+})
+
+describe('thread record mapping', () => {
+ it('round-trips a session through the thread record (model, folder, plan mode, seconds)', () => {
+ const s = session('a', { planMode: true })
+ const rec = sessionToThreadRecord(s)
+ expect(rec.assistants[0].model).toEqual({ id: 'gpt', engine: 'openai' })
+ expect(rec.updated).toBe(1_700_000_000)
+ const back = sessionFromThread(rec, {
+ version: 1,
+ turns: s.turns,
+ messages: s.messages,
+ })
+ expect(back.model).toEqual({ id: 'gpt', provider: 'openai' })
+ expect(back.folder).toBe('/proj')
+ expect(back.planMode).toBe(true)
+ expect(back.updated).toBe(1_700_000_000_000)
+ })
+
+ it('does not rewrite created and drops cleared plan mode / goal', () => {
+ const rec = sessionToThreadRecord(session('a'), {
+ id: 'a',
+ created: 9,
+ metadata: { mode: 'cowork', planMode: true, goal: { condition: 'x' } },
+ })
+ expect(rec.created).toBe(9)
+ expect(rec.metadata.planMode).toBeUndefined()
+ expect(rec.metadata.goal).toBeUndefined()
+ })
+})
+
+describe('loadCoworkSessions', () => {
+ let b: ReturnType<typeof makeBackend>
+ beforeEach(() => {
+ b = makeBackend()
+ })
+ const commit = (id: string, extra: Json = {}) => {
+ b.threads.set(id, { ...sessionToThreadRecord(session(id, extra)) })
+ b.extras.set(id, { version: 1, turns: session(id).turns, messages: session(id).messages })
+ }
+
+ it('loads cowork threads only, newest first, and ignores chat threads', async () => {
+ commit('old', { updated: 1_600_000_000_000 })
+ commit('new', { updated: 1_700_000_000_000 })
+ b.threads.set('chat', { id: 'chat', metadata: {} })
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: true })
+ expect(r.sessions.map((s) => s.id)).toEqual(['new', 'old'])
+ })
+
+ it('shows a session with a corrupt or missing sidecar as unavailable instead of hiding it', async () => {
+ commit('ok')
+ b.threads.set('bad', sessionToThreadRecord(session('bad')))
+ const broken = async (cmd: string, args: any) => {
+ if (cmd === 'read_thread_extra' && args.threadId === 'bad') throw new Error('corrupt')
+ return b.invoke(cmd, args)
+ }
+ b.threads.set('gone', sessionToThreadRecord(session('gone')))
+ const r = await loadCoworkSessions(broken as any, { migrationSettled: true })
+ expect(r.sessions.find((s) => s.id === 'bad')!.unavailable).toBe('unreadable-sidecar')
+ expect(r.sessions.find((s) => s.id === 'gone')!.unavailable).toBe('missing-sidecar')
+ expect(r.sessions.find((s) => s.id === 'ok')!.unavailable).toBeUndefined()
+ })
+
+ it('while the migration is unsettled, adds sessions only in the legacy blob', async () => {
+ commit('migrated')
+ b.settings.set(
+ CODE_SESSIONS_KEY,
+ JSON.stringify({ state: { sessions: [session('migrated'), session('only-legacy')] }, version: 1 })
+ )
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: false })
+ expect(r.sessions.map((s) => s.id).sort()).toEqual(['migrated', 'only-legacy'])
+ expect([...r.legacyIds]).toEqual(['only-legacy'])
+ })
+
+ it('does not read the legacy blob once the migration is settled', async () => {
+ b.settings.set(
+ CODE_SESSIONS_KEY,
+ JSON.stringify({ state: { sessions: [session('x')] }, version: 1 })
+ )
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: true })
+ expect(r.sessions).toHaveLength(0)
+ })
+
+ it('honours deleted ids and flags an id collision with a chat thread as unavailable', async () => {
+ b.threads.set('chat-id', { id: 'chat-id', metadata: {} })
+ b.settings.set(COWORK_DELETED_IDS_KEY, JSON.stringify(['deleted']))
+ b.settings.set(
+ CODE_SESSIONS_KEY,
+ JSON.stringify({
+ state: { sessions: [session('deleted'), session('chat-id'), session('fine')] },
+ version: 1,
+ })
+ )
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: false })
+ const ids = r.sessions.map((s) => s.id).sort()
+ expect(ids).toEqual(['chat-id', 'fine'])
+ expect(r.sessions.find((s) => s.id === 'chat-id')!.unavailable).toBe('id-collision')
+ })
+
+ it('resumes the saved current id only if that session still exists', async () => {
+ commit('a')
+ b.settings.set(COWORK_CURRENT_ID_KEY, 'a')
+ expect((await loadCoworkSessions(b.invoke, { migrationSettled: true })).currentId).toBe('a')
+ b.settings.set(COWORK_CURRENT_ID_KEY, 'zzz')
+ expect((await loadCoworkSessions(b.invoke, { migrationSettled: true })).currentId).toBeNull()
+ })
+
+ it.each(['{corrupt', JSON.stringify([42])])(
+ 'a corrupt deletion journal (%j) skips the legacy merge and overwrites nothing',
+ async (journal) => {
+ commit('committed')
+ b.settings.set(COWORK_DELETED_IDS_KEY, journal)
+ b.settings.set(
+ CODE_SESSIONS_KEY,
+ JSON.stringify({ state: { sessions: [session('was-deleted')] }, version: 1 })
+ )
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: false })
+ // Deletion intent is unreadable, so the blob must not be merged (fail
+ // closed against resurrection) — but committed threads still load.
+ expect(r.sessions.map((s) => s.id)).toEqual(['committed'])
+ expect(r.legacyIds.size).toBe(0)
+ // The unreadable journal itself is never replaced or rewritten by a load.
+ expect(b.settings.get(COWORK_DELETED_IDS_KEY)).toBe(journal)
+ // The hidden state is surfaced to the caller, never swallowed silently.
+ expect(r.deletionJournalError).toBeTruthy()
+ }
+ )
+
+ it('does not report a journal error on a healthy load', async () => {
+ commit('committed')
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: false })
+ expect(r.deletionJournalError).toBeUndefined()
+ })
+
+ it.each([
+ ['no legacy blob', undefined],
+ [
+ 'nothing mergeable in the blob',
+ // Already committed + empty: nothing the journal could protect.
+ JSON.stringify({
+ state: { sessions: [session('committed'), session('empty', { turns: [], messages: [] })] },
+ version: 1,
+ }),
+ ],
+ ])('a corrupt journal with %s raises no false journal error', async (_name, blob) => {
+ commit('committed')
+ b.settings.set(COWORK_DELETED_IDS_KEY, '{corrupt')
+ if (blob) b.settings.set(CODE_SESSIONS_KEY, blob)
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: false })
+ expect(r.deletionJournalError).toBeUndefined()
+ expect(r.sessions.map((s) => s.id)).toEqual(['committed'])
+ expect(b.settings.get(COWORK_DELETED_IDS_KEY)).toBe('{corrupt')
+ })
+})
+
+describe('sidecar version/shape containment', () => {
+ let b: ReturnType<typeof makeBackend>
+ beforeEach(() => {
+ b = makeBackend()
+ })
+ const seed = (id: string, sidecar: any) => {
+ b.threads.set(id, { ...sessionToThreadRecord(session(id)) })
+ b.extras.set(id, JSON.parse(JSON.stringify(sidecar)))
+ }
+ /** Load, then try to touch (rename + /clear) the session through write-through. */
+ const loadAndTouch = async (id: string) => {
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: true })
+ const s = r.sessions.find((x) => x.id === id)!
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 1 })
+ p.adopt(r.threads)
+ p.schedule({ ...s, title: 'renamed', turns: [], messages: [], updated: Date.now() })
+ await p.flush()
+ return s
+ }
+
+ it('a future-version sidecar loads read-only and its bytes survive a touch', async () => {
+ const v2 = { version: 2, turns: [], messages: [], future: { rich: true } }
+ seed('s', v2)
+ const s = await loadAndTouch('s')
+ expect(s.unavailable).toBe('unreadable-sidecar')
+ expect(b.extras.get('s')).toEqual(v2)
+ expect(b.log.filter((l) => l.startsWith('write_thread_extra'))).toHaveLength(0)
+ })
+
+ it.each([
+ ['null turns', { version: 1, turns: null, messages: [] }],
+ ['non-array messages', { version: 1, turns: [], messages: 'garbage' }],
+ ['missing version', { turns: [{ role: 'user', content: 'hi' }], messages: [] }],
+ ])('a malformed sidecar (%s) is contained read-only, bytes preserved', async (_name, sidecar) => {
+ seed('s', sidecar)
+ const s = await loadAndTouch('s')
+ expect(s.unavailable).toBe('unreadable-sidecar')
+ expect(b.extras.get('s')).toEqual(sidecar)
+ expect(b.log.filter((l) => l.startsWith('write_thread_extra'))).toHaveLength(0)
+ })
+
+ it('a valid v1 sidecar with rich optional data loads writable and an edit erases none of it', async () => {
+ const rich = {
+ version: 1,
+ turns: [{ role: 'user', content: 'hi' }],
+ messages: [{ id: 'm', role: 'user', parts: [{ type: 'text', text: 'hi' }] }],
+ history: [{ role: 'user', content: 'old' }],
+ subagents: [{ id: 'sub' }],
+ lastUsage: { inputTokens: 5 },
+ todos: [{ id: 't', text: 'todo' }],
+ }
+ seed('s', rich)
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: true })
+ const s = r.sessions.find((x) => x.id === 's')!
+ expect(s.unavailable).toBeUndefined()
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 1 })
+ p.adopt(r.threads)
+ p.schedule({ ...s, title: 'renamed' })
+ await p.flush()
+ // The touch wrote through and the rich payload round-tripped intact.
+ expect(b.threads.get('s')!.title).toBe('renamed')
+ expect(b.extras.get('s')).toEqual(rich)
+ })
+})
diff --git a/web-app/src/lib/__tests__/coworkPersistenceMirror.test.ts b/web-app/src/lib/__tests__/coworkPersistenceMirror.test.ts
new file mode 100644
index 000000000..d2447f9e4
--- /dev/null
+++ b/web-app/src/lib/__tests__/coworkPersistenceMirror.test.ts
@@ -0,0 +1,359 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import {
+ createCoworkPersistence,
+ loadCoworkSessions,
+ sessionToThreadRecord,
+} from '../coworkPersistence'
+import {
+ CODE_SESSIONS_KEY,
+ COWORK_MIGRATED_IDS_KEY,
+ COWORK_MIGRATION_ABANDONED_KEY,
+} from '../migrateCoworkSessions'
+import { coworkSessionToThreadMessages } from '../coworkThreadMessages'
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+type Json = Record<string, any>
+
+// In-memory backend with the Rust commands' semantics for the surface the
+// write-through uses, plus switches to inject failures.
+function makeBackend() {
+ const settings = new Map<string, string>()
+ const threads = new Map<string, Json>()
+ const extras = new Map<string, any>()
+ const logs = new Map<string, any[]>()
+ const log: string[] = []
+ const messageFailure: { error: unknown } = { error: null }
+ const invoke = async (cmd: string, args: Record<string, any> = {}) => {
+ log.push(cmd === 'write_thread_extra' ? `${cmd}:${args.threadId}` : cmd)
+ switch (cmd) {
+ case 'settings_get':
+ return settings.get(args.key) ?? null
+ case 'settings_set':
+ settings.set(args.key, args.value)
+ return
+ case 'settings_remove':
+ settings.delete(args.key)
+ return
+ case 'list_threads':
+ return [...threads.values()].map((t) => JSON.parse(JSON.stringify(t)))
+ case 'write_thread_extra':
+ if (!args.create && !threads.has(args.threadId)) {
+ throw new Error('thread_missing: Thread has no thread.json')
+ }
+ extras.set(args.threadId, JSON.parse(JSON.stringify(args.value)))
+ return
+ case 'replace_thread_messages':
+ if (!args.create && !threads.has(args.threadId)) {
+ throw new Error('thread_missing: Thread has no thread.json')
+ }
+ if (messageFailure.error) throw messageFailure.error
+ logs.set(args.threadId, JSON.parse(JSON.stringify(args.messages)))
+ return
+ case 'read_thread_extra':
+ return extras.get(args.threadId) ?? null
+ case 'create_thread': {
+ const existing = threads.get(args.thread.id)
+ if (existing) return existing
+ threads.set(args.thread.id, JSON.parse(JSON.stringify(args.thread)))
+ return args.thread
+ }
+ case 'modify_thread':
+ threads.set(args.thread.id, JSON.parse(JSON.stringify(args.thread)))
+ return
+ case 'delete_thread':
+ threads.delete(args.threadId)
+ extras.delete(args.threadId)
+ logs.delete(args.threadId)
+ return
+ default:
+ throw new Error(`unexpected ${cmd}`)
+ }
+ }
+ return { invoke: invoke as any, settings, threads, extras, logs, log, messageFailure }
+}
+
+const session = (id: string, extra: Json = {}): any => ({
+ id,
+ title: 'T ' + id,
+ model: { id: 'gpt', provider: 'openai' },
+ folder: '/proj',
+ turns: [{ role: 'user', content: 'hi' }],
+ messages: [{ id: 'm', role: 'user', parts: [{ type: 'text', text: 'hi' }] }],
+ updated: 1_700_000_000_000,
+ ...extra,
+})
+
+const reply = { id: 'm2', role: 'assistant', parts: [{ type: 'text', text: 'answer' }] }
+
+describe('messages.jsonl mirror (derived projection)', () => {
+ let b: ReturnType<typeof makeBackend>
+ beforeEach(() => {
+ vi.useFakeTimers()
+ b = makeBackend()
+ })
+ afterEach(() => vi.useRealTimers())
+
+ it('writes the sidecar first, then the converted messages, then thread.json last', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ p.schedule(session('a'))
+ await p.flush()
+ const order = b.log.filter((c) =>
+ ['write_thread_extra:a', 'replace_thread_messages', 'create_thread'].includes(c)
+ )
+ expect(order).toEqual(['write_thread_extra:a', 'replace_thread_messages', 'create_thread'])
+ const anchor = b.threads.get('a')!.metadata.messagesAnchorMs as number
+ expect(b.logs.get('a')).toEqual(
+ JSON.parse(JSON.stringify(coworkSessionToThreadMessages(session('a'), { anchorMs: anchor })))
+ )
+ })
+
+ it('the first mirror creates the directory, later ones need the thread', async () => {
+ const creates: unknown[] = []
+ const spy = async (cmd: string, args: any) => {
+ if (cmd === 'replace_thread_messages') creates.push(args.create)
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(spy as any, { debounceMs: 10 })
+ const s = session('a')
+ p.schedule(s)
+ await p.flush()
+ p.schedule({ ...s, messages: [...s.messages, reply] })
+ await p.flush()
+ expect(creates).toEqual([true, false])
+ })
+
+ it('is idempotent: re-flushing an unchanged transcript rewrites nothing', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ const s = session('a')
+ p.schedule(s)
+ await p.flush()
+ b.log.length = 0
+ // A title edit keeps the very same transcript arrays.
+ p.schedule({ ...s, title: 'renamed' })
+ await p.flush()
+ expect(b.log).not.toContain('replace_thread_messages')
+ expect(b.threads.get('a')!.title).toBe('renamed')
+ })
+
+ it('appending a turn never changes the stamps or ids of messages already written (prefix stays byte-stable)', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ const s1 = session('a')
+ p.schedule(s1)
+ await p.flush()
+ const first = JSON.stringify(b.logs.get('a')![0])
+ p.schedule({
+ ...s1,
+ updated: s1.updated + 999_000,
+ messages: [...s1.messages, reply],
+ turns: [...s1.turns, { role: 'assistant', content: 'answer' }],
+ })
+ await p.flush()
+ const after = b.logs.get('a')!
+ expect(after).toHaveLength(2)
+ expect(JSON.stringify(after[0])).toBe(first)
+ expect(after[1].created_at).toBeGreaterThan(after[0].created_at)
+ })
+
+ it('a failed mirror retries on its own, never blocks the sidecar or the record, and does not reject flush', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10, retryMs: 50 })
+ b.messageFailure.error = new Error('disk full')
+ p.schedule(session('a'))
+ await p.flush() // resolves: the authoritative data is durable
+ expect(b.extras.has('a')).toBe(true)
+ expect(b.threads.has('a')).toBe(true)
+ expect(b.logs.has('a')).toBe(false)
+ b.messageFailure.error = null
+ await vi.advanceTimersByTimeAsync(100)
+ await p.flush()
+ expect(b.logs.has('a')).toBe(true)
+ })
+
+ it('a failed mirror does not stop a later sidecar write from landing', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10, retryMs: 10_000 })
+ p.schedule(session('a'))
+ await p.flush()
+ b.messageFailure.error = new Error('disk full')
+ p.schedule(session('a', { title: 'newer', turns: [], messages: [], cleared: true }))
+ await p.flush()
+ expect(b.extras.get('a').turns).toHaveLength(0)
+ expect(b.threads.get('a')!.title).toBe('newer')
+ })
+
+ it('a PERMANENT mirror refusal is reported once and not retried', async () => {
+ const onError = vi.fn()
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10, retryMs: 20, onError })
+ b.messageFailure.error = new Error('PERMANENT: Thread has messages but no thread.json')
+ p.schedule(session('a'))
+ await p.flush()
+ const errors = onError.mock.calls.length
+ await vi.advanceTimersByTimeAsync(500)
+ expect(onError.mock.calls.length).toBe(errors)
+ expect(b.extras.has('a')).toBe(true)
+ })
+
+ it('a missing thread during a later write flags the session instead of recreating it', async () => {
+ const onThreadMissing = vi.fn()
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10, onThreadMissing })
+ p.schedule(session('a'))
+ await p.flush()
+ b.threads.delete('a') // deleted underneath us
+ p.schedule(session('a', { title: 'late' }))
+ await p.flush()
+ expect(onThreadMissing).toHaveBeenCalledWith('a', expect.anything())
+ expect(b.threads.has('a')).toBe(false)
+ })
+
+ it('delete drops a pending mirror and removes the log with the thread', async () => {
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ p.schedule(session('a'))
+ await p.flush()
+ p.schedule(session('a', { title: 'x', messages: [] }))
+ await p.remove('a')
+ await vi.advanceTimersByTimeAsync(100)
+ expect(b.logs.has('a')).toBe(false)
+ expect(b.threads.has('a')).toBe(false)
+ })
+
+ it('a crash between the sidecar and thread.json lists nothing, and the retry replaces (never appends)', async () => {
+ let crash = true
+ const flaky = async (cmd: string, args: any) => {
+ if (cmd === 'create_thread' && crash) {
+ crash = false
+ throw new Error('process died')
+ }
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(flaky as any, { debounceMs: 10, retryMs: 20 })
+ p.schedule(session('a'))
+ await vi.advanceTimersByTimeAsync(15)
+ expect(b.threads.has('a')).toBe(false) // not committed, so not listed
+ await vi.advanceTimersByTimeAsync(100)
+ await p.flush()
+ expect(b.threads.has('a')).toBe(true)
+ expect(b.logs.get('a')).toHaveLength(1)
+ })
+})
+
+describe('legacy sessions and the deletion journal', () => {
+ let b: ReturnType<typeof makeBackend>
+ beforeEach(() => {
+ vi.useFakeTimers()
+ b = makeBackend()
+ })
+ afterEach(() => vi.useRealTimers())
+
+ it('a legacy session edited during the background migration is written only after it settles', async () => {
+ let release!: () => void
+ const legacyGate = new Promise<void>((r) => (release = r))
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10, legacyGate })
+ p.schedule(session('legacy'), { legacy: true })
+ p.schedule(session('fresh'))
+ await vi.advanceTimersByTimeAsync(50)
+ expect(b.extras.has('fresh')).toBe(true) // a non-legacy session is never held back
+ expect(b.extras.has('legacy')).toBe(false)
+ release()
+ await p.flush()
+ expect(b.extras.has('legacy')).toBe(true)
+ })
+
+ it('a rejected gate still releases the held write', async () => {
+ const p = createCoworkPersistence(b.invoke, {
+ debounceMs: 10,
+ legacyGate: Promise.reject(new Error('migration blew up')),
+ })
+ p.schedule(session('legacy'), { legacy: true })
+ await p.flush()
+ expect(b.extras.has('legacy')).toBe(true)
+ })
+
+ it('a deleted legacy session is journaled and never comes back from the untouched blob', async () => {
+ b.settings.set(
+ CODE_SESSIONS_KEY,
+ JSON.stringify({ state: { sessions: [session('gone'), session('stay')] }, version: 1 })
+ )
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ await p.remove('gone', { recordDeleted: true })
+ const blobBefore = b.settings.get(CODE_SESSIONS_KEY)
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: false })
+ expect(r.sessions.map((s) => s.id)).toEqual(['stay'])
+ expect(b.settings.get(CODE_SESSIONS_KEY)).toBe(blobBefore) // rollback source untouched
+ })
+
+ it('a migrated id whose thread is gone stays deleted; a present one is not duplicated', async () => {
+ b.settings.set(
+ CODE_SESSIONS_KEY,
+ JSON.stringify({ state: { sessions: [session('m-gone'), session('m-here')] }, version: 1 })
+ )
+ b.settings.set(COWORK_MIGRATED_IDS_KEY, JSON.stringify(['m-gone', 'm-here']))
+ b.threads.set('m-here', sessionToThreadRecord(session('m-here')))
+ b.extras.set('m-here', {
+ version: 1,
+ turns: session('m-here').turns,
+ messages: session('m-here').messages,
+ })
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: false })
+ expect(r.sessions.map((s) => s.id)).toEqual(['m-here'])
+ })
+
+ it('an abandoned legacy session stays visible but read-only (never written)', async () => {
+ b.settings.set(
+ CODE_SESSIONS_KEY,
+ JSON.stringify({ state: { sessions: [session('bad')] }, version: 1 })
+ )
+ b.settings.set(
+ COWORK_MIGRATION_ABANDONED_KEY,
+ JSON.stringify([{ id: 'bad', error: 'PERMANENT: nope' }])
+ )
+ // Even a settled migration shows it: nothing disappears silently.
+ const r = await loadCoworkSessions(b.invoke, { migrationSettled: true })
+ expect(r.sessions.map((s) => [s.id, s.unavailable])).toEqual([['bad', 'id-collision']])
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10 })
+ p.schedule(r.sessions[0])
+ await p.flush()
+ expect(b.extras.has('bad')).toBe(false)
+ })
+
+ it('a PERMANENT write refusal stops retries and reports the session once', async () => {
+ const onWriteRefused = vi.fn()
+ const refusing = async (cmd: string, args: any) => {
+ if (cmd === 'write_thread_extra') throw new Error('PERMANENT: Invalid thread id')
+ return b.invoke(cmd, args)
+ }
+ const p = createCoworkPersistence(refusing as any, {
+ debounceMs: 10,
+ retryMs: 20,
+ onWriteRefused,
+ })
+ p.schedule(session('a'))
+ await p.flush()
+ await vi.advanceTimersByTimeAsync(500)
+ expect(onWriteRefused).toHaveBeenCalledTimes(1)
+ expect(b.threads.has('a')).toBe(false)
+ })
+
+ it('edits made in the shared thread list (rename, favorite, order, project) survive the next write-through', async () => {
+ const live: Json = {}
+ const p = createCoworkPersistence(b.invoke, { debounceMs: 10, liveRecord: () => live })
+ const s = session('a')
+ p.schedule(s)
+ await p.flush()
+ live.title = 'Renamed by the user'
+ live.metadata = {
+ titleSetManually: true,
+ is_favorite: true,
+ order: 3,
+ project: { id: 'p', name: 'P', updated_at: 1 },
+ }
+ p.schedule({
+ ...s,
+ title: 'Auto title',
+ turns: [...s.turns, { role: 'assistant', content: 'more' }],
+ })
+ await p.flush()
+ const rec = b.threads.get('a')!
+ expect(rec.title).toBe('Renamed by the user')
+ expect(rec.metadata.is_favorite).toBe(true)
+ expect(rec.metadata.order).toBe(3)
+ expect(rec.metadata.project.id).toBe('p')
+ })
+})
diff --git a/web-app/src/lib/__tests__/coworkSync.test.ts b/web-app/src/lib/__tests__/coworkSync.test.ts
new file mode 100644
index 000000000..ed056e519
--- /dev/null
+++ b/web-app/src/lib/__tests__/coworkSync.test.ts
@@ -0,0 +1,495 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+type Json = Record<string, any>
+
+// One in-memory backend serves the migration (through the service hub) and the
+// write-through, with the Rust commands' semantics.
+const backend = vi.hoisted(() => {
+ const settings = new Map<string, string>()
+ const threads = new Map<string, any>()
+ const extras = new Map<string, any>()
+ const logs = new Map<string, any[]>()
+ const log: string[] = []
+ const hooks: { before?: (cmd: string, args: Record<string, any>) => Promise<void> } = {}
+ const invoke = async (cmd: string, args: Record<string, any> = {}) => {
+ log.push(cmd)
+ await hooks.before?.(cmd, args)
+ switch (cmd) {
+ case 'settings_get':
+ return settings.get(args.key) ?? null
+ case 'settings_set':
+ settings.set(args.key, args.value)
+ return
+ case 'settings_remove':
+ settings.delete(args.key)
+ return
+ case 'list_threads':
+ return [...threads.values()].map((t) => JSON.parse(JSON.stringify(t)))
+ case 'write_thread_extra':
+ if (!args.create && !threads.has(args.threadId))
+ throw new Error('thread_missing: Thread has no thread.json')
+ extras.set(args.threadId, JSON.parse(JSON.stringify(args.value)))
+ return
+ case 'read_thread_extra':
+ return extras.get(args.threadId) ?? null
+ case 'replace_thread_messages':
+ if (!args.create && !threads.has(args.threadId))
+ throw new Error('thread_missing: Thread has no thread.json')
+ logs.set(args.threadId, JSON.parse(JSON.stringify(args.messages)))
+ return
+ case 'list_messages':
+ return logs.get(args.threadId) ?? []
+ case 'create_thread':
+ if (threads.has(args.thread.id)) return threads.get(args.thread.id)
+ threads.set(args.thread.id, JSON.parse(JSON.stringify(args.thread)))
+ return args.thread
+ case 'modify_thread':
+ if (!threads.has(args.thread.id))
+ throw new Error('thread_missing: Thread does not exist')
+ threads.set(args.thread.id, JSON.parse(JSON.stringify(args.thread)))
+ return
+ case 'delete_thread':
+ threads.delete(args.threadId)
+ extras.delete(args.threadId)
+ logs.delete(args.threadId)
+ return
+ default:
+ throw new Error(`unexpected ${cmd}`)
+ }
+ }
+ return { settings, threads, extras, logs, log, hooks, invoke }
+})
+
+const platform = vi.hoisted(() => ({ tauri: true }))
+vi.mock('@/lib/platform/utils', () => ({
+ isPlatformTauri: () => platform.tauri,
+ isPlatformIOS: () => false,
+ isPlatformAndroid: () => false,
+}))
+vi.mock('@/hooks/useServiceHub', () => ({
+ getServiceHub: () => ({
+ core: () => ({ invoke: backend.invoke }),
+ threads: () => ({ deleteThread: vi.fn(async () => {}) }),
+ }),
+}))
+const agentTools = vi.hoisted(() => ({
+ cleanupThreadWorkspace: vi.fn().mockResolvedValue(undefined),
+ copySessionWorkspaceToThread: vi.fn().mockResolvedValue({ copied: true }),
+ cancelAgentThreadBash: vi.fn().mockResolvedValue(undefined),
+ stopAgentSessionMonitors: vi.fn().mockResolvedValue(undefined),
+}))
+vi.mock('@/lib/agentTools', () => agentTools)
+const sonner = vi.hoisted(() => ({ warning: vi.fn(), error: vi.fn(), dismiss: vi.fn() }))
+vi.mock('sonner', () => ({ toast: sonner }))
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ i18n: { t: (key: string) => key },
+}))
+const closeWindow = vi.hoisted(() => ({
+ callback: null as null | ((event: { preventDefault: () => void }) => Promise<void>),
+}))
+vi.mock('@tauri-apps/api/window', () => ({
+ getCurrentWindow: () => ({
+ onCloseRequested: vi.fn(async (callback) => {
+ closeWindow.callback = callback
+ return () => {}
+ }),
+ }),
+}))
+
+import { useCoworkSessions } from '@/hooks/useCoworkSessions'
+import { registerCoworkRunForClose, isCoworkClosing } from '@/hooks/useCoworkRun'
+import { useThreads } from '@/hooks/useThreads'
+import {
+ startCoworkSync,
+ flushCowork,
+ flushCoworkDeletes,
+ flushCoworkStartupWarnings,
+ isCoworkMigrationDone,
+ COWORK_MIGRATION_BUDGET_MS,
+ __resetCoworkSyncForTests,
+} from '../coworkSync'
+import {
+ CODE_SESSIONS_KEY,
+ COWORK_DELETED_IDS_KEY,
+ COWORK_MIGRATION_FLAG_KEY,
+} from '../migrateCoworkSessions'
+import { coworkSessionToThreadMessages } from '../coworkThreadMessages'
+
+const legacy = (id: string, extra: Json = {}): Json => ({
+ id,
+ title: 'Legacy ' + id,
+ folder: null,
+ turns: [{ role: 'user', content: 'hi' }],
+ messages: [{ id: 'm', role: 'user', parts: [{ type: 'text', text: 'hi' }] }],
+ updated: 1_700_000_000_000,
+ ...extra,
+})
+
+const putBlob = (...sessions: Json[]) =>
+ backend.settings.set(
+ CODE_SESSIONS_KEY,
+ JSON.stringify({ state: { sessions }, version: 1 })
+ )
+
+const reply = { id: 'm2', role: 'assistant', parts: [{ type: 'text', text: 'ok' }] }
+
+describe('coworkSync', () => {
+ beforeEach(() => {
+ backend.settings.clear()
+ backend.threads.clear()
+ backend.extras.clear()
+ backend.logs.clear()
+ backend.log.length = 0
+ backend.hooks.before = undefined
+ agentTools.cleanupThreadWorkspace.mockClear()
+ sonner.warning.mockClear()
+ sonner.dismiss.mockClear()
+ platform.tauri = true
+ closeWindow.callback = null
+ __resetCoworkSyncForTests()
+ useCoworkSessions.setState({ sessions: [], currentId: null })
+ useThreads.setState({ threads: {} })
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ describe('startup', () => {
+ it('migrates legacy sessions into threads, then loads them into the store', async () => {
+ putBlob(legacy('a'), legacy('b'))
+ await startCoworkSync()
+ expect(backend.threads.get('a')!.metadata.mode).toBe('cowork')
+ expect(useCoworkSessions.getState().sessions.map((s) => s.id).sort()).toEqual(['a', 'b'])
+ expect(backend.settings.get(COWORK_MIGRATION_FLAG_KEY)).toBe('true')
+ expect(isCoworkMigrationDone()).toBe(true)
+ // The legacy blob is the rollback source and is never touched.
+ expect(backend.settings.has(CODE_SESSIONS_KEY)).toBe(true)
+ // Cowork threads reach the shared thread list (search, sidebar) exactly once.
+ expect(useThreads.getState().threads['a']).toBeTruthy()
+ expect(Object.keys(useThreads.getState().threads).sort()).toEqual(['a', 'b'])
+ })
+
+ it('hydration itself writes nothing back', async () => {
+ putBlob(legacy('a'))
+ await startCoworkSync()
+ await flushCowork()
+ const writes = backend.log.filter((c) =>
+ ['write_thread_extra', 'modify_thread', 'replace_thread_messages'].includes(c)
+ )
+ // The only writes are the migration's own (one sidecar, one messages log).
+ expect(writes.sort()).toEqual(['replace_thread_messages', 'write_thread_extra'])
+ })
+
+ it('is a no-op off the desktop app', async () => {
+ platform.tauri = false
+ await startCoworkSync()
+ expect(backend.log).toEqual([])
+ })
+
+ it('runs once for concurrent callers and a failed start is retried', async () => {
+ putBlob(legacy('a'))
+ await Promise.all([startCoworkSync(), startCoworkSync()])
+ expect(backend.log.filter((c) => c === 'list_threads').length).toBeLessThanOrEqual(2)
+ const before = backend.log.length
+ await startCoworkSync()
+ expect(backend.log.length).toBe(before)
+ })
+
+ it('a session created before hydration finished is kept and wins over the loaded copy', async () => {
+ putBlob(legacy('a', { title: 'On disk' }))
+ useCoworkSessions.setState({
+ sessions: [
+ { id: 'a', title: 'In memory', folder: null, turns: [], messages: [], updated: 5 } as any,
+ { id: 'early', title: 'Early', folder: null, turns: [], messages: [], updated: 6 } as any,
+ ],
+ currentId: 'early',
+ })
+ await startCoworkSync()
+ const byId = Object.fromEntries(useCoworkSessions.getState().sessions.map((s) => [s.id, s]))
+ expect(byId.a.title).toBe('In memory')
+ expect(byId.early).toBeTruthy()
+ expect(useCoworkSessions.getState().currentId).toBe('early')
+ })
+
+ it('surfaces an unreadable deletion journal and flushes the warning after the toaster mounts', async () => {
+ putBlob(legacy('a'))
+ backend.settings.set(COWORK_DELETED_IDS_KEY, '{corrupt')
+ // The migration fails closed on the journal, leaving the blob unsettled.
+ await startCoworkSync()
+ expect(sonner.warning).toHaveBeenCalledWith(
+ 'common:coworkSync.journalUnreadableTitle',
+ expect.objectContaining({
+ id: 'cowork-deletion-journal-unreadable',
+ description: 'common:coworkSync.journalUnreadableDescription',
+ })
+ )
+ sonner.warning.mockClear()
+ flushCoworkStartupWarnings()
+ expect(sonner.warning).toHaveBeenCalledTimes(1)
+ // The corrupt bytes are never rewritten.
+ expect(backend.settings.get(COWORK_DELETED_IDS_KEY)).toBe('{corrupt')
+ })
+ })
+
+ describe('write-through', () => {
+ it('a new session is persisted as thread + sidecar + converted messages, sidecar first and thread.json last', async () => {
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().setMessages(id, legacy('x').messages)
+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'hi' } as any], legacy('x').messages, [])
+ await flushCowork()
+ const order = backend.log.filter((c) =>
+ ['write_thread_extra', 'replace_thread_messages', 'create_thread'].includes(c)
+ )
+ expect(order).toEqual(['write_thread_extra', 'replace_thread_messages', 'create_thread'])
+ const session = useCoworkSessions.getState().sessions.find((s) => s.id === id)!
+ expect(backend.extras.get(id).messages).toEqual(session.messages)
+ expect(backend.logs.get(id)!.length).toBe(coworkSessionToThreadMessages(session).length)
+ expect(useThreads.getState().threads[id]).toBeTruthy()
+ })
+
+ it('an untouched blank session is never written', async () => {
+ await startCoworkSync()
+ useCoworkSessions.getState().createSession()
+ await flushCowork()
+ expect(backend.threads.size).toBe(0)
+ })
+
+ it('a reload sees exactly what was written (hydration reads the sidecar)', async () => {
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().setFolder(id, '/work')
+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'hi' } as any], legacy('x').messages, [])
+ useCoworkSessions.getState().setTitle(id, 'Named')
+ await flushCowork()
+ const before = useCoworkSessions.getState().sessions.find((s) => s.id === id)!
+
+ __resetCoworkSyncForTests()
+ useCoworkSessions.setState({ sessions: [], currentId: null })
+ useThreads.setState({ threads: {} })
+ await startCoworkSync()
+ const after = useCoworkSessions.getState().sessions.find((s) => s.id === id)!
+ expect(after.title).toBe('Named')
+ expect(after.folder).toBe('/work')
+ expect(after.messages).toEqual(before.messages)
+ expect(after.turns).toEqual(before.turns)
+ })
+
+ it('a migrated thread keeps its message stamps when the live session appends a turn', async () => {
+ putBlob(legacy('a'))
+ await startCoworkSync()
+ await flushCowork()
+ const migrated = JSON.stringify(backend.logs.get('a')![0])
+ const s = useCoworkSessions.getState().sessions.find((x) => x.id === 'a')!
+ useCoworkSessions.getState().commitTurns(
+ 'a',
+ [{ role: 'assistant', content: 'ok' } as any],
+ [...s.messages, reply as any],
+ []
+ )
+ await flushCowork()
+ const after = backend.logs.get('a')!
+ expect(after).toHaveLength(2)
+ expect(JSON.stringify(after[0])).toBe(migrated)
+ })
+
+ it('a thread deleted underneath a live session flags it unavailable and stops writing', async () => {
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'hi' } as any], legacy('x').messages, [])
+ await flushCowork()
+ backend.threads.delete(id)
+ useCoworkSessions.getState().setTitle(id, 'late')
+ await flushCowork()
+ expect(useCoworkSessions.getState().sessions.find((s) => s.id === id)!.unavailable).toBe('missing-thread')
+ expect(sonner.warning).toHaveBeenCalledWith(
+ 'common:coworkSync.missingThreadTitle',
+ expect.objectContaining({ id: `cowork-missing-thread-${id}` })
+ )
+ expect(backend.threads.has(id)).toBe(false)
+ })
+ })
+
+ describe('deletion', () => {
+ it('deleting a session removes its thread and sandbox, and the thread list row', async () => {
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'hi' } as any], legacy('x').messages, [])
+ await flushCowork()
+ useCoworkSessions.getState().deleteSession(id)
+ await flushCoworkDeletes()
+ expect(backend.threads.has(id)).toBe(false)
+ expect(useThreads.getState().threads[id]).toBeUndefined()
+ expect(agentTools.cleanupThreadWorkspace).toHaveBeenCalledWith(id)
+ })
+
+ it('while the migration is unsettled the deletion is journaled; after a restart it stays deleted and the blob is untouched', async () => {
+ putBlob(legacy('a'), legacy('b'))
+ // Make the migration fail transiently so the blob stays live.
+ agentTools.copySessionWorkspaceToThread.mockRejectedValueOnce(new Error('disk busy'))
+ await startCoworkSync()
+ expect(isCoworkMigrationDone()).toBe(false)
+ const blob = backend.settings.get(CODE_SESSIONS_KEY)
+ useCoworkSessions.getState().deleteSession('a')
+ await flushCoworkDeletes()
+ expect(JSON.parse(backend.settings.get(COWORK_DELETED_IDS_KEY)!)).toContain('a')
+
+ __resetCoworkSyncForTests()
+ useCoworkSessions.setState({ sessions: [], currentId: null })
+ useThreads.setState({ threads: {} })
+ await startCoworkSync()
+ expect(useCoworkSessions.getState().sessions.map((s) => s.id)).toEqual(['b'])
+ expect(backend.threads.has('a')).toBe(false)
+ expect(backend.settings.get(CODE_SESSIONS_KEY)).toBe(blob)
+ })
+
+ it('a failed delete restores the session and reports the failure on flush', async () => {
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'hi' } as any], legacy('x').messages, [])
+ await flushCowork()
+ backend.hooks.before = async (cmd) => {
+ if (cmd === 'delete_thread') throw new Error('permission denied')
+ }
+ useCoworkSessions.getState().deleteSession(id)
+ await expect(flushCoworkDeletes()).rejects.toThrow('permission denied')
+ expect(useCoworkSessions.getState().sessions.some((s) => s.id === id)).toBe(true)
+ })
+
+ it('deleting the thread from the shared thread list goes through the session store', async () => {
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'hi' } as any], legacy('x').messages, [])
+ await flushCowork()
+ useThreads.getState().deleteThread(id)
+ await flushCoworkDeletes()
+ expect(useCoworkSessions.getState().sessions.some((s) => s.id === id)).toBe(false)
+ expect(backend.threads.has(id)).toBe(false)
+ })
+
+ it('Delete All spares Cowork conversations', async () => {
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'hi' } as any], legacy('x').messages, [])
+ await flushCowork()
+ useThreads.getState().deleteAllThreads()
+ await flushCoworkDeletes()
+ expect(useThreads.getState().threads[id]).toBeTruthy()
+ expect(backend.threads.has(id)).toBe(true)
+ })
+ })
+
+ describe('a migration that overruns its startup budget', () => {
+ it('renders without waiting, then brings in the migrated sessions and holds back legacy writes until it settles', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ putBlob(legacy('a'), legacy('b'))
+ let release!: () => void
+ const gate = new Promise<void>((r) => (release = r))
+ backend.hooks.before = async (cmd) => {
+ if (cmd === 'replace_thread_messages') await gate
+ }
+ const started = startCoworkSync()
+ await vi.advanceTimersByTimeAsync(COWORK_MIGRATION_BUDGET_MS + 100)
+ await started
+ expect(isCoworkMigrationDone()).toBe(false)
+ // Legacy-only sessions are visible meanwhile, nothing is lost.
+ expect(useCoworkSessions.getState().sessions.map((s) => s.id).sort()).toEqual(['a', 'b'])
+ // The user edits a legacy session before the migration reaches it.
+ useCoworkSessions.getState().setTitle('a', 'Edited meanwhile')
+ await vi.advanceTimersByTimeAsync(1500)
+ expect(backend.threads.get('a')).toBeUndefined()
+ release()
+ await vi.advanceTimersByTimeAsync(200)
+ await flushCowork()
+ expect(isCoworkMigrationDone()).toBe(true)
+ // The newer write-through wins over the blob's older copy.
+ expect(backend.threads.get('a')!.title).toBe('Edited meanwhile')
+ expect(backend.threads.has('b')).toBe(true)
+ })
+
+ it('a session deleted while the migration was still running does not come back', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ putBlob(legacy('a'), legacy('b'))
+ let release!: () => void
+ const gate = new Promise<void>((r) => (release = r))
+ backend.hooks.before = async (cmd) => {
+ if (cmd === 'write_thread_extra') await gate
+ }
+ const started = startCoworkSync()
+ await vi.advanceTimersByTimeAsync(COWORK_MIGRATION_BUDGET_MS + 100)
+ await started
+ useCoworkSessions.getState().deleteSession('a')
+ await vi.advanceTimersByTimeAsync(50)
+ release()
+ await vi.advanceTimersByTimeAsync(500)
+ await flushCoworkDeletes()
+ await flushCowork()
+ expect(useCoworkSessions.getState().sessions.map((s) => s.id)).toEqual(['b'])
+ expect(JSON.parse(backend.settings.get(COWORK_DELETED_IDS_KEY)!)).toContain('a')
+ expect(backend.threads.has('a')).toBe(false)
+ expect(useThreads.getState().threads['a']).toBeUndefined()
+ })
+ })
+
+ describe('window close', () => {
+ const closeEvent = () => ({ preventDefault: vi.fn() })
+
+ it('waits for live runs to commit, then flushes every write, before letting the window close', async () => {
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ let commit!: () => void
+ const committed = new Promise<void>((r) => (commit = r))
+ registerCoworkRunForClose(async () => {
+ await committed
+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'last words' } as any], legacy('x').messages, [])
+ })
+ const event = closeEvent()
+ let done = false
+ const closing = closeWindow.callback!(event).then(() => (done = true))
+ await Promise.resolve()
+ expect(done).toBe(false)
+ commit()
+ await closing
+ expect(event.preventDefault).not.toHaveBeenCalled()
+ // The run's final commit made it to disk before the close resolved.
+ expect(backend.extras.get(id).turns).toEqual([{ role: 'user', content: 'last words' }])
+ expect(backend.threads.has(id)).toBe(true)
+ })
+
+ it('prevents the close when a write cannot be flushed, keeps the unsaved session, and a retry succeeds', async () => {
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'keep' } as any], legacy('x').messages, [])
+ let failing = true
+ backend.hooks.before = async (cmd) => {
+ if (failing && cmd === 'write_thread_extra') throw new Error('disk full')
+ }
+ const first = closeEvent()
+ await closeWindow.callback!(first)
+ expect(first.preventDefault).toHaveBeenCalled()
+ expect(isCoworkClosing()).toBe(false)
+ expect(useCoworkSessions.getState().sessions.some((s) => s.id === id)).toBe(true)
+ failing = false
+ const second = closeEvent()
+ await closeWindow.callback!(second)
+ expect(second.preventDefault).not.toHaveBeenCalled()
+ expect(backend.extras.get(id).turns).toHaveLength(1)
+ })
+
+ it('a failing derived messages mirror never traps the window open', async () => {
+ await startCoworkSync()
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().commitTurns(id, [{ role: 'user', content: 'keep' } as any], legacy('x').messages, [])
+ backend.hooks.before = async (cmd) => {
+ if (cmd === 'replace_thread_messages') throw new Error('mirror broke')
+ }
+ const event = closeEvent()
+ await closeWindow.callback!(event)
+ expect(event.preventDefault).not.toHaveBeenCalled()
+ expect(backend.extras.has(id)).toBe(true)
+ })
+ })
+})
diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.ts
index 8d9885fc1..6142fe6d2 100644
--- a/web-app/src/lib/agentTools.ts
+++ b/web-app/src/lib/agentTools.ts
@@ -414,6 +414,13 @@ export async function cancelAgentThreadBash(sessionId: string): Promise<void> {
}
}
+/** Close must confirm native teardown rather than treating it as best-effort. */
+export async function cancelAgentThreadBashStrict(
+ sessionId: string
+): Promise<void> {
+ await cancelThreadBash(sessionId)
+}
+
/** A file claimed for a subagent's answer: the name to fill it by, and its
* real path in the session scratch, which the parent agent can `read`. */
export type SubagentResultFile = { file: string; path: string }
diff --git a/web-app/src/lib/coworkDelete.ts b/web-app/src/lib/coworkDelete.ts
new file mode 100644
index 000000000..88ce1cb40
--- /dev/null
+++ b/web-app/src/lib/coworkDelete.ts
@@ -0,0 +1,28 @@
+import { useCoworkSessions } from '@/hooks/useCoworkSessions'
+import { useCoworkRun } from '@/hooks/useCoworkRun'
+import { abortRun } from '@/lib/coworkRunner'
+import { dropMonitorLane } from '@/lib/coworkMonitor'
+import { cancelAgentThreadBash, stopAgentSessionMonitors } from '@/lib/agentTools'
+
+/**
+ * Whether a Cowork session with this id is live in the session store. While it
+ * is, the store (via `coworkSync`) owns the thread's persistence and deletion.
+ */
+export const hasCoworkSession = (id: string): boolean =>
+ useCoworkSessions.getState().sessions.some((s) => s.id === id)
+
+/**
+ * Delete a Cowork conversation from anywhere (the shared thread list, a bulk
+ * delete). A running turn and its watchers die with it, and the removal goes
+ * through the session store so `coworkSync` journals it, deletes the thread and
+ * reclaims the sandbox. Deleting the thread record behind the store's back would
+ * leave a live session that fails its next write.
+ */
+export function deleteCoworkConversation(id: string): void {
+ abortRun(id)
+ void cancelAgentThreadBash(id)
+ void stopAgentSessionMonitors(id)
+ dropMonitorLane(id)
+ useCoworkRun.getState().clearMonitors(id)
+ useCoworkSessions.getState().deleteSession(id)
+}
diff --git a/web-app/src/lib/coworkPersistence.ts b/web-app/src/lib/coworkPersistence.ts
new file mode 100644
index 000000000..3d4d88ec3
--- /dev/null
+++ b/web-app/src/lib/coworkPersistence.ts
@@ -0,0 +1,860 @@
+import type { CoworkSession } from '@/hooks/useCoworkSessions'
+import {
+ CODE_SESSIONS_KEY,
+ COWORK_DELETED_IDS_KEY,
+ COWORK_MIGRATED_IDS_KEY,
+ COWORK_MIGRATION_ABANDONED_KEY,
+ COWORK_SIDECAR,
+ PERMANENT_ERROR_PREFIX,
+ readAbandoned,
+ readCoworkSessions,
+ readDeletedIds,
+ readIds,
+ sameJson,
+ sessionToSidecar,
+ type CoworkSidecar,
+ type Invoke,
+} from '@/lib/migrateCoworkSessions'
+import {
+ coworkSessionToThreadMessages,
+ defaultAnchorMs,
+} from '@/lib/coworkThreadMessages'
+
+/**
+ * Persistence for Cowork sessions stored as threads (`metadata.mode =
+ * "cowork"`): `thread.json` for the list fields, `cowork.json` for the
+ * transcript.
+ *
+ * Protocol:
+ * - One serialized write queue per session; a newer snapshot never races an
+ * older one. Writes are debounced; `flush()` awaits queued AND in-flight work.
+ * - A failed write keeps the session dirty and retries; nothing is dropped.
+ * - First commit is sidecar-first, `thread.json` last. Later writes go sidecar
+ * then `thread.json`, which is a read-modify-write that spreads the metadata
+ * already on disk.
+ * - Deleting tombstones the id first: pending timers are cancelled, an
+ * in-flight write is drained, late writes for the id are dropped, then the
+ * thread directory is deleted. The backend refuses sidecar writes for a thread
+ * with no `thread.json`, so a straggler cannot resurrect it.
+ * - The sidecar is the transcript authority and what hydration reads. After it
+ * is written, the transcript is also mirrored into `messages.jsonl`
+ * (`replace_thread_messages`, converted by `coworkSessionToThreadMessages`) so
+ * the CLI, search and extensions can read the thread. The mirror is a derived
+ * projection: a failed mirror never blocks the sidecar or the thread record,
+ * it only keeps the session dirty so the next attempt retries it.
+ * - A session never persisted and still empty is not written; a persisted
+ * session that becomes empty (/clear, rewind) IS written.
+ * - Sessions flagged `unavailable` are shown but never written back.
+ */
+
+export const COWORK_CURRENT_ID_KEY = 'cowork_current_id'
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type Json = Record<string, any>
+
+const toSeconds = (ms: number) => (ms > 1e12 ? Math.floor(ms / 1000) : ms)
+
+// A cleared session was used: it is never a droppable blank placeholder.
+const isEmpty = (s: CoworkSession) =>
+ !s.cleared && (s.turns?.length ?? 0) === 0 && (s.messages?.length ?? 0) === 0
+
+/**
+ * The thread record for a session. `existing` is the record already on disk:
+ * its other fields and metadata keys (order, is_favorite, ...) are preserved
+ * and `created` is never rewritten.
+ */
+export function sessionToThreadRecord(
+ s: CoworkSession,
+ existing?: Json,
+ legacy = false
+): Json {
+ const seconds = toSeconds(s.updated)
+ const metadata: Json = {
+ ...(existing?.metadata ?? {}),
+ mode: 'cowork',
+ folder: s.folder ?? null,
+ }
+ if (s.folderAccess) metadata.folderAccess = s.folderAccess
+ else delete metadata.folderAccess
+ // `project` can also be assigned from the shared thread list, which the
+ // session store does not see: only a session that carries the key (a set or
+ // an explicit clear) owns it.
+ if (s.project !== undefined) metadata.project = s.project
+ else if ('project' in s) delete metadata.project
+ if (s.planMode !== undefined) metadata.planMode = s.planMode
+ else delete metadata.planMode
+ if (s.goal !== undefined) metadata.goal = s.goal
+ else delete metadata.goal
+ if (s.cleared) metadata.cleared = true
+ else delete metadata.cleared
+ if (legacy && !metadata.migratedFrom) {
+ metadata.migratedFrom = { store: CODE_SESSIONS_KEY, updated: s.updated }
+ }
+ // Anchor of the messages.jsonl stamps: fixed on the first write-through (or
+ // taken from what the migration used, see `loadCoworkSessions`) and kept, so
+ // later turns never move the stamps of earlier messages.
+ if (typeof metadata.messagesAnchorMs !== 'number') {
+ metadata.messagesAnchorMs = defaultAnchorMs(s)
+ }
+ const assistant = existing?.assistants?.[0] ?? { id: 'model-only', name: 'Model' }
+ return {
+ ...(existing ?? {}),
+ id: s.id,
+ object: 'thread',
+ // A rename made in the shared thread list wins over the session's title.
+ title:
+ metadata.titleSetManually === true && typeof existing?.title === 'string'
+ ? existing.title
+ : s.title,
+ assistants: [
+ {
+ ...assistant,
+ model: {
+ id: s.model?.id ?? '*',
+ engine: s.model?.provider ?? 'llamacpp',
+ },
+ },
+ ],
+ created: existing?.created ?? seconds,
+ updated: seconds,
+ metadata,
+ }
+}
+
+/** Rebuild a session from its thread record and sidecar. */
+export function sessionFromThread(
+ thread: Json,
+ sidecar: Partial<CoworkSidecar> | null,
+ unavailable?: CoworkSession['unavailable']
+): CoworkSession {
+ const model = thread.assistants?.[0]?.model
+ const meta = thread.metadata ?? {}
+ const updated = typeof thread.updated === 'number' ? thread.updated : 0
+ return {
+ id: String(thread.id),
+ title: typeof thread.title === 'string' ? thread.title : 'New session',
+ model:
+ model && model.id && model.id !== '*'
+ ? { id: String(model.id), provider: String(model.engine ?? 'llamacpp') }
+ : undefined,
+ folder: typeof meta.folder === 'string' ? meta.folder : null,
+ ...((meta.folderAccess === 'read' || meta.folderAccess === 'write') && {
+ folderAccess: meta.folderAccess as 'read' | 'write',
+ }),
+ ...(meta.project && { project: meta.project }),
+ turns: sidecar?.turns ?? [],
+ messages: sidecar?.messages ?? [],
+ ...(sidecar?.history !== undefined && { history: sidecar.history }),
+ ...(sidecar?.subagents !== undefined && { subagents: sidecar.subagents }),
+ ...(sidecar?.lastUsage !== undefined && { lastUsage: sidecar.lastUsage }),
+ ...(sidecar?.todos !== undefined && { todos: sidecar.todos }),
+ ...(meta.planMode !== undefined && { planMode: meta.planMode }),
+ ...(meta.goal !== undefined && { goal: meta.goal }),
+ ...(meta.cleared === true && { cleared: true as const }),
+ updated: updated * 1000,
+ ...(unavailable && { unavailable }),
+ }
+}
+
+/**
+ * Only consume a sidecar whose shape is the one this build writes
+ * (`sessionToSidecar`: `version: 1` with array `turns`/`messages`, every
+ * sidecar writer since the format exists has written both arrays). Anything
+ * else, a newer format from a future build after a downgrade, or a malformed
+ * v1, must NOT load as an empty-but-writable session: the next touch (rename,
+ * `updated` bump, /clear) would serialize an empty v1 snapshot over the
+ * on-disk bytes. Such sessions are contained as `unreadable-sidecar`: shown
+ * read-only, never written back, bytes preserved.
+ */
+function isConsumableSidecar(side: Partial<CoworkSidecar>): boolean {
+ return (
+ side.version === 1 &&
+ Array.isArray(side.turns) &&
+ Array.isArray(side.messages)
+ )
+}
+
+/** Control flow only: the legacy blob does not need to be read. */
+class SkipBlob extends Error {}
+
+export type LoadedCoworkSessions = {
+ sessions: CoworkSession[]
+ currentId: string | null
+ /** Sessions sourced from the legacy `code-sessions` blob, not yet threads. */
+ legacyIds: Set<string>
+ /** Thread records of the sessions that are already persisted. */
+ threads: Json[]
+ /**
+ * Set when the deletion journal was unreadable and the legacy-blob merge was
+ * therefore skipped (fail closed against resurrecting deleted sessions).
+ * The caller must surface this: it hides legacy sessions on every launch
+ * until the journal is repaired, and is silent data-hiding otherwise.
+ */
+ deletionJournalError?: string
+}
+
+/**
+ * Read every Cowork session. One `list_threads` is the source of truth. While
+ * the migration is unsettled, sessions still only in the legacy blob are added
+ * so a failed migration never makes a session disappear.
+ */
+export async function loadCoworkSessions(
+ invoke: Invoke,
+ opts: { migrationSettled: boolean }
+): Promise<LoadedCoworkSessions> {
+ // The abandoned list is tiny and tells whether a settled migration still
+ // leaves blob sessions to show. The blob itself can be huge, so it is only
+ // read when it matters.
+ let abandonedIds = new Set<string>()
+ try {
+ abandonedIds = new Set(
+ readAbandoned(
+ await invoke<string | null>('settings_get', {
+ key: COWORK_MIGRATION_ABANDONED_KEY,
+ })
+ ).map((a) => a.id)
+ )
+ } catch (e) {
+ console.warn('[cowork] could not read the abandoned list:', e)
+ }
+ const readBlob = !opts.migrationSettled || abandonedIds.size > 0
+ const all = (await invoke<Json[]>('list_threads')) ?? []
+ const coworkThreads = all.filter(
+ (t) => typeof t?.id === 'string' && t.metadata?.mode === 'cowork'
+ )
+ const chatIds = new Set(
+ all
+ .filter((t) => typeof t?.id === 'string' && t.metadata?.mode !== 'cowork')
+ .map((t) => t.id as string)
+ )
+
+ const sessions: CoworkSession[] = await Promise.all(
+ coworkThreads.map(async (t) => {
+ try {
+ const side = await invoke<CoworkSidecar | null>('read_thread_extra', {
+ threadId: t.id,
+ name: COWORK_SIDECAR,
+ })
+ if (!side) return sessionFromThread(t, null, 'missing-sidecar')
+ if (!isConsumableSidecar(side)) {
+ console.warn(
+ `[cowork] sidecar for ${t.id} has an unknown version or shape; showing it read-only`
+ )
+ return sessionFromThread(t, null, 'unreadable-sidecar')
+ }
+ const session = sessionFromThread(t, side)
+ // A thread the migration created carries no anchor: its messages were
+ // stamped from the session's exact `updated`. Record that on the
+ // adopted record (in memory; the first write persists it) so the live
+ // session keeps those stamps instead of re-stamping the whole log.
+ if (typeof t.metadata?.messagesAnchorMs !== 'number') {
+ const exact = t.metadata?.migratedFrom?.updated
+ t.metadata = {
+ ...(t.metadata ?? {}),
+ messagesAnchorMs: defaultAnchorMs(
+ session,
+ typeof exact === 'number' ? exact : undefined
+ ),
+ }
+ }
+ return session
+ } catch (e) {
+ console.warn(`[cowork] unreadable sidecar for ${t.id}:`, e)
+ return sessionFromThread(t, null, 'unreadable-sidecar')
+ }
+ })
+ )
+
+ const legacyIds = new Set<string>()
+ let deletionJournalError: string | undefined
+ try {
+ if (!readBlob) throw new SkipBlob()
+ const have = new Set(sessions.map((s) => s.id))
+ const blob = readCoworkSessions(
+ await invoke<string | null>('settings_get', { key: CODE_SESSIONS_KEY })
+ )
+ // A migrated id whose thread is gone was deleted by the user (in main
+ // chat or here), so the untouched blob must not bring it back.
+ const migratedIds = new Set(
+ readIds(
+ await invoke<string | null>('settings_get', {
+ key: COWORK_MIGRATED_IDS_KEY,
+ })
+ )
+ )
+ // An abandoned id can never be written as a thread (an id another
+ // conversation owns, an id the backend refuses). It stays visible so no
+ // session silently disappears, but read-only: a save would fail forever.
+ // Once the migration settled the blob is only consulted for sessions
+ // the migration abandoned, so none of them silently disappears.
+ const mergeable = blob.filter(
+ (s) =>
+ !have.has(s.id) &&
+ !migratedIds.has(s.id) &&
+ !isEmpty(s) &&
+ (!opts.migrationSettled || abandonedIds.has(s.id))
+ )
+ // The journal is read (strictly) only when there is actually something
+ // it could protect: with nothing mergeable, a corrupt journal must not
+ // raise a false warning on every launch. With deletion intent
+ // unreadable AND mergeable sessions present, the merge is skipped
+ // entirely (fail closed against resurrection; committed threads still
+ // load, the corrupt bytes are never rewritten) and the state is
+ // reported to the caller so it is shown to the user, never hidden.
+ if (mergeable.length > 0) {
+ let deleted: Set<string> | null = null
+ try {
+ deleted = await readDeletedIds(invoke)
+ } catch (e) {
+ deletionJournalError = e instanceof Error ? e.message : String(e)
+ console.warn(
+ '[cowork] deletion journal unreadable; skipping the legacy sessions blob:',
+ e
+ )
+ }
+ if (deleted) {
+ for (const s of mergeable) {
+ if (deleted.has(s.id)) continue
+ if (chatIds.has(s.id) || abandonedIds.has(s.id)) {
+ sessions.push({ ...s, unavailable: 'id-collision' })
+ } else {
+ sessions.push(s)
+ legacyIds.add(s.id)
+ }
+ }
+ }
+ }
+ } catch (e) {
+ if (!(e instanceof SkipBlob)) {
+ console.warn('[cowork] skipping the legacy sessions blob:', e)
+ }
+ }
+
+ sessions.sort((a, b) => b.updated - a.updated)
+
+ let currentId: string | null = null
+ try {
+ const saved = await invoke<string | null>('settings_get', {
+ key: COWORK_CURRENT_ID_KEY,
+ })
+ if (saved && sessions.some((s) => s.id === saved)) currentId = saved
+ } catch {
+ /* resume is best effort */
+ }
+
+ return {
+ sessions,
+ currentId,
+ legacyIds,
+ threads: coworkThreads,
+ ...(deletionJournalError !== undefined && { deletionJournalError }),
+ }
+}
+
+/**
+ * True only for the host's stable `thread_missing:` error (see
+ * THREAD_MISSING_ERROR_CODE in src-tauri threads/commands.rs). Transient I/O
+ * failures never carry it, so they keep the bounded dirty/retry path.
+ */
+/** thread.json metadata keys the shared thread list may edit on its own. */
+const LIVE_METADATA_KEYS = [
+ 'is_favorite',
+ 'order',
+ 'project',
+ 'titleSetManually',
+] as const
+
+export function isPermanentError(error: unknown): boolean {
+ return toMessage(error).trimStart().startsWith(PERMANENT_ERROR_PREFIX)
+}
+
+export function isMissingThreadError(error: unknown): boolean {
+ return toMessage(error).startsWith('thread_missing:')
+}
+
+// Tauri commands reject with a string or `{ message }`, plugins with an Error.
+function toMessage(error: unknown): string {
+ if (typeof error === 'string') return error
+ if (error instanceof Error) return error.message
+ const message = (error as { message?: unknown } | null)?.message
+ return typeof message === 'string' ? message : ''
+}
+
+export type CoworkPersistence = {
+ /** Record a new snapshot of a session; written after the debounce. */
+ schedule(session: CoworkSession, opts?: { legacy?: boolean; allowEmpty?: boolean }): void
+ /** Delete a session: tombstone, drain, then delete its thread. */
+ remove(id: string, opts?: { recordDeleted?: boolean; preserveThread?: boolean }): Promise<void>
+ setCurrentId(id: string | null): void
+ /** Seed the known on-disk thread records after hydration. */
+ adopt(threads: Json[]): void
+ isPersisted(id: string): boolean
+ /** Drains queued/in-flight work; rejects if writes remain after bounded retries. */
+ flush(): Promise<void>
+ /**
+ * Bounded, target-only drain: settles just this session's queued/in-flight
+ * write (and its own pending deletion rollback). Never touches other sessions
+ * or the current-id write; rejects if the target is still unwritten.
+ */
+ flushSession(id: string): Promise<void>
+}
+
+export function createCoworkPersistence(
+ invoke: Invoke,
+ opts: {
+ debounceMs?: number
+ retryMs?: number
+ onThreadWritten?: (thread: Json) => void
+ onThreadRemoved?: (id: string) => void
+ onError?: (id: string, error: unknown) => void
+ /**
+ * The host confirmed the session's thread no longer exists. Retries stop and
+ * the in-memory snapshot is kept; the caller should mark it unavailable.
+ */
+ onThreadMissing?: (id: string, session: CoworkSession) => void
+ /**
+ * Held until it settles before any session that is still only in the
+ * legacy blob is written. The background migration copies those sessions
+ * into threads (and would overwrite a newer sidecar with the blob's older
+ * one), so a write-through for the same id must land after it.
+ */
+ legacyGate?: Promise<unknown>
+ /**
+ * The freshest thread-list copy of a thread, in disk shape, so edits made
+ * through the shared thread list are not reverted by the next write.
+ */
+ liveRecord?: (id: string) => Json | undefined
+ /** The host permanently refuses this session's writes (`PERMANENT: ...`). */
+ onWriteRefused?: (id: string, session: CoworkSession) => void
+ } = {}
+): CoworkPersistence {
+ const debounceMs = opts.debounceMs ?? 400
+ const retryMs = opts.retryMs ?? 3000
+
+ const latest = new Map<string, { session: CoworkSession; legacy: boolean }>()
+ const dirty = new Set<string>()
+ const timers = new Map<string, ReturnType<typeof setTimeout>>()
+ const chains = new Map<string, Promise<void>>()
+ // The last thread record THIS layer wrote (or adopted at hydration). The
+ // write-through rebuilds thread.json from it, so an out-of-band edit to a
+ // cowork thread between our writes would be reverted. Acceptable while this
+ // layer is the only cowork thread writer in the process (single-instance
+ // plugin; cowork rows expose no rename/favorite UI); a second writer would
+ // need a re-read or a merge-on-live-record here (as the create-conflict
+ // branch below already does).
+ const persisted = new Map<string, Json>()
+ const tombstones = new Set<string>()
+ // Failed compensation stays queued until flush (no background busy-loop).
+ // Keep its tombstone until the durable deletion intent really is removed.
+ const pendingRollbacks = new Set<string>()
+
+ let deletionJournalChain: Promise<void> = Promise.resolve()
+ const updateDeletionJournal = (update: () => Promise<void>) => {
+ const next = deletionJournalChain.then(update)
+ deletionJournalChain = next.catch(() => {})
+ return next
+ }
+
+ const rollbackDeletion = async (id: string) => {
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try {
+ await updateDeletionJournal(async () => {
+ if (!pendingRollbacks.has(id)) return
+ // Re-read in the shared queue so concurrent deletions are preserved.
+ // The strict read means a mutation can never replace unreadable
+ // deletion intent with an empty set.
+ const ids = await readDeletedIds(invoke)
+ ids.delete(id)
+ await invoke('settings_set', {
+ key: COWORK_DELETED_IDS_KEY,
+ value: JSON.stringify([...ids]),
+ })
+ pendingRollbacks.delete(id)
+ tombstones.delete(id)
+ })
+ return
+ } catch (error) {
+ if (attempt === 2) throw error
+ }
+ }
+ }
+
+ // Sessions whose thread the host confirmed missing: never written again.
+ const missing = new Set<string>()
+ // Sessions the host permanently refuses to write: never written again.
+ const refused = new Set<string>()
+
+ let currentIdDirty = false
+ let currentIdValue: string | null = null
+ let currentIdTimer: ReturnType<typeof setTimeout> | null = null
+ let currentIdChain: Promise<void> = Promise.resolve()
+
+ // Dirty ids a flush must not report success over.
+ const blocking = () => [...dirty].filter((id) => !mirrorOnly.has(id))
+
+ const clearTimer = (id: string) => {
+ const t = timers.get(id)
+ if (t !== undefined) clearTimeout(t)
+ timers.delete(id)
+ }
+
+ // What the last successful mirror was built from. The projection is a pure
+ // function of these, so an unchanged transcript (a title or folder edit) is
+ // not rewritten: the sidecar already carries the whole transcript, and a
+ // second full rewrite per keystroke-sized change would double the cost.
+ // The record on disk can also be edited from the shared thread list (rename,
+ // favorite, order, project), which writes thread.json itself. Overlay the
+ // freshest of those fields onto the record this layer last wrote, so the next
+ // write-through does not revert them.
+ const withLive = (id: string, existing: Json | undefined) => {
+ const live = existing ? opts.liveRecord?.(id) : undefined
+ if (!existing || !live) return existing
+ return {
+ ...existing,
+ ...(typeof live.title === 'string' && live.metadata?.titleSetManually === true
+ ? { title: live.title }
+ : {}),
+ metadata: {
+ ...(existing.metadata ?? {}),
+ ...Object.fromEntries(
+ LIVE_METADATA_KEYS.filter((k) => live.metadata && k in live.metadata).map(
+ (k) => [k, live.metadata?.[k]]
+ )
+ ),
+ },
+ }
+ }
+
+ const mirrored = new Map<
+ string,
+ { messages: CoworkSession['messages']; turns: CoworkSession['turns'] }
+ >()
+
+ // Ids whose only unfinished work is the derived messages.jsonl mirror: the
+ // authoritative sidecar and thread record are already durable. They retry on
+ // the timer and on every flush, but a flush does not REJECT for them, so a
+ // persistently failing projection can never trap the window open on close.
+ const mirrorOnly = new Set<string>()
+
+ const scheduleRetry = (id: string, isMirror: boolean, error?: unknown) => {
+ dirty.add(id)
+ if (isMirror) mirrorOnly.add(id)
+ else mirrorOnly.delete(id)
+ opts.onError?.(id, error ?? new Error('messages mirror failed'))
+ if (!timers.has(id) && !tombstones.has(id)) {
+ timers.set(
+ id,
+ setTimeout(() => {
+ timers.delete(id)
+ enqueue(id)
+ }, retryMs)
+ )
+ }
+ }
+
+ /**
+ * Mirror the transcript into messages.jsonl. Resolves true when it failed
+ * transiently and must be retried; a missing thread propagates (the caller
+ * treats it exactly like a missing sidecar target); a PERMANENT refusal
+ * (a foreign log the backend will not overwrite) is reported once and not
+ * retried, because retrying cannot fix it and the sidecar stays authoritative.
+ */
+ const mirrorMessages = async (
+ id: string,
+ session: CoworkSession,
+ create: boolean,
+ anchorMs: number
+ ): Promise<boolean> => {
+ const last = mirrored.get(id)
+ if (
+ !create &&
+ last &&
+ last.messages === session.messages &&
+ last.turns === session.turns
+ ) {
+ return false
+ }
+ try {
+ await invoke('replace_thread_messages', {
+ threadId: id,
+ messages: coworkSessionToThreadMessages(session, { anchorMs }),
+ create,
+ })
+ mirrored.set(id, { messages: session.messages, turns: session.turns })
+ return false
+ } catch (e) {
+ if (isMissingThreadError(e)) throw e
+ if (isPermanentError(e)) {
+ console.warn(`[cowork] messages mirror refused for ${id}; not retrying:`, e)
+ opts.onError?.(id, e)
+ return false
+ }
+ return true
+ }
+ }
+
+ const writeOnce = async (id: string) => {
+ if (tombstones.has(id)) {
+ if (pendingRollbacks.has(id)) return
+ dirty.delete(id)
+ return
+ }
+ if (!dirty.has(id)) return
+ const entry = latest.get(id)
+ if (!entry) {
+ dirty.delete(id)
+ return
+ }
+ // A mutation that lands while this write is in flight re-marks the id dirty
+ // and queues the next write behind this one.
+ dirty.delete(id)
+ mirrorOnly.delete(id)
+ const { session, legacy } = entry
+ try {
+ if (legacy && opts.legacyGate) await opts.legacyGate.catch(() => undefined)
+ const existing = withLive(id, persisted.get(id))
+ const record = sessionToThreadRecord(session, existing, legacy)
+ // Re-check right before ANY write: a late flush after delete must not
+ // recreate the sidecar (`create: true`) of a deleted session.
+ if (tombstones.has(id)) return
+ await invoke('write_thread_extra', {
+ threadId: id,
+ name: COWORK_SIDECAR,
+ value: sessionToSidecar(session),
+ create: !existing,
+ })
+ if (tombstones.has(id)) return
+ // The derived messages.jsonl projection. Never blocks the record below.
+ // Stamped from the record's fixed anchor, not from the moving `updated`,
+ // so appending never rewrites earlier message stamps.
+ const mirrorFailed = await mirrorMessages(
+ id,
+ session,
+ !existing,
+ Number(record.metadata.messagesAnchorMs)
+ )
+ if (tombstones.has(id)) return
+ if (existing) {
+ await invoke('modify_thread', { thread: record })
+ persisted.set(id, record)
+ opts.onThreadWritten?.(record)
+ } else {
+ const created = await invoke<Json>('create_thread', { thread: record })
+ if (created && !sameJson(created, record)) {
+ // The thread already existed on disk (e.g. migrated earlier): apply
+ // this snapshot on top of what is there.
+ const merged = sessionToThreadRecord(session, created, legacy)
+ await invoke('modify_thread', { thread: merged })
+ persisted.set(id, merged)
+ opts.onThreadWritten?.(merged)
+ } else {
+ persisted.set(id, record)
+ opts.onThreadWritten?.(record)
+ }
+ }
+ if (mirrorFailed) scheduleRetry(id, true)
+ } catch (e) {
+ // The host confirmed the thread is gone (not a transient failure). Never
+ // recreate it (a deleted chat must not resurrect) and never retry: drop the
+ // dirty flag so flush/close settle, keep the snapshot readable in memory.
+ // A pending deletion keeps its normal tombstone/rollback handling instead.
+ if (isMissingThreadError(e) && !tombstones.has(id)) {
+ missing.add(id)
+ dirty.delete(id)
+ clearTimer(id)
+ opts.onError?.(id, e)
+ opts.onThreadMissing?.(id, session)
+ return
+ }
+ // A PERMANENT refusal (an id the backend will never accept, a directory
+ // that is someone else's) repeats forever: stop, keep the in-memory
+ // snapshot, and let the caller flag the session read-only. Nothing on
+ // disk is touched.
+ if (isPermanentError(e) && !tombstones.has(id)) {
+ refused.add(id)
+ dirty.delete(id)
+ clearTimer(id)
+ opts.onError?.(id, e)
+ opts.onWriteRefused?.(id, session)
+ return
+ }
+ scheduleRetry(id, false, e)
+ }
+ }
+
+ const enqueue = (id: string): Promise<void> => {
+ const next = (chains.get(id) ?? Promise.resolve()).then(() => writeOnce(id))
+ chains.set(id, next)
+ return next
+ }
+
+ const writeCurrentId = async () => {
+ if (!currentIdDirty) return
+ currentIdDirty = false
+ try {
+ if (currentIdValue) {
+ await invoke('settings_set', {
+ key: COWORK_CURRENT_ID_KEY,
+ value: currentIdValue,
+ })
+ } else {
+ await invoke('settings_remove', { key: COWORK_CURRENT_ID_KEY })
+ }
+ } catch (e) {
+ currentIdDirty = true
+ opts.onError?.('current-id', e)
+ }
+ }
+
+ const enqueueCurrentId = () => {
+ currentIdChain = currentIdChain.then(writeCurrentId)
+ return currentIdChain
+ }
+
+ return {
+ schedule(session, o) {
+ const id = session.id
+ if ((tombstones.has(id) && !pendingRollbacks.has(id)) || session.unavailable || missing.has(id) || refused.has(id)) return
+ if (!persisted.has(id) && isEmpty(session) && !o?.allowEmpty) return
+ const prev = latest.get(id)
+ latest.set(id, { session, legacy: o?.legacy ?? prev?.legacy ?? false })
+ dirty.add(id)
+ mirrorOnly.delete(id)
+ clearTimer(id)
+ // The sync layer restores failed removals immediately. Retain that
+ // snapshot, but do not write it or claim recovery before compensation.
+ if (pendingRollbacks.has(id)) return
+ timers.set(
+ id,
+ setTimeout(() => {
+ timers.delete(id)
+ enqueue(id)
+ }, debounceMs)
+ )
+ },
+
+ async remove(id, o) {
+ if (pendingRollbacks.has(id)) await rollbackDeletion(id)
+ missing.delete(id)
+ refused.delete(id)
+ tombstones.add(id)
+ clearTimer(id)
+ dirty.delete(id)
+ mirrorOnly.delete(id)
+ mirrored.delete(id)
+ const snapshot = latest.get(id)
+ latest.delete(id)
+ await (chains.get(id) ?? Promise.resolve())
+ let journalAdded = false
+ let deletionCompleted = false
+ try {
+ // Record durable intent before deleting files. The key is shared by
+ // every session, so serialize read-modify-write across bulk removals.
+ if (o?.recordDeleted) {
+ await updateDeletionJournal(async () => {
+ const ids = await readDeletedIds(invoke)
+ if (ids.has(id)) return
+ ids.add(id)
+ await invoke('settings_set', {
+ key: COWORK_DELETED_IDS_KEY,
+ value: JSON.stringify([...ids]),
+ })
+ journalAdded = true
+ })
+ }
+ if (!o?.preserveThread) await invoke('delete_thread', { threadId: id })
+ deletionCompleted = true
+ persisted.delete(id)
+ if (!o?.preserveThread) opts.onThreadRemoved?.(id)
+ } catch (e) {
+ if (journalAdded && !deletionCompleted) {
+ pendingRollbacks.add(id)
+ try {
+ // Undo only this removal's new intent, not a pre-existing marker.
+ await rollbackDeletion(id)
+ } catch (rollbackError) {
+ if (snapshot && !latest.has(id)) {
+ latest.set(id, snapshot)
+ dirty.add(id)
+ }
+ const error = new Error(`${String(e)}; deletion recovery pending: ${String(rollbackError)}`)
+ opts.onError?.(id, error)
+ throw error
+ }
+ }
+ // The authoritative store can restore the session and retry deletion.
+ // Pending compensation instead retains edits and its tombstone above.
+ tombstones.delete(id)
+ opts.onError?.(id, e)
+ throw e
+ }
+ },
+
+ setCurrentId(id) {
+ currentIdValue = id
+ currentIdDirty = true
+ if (currentIdTimer) clearTimeout(currentIdTimer)
+ currentIdTimer = setTimeout(() => {
+ currentIdTimer = null
+ enqueueCurrentId()
+ }, debounceMs)
+ },
+
+ adopt(threads) {
+ for (const t of threads) {
+ // A record this layer wrote is newer than any list read.
+ if (typeof t?.id === 'string' && !persisted.has(t.id)) persisted.set(t.id, t)
+ }
+ },
+
+ isPersisted: (id) => persisted.has(id),
+
+ async flushSession(id) {
+ // A target being deleted (or whose thread the host confirmed gone) must
+ // never report success: the caller would start work on a doomed record.
+ const assertUsable = () => {
+ if (tombstones.has(id)) throw new Error(`Cowork session ${id} is being deleted or was deleted`)
+ if (missing.has(id)) throw new Error(`Cowork session ${id} thread is missing`)
+ if (refused.has(id)) throw new Error(`Cowork session ${id} cannot be written`)
+ }
+ if (pendingRollbacks.has(id)) await rollbackDeletion(id)
+ assertUsable()
+ for (let pass = 0; pass < 3; pass++) {
+ if (dirty.has(id)) {
+ clearTimer(id)
+ enqueue(id)
+ }
+ await (chains.get(id) ?? Promise.resolve())
+ assertUsable()
+ if (!dirty.has(id) || mirrorOnly.has(id)) return
+ }
+ throw new Error(`Cowork persistence flush failed; pending writes: ${id}`)
+ },
+
+ async flush() {
+ // A flush must not report success with failed recovery still queued.
+ // Each call makes bounded attempts; storage failure never spins forever.
+ await Promise.all([...pendingRollbacks].map((id) => rollbackDeletion(id)))
+ await deletionJournalChain
+ for (let pass = 0; pass < 3; pass++) {
+ for (const id of [...dirty]) {
+ clearTimer(id)
+ enqueue(id)
+ }
+ // Include writes already in flight even when they temporarily cleared
+ // their dirty flag. Failures re-mark it before the next pass.
+ await Promise.all([...chains.values()])
+ if (currentIdTimer) {
+ clearTimeout(currentIdTimer)
+ currentIdTimer = null
+ }
+ await enqueueCurrentId()
+ if (blocking().length === 0 && !currentIdDirty) return
+ }
+ // Keep snapshots, dirty flags and session retry timers intact: a later
+ // flush (or background retry) must be able to recover without a new edit.
+ const pending = [...blocking(), ...(currentIdDirty ? ['current-id'] : [])]
+ throw new Error(`Cowork persistence flush failed; pending writes: ${pending.join(', ')}`)
+ },
+ }
+}
diff --git a/web-app/src/lib/coworkSync.ts b/web-app/src/lib/coworkSync.ts
new file mode 100644
index 000000000..f51627f0e
--- /dev/null
+++ b/web-app/src/lib/coworkSync.ts
@@ -0,0 +1,476 @@
+import { toast } from 'sonner'
+import { i18n } from '@/i18n/react-i18next-compat'
+import {
+ quiesceChats,
+ resumeChatsAfterPreventedClose,
+ withChatCloseDeadline,
+} from '@/lib/chatClose'
+import {
+ quiesceCoworkRuns,
+ resumeCoworkAfterPreventedClose,
+ __resetCoworkRunCloseForTests,
+} from '@/hooks/useCoworkRun'
+import { useCoworkSessions, type CoworkSession } from '@/hooks/useCoworkSessions'
+import { useThreads } from '@/hooks/useThreads'
+import { getServiceHub } from '@/hooks/useServiceHub'
+import {
+ isPlatformAndroid,
+ isPlatformIOS,
+ isPlatformTauri,
+} from '@/lib/platform/utils'
+import {
+ createCoworkPersistence,
+ loadCoworkSessions,
+ type CoworkPersistence,
+} from '@/lib/coworkPersistence'
+import {
+ isCoworkMigrationSettled,
+ migrateCoworkSessionsOnStartup,
+ readDeletedIds,
+ type CoworkMigrationResult,
+ type Invoke,
+} from '@/lib/migrateCoworkSessions'
+import { cleanupThreadWorkspace } from '@/lib/agentTools'
+
+/**
+ * Connects the Cowork session store to thread storage.
+ *
+ * Startup, in order: migrate legacy `code-sessions` -> threads (bounded wait),
+ * load Cowork threads, MERGE them into the store (sessions created in the
+ * meantime are kept), mirror them into the shared thread list, then start
+ * write-through. Write-through is not running while the store is being
+ * hydrated, so loading never writes anything back.
+ *
+ * The legacy blob stays alive (it is the rollback source and is never edited),
+ * so two rules keep it from fighting the threads:
+ * - a session deleted while the blob can still be read is recorded in the
+ * `cowork_deleted_ids` journal, which both the migration and the loader honor;
+ * - a legacy session that is edited before the background migration reaches it
+ * is written only after that migration settles (`legacyGate`), so the copy of
+ * the older blob never overwrites the newer write-through.
+ */
+
+/**
+ * How long startup waits for the Cowork migration. Past it the app renders and
+ * the migration keeps running; the sessions are re-loaded when it finishes.
+ */
+export const COWORK_MIGRATION_BUDGET_MS = 3000
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type Json = Record<string, any>
+
+let persistence: CoworkPersistence | null = null
+let unsubscribe: (() => void) | null = null
+let startPromise: Promise<void> | null = null
+let migrationSettled = false
+const pendingDeletes = new Set<Promise<void>>()
+let deleteFailure: unknown = null
+let pendingStartupWarning: (() => void) | null = null
+let closeListenersInstalled = false
+
+/**
+ * Re-raise startup warnings once a sonner `<Toaster>` is mounted. Sonner drops
+ * toasts created before its Toaster subscribes, and startup warnings are
+ * raised while the providers still gate rendering on startup itself, so the
+ * Toaster host calls this from its mount effect. Idempotent: warnings use
+ * stable toast ids, so a re-fire updates rather than duplicates.
+ */
+export function flushCoworkStartupWarnings(): void {
+ pendingStartupWarning?.()
+}
+
+const getInvoke = (): Invoke => {
+ const core = getServiceHub().core()
+ return core.invoke.bind(core) as Invoke
+}
+
+/** Mirror a persisted Cowork thread into the shared thread list (and search). */
+function upsertThread(thread: Json) {
+ const model = thread.assistants?.[0]?.model
+ const existing = useThreads.getState().threads[thread.id]
+ const next = {
+ ...(existing ?? {}),
+ ...thread,
+ model:
+ model && model.id !== '*'
+ ? { id: model.id, provider: model.engine ?? 'llamacpp' }
+ : existing?.model,
+ updated: thread.updated,
+ isFavorite: thread.metadata?.is_favorite ?? existing?.isFavorite,
+ order: thread.metadata?.order ?? existing?.order,
+ metadata: { ...(thread.metadata ?? {}) },
+ } as Thread
+ const all = { ...useThreads.getState().threads, [next.id]: next }
+ useThreads.getState().setThreads(Object.values(all))
+}
+
+function removeThread(id: string) {
+ const { [id]: _gone, ...rest } = useThreads.getState().threads
+ void _gone
+ useThreads.getState().setThreads(Object.values(rest))
+}
+
+function diff(prev: CoworkSession[], next: CoworkSession[]) {
+ const before = new Map(prev.map((s) => [s.id, s]))
+ const after = new Set(next.map((s) => s.id))
+ const changed = next.filter((s) => before.get(s.id) !== s)
+ const removed = prev.filter((s) => !after.has(s.id)).map((s) => s.id)
+ return { changed, removed }
+}
+
+export function getCoworkPersistence(): CoworkPersistence | null {
+ return persistence
+}
+
+export function isCoworkMigrationDone(): boolean {
+ return migrationSettled
+}
+
+/** Await in-flight Cowork deletions (used before the window closes). */
+export async function flushCoworkDeletes(): Promise<void> {
+ if (startPromise) await startPromise
+ await Promise.all([...pendingDeletes])
+ if (deleteFailure) {
+ const failure = deleteFailure
+ deleteFailure = null
+ throw failure
+ }
+}
+
+/** Await queued and in-flight Cowork writes. */
+export async function flushCowork(): Promise<void> {
+ await persistence?.flush()
+}
+
+const supportsCowork = () =>
+ isPlatformTauri() && !isPlatformIOS() && !isPlatformAndroid()
+
+/** Resolves with the work's outcome, or with `'timeout'` after `ms`. */
+async function withinBudget<T>(work: Promise<T>, ms: number): Promise<T | 'timeout'> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const timeout = new Promise<'timeout'>((resolve) => {
+ timer = setTimeout(() => resolve('timeout'), ms)
+ })
+ try {
+ return await Promise.race([work, timeout])
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+/**
+ * Start (once) the Cowork <-> thread sync. Safe to call from several places:
+ * later callers share the running start; a failed start is forgotten so the
+ * next call retries. Never rejects for a failed migration, only for a failure
+ * to load or wire up the store.
+ */
+export function startCoworkSync(): Promise<void> {
+ if (!supportsCowork()) return Promise.resolve()
+ startPromise ??= doStart().catch((e) => {
+ startPromise = null
+ console.warn('[cowork] sync failed to start; operations must retry initialization:', e)
+ throw e
+ })
+ return startPromise
+}
+
+async function doStart() {
+ const invoke = getInvoke()
+
+ // 1. One-time, idempotent copy of legacy sessions into threads. It never
+ // throws. Startup waits for it only for a bounded time: a huge history
+ // must not keep the app from rendering. Past the budget the rest finishes
+ // in the background and the sessions are re-loaded when it does.
+ const migration = migrateCoworkSessionsOnStartup().catch(() => null)
+ const outcome = await withinBudget(migration, COWORK_MIGRATION_BUDGET_MS)
+ const background = outcome === 'timeout' ? migration : null
+ migrationSettled = await settledAfter(invoke, outcome)
+
+ // 2. Load. An unsettled migration keeps legacy-only sessions visible.
+ const loaded = await loadCoworkSessions(invoke, { migrationSettled })
+
+ // Failing closed on an unreadable deletion journal must not hide data
+ // silently: legacy sessions stay hidden and their deletion stays blocked on
+ // EVERY launch until the journal is repaired, so warn persistently on every
+ // launch. Never auto-repair, quarantine, or drop the journal: rewriting it
+ // could resurrect sessions the user deleted.
+ if (loaded.deletionJournalError) {
+ const warn = () =>
+ toast.warning(i18n.t('common:coworkSync.journalUnreadableTitle'), {
+ id: 'cowork-deletion-journal-unreadable',
+ duration: Infinity,
+ description: i18n.t('common:coworkSync.journalUnreadableDescription'),
+ })
+ // This startup gates provider render, so the Toaster is usually NOT mounted
+ // yet and sonner drops toasts created before it subscribes. Fire now for an
+ // already-mounted toaster AND keep the warning for the post-mount flush;
+ // the stable id makes double delivery idempotent.
+ pendingStartupWarning = warn
+ warn()
+ } else {
+ pendingStartupWarning = null
+ }
+
+ const p = createCoworkPersistence(invoke, {
+ legacyGate: background ?? undefined,
+ liveRecord: (id) => {
+ const t = useThreads.getState().threads[id]
+ if (!t) return undefined
+ return {
+ title: t.title,
+ metadata: {
+ ...(t.metadata ?? {}),
+ is_favorite: t.isFavorite,
+ order: t.order,
+ },
+ }
+ },
+ onThreadWritten: upsertThread,
+ onThreadRemoved: (id) => {
+ removeThread(id)
+ // The conversation is gone: its persistent warning would otherwise linger.
+ toast.dismiss(`cowork-missing-thread-${id}`)
+ toast.dismiss(`cowork-write-refused-${id}`)
+ },
+ onError: (id, e) => console.warn(`[cowork] write failed for ${id}:`, e),
+ onThreadMissing: (id) => {
+ // Keep the readable in-memory session (delete/export still work); it is
+ // flagged so it is never written back or recreated from a stale snapshot.
+ markUnavailable(id, 'missing-thread')
+ toast.warning(i18n.t('common:coworkSync.missingThreadTitle'), {
+ id: `cowork-missing-thread-${id}`,
+ description: i18n.t('common:coworkSync.missingThreadDescription'),
+ duration: Infinity,
+ })
+ },
+ onWriteRefused: (id) => {
+ // The backend permanently refuses this id: show it read-only instead of
+ // retrying forever.
+ markUnavailable(id, 'id-collision')
+ toast.warning(i18n.t('common:coworkSync.writeRefusedTitle'), {
+ id: `cowork-write-refused-${id}`,
+ description: i18n.t('common:coworkSync.writeRefusedDescription'),
+ duration: Infinity,
+ })
+ },
+ })
+ p.adopt(loaded.threads)
+ persistence = p
+
+ // Ids the store ever held from here on: a session absent from the store that
+ // was present at some point was deleted meanwhile and must not be re-added by
+ // the background reload.
+ const seen = new Set<string>()
+ for (const s of useCoworkSessions.getState().sessions) seen.add(s.id)
+
+ // 3. Merge: sessions created before hydration finished are kept, and win
+ // over the loaded copy of the same id (the store is newer than the disk).
+ mergeLoaded(loaded.sessions, loaded.currentId)
+ for (const s of loaded.sessions) seen.add(s.id)
+
+ // Cowork conversations also live in the shared thread list so search and the
+ // sidebar see them. Do this once; later writes upsert through onThreadWritten.
+ for (const t of loaded.threads) upsertThread(t)
+
+ // 4. Write-through from here on.
+ let prev = useCoworkSessions.getState()
+ const legacyIds = loaded.legacyIds
+ p.setCurrentId(prev.currentId)
+ unsubscribe?.()
+ unsubscribe = useCoworkSessions.subscribe((state) => {
+ if (state.currentId !== prev.currentId) p.setCurrentId(state.currentId)
+ if (state.sessions !== prev.sessions) {
+ const { changed, removed } = diff(prev.sessions, state.sessions)
+ for (const s of changed) {
+ seen.add(s.id)
+ p.schedule(s, { legacy: legacyIds.has(s.id) })
+ }
+ for (const id of removed) {
+ const snapshot = prev.sessions.find((session) => session.id === id)
+ const collision = snapshot?.unavailable === 'id-collision'
+ const removal = (async () => {
+ await p.remove(id, {
+ // While the legacy blob can still be read, deletion intent must
+ // survive in the journal or the blob brings the session back. An
+ // abandoned legacy session (shown as id-collision) stays in the
+ // blob forever, so it is journaled even after the migration settled.
+ recordDeleted: !migrationSettled || collision,
+ // A collision shares its id with an unrelated chat: never delete it.
+ preserveThread: collision,
+ })
+ // Workspace reclamation cannot turn a successful durable deletion back
+ // into a visible session. It is best-effort and retried by the sweep.
+ if (!collision) await cleanupThreadWorkspace(id)
+ })()
+ pendingDeletes.add(removal)
+ void removal
+ .catch((error) => {
+ deleteFailure = error
+ if (snapshot) {
+ useCoworkSessions.setState((current) => ({
+ sessions: current.sessions.some((session) => session.id === id)
+ ? current.sessions
+ : [...current.sessions, snapshot],
+ }))
+ }
+ console.warn(`[cowork] delete failed for ${id}:`, error)
+ })
+ .finally(() => pendingDeletes.delete(removal))
+ }
+ }
+ prev = state
+ })
+
+ // 5. The migration overran its budget: when it finishes, bring in what it
+ // created.
+ if (background) {
+ void background
+ .then((late) => finishLateMigration(invoke, late, seen))
+ .catch((error) => {
+ console.warn('[cowork] reload after the background migration failed:', error)
+ })
+ }
+
+ // 6. Flush when the app is hidden or closed.
+ await installCloseHandlers()
+}
+
+/** Settled = the legacy blob never needs to be read again. */
+async function settledAfter(
+ invoke: Invoke,
+ outcome: CoworkMigrationResult | null | 'timeout'
+): Promise<boolean> {
+ if (outcome === 'timeout') return false
+ if (outcome && outcome.status !== 'partial') return true
+ try {
+ return await isCoworkMigrationSettled(invoke)
+ } catch {
+ return false
+ }
+}
+
+function markUnavailable(id: string, reason: NonNullable<CoworkSession['unavailable']>) {
+ useCoworkSessions.setState((s) => ({
+ sessions: s.sessions.map((x) => (x.id === id ? { ...x, unavailable: reason } : x)),
+ }))
+}
+
+/** Merge loaded sessions under whatever the store already holds. */
+function mergeLoaded(loaded: CoworkSession[], loadedCurrentId: string | null) {
+ useCoworkSessions.setState((s) => {
+ const have = new Set(s.sessions.map((x) => x.id))
+ const sessions = [...s.sessions, ...loaded.filter((x) => !have.has(x.id))].sort(
+ (a, b) => b.updated - a.updated
+ )
+ const currentId =
+ s.currentId && sessions.some((x) => x.id === s.currentId)
+ ? s.currentId
+ : loadedCurrentId
+ return { sessions, currentId }
+ })
+}
+
+/**
+ * The background migration finished after startup. Re-read the threads: it
+ * created the ones that were still legacy-only. The store is already newer than
+ * the disk, so only sessions it does not hold are added, and never one the user
+ * deleted meanwhile (`seen`). A thread the migration created for a session
+ * deleted in the meantime (the deletion landed between its journal read and its
+ * commit) is removed here, because the journal is authoritative.
+ */
+async function finishLateMigration(
+ invoke: Invoke,
+ late: CoworkMigrationResult | null,
+ seen: Set<string>
+) {
+ migrationSettled = await settledAfter(invoke, late)
+ const p = persistence
+ if (!p) return
+ const loaded = await loadCoworkSessions(invoke, { migrationSettled })
+ let deleted = new Set<string>()
+ try {
+ deleted = await readDeletedIds(invoke)
+ } catch {
+ // Unreadable journal: the load already warned; add nothing that is deleted-looking.
+ }
+ const inStore = new Set(useCoworkSessions.getState().sessions.map((x) => x.id))
+ for (const t of loaded.threads) {
+ if (typeof t?.id === 'string' && deleted.has(t.id) && !inStore.has(t.id)) {
+ // Resurrected by the migration against a recorded deletion.
+ void p.remove(t.id, { recordDeleted: false }).catch((error) => {
+ console.warn(`[cowork] could not remove ${t.id} after the migration:`, error)
+ })
+ }
+ }
+ p.adopt(loaded.threads)
+ const fresh = loaded.sessions.filter(
+ (s) => !inStore.has(s.id) && !seen.has(s.id) && !deleted.has(s.id)
+ )
+ if (fresh.length > 0) mergeLoaded(fresh, null)
+ for (const t of loaded.threads) {
+ if (!deleted.has(t.id) && (!seen.has(t.id) || inStore.has(t.id))) upsertThread(t)
+ }
+}
+
+async function installCloseHandlers() {
+ if (closeListenersInstalled) return
+ closeListenersInstalled = true
+ if (typeof document !== 'undefined') {
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'hidden') {
+ void Promise.all([flushCowork(), flushCoworkDeletes()]).catch((error) =>
+ console.warn('[cowork] background flush failed:', error)
+ )
+ }
+ })
+ }
+ if (typeof window === 'undefined') return
+ window.addEventListener('beforeunload', () => {
+ void Promise.all([flushCowork(), flushCoworkDeletes()]).catch((error) =>
+ console.warn('[cowork] unload flush failed:', error)
+ )
+ })
+ try {
+ const { getCurrentWindow } = await import('@tauri-apps/api/window')
+ await getCurrentWindow().onCloseRequested(async (event) => {
+ // Awaiting here holds the close until every queued and in-flight write
+ // has settled. On failure keep the window (and the unsaved state) alive;
+ // another close request retries storage rather than losing the run.
+ try {
+ // A live run has not committed its transcript or wire history yet: stop
+ // it and await its final commit BEFORE draining storage, or the last
+ // turn would be written after the flush. Still flush the other sessions
+ // if one participant fails to settle cleanly.
+ await withChatCloseDeadline(
+ (async () => {
+ const runs = await Promise.allSettled([quiesceCoworkRuns(), quiesceChats()])
+ const writes = await Promise.allSettled([flushCowork(), flushCoworkDeletes()])
+ const failed = [...runs, ...writes].find((r) => r.status === 'rejected')
+ if (failed?.status === 'rejected') throw failed.reason
+ })()
+ )
+ } catch (e) {
+ event.preventDefault()
+ resumeCoworkAfterPreventedClose()
+ resumeChatsAfterPreventedClose()
+ console.warn('[cowork] flush on close failed:', e)
+ }
+ })
+ } catch (e) {
+ console.warn('[cowork] could not register the close handler:', e)
+ }
+}
+
+/** Test seam: forget all module state. */
+export function __resetCoworkSyncForTests() {
+ __resetCoworkRunCloseForTests()
+ unsubscribe?.()
+ unsubscribe = null
+ persistence = null
+ startPromise = null
+ migrationSettled = false
+ pendingDeletes.clear()
+ deleteFailure = null
+ pendingStartupWarning = null
+ closeListenersInstalled = false
+}
diff --git a/web-app/src/lib/coworkTodo.ts b/web-app/src/lib/coworkTodo.ts
index 41ca88ae9..efd9159e7 100644
--- a/web-app/src/lib/coworkTodo.ts
+++ b/web-app/src/lib/coworkTodo.ts
@@ -1,4 +1,11 @@
-import type { TodoItem, TodoList, TodoPhase } from '@/types/coworkSession'
+import type {
+ CoworkTurn,
+ TodoItem,
+ TodoList,
+ TodoPhase,
+} from '@/types/coworkSession'
+
+export const TODO_TOOL_NAME = 'todo'
/**
* The `todo` tool's reducer, ported from `core/agent/todo.rs`.
@@ -294,3 +301,59 @@ export function todoProgress(list: TodoList): { done: number; total: number } {
const tasks = allTasks(list)
return { done: tasks.filter(isTerminal).length, total: tasks.length }
}
+
+/** Shared snapshot validation for transcript projections without SDK/store imports. */
+export function isTodoList(value: unknown): value is TodoList {
+ if (
+ !value ||
+ typeof value !== 'object' ||
+ !('phases' in value) ||
+ !Array.isArray(value.phases)
+ )
+ return false
+ return value.phases.every((phase: unknown) => {
+ if (
+ !phase ||
+ typeof phase !== 'object' ||
+ !('name' in phase) ||
+ typeof phase.name !== 'string' ||
+ !('tasks' in phase) ||
+ !Array.isArray(phase.tasks)
+ )
+ return false
+ return phase.tasks.every(
+ (task: unknown) =>
+ task &&
+ typeof task === 'object' &&
+ 'content' in task &&
+ typeof task.content === 'string' &&
+ 'status' in task &&
+ ['pending', 'in_progress', 'completed', 'abandoned'].includes(
+ String(task.status)
+ )
+ )
+ })
+}
+
+/** Store rewind projection stays pure and does not load SDK/tool registries. */
+export function todosFromTurns(
+ turns: readonly CoworkTurn[]
+): TodoList | undefined {
+ let latest: TodoList | undefined
+ for (const turn of turns) {
+ if (
+ turn.role !== 'tool' ||
+ turn.name !== TODO_TOOL_NAME ||
+ turn.status === 'running' ||
+ turn.isError
+ )
+ continue
+ try {
+ const value: unknown = JSON.parse(turn.result ?? turn.content)
+ if (isTodoList(value)) latest = value
+ } catch {
+ /* A failed result is not a snapshot. */
+ }
+ }
+ return latest
+}
diff --git a/web-app/src/lib/hydrateStores.ts b/web-app/src/lib/hydrateStores.ts
index fe0f5a66a..2ae34e36b 100644
--- a/web-app/src/lib/hydrateStores.ts
+++ b/web-app/src/lib/hydrateStores.ts
@@ -20,7 +20,6 @@ import { useJanModelPromptDismissed } from '@/hooks/useJanModelPrompt'
import { useDefaultEmbeddingModel } from '@/hooks/useDefaultEmbeddingModel'
import { useAgentMode } from '@/hooks/useAgentMode'
import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
-import { useCoworkSessions } from '@/hooks/useCoworkSessions'
import { useCoworkConfig } from '@/hooks/useCoworkConfig'
import { useChatShell } from '@/hooks/useChatShell'
import { useCoTDuration } from '@/hooks/useCoTDuration'
@@ -57,7 +56,6 @@ const secondaryStores = [
useDefaultEmbeddingModel,
useAgentMode,
useWebSearchConfig,
- useCoworkSessions,
useCoworkConfig,
useChatShell,
useCoTDuration,
diff --git a/web-app/src/lib/threadMode.ts b/web-app/src/lib/threadMode.ts
new file mode 100644
index 000000000..7def3615a
--- /dev/null
+++ b/web-app/src/lib/threadMode.ts
@@ -0,0 +1,19 @@
+/**
+ * A conversation runs either as a Chat or as a Cowork task. The mode is stored
+ * on the thread as `metadata.mode`; absent means chat, so every thread written
+ * before Cowork was merged into threads is a chat. The mode only selects the
+ * runner: every thread, whatever its mode, uses the thread sandbox.
+ */
+export type ThreadMode = 'chat' | 'cowork'
+
+type WithMetadata =
+ | { metadata?: Record<string, unknown> | null }
+ | null
+ | undefined
+
+export function getThreadMode(thread: WithMetadata): ThreadMode {
+ return thread?.metadata?.mode === 'cowork' ? 'cowork' : 'chat'
+}
+
+export const isCoworkThread = (thread: WithMetadata): boolean =>
+ getThreadMode(thread) === 'cowork'
diff --git a/web-app/src/locales/de-DE/common.json b/web-app/src/locales/de-DE/common.json
index edec482c5..a2a0e49d9 100644
--- a/web-app/src/locales/de-DE/common.json
+++ b/web-app/src/locales/de-DE/common.json
@@ -406,5 +406,13 @@
"forceQuit": "Force quit",
"forcing": "Force quitting…",
"shuttingDown": "Shutting down…"
+ },
+ "coworkSync": {
+ "journalUnreadableTitle": "Einige importierte Cowork-Unterhaltungen sind ausgeblendet",
+ "journalUnreadableDescription": "Jan kann seine Löschliste nicht lesen. Unterhaltungen aus einer älteren Version bleiben daher ausgeblendet, damit bereits gelöschte nicht wiederhergestellt werden, und das Löschen von Cowork-Unterhaltungen ist vorübergehend gesperrt. Ihre Daten sind unverändert. So stellen Sie den Normalzustand her: Beenden Sie Jan zuerst vollständig, denn Jan schreibt settings.json während der Laufzeit aus dem Speicher neu und würde Ihre Änderung rückgängig machen. Korrigieren oder entfernen Sie dann den Eintrag 'cowork_deleted_ids' in settings.json. Wenn Sie ihn entfernen, werden alle importierten Unterhaltungen wiederhergestellt, auch bereits gelöschte.",
+ "missingThreadTitle": "Eine Cowork-Unterhaltung konnte nicht gespeichert werden",
+ "missingThreadDescription": "Der gespeicherte Thread fehlt, daher werden Änderungen nicht mehr gespeichert. Sie können ihn weiterhin lesen, exportieren oder löschen.",
+ "writeRefusedTitle": "Eine Cowork-Unterhaltung kann nicht gespeichert werden",
+ "writeRefusedDescription": "Jan kann diese Unterhaltung nicht unter ihrer aktuellen ID speichern, daher werden Änderungen nicht gespeichert. Sie können sie weiterhin lesen, exportieren oder löschen."
}
}
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 1a9dd3a53..54ec85178 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -789,5 +789,13 @@
"askRecommended": "Recommended",
"askSelectedCount": "{{count}} selected",
"askSomethingElse": "Something else",
- "submit": "Submit"
+ "submit": "Submit",
+ "coworkSync": {
+ "journalUnreadableTitle": "Some imported Cowork conversations are hidden",
+ "journalUnreadableDescription": "Jan can't read its deletion record, so conversations imported from an older version stay hidden rather than risk restoring ones you already deleted, and deleting any Cowork conversation is temporarily blocked. Your data is untouched. To recover: quit Jan completely first, because Jan rewrites settings.json from memory while it runs and would undo your edit. Then fix or remove the 'cowork_deleted_ids' entry in settings.json. Removing it restores every imported conversation, including any you had deleted.",
+ "missingThreadTitle": "A Cowork conversation could not be saved",
+ "missingThreadDescription": "Its stored thread is missing, so changes are no longer saved. You can still read, export or delete it.",
+ "writeRefusedTitle": "A Cowork conversation cannot be saved",
+ "writeRefusedDescription": "Jan cannot store this conversation under its current id, so changes are not saved. You can still read, export or delete it."
+ }
}
diff --git a/web-app/src/locales/fr/common.json b/web-app/src/locales/fr/common.json
index d57d52054..925578cd0 100644
--- a/web-app/src/locales/fr/common.json
+++ b/web-app/src/locales/fr/common.json
@@ -409,5 +409,13 @@
"forceQuit": "Force quit",
"forcing": "Force quitting…",
"shuttingDown": "Shutting down…"
+ },
+ "coworkSync": {
+ "journalUnreadableTitle": "Certaines conversations Cowork importées sont masquées",
+ "journalUnreadableDescription": "Jan ne peut pas lire son registre de suppressions : les conversations importées d'une ancienne version restent donc masquées plutôt que de risquer de restaurer celles que vous avez déjà supprimées, et la suppression d'une conversation Cowork est temporairement bloquée. Vos données sont intactes. Pour rétablir la situation : quittez d'abord complètement Jan, car il réécrit settings.json depuis la mémoire pendant son exécution et annulerait votre modification. Corrigez ou supprimez ensuite l'entrée 'cowork_deleted_ids' dans settings.json. La supprimer restaure toutes les conversations importées, y compris celles que vous aviez supprimées.",
+ "missingThreadTitle": "Une conversation Cowork n'a pas pu être enregistrée",
+ "missingThreadDescription": "Son fil enregistré est introuvable, les modifications ne sont donc plus enregistrées. Vous pouvez toujours le lire, l'exporter ou le supprimer.",
+ "writeRefusedTitle": "Une conversation Cowork ne peut pas être enregistrée",
+ "writeRefusedDescription": "Jan ne peut pas enregistrer cette conversation sous son identifiant actuel, les modifications ne sont donc pas enregistrées. Vous pouvez toujours la lire, l'exporter ou la supprimer."
}
}
diff --git a/web-app/src/locales/ja/common.json b/web-app/src/locales/ja/common.json
index 55641322f..bc6e0f069 100644
--- a/web-app/src/locales/ja/common.json
+++ b/web-app/src/locales/ja/common.json
@@ -523,5 +523,13 @@
"forceQuit": "強制終了",
"forcing": "強制終了しています…",
"shuttingDown": "シャットダウンしています…"
+ },
+ "coworkSync": {
+ "journalUnreadableTitle": "インポートした一部のCowork会話が非表示になっています",
+ "journalUnreadableDescription": "Janが削除記録を読み取れないため、削除済みの会話を誤って復元しないよう、以前のバージョンからインポートした会話は非表示のままです。また、Cowork会話の削除は一時的にブロックされています。データは変更されていません。復旧するには、まずJanを完全に終了してください。Janは実行中にメモリからsettings.jsonを書き直すため、編集内容が元に戻ってしまいます。その後、settings.jsonの 'cowork_deleted_ids' を修正するか削除してください。削除すると、すでに削除した会話を含め、インポートしたすべての会話が復元されます。",
+ "missingThreadTitle": "Cowork会話を保存できませんでした",
+ "missingThreadDescription": "保存されているスレッドが見つからないため、変更は保存されなくなりました。読み取り、エクスポート、削除は引き続き可能です。",
+ "writeRefusedTitle": "Cowork会話を保存できません",
+ "writeRefusedDescription": "Janはこの会話を現在のIDで保存できないため、変更は保存されません。読み取り、エクスポート、削除は引き続き可能です。"
}
}
diff --git a/web-app/src/locales/zh-CN/common.json b/web-app/src/locales/zh-CN/common.json
index 907299091..6873d54e9 100644
--- a/web-app/src/locales/zh-CN/common.json
+++ b/web-app/src/locales/zh-CN/common.json
@@ -585,5 +585,13 @@
"askSelectedCount": "已选 {{count}} 个",
"askSomethingElse": "其他",
"askSomethingElsePlaceholder": "键入您自己的回答",
- "submit": "提交"
+ "submit": "提交",
+ "coworkSync": {
+ "journalUnreadableTitle": "部分已导入的 Cowork 对话被隐藏",
+ "journalUnreadableDescription": "Jan 无法读取其删除记录,为避免恢复您已删除的对话,从旧版本导入的对话将保持隐藏,并且暂时无法删除任何 Cowork 对话。您的数据未受影响。恢复方法:请先完全退出 Jan,因为 Jan 运行时会用内存中的内容重写 settings.json,会撤销您的修改。然后修正或删除 settings.json 中的 'cowork_deleted_ids' 条目。删除该条目会恢复所有已导入的对话,包括您已删除的对话。",
+ "missingThreadTitle": "无法保存 Cowork 对话",
+ "missingThreadDescription": "其存储的会话线程已丢失,因此不再保存更改。您仍可阅读、导出或删除它。",
+ "writeRefusedTitle": "无法保存 Cowork 对话",
+ "writeRefusedDescription": "Jan 无法以当前 ID 存储此对话,因此不会保存更改。您仍可阅读、导出或删除它。"
+ }
}
diff --git a/web-app/src/providers/DataProvider.tsx b/web-app/src/providers/DataProvider.tsx
index 75a7bf529..3f9506cda 100644
--- a/web-app/src/providers/DataProvider.tsx
+++ b/web-app/src/providers/DataProvider.tsx
@@ -9,6 +9,7 @@ import { useAssistant } from '@/hooks/useAssistant'
import { useNavigate } from '@tanstack/react-router'
import { route } from '@/constants/routes'
import { useThreads } from '@/hooks/useThreads'
+import { useCoworkSessions } from '@/hooks/useCoworkSessions'
import { useLocalApiServer } from '@/hooks/useLocalApiServer'
import { useAppState } from '@/hooks/useAppState'
import { AppEvent, events, HUGGINGFACE_TOKEN_SECRET_KEY } from '@janhq/core'
@@ -311,6 +312,10 @@ export function DataProvider() {
}
setThreads(threads)
setThreadsLoading(false)
+ // SUCCESS branch only (never the retry-exhaustion catch): the service
+ // throws on a non-array response, so reaching here means a validated
+ // listing, including a genuinely empty one.
+ useThreads.getState().markThreadsHydrated()
// Collect agent sandboxes whose thread is gone (crash, or a thread
// deleted while the app was closed). Once per session, and only on a
// non-empty result: sweeping against an empty list would delete live
@@ -318,7 +323,15 @@ export function DataProvider() {
// Leftovers then wait for the next startup that does see threads.
if (!sweptWorkspaces.current && threads.length > 0) {
sweptWorkspaces.current = true
- sweepThreadWorkspaces(threads.map((t) => t.id))
+ // A Cowork session that already started running keeps its sandbox
+ // before its thread.json exists (first write is debounced), so the
+ // live session ids are kept as well.
+ sweepThreadWorkspaces([
+ ...new Set([
+ ...threads.map((t) => t.id),
+ ...useCoworkSessions.getState().sessions.map((x) => x.id),
+ ]),
+ ])
}
})
.catch(() => {
diff --git a/web-app/src/providers/ServiceHubProvider.tsx b/web-app/src/providers/ServiceHubProvider.tsx
index 60abb11a9..162ee83e7 100644
--- a/web-app/src/providers/ServiceHubProvider.tsx
+++ b/web-app/src/providers/ServiceHubProvider.tsx
@@ -3,30 +3,7 @@ import { initializeServiceHub } from '@/services'
import { initializeServiceHubStore } from '@/hooks/useServiceHub'
import { hydrateBackendStores } from '@/lib/hydrateStores'
import { migrateLocalStorageToBackend } from '@/lib/migrateLocalStorageSettings'
-import { migrateCoworkSessionsOnStartup } from '@/lib/migrateCoworkSessions'
-import { refreshThreadsFromBackend } from '@/lib/refreshThreads'
-
-/**
- * How long startup waits for the Cowork migration. Past it the app renders and
- * the migration keeps running; the thread list is refreshed when it finishes.
- */
-export const COWORK_MIGRATION_BUDGET_MS = 3000
-
-/** Resolves with the work's outcome, or with `'timeout'` after `ms`. */
-async function withinBudget<T>(
- work: Promise<T>,
- ms: number
-): Promise<T | 'timeout'> {
- let timer: ReturnType<typeof setTimeout> | undefined
- const timeout = new Promise<'timeout'>((resolve) => {
- timer = setTimeout(() => resolve('timeout'), ms)
- })
- try {
- return await Promise.race([work, timeout])
- } finally {
- clearTimeout(timer)
- }
-}
+import { startCoworkSync } from '@/lib/coworkSync'
interface ServiceHubProviderProps {
children: React.ReactNode
@@ -46,26 +23,14 @@ export function ServiceHubProvider({ children }: ServiceHubProviderProps) {
// Settings stores use async backend storage; hydrate before rendering
// children so no component reads pre-hydration defaults.
await hydrateBackendStores()
- // One-time copy of Cowork sessions into threads. Children list threads
- // on mount, so it is awaited, but only for a bounded time: a huge
- // history must not keep the app from rendering. When it overruns, the
- // rest finishes in the background and the thread list is refreshed
- // then. Neither path throws.
- const migration = migrateCoworkSessionsOnStartup()
- const outcome = await withinBudget(
- migration.catch(() => null),
- COWORK_MIGRATION_BUDGET_MS
- )
- if (outcome === 'timeout') {
- void migration
- .then((late) => {
- if (late && late.migrated.length > 0) {
- return refreshThreadsFromBackend()
- }
- })
- .catch((error) => {
- console.warn('[cowork-migration] late refresh failed:', error)
- })
+ // Cowork sessions are threads: migrate legacy sessions (bounded wait,
+ // the rest finishes in the background), load them and start
+ // write-through, before any route renders so a deep link never sees an
+ // empty store. A failed start must not keep the app from rendering.
+ try {
+ await startCoworkSync()
+ } catch (error) {
+ console.warn('[cowork] startup sync failed; the app still renders:', error)
}
setIsReady(true)
})
diff --git a/web-app/src/providers/ToasterProvider.tsx b/web-app/src/providers/ToasterProvider.tsx
index 5328efc02..d1b877ce9 100644
--- a/web-app/src/providers/ToasterProvider.tsx
+++ b/web-app/src/providers/ToasterProvider.tsx
@@ -1,12 +1,22 @@
+import { useEffect } from 'react'
import { Toaster } from '@/components/ui/sonner'
import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'
import { getToastOffset } from '@/utils/toastPlacement'
+import { flushCoworkStartupWarnings } from '@/lib/coworkSync'
export function ToasterProvider() {
const notificationPosition = useInterfaceSettings(
(s) => s.notificationPosition
)
+ // Startup warnings can be raised before any <Toaster> exists (providers gate
+ // rendering on startup), and sonner drops pre-mount toasts. The child
+ // <Toaster>'s subscription effect runs before this parent effect, so
+ // re-raising here is reliably visible.
+ useEffect(() => {
+ flushCoworkStartupWarnings()
+ }, [])
+
return (
<Toaster
richColors
diff --git a/web-app/src/providers/__tests__/DataProvider.test.tsx b/web-app/src/providers/__tests__/DataProvider.test.tsx
index 58bd80913..20c396f58 100644
--- a/web-app/src/providers/__tests__/DataProvider.test.tsx
+++ b/web-app/src/providers/__tests__/DataProvider.test.tsx
@@ -18,6 +18,9 @@ const h = vi.hoisted(() => {
setThreads: vi.fn(),
setThreadsLoading: vi.fn(),
threadsInStore: {} as Record<string, unknown>,
+ markThreadsHydrated: vi.fn(),
+ sweepThreadWorkspaces: vi.fn(),
+ coworkSessions: [] as Array<{ id: string }>,
setLastServerModels: vi.fn(),
setServerPort: vi.fn(),
setServerStatus: vi.fn(),
@@ -76,6 +79,12 @@ vi.mock('@/hooks/useAssistant', () => ({
useAssistant: () => ({ setAssistants: h.setAssistants }),
}))
+vi.mock('@/lib/agentTools', () => ({
+ sweepThreadWorkspaces: h.sweepThreadWorkspaces,
+}))
+vi.mock('@/hooks/useCoworkSessions', () => ({
+ useCoworkSessions: { getState: () => ({ sessions: h.coworkSessions }) },
+}))
vi.mock('@/hooks/useThreads', () => {
const state = () => ({
setThreads: h.setThreads,
@@ -88,7 +97,10 @@ vi.mock('@/hooks/useThreads', () => {
(selector?: (s: unknown) => unknown): unknown
getState: () => { threads: Record<string, unknown> }
}
- useThreads.getState = () => ({ threads: h.threadsInStore })
+ useThreads.getState = () => ({
+ threads: h.threadsInStore,
+ markThreadsHydrated: h.markThreadsHydrated,
+ })
return { useThreads }
})
@@ -213,6 +225,9 @@ describe('DataProvider', () => {
resetHubState()
h.providers = []
h.threadsInStore = {}
+ h.markThreadsHydrated.mockClear()
+ h.sweepThreadWorkspaces.mockClear()
+ h.coworkSessions = []
h.isDev.mockReturnValue(false)
h.providerHasRemoteApiKeys.mockReturnValue(true)
h.providerRemoteApiKeyChain.mockReturnValue(['key-1'])
@@ -278,6 +293,30 @@ describe('DataProvider', () => {
})
})
+ it('marks the thread list hydrated only after a successful listing (an empty one counts), never on a failed attempt', async () => {
+ hubState.fetchThreads
+ .mockRejectedValueOnce(new Error('backend not ready'))
+ .mockResolvedValueOnce([])
+ render(<DataProvider />)
+ await waitFor(() => expect(hubState.fetchThreads).toHaveBeenCalledTimes(2))
+ await waitFor(() => expect(h.markThreadsHydrated).toHaveBeenCalledTimes(1))
+ })
+
+ it('keeps the sandbox of a live Cowork session that has no thread.json yet when sweeping', async () => {
+ h.coworkSessions = [{ id: 'live-unsaved' }]
+ hubState.fetchThreads.mockResolvedValue([{ id: 't1' }])
+ render(<DataProvider />)
+ await waitFor(() => expect(h.sweepThreadWorkspaces).toHaveBeenCalledTimes(1))
+ expect(h.sweepThreadWorkspaces.mock.calls[0][0].sort()).toEqual(['live-unsaved', 't1'])
+ })
+
+ it('never marks the thread list hydrated when every attempt fails', async () => {
+ hubState.fetchThreads.mockRejectedValue(new Error('backend not ready'))
+ render(<DataProvider />)
+ await waitFor(() => expect(hubState.fetchThreads).toHaveBeenCalled())
+ expect(h.markThreadsHydrated).not.toHaveBeenCalled()
+ })
+
it('does not wipe a populated thread list when fetchThreads resolves empty', async () => {
h.threadsInStore = { t1: { id: 't1' } }
hubState.fetchThreads.mockResolvedValue([])
diff --git a/web-app/src/providers/__tests__/ServiceHubProvider.test.tsx b/web-app/src/providers/__tests__/ServiceHubProvider.test.tsx
index 71583f521..5b258dfff 100644
--- a/web-app/src/providers/__tests__/ServiceHubProvider.test.tsx
+++ b/web-app/src/providers/__tests__/ServiceHubProvider.test.tsx
@@ -1,13 +1,12 @@
-import { render, screen, waitFor, act } from '@testing-library/react'
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { render, screen, waitFor } from '@testing-library/react'
+import { describe, it, expect, vi, beforeEach } from 'vitest'
const h = vi.hoisted(() => ({
order: [] as string[],
initializeServiceHub: vi.fn(),
migrateLocalStorageToBackend: vi.fn(),
hydrateBackendStores: vi.fn(),
- migrateCoworkSessionsOnStartup: vi.fn(),
- refreshThreadsFromBackend: vi.fn(),
+ startCoworkSync: vi.fn(),
}))
vi.mock('@/services', () => ({
@@ -22,18 +21,11 @@ vi.mock('@/lib/migrateLocalStorageSettings', () => ({
vi.mock('@/lib/hydrateStores', () => ({
hydrateBackendStores: h.hydrateBackendStores,
}))
-vi.mock('@/lib/migrateCoworkSessions', () => ({
- migrateCoworkSessionsOnStartup: h.migrateCoworkSessionsOnStartup,
+vi.mock('@/lib/coworkSync', () => ({
+ startCoworkSync: h.startCoworkSync,
}))
-vi.mock('@/lib/refreshThreads', () => ({
- refreshThreadsFromBackend: h.refreshThreadsFromBackend,
-}))
-
-import {
- ServiceHubProvider,
- COWORK_MIGRATION_BUDGET_MS,
-} from '../ServiceHubProvider'
+import { ServiceHubProvider } from '../ServiceHubProvider'
describe('ServiceHubProvider', () => {
beforeEach(() => {
@@ -45,14 +37,12 @@ describe('ServiceHubProvider', () => {
h.hydrateBackendStores.mockReset().mockImplementation(async () => {
h.order.push('hydrate')
})
- h.refreshThreadsFromBackend.mockReset().mockResolvedValue(undefined)
- h.migrateCoworkSessionsOnStartup.mockReset().mockImplementation(async () => {
- h.order.push('cowork-migration')
- return null
+ h.startCoworkSync.mockReset().mockImplementation(async () => {
+ h.order.push('cowork-sync')
})
})
- it('migrates Cowork sessions after the stores hydrate and before children render', async () => {
+ it('starts the Cowork sync after the stores hydrate and before children render', async () => {
render(
<ServiceHubProvider>
<div data-testid="child" />
@@ -61,11 +51,11 @@ describe('ServiceHubProvider', () => {
expect(screen.queryByTestId('child')).toBeNull()
await waitFor(() => expect(screen.getByTestId('child')).toBeTruthy())
// Children fetch threads on mount, so the migrated threads must exist by then.
- expect(h.order).toEqual(['settings-migration', 'hydrate', 'cowork-migration'])
+ expect(h.order).toEqual(['settings-migration', 'hydrate', 'cowork-sync'])
})
- it('still renders the app when the Cowork migration rejects', async () => {
- h.migrateCoworkSessionsOnStartup.mockRejectedValue(new Error('boom'))
+ it('still renders the app when the Cowork sync fails to start', async () => {
+ h.startCoworkSync.mockRejectedValue(new Error('boom'))
render(
<ServiceHubProvider>
<div data-testid="child" />
@@ -74,96 +64,14 @@ describe('ServiceHubProvider', () => {
await waitFor(() => expect(screen.getByTestId('child')).toBeTruthy())
})
- describe('a slow Cowork migration', () => {
- afterEach(() => {
- vi.useRealTimers()
- })
-
- const result = (migrated: string[]) => ({
- status: 'complete' as const,
- migrated,
- skipped: [],
- abandoned: [],
- failed: [],
- })
-
- const deferred = () => {
- let resolve: (r: ReturnType<typeof result>) => void = () => {}
- let reject: (e: Error) => void = () => {}
- const promise = new Promise<ReturnType<typeof result>>((res, rej) => {
- resolve = res
- reject = rej
- })
- return { promise, resolve, reject }
- }
-
- const mountSlow = () => {
- vi.useFakeTimers({ shouldAdvanceTime: true })
- const d = deferred()
- h.migrateCoworkSessionsOnStartup.mockReturnValue(d.promise)
- render(
- <ServiceHubProvider>
- <div data-testid="child" />
- </ServiceHubProvider>
- )
- return d
- }
-
- it('does not hold the app past its budget, then refreshes the thread list when it finishes', async () => {
- const d = mountSlow()
- expect(screen.queryByTestId('child')).toBeNull()
- await act(async () => {
- await vi.advanceTimersByTimeAsync(COWORK_MIGRATION_BUDGET_MS + 50)
- })
- expect(screen.getByTestId('child')).toBeTruthy()
- expect(h.refreshThreadsFromBackend).not.toHaveBeenCalled()
-
- await act(async () => {
- d.resolve(result(['s1']))
- })
- await waitFor(() =>
- expect(h.refreshThreadsFromBackend).toHaveBeenCalledTimes(1)
- )
- })
-
- it('does not refresh when the late migration copied nothing', async () => {
- const d = mountSlow()
- await vi.advanceTimersByTimeAsync(COWORK_MIGRATION_BUDGET_MS + 50)
- await act(async () => {
- d.resolve(result([]))
- })
- expect(h.refreshThreadsFromBackend).not.toHaveBeenCalled()
- })
-
- it('a late rejection stays non-throwing', async () => {
- const d = mountSlow()
- await vi.advanceTimersByTimeAsync(COWORK_MIGRATION_BUDGET_MS + 50)
- await act(async () => {
- d.reject(new Error('late boom'))
- })
- expect(screen.getByTestId('child')).toBeTruthy()
- expect(h.refreshThreadsFromBackend).not.toHaveBeenCalled()
- })
-
- it('a failing refresh stays non-throwing', async () => {
- h.refreshThreadsFromBackend.mockRejectedValue(new Error('refresh boom'))
- const d = mountSlow()
- await vi.advanceTimersByTimeAsync(COWORK_MIGRATION_BUDGET_MS + 50)
- await act(async () => {
- d.resolve(result(['s1']))
- })
- expect(screen.getByTestId('child')).toBeTruthy()
- })
-
- it('a migration that finishes inside the budget needs no refresh', async () => {
- h.migrateCoworkSessionsOnStartup.mockResolvedValue(result(['s1']))
- render(
- <ServiceHubProvider>
- <div data-testid="child" />
- </ServiceHubProvider>
- )
- await waitFor(() => expect(screen.getByTestId('child')).toBeTruthy())
- expect(h.refreshThreadsFromBackend).not.toHaveBeenCalled()
- })
+ it('still renders the app when service initialization fails', async () => {
+ h.initializeServiceHub.mockRejectedValue(new Error('no hub'))
+ render(
+ <ServiceHubProvider>
+ <div data-testid="child" />
+ </ServiceHubProvider>
+ )
+ await waitFor(() => expect(screen.getByTestId('child')).toBeTruthy())
+ expect(h.startCoworkSync).not.toHaveBeenCalled()
})
})
diff --git a/web-app/src/routes/__tests__/coworkSkills.test.tsx b/web-app/src/routes/__tests__/coworkSkills.test.tsx
index 7d3551e0c..3faa91490 100644
--- a/web-app/src/routes/__tests__/coworkSkills.test.tsx
+++ b/web-app/src/routes/__tests__/coworkSkills.test.tsx
@@ -239,6 +239,11 @@ import { useCoworkRun } from '@/hooks/useCoworkRun'
import { useMessageQueue } from '@/stores/message-queue-store'
import { useModelProvider } from '@/hooks/useModelProvider'
import { answerAsk } from '@/lib/coworkRunner'
+import {
+ sessionFromThread,
+ sessionToThreadRecord,
+} from '@/lib/coworkPersistence'
+import { sessionToSidecar } from '@/lib/migrateCoworkSessions'
import { localStorageKey } from '@/constants/localStorage'
// The router mock returns the supplied component options directly.
const routeOptions = Route as unknown as { component: () => ReactNode }
@@ -484,10 +489,16 @@ it('restores each session model after switching and persisted-store rehydration'
expect(document.querySelector('header')).toHaveTextContent('second-model')
)
view.unmount()
- const savedSessions = backend.storage.get(localStorageKey.coworkSessions)!
+ // A restart: every session goes through the record it is stored as (thread
+ // record + sidecar) and back, which is what write-through hydration does.
+ const restored = useCoworkSessions.getState().sessions.map((session) =>
+ sessionFromThread(
+ sessionToThreadRecord(session),
+ sessionToSidecar(session)
+ )
+ )
useCoworkSessions.setState({ sessions: [], currentId: null })
- backend.storage.set(localStorageKey.coworkSessions, savedSessions)
- await useCoworkSessions.persist.rehydrate()
+ useCoworkSessions.setState({ sessions: restored, currentId: a })
render(<CoworkPage />)
await waitFor(() =>
expect(document.querySelector('header')).toHaveTextContent('second-model')
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index 41b11b50b..c2d8bd8e6 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -109,6 +109,7 @@ import {
writeBlackboard,
importAttachment,
cancelAgentThreadBash,
+ cancelAgentThreadBashStrict,
activeAgentMonitorIds,
} from '@/lib/agentTools'
import { monitorLaneFor, type MonitorLane } from '@/lib/coworkMonitor'
@@ -127,7 +128,11 @@ import {
type StreamSink,
type ToolOutcome,
} from '@/lib/coworkRunner'
-import { useCoworkRun } from '@/hooks/useCoworkRun'
+import {
+ useCoworkRun,
+ registerCoworkRunForClose,
+ isCoworkClosing,
+} from '@/hooks/useCoworkRun'
import {
listSubagents,
type SubagentDefinition,
@@ -454,7 +459,15 @@ function CoworkPage() {
) => {
const store = useCoworkSessions.getState()
const current = store.sessions.find((s) => s.id === sid)
- if (!current || useCoworkRun.getState().runId[sid]) return
+ // A closing window has already stopped its runs; a new one would start a
+ // turn nobody awaits. An unavailable session is read-only by design.
+ if (
+ isCoworkClosing() ||
+ !current ||
+ current.unavailable ||
+ useCoworkRun.getState().runId[sid]
+ )
+ return
if (!text && !(current?.messages?.length ?? 0)) return
const modelState = useModelProvider.getState()
const modelChoice =
@@ -495,6 +508,47 @@ function CoworkPage() {
useCoworkRun
.getState()
.beginRun(sid, handle.runId, text ?? '', attachments?.media)
+ // The window-close handshake (see coworkSync) must stop this run and wait
+ // for its final commit: until the `finally` below commits, the transcript
+ // and wire history exist only in this closure. Registered synchronously with
+ // the claim so a background or unmounted run participates too.
+ let resolveDone!: () => void
+ const done = new Promise<void>((resolve) => {
+ resolveDone = resolve
+ })
+ let closeRequested = false
+ let cancellationConfirmed = false
+ let committed = false
+ const unregisterClose = registerCoworkRunForClose(async () => {
+ closeRequested = true
+ abortRun(sid)
+ // A JS abort cannot kill native shells, nor force a stalled promise to
+ // settle. Refuse the close if teardown cannot be confirmed in time and
+ // stay registered so a later close can retry.
+ let timeout: ReturnType<typeof setTimeout> | undefined
+ try {
+ await Promise.race([
+ Promise.all([
+ done,
+ cancelAgentThreadBashStrict(sid).then(() => {
+ cancellationConfirmed = true
+ if (committed) unregisterClose()
+ }),
+ ]),
+ new Promise<never>((_, reject) => {
+ timeout = setTimeout(
+ () =>
+ reject(
+ new Error('Cowork teardown did not settle; keeping the window open')
+ ),
+ 5000
+ )
+ }),
+ ])
+ } finally {
+ clearTimeout(timeout)
+ }
+ })
let runTurns: CoworkTurn[] = []
let liveFrame: number | null = null
const syncLive = () => {
@@ -547,10 +601,15 @@ function CoworkPage() {
return
}
}
- if (text && current?.title === 'New session')
- // Collapse newlines/runs of whitespace so a pasted multi-line prompt
- // doesn't become an unreadable sidebar title.
- store.setTitle(sid, text.trim().replace(/\s+/g, ' ').slice(0, 40))
+ // Only while the title is still the default: a rename made during the
+ // awaits above (skill expansion) must win. Newlines and runs of
+ // whitespace are collapsed so a pasted multi-line prompt does not become
+ // an unreadable sidebar title.
+ if (text)
+ store.setTitleIfDefault(
+ sid,
+ text.trim().replace(/\s+/g, ' ').slice(0, 40)
+ )
runTurns = text
? [userTurn(text, attachments?.media, attachments?.files)]
@@ -1042,6 +1101,9 @@ function CoworkPage() {
useCoworkRun.getState().subagents[sid] ?? [],
outcome?.usage ?? undefined
)
+ committed = true
+ resolveDone()
+ if (!closeRequested || cancellationConfirmed) unregisterClose()
if (liveFrame != null) cancelAnimationFrame(liveFrame)
for (const resolve of handle.pendingAsks.values()) resolve(null)
handle.pendingAsks.clear()
@@ -1061,7 +1123,7 @@ function CoworkPage() {
// budget halt leaves the queue in place, visible as chips in the input.
if (stop === 'error') {
useMessageQueue.getState().clearQueue(sid)
- } else if (stop === 'done') {
+ } else if (stop === 'done' && !isCoworkClosing()) {
// Continue the originating session with its captured model and skill
// context, even when a different session is now being viewed.
setTimeout(() => {
diff --git a/web-app/src/services/__tests__/threads.test.ts b/web-app/src/services/__tests__/threads.test.ts
index ac5992d68..691870476 100644
--- a/web-app/src/services/__tests__/threads.test.ts
+++ b/web-app/src/services/__tests__/threads.test.ts
@@ -121,12 +121,13 @@ describe('DefaultThreadsService', () => {
expect(result).toEqual([])
})
- it('should handle null/undefined response', async () => {
+ it('should reject a null/undefined response instead of reporting no threads', async () => {
api.listThreads.mockResolvedValue(null)
- const result = await threadsService.fetchThreads()
-
- expect(result).toEqual([])
+ // Not-ready is not "zero threads": the caller must retry, not wipe.
+ await expect(threadsService.fetchThreads()).rejects.toThrow(
+ /non-array/
+ )
})
})
@@ -478,12 +479,15 @@ describe('DefaultThreadsService', () => {
)
})
- it('should handle fetchThreads with non-array response', async () => {
+ it('should reject fetchThreads with a non-array response', async () => {
api.listThreads.mockResolvedValue('not-an-array')
- const result = await threadsService.fetchThreads()
-
- expect(result).toEqual([])
+ await expect(threadsService.fetchThreads()).rejects.toThrow(
+ /non-array/
+ )
+ // A real empty listing is still an empty list.
+ api.listThreads.mockResolvedValue([])
+ await expect(threadsService.fetchThreads()).resolves.toEqual([])
})
it('should handle createThread with missing metadata in response', async () => {
diff --git a/web-app/src/services/threads/default.ts b/web-app/src/services/threads/default.ts
index 9904c4b25..0d927fbea 100644
--- a/web-app/src/services/threads/default.ts
+++ b/web-app/src/services/threads/default.ts
@@ -31,7 +31,11 @@ export class DefaultThreadsService implements ThreadsService {
// wiping the list with [].
const threads: StoredThread[] | null | undefined =
await window.core?.api?.listThreads()
- if (!Array.isArray(threads)) return []
+ // A non-array is a malformed/not-ready response, not "zero threads": only
+ // a real [] may be reported as an empty listing.
+ if (!Array.isArray(threads)) {
+ throw new Error('Thread listing returned a non-array response')
+ }
// new String("id") !== "id"
threads.forEach((e) => {