Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(sharing): make task closure terminal updates atomic
DavidShen2efc6268b592
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 1589917913..9e3a4152af 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -453,6 +453,8 @@ function dispatchTx(readyDb, payload) {return sessionsRenameTitles(readyDb, request.args);case 'sessions.setStatus':return sessionsSetStatus(readyDb, request.args);+ case 'sessions.setTerminalStatus':+ return sessionsSetTerminalStatus(readyDb, request.args);case 'recentWorkdirs.mergeWindowsIdentity':return recentWorkdirsMergeWindowsIdentity(readyDb, request.args);case 'recentWorkdirs.removeWindowsIdentity':@@ -1076,6 +1078,7 @@ function sessionsSetStatus(readyDb, args) {expectString(id, 'sessionId'),);const status = expectString(payload.status, 'status');+ const closeSharedTasks = payload.closeSharedTasks === true;if (status !== 'active' && status !== 'archived') {throw Object.assign(new Error('invalid status: ' + status), { code: 'INVALID_ARGS' });}@@ -1102,6 +1105,9 @@ function sessionsSetStatus(readyDb, args) {});}const updated = updateSession.get(status, now, sessionId);+ if (closeSharedTasks && status === 'archived') {+ readyDb.prepare(CLOSE_SHARED_TASKS_FOR_SESSION_SQL).run(now, sessionId);+ }if (!updated) throw Object.assign(new Error('Session 不存在: ' + sessionId), { code: 'NOT_FOUND' });applied.push({sessionId: updated.id,@@ -1117,6 +1123,29 @@ function sessionsSetStatus(readyDb, args) {})();}+// Keep this in sync with worker/opHandlers/tx.ts.+function sessionsSetTerminalStatus(readyDb, args) {+ const payload = asRecord(args, 'sessions.setTerminalStatus args');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const status = expectString(payload.status, 'status');+ if (status !== 'archived' && status !== 'deleted') {+ throw Object.assign(new Error('invalid terminal status: ' + status), { code: 'INVALID_ARGS' });+ }+ return readyDb.transaction(() => {+ const existing = readyDb.prepare('SELECT id, status, source FROM sessions WHERE id = ? LIMIT 1').get(sessionId);+ if (!existing) throw Object.assign(new Error('Session not found: ' + sessionId), { code: 'NOT_FOUND' });+ if (existing.status === 'deleted') throw Object.assign(new Error('Deleted session cannot change status: ' + sessionId), { code: 'PRECONDITION_FAILED' });+ if (existing.source === 'bot') throw Object.assign(new Error('Bot sessions must use Bot lifecycle: ' + sessionId), { code: 'PRECONDITION_FAILED' });+ const now = Date.now();+ readyDb.prepare(CLOSE_SHARED_TASKS_FOR_SESSION_SQL).run(now, sessionId);+ const updated = readyDb.prepare(+ 'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, remote_host_id AS remoteHostId, source',+ ).get(status, now, sessionId);+ if (!updated) throw Object.assign(new Error('Session not found: ' + sessionId), { code: 'NOT_FOUND' });+ return { ...updated, sessionId: updated.id, status };+ })();+}+function compactSessionToolResults(readyDb, args) {const payload = asRecord(args, 'toolResults.compactSession args');const sessionId = expectString(payload.sessionId, 'sessionId');diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex 9811b82e03..b775b439c0 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -1785,6 +1785,34 @@ describe('db worker tx handlers', () => {},);+ it.each([false, true])(+ 'sessions.setTerminalStatus commits the local-close fence atomically (inline=%s)',+ async (useInlineWorker) => {+ await withClient(+ async (client) => {+ await seedSession(client, 'terminal');+ await client.exec(+ `INSERT INTO shared_task_events (shared_task_id, session_id, revision, kind, terminal, snapshot, recorded_at)+ VALUES (?, ?, 1, 'authority', 0, ?, ?)`,+ ['share-terminal', 'terminal', JSON.stringify({ sharedTaskId: 'share-terminal' }), Date.now()],+ );+ await expect(client.tx('sessions.setTerminalStatus', {+ sessionId: 'terminal',+ status: 'archived',+ })).resolves.toEqual(expect.objectContaining({ sessionId: 'terminal', status: 'archived' }));+ await expect(client.query('SELECT status FROM sessions WHERE id = ?', ['terminal']))+ .resolves.toEqual([{ status: 'archived' }]);+ await expect(client.query(+ `SELECT terminal FROM shared_task_events+ WHERE shared_task_id = ? AND kind = 'local-close' AND revision = 0`,+ ['share-terminal'],+ )).resolves.toEqual([{ terminal: 1 }]);+ },+ { useInlineWorker },+ );+ },+ );+it('rewind.commit follows transcript parent links and preserves the prior assistant when timestamps are inverted', async () => {await withClient(async (client) => {await seedSession(client, 's1');diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 341b66e5e5..c87381248a 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -22,6 +22,7 @@ export type DbTxName =| 'orca.reconcileInactiveTeamWorkersForLead'| 'sessions.renameTitles'| 'sessions.setStatus'+ | 'sessions.setTerminalStatus'| 'recentWorkdirs.mergeWindowsIdentity'| 'recentWorkdirs.removeWindowsIdentity'| 'projectAliases.replaceIdentity'@@ -343,6 +344,12 @@ export interface SessionsRenameTitleResult {export interface SessionsSetStatusArgs {sessionIds: string[];status: 'active' | 'archived';+ closeSharedTasks?: boolean;+}++export interface SessionsSetTerminalStatusArgs {+ sessionId: string;+ status: 'archived' | 'deleted';}/** resume 停泊失败后的原子回落:清失效绑定并把边界改成全量交接。 */@@ -1178,6 +1185,7 @@ export type DbTxArgsByName = {'orca.reconcileInactiveTeamWorkersForLead': OrcaReconcileInactiveTeamWorkersForLeadArgs;'sessions.renameTitles': SessionsRenameTitlesArgs;'sessions.setStatus': SessionsSetStatusArgs;+ 'sessions.setTerminalStatus': SessionsSetTerminalStatusArgs;'recentWorkdirs.mergeWindowsIdentity': RecentWorkdirsMergeWindowsIdentityArgs;'recentWorkdirs.removeWindowsIdentity': RecentWorkdirsRemoveWindowsIdentityArgs;'taskTags.execute': TaskTagRequest & { newId?: string; callerSessionId?: string };@@ -1251,6 +1259,7 @@ export type DbTxResultByName = {'orca.reconcileInactiveTeamWorkersForLead': string[];'sessions.renameTitles': SessionsRenameTitleResult[];'sessions.setStatus': SessionsSetStatusResultItem[];+ 'sessions.setTerminalStatus': SessionsSetStatusResultItem;'recentWorkdirs.mergeWindowsIdentity': undefined;'recentWorkdirs.removeWindowsIdentity': { changes: number };'taskTags.execute': TaskTagResult;diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex c551b58c23..99501ce69e 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -342,6 +342,23 @@ async function writeSessionPatch(throwIpcError('PRECONDITION_FAILED', '已删除的任务不能恢复或归档');}+async function setTerminalSessionStatus(+ dbClient: DbClient,+ sessionId: string,+ status: 'archived' | 'deleted',+): Promise<void> {+ try {+ await dbClient.tx('sessions.setTerminalStatus', { sessionId, status });+ } catch (error) {+ const code = (error as { code?: string }).code;+ const message = error instanceof Error ? error.message : String(error);+ if (code === 'NOT_FOUND' || code === 'INVALID_PARAMS' || code === 'PRECONDITION_FAILED') {+ throwIpcError(code, message);+ }+ throw error;+ }+}+export function captureSessionRecycleScope(dbClient: DbClient = getDbClient(),): SessionRecycleScope {@@ -1954,14 +1971,24 @@ export async function updateSessionInDb(await moveGuard?.beforeWrite?.();moveGuard?.assertCurrent();const terminal = p.status === 'archived' || p.status === 'deleted';- const prepared = terminal ? await prepareSharedTaskClosure(sid, dbClient) : null;- try {+ if (terminal) {+ if (typeof dbClient.tx === 'function') {+ const { status: _status, ...nonTerminalPatch } = setObj;+ await writeSessionPatch(db, sid, nonTerminalPatch, undefined);+ await setTerminalSessionStatus(dbClient, sid, p.status as 'archived' | 'deleted');+ } else {+ const prepared = await prepareSharedTaskClosure(sid, dbClient);+ try {+ await writeSessionPatch(db, sid, setObj, p.status);+ } catch (error) {+ await rollbackSharedTaskClosure(dbClient, prepared);+ throw error;+ }+ await finalizeSharedTaskClosure(dbClient, prepared);+ }+ } else {await writeSessionPatch(db, sid, setObj, p.status);- } catch (error) {- await rollbackSharedTaskClosure(dbClient, prepared);- throw error;}- await finalizeSharedTaskClosure(dbClient, prepared);cleanupSessionRuntimeForTerminalStatus(sid, p.status);if (terminal) {const { closeSharedTaskForTask } = await import('../../device-link/sharedTaskRuntime.js');@@ -2127,14 +2154,24 @@ export async function patchSessionMetaInDb(const updated = await withStatusWriteLock(db, sessionId, patch.status, async () => {if (patch.status !== undefined) await assertGenericSessionLifecycleAllowed(db, sessionId);const terminal = patch.status === 'archived' || patch.status === 'deleted';- const prepared = terminal ? await prepareSharedTaskClosure(sessionId, dbClient) : null;- try {+ if (terminal) {+ if (typeof dbClient.tx === 'function') {+ const { status: _status, ...nonTerminalPatch } = setObj;+ await writeSessionPatch(db, sessionId, nonTerminalPatch, undefined);+ await setTerminalSessionStatus(dbClient, sessionId, patch.status as 'archived' | 'deleted');+ } else {+ const prepared = await prepareSharedTaskClosure(sessionId, dbClient);+ try {+ await writeSessionPatch(db, sessionId, setObj, patch.status);+ } catch (error) {+ await rollbackSharedTaskClosure(dbClient, prepared);+ throw error;+ }+ await finalizeSharedTaskClosure(dbClient, prepared);+ }+ } else {await writeSessionPatch(db, sessionId, setObj, patch.status);- } catch (error) {- await rollbackSharedTaskClosure(dbClient, prepared);- throw error;}- await finalizeSharedTaskClosure(dbClient, prepared);const row = await selectSessionWithCount(db, sessionId);if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');if (patch.pinnedAt !== undefined && row.pinnedAt == null) {@@ -2331,43 +2368,28 @@ export async function setSessionsStatusInDb(}const physicalResources = await Promise.all([...new Set(resources)].map(physicalWorktreeKey));return withWorktreeMutation(resources, async () => {- const prepared: SharedTaskClosurePreparation[] = [];- let committed = false;- try {- if (status === 'archived') {- for (const id of sessionIds) {- const closure = await prepareSharedTaskClosure(id, dbClient);- if (closure) prepared.push(closure);- }- }- if (status === 'archived') {- for (const id of sessionIds) await requestWorktreeRecycle(id, perSession.get(id));- }- const rows = await dbClient.tx('sessions.setStatus', { sessionIds, status }).catch((err) => {+ if (status === 'archived') {+ for (const id of sessionIds) await requestWorktreeRecycle(id, perSession.get(id));+ }+ const rows = await dbClient.tx('sessions.setStatus', status === 'archived'+ ? { sessionIds, status, closeSharedTasks: true }+ : { sessionIds, status }).catch((err) => {const code = (err as { code?: string }).code;const message = err instanceof Error ? err.message : String(err);if (code === 'NOT_FOUND' || code === 'INVALID_PARAMS' || code === 'PRECONDITION_FAILED') {throwIpcError(code, message);}throw err;- });- committed = true;- for (const closure of prepared) await finalizeSharedTaskClosure(dbClient, closure);- for (const item of rows) {+ });+ for (const item of rows) {cleanupSessionRuntimeForTerminalStatus(item.sessionId, item.status);if (item.status === 'archived') {const { closeSharedTaskForTask } = await import('../../device-link/sharedTaskRuntime.js');await closeSharedTaskForTask(item.sessionId, dbClient);}- }- for (const resource of physicalResources) notifyWorktreeRecycleOpportunity(resource);- return rows;- } catch (error) {- if (!committed) {- for (const closure of prepared) await rollbackSharedTaskClosure(dbClient, closure);- }- throw error;}+ for (const resource of physicalResources) notifyWorktreeRecycleOpportunity(resource);+ return rows;});});for (const item of applied) {diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex d46e0b3cd3..b729bc1fc6 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -81,6 +81,8 @@ export function tx(db: Database.Database, args: unknown): unknown {return sessionsRenameTitles(db, txArgs);case 'sessions.setStatus':return sessionsSetStatus(db, txArgs);+ case 'sessions.setTerminalStatus':+ return sessionsSetTerminalStatus(db, txArgs);case 'recentWorkdirs.mergeWindowsIdentity':return recentWorkdirsMergeWindowsIdentity(db, txArgs);case 'recentWorkdirs.removeWindowsIdentity':@@ -1832,6 +1834,7 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{expectString(id, 'sessionId'),);const status = expectString(payload.status, 'status');+ const closeSharedTasks = payload.closeSharedTasks === true;if (status !== 'active' && status !== 'archived') {throw invalidArgs(`invalid status: ${status}`);}@@ -1873,6 +1876,9 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{if (!updated) {throw Object.assign(new Error(`Session 不存在: ${sessionId}`), { code: 'NOT_FOUND' });}+ if (closeSharedTasks && status === 'archived') {+ db.prepare(CLOSE_SHARED_TASKS_FOR_SESSION_SQL).run(now, sessionId);+ }applied.push({sessionId: updated.id,title: updated.title,@@ -1896,6 +1902,41 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{}>;}+/** Atomically persist a terminal task status and its local-close fence. */+function sessionsSetTerminalStatus(db: Database.Database, args: unknown): {+ sessionId: string;+ title: string | null;+ workingDir: string | null;+ workspaceKind: string | null;+ remoteHostId: string | null;+ source: string | null;+ status: 'archived' | 'deleted';+} {+ const payload = asRecord(args, 'sessions.setTerminalStatus args');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const status = expectString(payload.status, 'status');+ if (status !== 'archived' && status !== 'deleted') throw invalidArgs('invalid terminal status: ' + status);+ const transaction = db.transaction(() => {+ const existing = db.prepare('SELECT id, status, source FROM sessions WHERE id = ? LIMIT 1').get(sessionId) as+ | { id: string; status: string; source: string } | undefined;+ if (!existing) throw Object.assign(new Error('Session not found: ' + sessionId), { code: 'NOT_FOUND' });+ if (existing.status === 'deleted') throw Object.assign(new Error('Deleted session cannot change status: ' + sessionId), { code: 'PRECONDITION_FAILED' });+ if (existing.source === 'bot') throw Object.assign(new Error('Bot sessions must use Bot lifecycle: ' + sessionId), { code: 'PRECONDITION_FAILED' });+ const now = Date.now();+ if (status === 'archived' || status === 'deleted') db.prepare(CLOSE_SHARED_TASKS_FOR_SESSION_SQL).run(now, sessionId);+ const updated = db.prepare(+ 'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, remote_host_id AS remoteHostId, source',+ ).get(status, now, sessionId) as {+ id: string; title: string | null; workingDir: string | null; workspaceKind: string | null; remoteHostId: string | null; source: string | null;+ } | undefined;+ if (!updated) throw Object.assign(new Error('Session not found: ' + sessionId), { code: 'NOT_FOUND' });+ return { ...updated, sessionId: updated.id, status };+ });+ return transaction() as {+ sessionId: string; title: string | null; workingDir: string | null; workspaceKind: string | null; remoteHostId: string | null; source: string | null; status: 'archived' | 'deleted';+ };+}+function invalidateSessionListProjection(db: Database.Database, sessionId: string): void {db.prepare('UPDATE sessions SET list_preview = NULL, list_preview_role = NULL, list_message_count = NULL WHERE id = ?',diff --git a/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx b/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsxindex ea89df37a2..9bbff66852 100644--- a/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx+++ b/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx@@ -15,7 +15,9 @@ import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { JoinSharedTaskDialog } from './JoinSharedTaskDialog';import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';import { toast } from '@/lib/toast';+import { resetRemoteDataOwnerPushFence } from '@/lib/remoteDataOwnerPushFence';import { sharedTaskErrorKey } from './sharedTaskCompatibility';+import { remoteProjectsStore } from './remoteProjectsStore';type SharedTaskTab = 'current' | 'owned';type ConfirmState =@@ -37,6 +39,7 @@ export function SharedTaskButton({ session }: { session: Session }) {const [open, setOpen] = useState(false);const [tab, setTab] = useState<SharedTaskTab>('current');const [state, setState] = useState<SharedTaskHostState | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);const [owned, setOwned] = useState<SharedTaskOwnedItem[] | null>(null);const [confirm, setConfirm] = useState<ConfirmState | null>(null);const [busy, setBusy] = useState(false);@@ -52,11 +55,20 @@ export function SharedTaskButton({ session }: { session: Session }) {const result: SharedTaskHostState = guestSharedTaskId? { available: true, detail: await window.electronAPI.sharedTask.account({ action: 'get', sharedTaskId: guestSharedTaskId }) as SharedTaskDetail }: await host({ action: 'state', sessionId: session.id }) as SharedTaskHostState;- if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)) setState(result);+ if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)) {+ setState(result);+ setLoadError(null);+ }} catch (error) {- if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)- && sharedTaskErrorKey(error) === 'sharedTask.upgrade') {- setState({ available: false, detail: null });+ if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)) {+ const key = sharedTaskErrorKey(error);+ if (key === 'sharedTask.upgrade') {+ setState({ available: false, detail: null });+ setLoadError(null);+ } else {+ setState(null);+ setLoadError(key);+ }}}}, [guestSharedTaskId, host, session.id]);@@ -73,7 +85,7 @@ export function SharedTaskButton({ session }: { session: Session }) {const tabRef = useRef<SharedTaskTab>('current');useEffect(() => {const captured = ++epoch.current;- setState(null); setOwned(null); setConfirm(null); setTab('current');+ setState(null); setLoadError(null); setOwned(null); setConfirm(null); setTab('current');tabRef.current = 'current';pending.current = false; setBusy(false);void load(captured);@@ -151,6 +163,13 @@ export function SharedTaskButton({ session }: { session: Session }) {return { title: t('sharedTask.leaveTitle'), body: t('sharedTask.leaveBody'), keep: t('sharedTask.leaveKeep'), action: t('sharedTask.leave'),run: () => void run(async () => {await window.electronAPI.sharedTask.account({ action: 'leave', sharedTaskId: guestSharedTaskId! });+ const peerId = session.deviceLinkDeviceId;+ if (peerId) {+ remoteProjectsStore.removeDevice(peerId);+ resetRemoteDataOwnerPushFence(peerId);+ await window.electronAPI.deviceLink.closeLink(peerId).catch(() => undefined);+ }+ window.dispatchEvent(new Event('cindy:shared-task-owned-changed'));setConfirm(null); setOpen(false);}, false) };case 'closeCurrent':@@ -165,7 +184,11 @@ export function SharedTaskButton({ session }: { session: Session }) {const emptyIcon = (icon: React.ReactNode) => <span className="mb-4 inline-flex size-11 items-center justify-center rounded-full border border-[var(--border-default)]">{icon}</span>;const noticeClass = 'my-4 flex items-start gap-2 rounded-lg bg-[var(--surface-chip)] p-3 text-12 text-[var(--text-secondary)]';const avatarClass = 'inline-flex size-7 shrink-0 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface-chip)] text-11';- const currentTab = !state ? <p className="text-[var(--text-secondary)]">{t('sharedTask.sharing')}</p>+ const currentTab = loadError ? <div className="px-1 py-6 text-center">+ <p className="mb-4 text-[var(--text-secondary)]">{t(loadError)}</p>+ <Button variant="secondary" size="lg" onClick={() => void load(epoch.current)}>{t('sharedTask.retryAction')}</Button>+ </div>+ : !state ? <p className="text-[var(--text-secondary)]">{t('sharedTask.sharing')}</p>: !state.available ? <p className="text-[var(--text-secondary)]">{t('sharedTask.upgrade')}</p>: !detail && !guestSharedTaskId ? <><p className="mb-4 text-[var(--text-secondary)]">{t('sharedTask.startIntro')}</p>diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsxindex 6a6ea6f2b2..fe98d879d8 100644--- a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx+++ b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx@@ -8,10 +8,12 @@ import { SharedTaskButton } from '../SharedTaskButton';import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';import type { Session } from '@/lib/ccAgent.types';import { toast } from '@/lib/toast';-const state = vi.hoisted(() => ({ invoke: vi.fn(), host: vi.fn(), account: vi.fn(), t: vi.fn((key: string, _options?: unknown) => key) }));+const state = vi.hoisted(() => ({ invoke: vi.fn(), host: vi.fn(), account: vi.fn(), closeLink: vi.fn(), removeDevice: vi.fn(), resetFence: vi.fn(), t: vi.fn((key: string, _options?: unknown) => key) }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: state.t }) }));vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'owner' }) }));vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));+vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ resetRemoteDataOwnerPushFence: state.resetFence }));+vi.mock('../remoteProjectsStore', () => ({ remoteProjectsStore: { removeDevice: state.removeDevice } }));let container: HTMLDivElement;let root: Root;const ownerSession = { id: 'session-1' } as Session;@@ -29,7 +31,7 @@ beforeEach(() => {Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });vi.clearAllMocks(); setDataOwnerGeneration('owner');Object.assign(window, { electronAPI: {- deviceLink: { invoke: state.invoke },+ deviceLink: { invoke: state.invoke, closeLink: state.closeLink },sharedTask: { host: state.host, account: state.account },} });state.host.mockResolvedValue({ available: true, detail });@@ -52,9 +54,21 @@ it('renders an upgrade instruction when an old host rejects the new channel', asit('does not mislabel a timeout as an old host', async () => {state.host.mockRejectedValue(new Error('[DEVICE_LINK_TIMEOUT] timeout'));const body = await openWindow(ownerSession);- await waitFor(() => expect(body.textContent).toContain('sharedTask.sharing'));+ await waitFor(() => expect(body.textContent).toContain('sharedTask.requestTimedOut'));+ expect(within(body).getByRole('button', { name: 'sharedTask.retryAction' })).toBeDefined();expect(body.textContent).not.toContain('sharedTask.upgrade');});+it('retries a disconnected host after showing a recoverable error', async () => {+ let calls = 0;+ state.host.mockImplementation(() => ++calls <= 2+ ? Promise.reject(new Error('[DEVICE_LINK_NOT_CONNECTED] disconnected'))+ : Promise.resolve({ available: true, detail }));+ const body = await openWindow(ownerSession);+ await waitFor(() => expect(body.textContent).toContain('sharedTask.connectionFailed'));+ fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.retryAction' }));+ await waitFor(() => expect(body.textContent).toContain('sharedTask.inviteBoxTitle'));+ expect(state.host).toHaveBeenCalledTimes(3);+});it('distinguishes a local clipboard failure from a shared-task request failure', async () => {const copy = vi.fn().mockRejectedValue(new DOMException('Document is not focused.', 'NotAllowedError'));Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: copy } });@@ -301,3 +315,17 @@ it('does not offer to enter a guest task that is already open', async () => {expect(within(body).queryByRole('button', { name: 'sharedTask.enterTask' })).toBeNull();expect(within(body).getByRole('button', { name: 'sharedTask.leave' })).toBeDefined();});+it('cleans up the guest peer immediately after leaving', async () => {+ state.account.mockImplementation((command: { action: string }) => command.action === 'get'+ ? Promise.resolve(detail)+ : Promise.resolve([]));+ const peer = sharedTaskHostPeer('st1', 'desktop');+ const body = await openWindow({ id: 'session-1', deviceLinkDeviceId: peer } as Session);+ await waitFor(() => expect(body.textContent).toContain('sharedTask.joinedTitle'));+ fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.leave' }));+ fireEvent.click(within(body).getByRole('alertdialog').querySelector('button:last-child')!);+ await waitFor(() => expect(state.account).toHaveBeenCalledWith({ action: 'leave', sharedTaskId: 'st1' }));+ expect(state.removeDevice).toHaveBeenCalledWith(peer);+ expect(state.resetFence).toHaveBeenCalledWith(peer);+ expect(state.closeLink).toHaveBeenCalledWith(peer);+});