Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(sharing): propagate terminal task closure across profile instances
DavidShenb18f6a9f0b75
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.tsindex 1746bae007..5de3465b0f 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts@@ -54,6 +54,42 @@ beforeEach(() => {host = new SharedTaskHost(options);});describe('task host sharedTask lifecycle', () => {+ it('consumes another instance closure offline and invalidates captured access without touching another share', async () => {+ await host.open('session');+ const old = host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))!;+ const secondDetail = { ...detail(), sharedTaskId: 'other-share', sessionId: 'other-session' };+ api.create.mockResolvedValueOnce({ sharedTaskId: 'other-share', revision: 1 });+ api.get.mockResolvedValueOnce(secondDetail);+ await host.open('other-session');+ const other = host.capturePeer(sharedTaskGuestPeer('other-share', 'member-b', 'phone-b'))!;+ await options.journal.close(detail());+ vi.mocked(options.revoke).mockClear();+ api.list.mockRejectedValue(new Error('offline'));+ await host.restore(false);+ expect(old.isCurrent()).toBe(false);+ expect(canRead()).toBe(false);+ expect(other.isCurrent()).toBe(true);+ expect(options.revoke).toHaveBeenCalledExactlyOnceWith('sharedTask');+ expect(api.list).not.toHaveBeenCalled();+ await expect(host.restore()).rejects.toThrow('offline');+ expect(old.isCurrent()).toBe(false);+ });+ it.each(['archived', 'deleted'])('closes externally %s tasks even when the writing process never notified runtime', async (status) => {+ await host.open('session');+ const old = host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))!;+ options.readSession = vi.fn(async (id) => ({ id, title: 'Task', status }));+ await host.restore();+ expect(old.isCurrent()).toBe(false);+ expect(records.get('sharedTask')?.terminal).toBe(true);+ expect(api.close).toHaveBeenCalledWith('sharedTask');+ });+ it('closes a server-side share for a deleted task that was never restored locally', async () => {+ options.readSession = vi.fn(async () => null);+ await host.restore();+ expect(records.get('sharedTask')?.terminal).toBe(true);+ expect(api.close).toHaveBeenCalledWith('sharedTask');+ expect(api.get).not.toHaveBeenCalled();+ });it('allows first sharing after an unshared task is archived and restored', async () => {await host.closeLocallyForBoundary('session');options.readSession = vi.fn(async (id) => ({ id, title: 'Task', status: 'archived' }));diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.tsindex 23acedf77b..0b39ac9dbc 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts@@ -11,10 +11,10 @@ const state = vi.hoisted(() => ({session: { mode: 'cloud', dataOwnerId: 'owner', generation: 1 }, boundary: false,db: { client: { query: vi.fn() }, clientEpoch: 1 },hosts: [] as HostRecord[], dispatch: vi.fn(),- captureClose: vi.fn(), close: vi.fn(),+ captureClose: vi.fn(), close: vi.fn(), journalClose: vi.fn(),}));vi.mock('../../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot: () => state.db }));-vi.mock('../../localDb/sharedTasks.js', () => ({ createSharedTaskJournal: () => ({}) }));+vi.mock('../../localDb/sharedTasks.js', () => ({ createSharedTaskJournal: () => ({}), closeSharedTasksInJournalForSession: state.journalClose }));vi.mock('../../appSessionState.js', () => ({activeOwnerScopeKey: () => [state.session.mode, state.session.dataOwnerId, state.session.generation].join(':'),getActiveAppSession: () => ({ ...state.session }), isAppSessionBoundaryPending: () => state.boundary,@@ -36,7 +36,7 @@ vi.mock('../sharedTaskHost.js', () => ({},}));-import { closeSharedTasksBeforeLogout, requireSharedTaskHost, startSharedTaskRuntime, stopSharedTaskRuntime } from '../sharedTaskRuntime';+import { closeSharedTaskForTask, closeSharedTasksBeforeLogout, requireSharedTaskHost, startSharedTaskRuntime, stopSharedTaskRuntime } from '../sharedTaskRuntime';function start() {const client = { hasServerCapability: () => true, getStatus: () => 'online', start: vi.fn(), stop: vi.fn(), revoke: vi.fn() };@@ -53,6 +53,7 @@ beforeEach(async () => {state.hosts.length = 0; state.dispatch.mockClear();state.captureClose.mockReset().mockReturnValue(state.close);state.close.mockReset().mockResolvedValue({ status: 'closed' });+ state.journalClose.mockReset().mockResolvedValue(['sharedTask-a']);});afterEach(async () => {await stopSharedTaskRuntime();@@ -60,6 +61,39 @@ afterEach(async () => {});describe('shared runtime stable owner recommit', () => {+ it('persists terminal changes without a relay binding and closes using captured credentials', async () => {+ const db = state.db.client;+ let finish!: (ids: string[]) => void;+ state.journalClose.mockImplementation(() => new Promise<string[]>((resolve) => { finish = resolve; }));+ const pending = closeSharedTaskForTask('session', db);+ expect(state.journalClose).toHaveBeenCalledWith(db, 'session');+ expect(state.captureClose).toHaveBeenCalledWith('owner', 'global');+ expect(state.close).not.toHaveBeenCalled();+ state.accountId = 'new-owner'; state.region = 'cn';+ state.db = { client: { query: vi.fn() }, clientEpoch: 2 };+ finish(['sharedTask-a']);+ await pending;+ expect(state.close).toHaveBeenCalledExactlyOnceWith('sharedTask-a');+ expect(state.captureClose).toHaveBeenCalledTimes(1);+ });+ it('does not report a non-owner closure durable on disk failure', async () => {+ state.journalClose.mockRejectedValue(new Error('disk failed'));+ await expect(closeSharedTaskForTask('session', state.db.client)).rejects.toThrow('disk failed');+ expect(state.close).not.toHaveBeenCalled();+ });+ it('retains offline closure intent and ignores a different profile DB', async () => {+ state.close.mockRejectedValue(new Error('offline'));+ await expect(closeSharedTaskForTask('session', state.db.client)).resolves.toBeUndefined();+ expect(state.journalClose).toHaveBeenCalledOnce();+ await closeSharedTaskForTask('session', {});+ expect(state.journalClose).toHaveBeenCalledOnce();+ });+ it('reconciles profile-local terminal changes while relay is offline', async () => {+ const relay = start();+ relay.getStatus = () => 'connecting';+ await vi.advanceTimersByTimeAsync(5_000);+ expect(state.hosts[0].restore).toHaveBeenLastCalledWith(false);+ });it('preserves creation cleanup across same-profile rebind but not database replacement', () => {start();const original = state.hosts[0].options.creationState;diff --git a/apps/desktop/src/main/device-link/sharedTaskHost.ts b/apps/desktop/src/main/device-link/sharedTaskHost.tsindex 7a9cccc796..a30fa73518 100644--- a/apps/desktop/src/main/device-link/sharedTaskHost.ts+++ b/apps/desktop/src/main/device-link/sharedTaskHost.ts@@ -196,10 +196,37 @@ export class SharedTaskHost {return created.sharedTaskId;}- async restore(): Promise<void> {+ private revokeLocally(sharedTaskId: string): void {+ const alreadyClosed = this.closed.has(sharedTaskId);+ this.closed.add(sharedTaskId);+ const entry = this.entries.get(sharedTaskId);+ entry?.access.close();+ if (entry?.detail) entry.detail = Object.freeze({ ...entry.detail, status: 'closed' });+ if (!alreadyClosed) {+ this.options.revoke(sharedTaskId);+ this.options.changed(sharedTaskId);+ }+ }++ async restore(allowNetwork = true): Promise<void> {this.assertCurrent();const journal = await this.options.journal.latest();this.assertCurrent();+ // Shared profile writers hand off terminal changes through the journal.+ // Close access objects as well as the index so existing captures also expire.+ for (const item of journal) if (item.terminal) this.revokeLocally(item.sharedTaskId);+ const sessions = new Set([...this.entries.values()].map((entry) => entry.identity.sessionId));+ for (const identity of this.created.values()) sessions.add(identity.sessionId);+ for (const sessionId of this.creating.values()) sessions.add(sessionId);+ for (const sessionId of sessions) {+ const session = await this.options.readSession(sessionId);+ this.assertCurrent();+ if ((!session || session.status !== 'active') && !this.closedSessions.has(sessionId)) {+ await this.closeLocallyForBoundary(sessionId);+ this.assertCurrent();+ }+ }+ if (!allowNetwork) return;const active = await this.options.api.list();this.assertCurrent();const owned = active.filter((item) => item.ownerAccountId === this.options.ownerAccountId && item.hostDeviceId === this.options.hostDeviceId);@@ -215,6 +242,15 @@ export class SharedTaskHost {}for (const item of owned) {this.assertCurrent();+ // Covers a create that reached the server but was never accepted/journaled+ // here, and a terminal write made by a different process before startup.+ const session = await this.options.readSession(item.sessionId);+ this.assertCurrent();+ if (!session || session.status !== 'active') {+ this.revokeLocally(item.sharedTaskId);+ await this.options.journal.close(item);+ this.assertCurrent();+ }if (this.closed.has(item.sharedTaskId)) {// Retry a previous explicit close that was persisted before connectivity// failed. A process restart itself never closes an active sharedTask.diff --git a/apps/desktop/src/main/device-link/sharedTaskRuntime.ts b/apps/desktop/src/main/device-link/sharedTaskRuntime.tsindex bcb9c51ca4..2e47c8d018 100644--- a/apps/desktop/src/main/device-link/sharedTaskRuntime.ts+++ b/apps/desktop/src/main/device-link/sharedTaskRuntime.ts@@ -1,6 +1,6 @@import { SHARED_TASK_CAPABILITY, type DeviceLinkClient } from '@cindy/device-link';import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';-import { createSharedTaskJournal } from '../localDb/sharedTasks.js';+import { closeSharedTasksInJournalForSession, createSharedTaskJournal } from '../localDb/sharedTasks.js';import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';import { getAuthState, getCurrentUserId, getDeviceId, getActiveAuthRealm } from '../authManager.js';import { createLogger } from '../logger.js';@@ -80,10 +80,13 @@ export function startSharedTaskRuntime(options: {};const refresh = async () => {if (!current()) { rebindIfStable(); return; }- if (refreshing || !current() || !options.client.hasServerCapability(SHARED_TASK_CAPABILITY) ||- options.client.getStatus() !== 'online') return;+ if (refreshing || !current()) return;refreshing = true;- try { await host.restore(); }+ try {+ // Local terminal records must revoke captures even while HTTP/relay is down.+ await host.restore(options.client.hasServerCapability(SHARED_TASK_CAPABILITY) &&+ options.client.getStatus() === 'online');+ }catch { if (current()) log.debug('sharedTask authority refresh unavailable; retrying on next tick'); }finally { refreshing = false; }};@@ -129,9 +132,14 @@ export async function closeSharedTasksBeforeLogout(): Promise<void> {/** Terminal task state is durable before this runs; never reopen it on a later restore. */export async function closeSharedTaskForTask(sessionId: string, database: unknown): Promise<void> {- if (getCurrentDbClientSnapshot()?.client !== database) return;- if (!binding || binding.dbEpoch !== getCurrentDbClientSnapshot()?.clientEpoch) return;- const ids = await binding.host.closeLocallyForBoundary(sessionId);+ const db = getCurrentDbClientSnapshot();+ if (!db || db.client !== database) return;+ const outgoing = binding?.database === db.client && binding.dbEpoch === db.clientEpoch ? binding : null;+ // Capture before any await: old-profile cleanup must never use a new account.+ const ownerAccountId = getCurrentUserId();+ const close = ownerAccountId ? captureSharedTaskBoundaryClose(ownerAccountId, getActiveAuthRealm()) : null;+ const localIds = outgoing ? await outgoing.host.closeLocallyForBoundary(sessionId) : [];+ const ids = new Set([...localIds, ...await closeSharedTasksInJournalForSession(db.client, sessionId)]);// Network failure is retried from the terminal journal; never undo the task archive.- for (const id of ids) void sharedTaskApi.close(id).catch(() => undefined);+ if (close) await Promise.allSettled([...ids].map((id) => close(id)));}diff --git a/apps/desktop/src/main/localDb/__tests__/sharedTasks.test.ts b/apps/desktop/src/main/localDb/__tests__/sharedTasks.test.tsindex 2f75f7ddf3..5b3b0e230a 100644--- a/apps/desktop/src/main/localDb/__tests__/sharedTasks.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/sharedTasks.test.ts@@ -2,7 +2,7 @@ import Database from 'better-sqlite3';import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { createSharedTaskJournal } from '../sharedTasks.js';+import { closeSharedTasksInJournalForSession, createSharedTaskJournal } from '../sharedTasks.js';import type { SharedTaskSnapshot } from '@cindy/device-link';const snapshot = (revision = 1): SharedTaskSnapshot => ({@@ -24,6 +24,22 @@ beforeEach(() => {afterEach(() => db.close());describe('sharedTask authority journal', () => {+ it('hands off all generations of only the terminal task through the shared profile journal', async () => {+ await journal.recordAuthority(snapshot());+ await journal.recordAuthority({ ...snapshot(), sharedTaskId: 'new-share' });+ await journal.recordAuthority({ ...snapshot(), sharedTaskId: 'other-share', sessionId: 'other-session' });+ const writer = {+ async exec(sql: string, params: unknown[] = []) { return db.prepare(sql).run(...params); },+ async query<T>(sql: string, params: unknown[] = []) { return db.prepare(sql).all(...params) as T[]; },+ };+ expect((await closeSharedTasksInJournalForSession(writer, 'session')).sort()).toEqual(['new-share', 'sharedTask']);+ await closeSharedTasksInJournalForSession(writer, 'session');+ expect(await journal.recordAuthority(snapshot(99))).toBe(false);+ const records = await journal.latest();+ expect(records.filter((item) => item.sessionId === 'session').every((item) => item.terminal)).toBe(true);+ expect(records.find((item) => item.sharedTaskId === 'other-share')?.terminal).toBe(false);+ expect(await closeSharedTasksInJournalForSession(writer, 'unshared')).toEqual([]);+ });it('retains membership changes and reads only the latest authority', async () => {expect(await journal.recordAuthority(snapshot())).toBe(true);expect(await journal.recordAuthority({ ...snapshot(2), guests: [] })).toBe(true);diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 4c137ceede..1589917913 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -1,4 +1,5 @@import { runTaskTagsTransaction } from '../worker/opHandlers/taskTagsTx.js';+import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL } from '../sharedTaskClosureSql.js';import fs from 'node:fs';import path from 'node:path';import { Worker } from 'node:worker_threads';@@ -17,6 +18,7 @@ import {import { isBackgroundDbRpc } from './rpcAdmission.js';const WORKER_CODE = `+const CLOSE_SHARED_TASKS_FOR_SESSION_SQL = ${JSON.stringify(CLOSE_SHARED_TASKS_FOR_SESSION_SQL)};const runTaskTagsTransaction = ${runTaskTagsTransaction.toString()};// 旧版 inline worker fallback。默认运行时走 .vite/build/dbWorker.js;// 这段只作为打包路径回滚口保留,后续验证 macOS / Windows packaged 后删除。@@ -1247,6 +1249,7 @@ function sessionImportShare(readyDb, args) {const replacementUpdatedAt = expectNumber(session.updatedAt, 'session.updatedAt');for (const replacedSession of replaceSessions) {deleteReplacedSession.run(replacementUpdatedAt, replacedSession.id);+ readyDb.prepare(CLOSE_SHARED_TASKS_FOR_SESSION_SQL).run(replacementUpdatedAt, replacedSession.id);}let count = insertSessionWithMessages(session, messages);if (orca) {diff --git a/apps/desktop/src/main/localDb/sharedTaskClosureSql.ts b/apps/desktop/src/main/localDb/sharedTaskClosureSql.tsnew file mode 100644index 0000000000..cec3f5f521--- /dev/null+++ b/apps/desktop/src/main/localDb/sharedTaskClosureSql.ts@@ -0,0 +1,8 @@+/** Atomic, profile-local handoff of task closure to whichever process owns relay.+ * Reused inside replacement transactions so rollback also preserves sharing. */+export const CLOSE_SHARED_TASKS_FOR_SESSION_SQL = `+ INSERT INTO shared_task_events (shared_task_id, session_id, revision, kind, terminal, snapshot, recorded_at)+ SELECT DISTINCT shared_task_id, session_id, 0, 'local-close', 1, NULL, ?+ FROM shared_task_events WHERE session_id = ?+ ON CONFLICT (shared_task_id, kind, revision) DO NOTHING+`;diff --git a/apps/desktop/src/main/localDb/sharedTasks.ts b/apps/desktop/src/main/localDb/sharedTasks.tsindex 8baa2304ed..434f5d003d 100644--- a/apps/desktop/src/main/localDb/sharedTasks.ts+++ b/apps/desktop/src/main/localDb/sharedTasks.ts@@ -1,5 +1,14 @@import { parseSharedTaskSnapshot, type SharedTaskIdentity, type SharedTaskSnapshot } from '@cindy/device-link';import type { DbClient } from './client/DbClient.js';+import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL } from './sharedTaskClosureSql.js';++/** Does not require a live Host; the captured profile DB owns these closures. */+export async function closeSharedTasksInJournalForSession(db: Pick<DbClient, 'exec' | 'query'>, sessionId: string): Promise<string[]> {+ await db.exec(CLOSE_SHARED_TASKS_FOR_SESSION_SQL, [Date.now(), sessionId]);+ const rows = await db.query<{ shared_task_id: string }>(+ 'SELECT DISTINCT shared_task_id FROM shared_task_events WHERE session_id = ? AND terminal = 1', [sessionId]);+ return rows.map((row) => row.shared_task_id);+}export interface SharedTaskJournalEntry {sharedTaskId: string;diff --git a/apps/desktop/src/main/localDb/worker/__tests__/sessionImportShareTx.test.ts b/apps/desktop/src/main/localDb/worker/__tests__/sessionImportShareTx.test.tsindex 233dce916a..e08c6fbdfa 100644--- a/apps/desktop/src/main/localDb/worker/__tests__/sessionImportShareTx.test.ts+++ b/apps/desktop/src/main/localDb/worker/__tests__/sessionImportShareTx.test.ts@@ -1,4 +1,6 @@import Database from 'better-sqlite3';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { tx } from '../opHandlers/tx.js';@@ -151,6 +153,7 @@ describe('tx session.importShare', () => {beforeEach(() => {db = new Database(':memory:');createTables(db);+ db.exec(readFileSync(resolve(process.cwd(), 'drizzle/0114_shared_task_events.sql'), 'utf8'));});afterEach(() => {@@ -353,7 +356,11 @@ describe('tx session.importShare', () => {replaceSessions?: Array<{ id: string; status: 'active' | 'archived' }>;}).replaceSessions = [{ id: 'existing-session', status: 'active' }];+ db.prepare(+ "INSERT INTO shared_task_events (shared_task_id, session_id, revision, kind, terminal, recorded_at) VALUES ('old-share', 'existing-session', 1, 'authority', 0, 1)",+ ).run();tx(db, args);+ expect(db.prepare("SELECT terminal FROM shared_task_events WHERE shared_task_id = 'old-share' ORDER BY id DESC LIMIT 1").get()).toEqual({ terminal: 1 });expect(db.prepare('SELECT status FROM sessions WHERE id = ?').get('existing-session'),@@ -404,7 +411,11 @@ describe('tx session.importShare', () => {}).replaceSessions = [{ id: 'existing-session', status: 'active' }];(args.args.orca.workers[0].session as Record<string, unknown>).title = 42;+ db.prepare(+ "INSERT INTO shared_task_events (shared_task_id, session_id, revision, kind, terminal, recorded_at) VALUES ('old-share', 'existing-session', 1, 'authority', 0, 1)",+ ).run();expect(() => tx(db, args)).toThrow();+ expect(db.prepare("SELECT terminal FROM shared_task_events WHERE shared_task_id = 'old-share' ORDER BY id DESC LIMIT 1").get()).toEqual({ terminal: 0 });expect(db.prepare('SELECT status FROM sessions WHERE id = ?').get('existing-session'),diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 9501055ea5..5bd0d6dff7 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -1,4 +1,5 @@import { runTaskTagsTransaction } from './taskTagsTx.js';+import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL } from '../../sharedTaskClosureSql.js';import { normalizeBotName } from '../../../../shared/botCreation.js';import { inferBotTemplatePresetId } from '../../../../shared/botTemplatePreset.js';// inproc 回滚口:仅在 XDT_DB_INPROC=true 时使用。@@ -2832,6 +2833,7 @@ function sessionImportShare(db: Database.Database, args: unknown): { messageCounconst replacementUpdatedAt = expectNumber(session.updatedAt, 'session.updatedAt');for (const replacedSession of replaceSessions) {deleteReplacedSession.run(replacementUpdatedAt, replacedSession.id);+ db.prepare(CLOSE_SHARED_TASKS_FOR_SESSION_SQL).run(replacementUpdatedAt, replacedSession.id);}let messageCount = insertSessionWithMessages(session, messages);if (orca) {diff --git a/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts b/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.tsindex bf4a09d573..530332efdf 100644--- a/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts+++ b/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts@@ -57,6 +57,8 @@ const cindyMediaMock = vi.hoisted(() => ({const legacyImageMock = vi.hoisted(() => ({removeSessionCalls: [] as string[],}));+const closeSharedTaskForTask = vi.hoisted(() => vi.fn());+vi.mock('../../device-link/sharedTaskRuntime.js', () => ({ closeSharedTaskForTask }));vi.mock('electron', () => ({app: { getPath: () => tmpRoot, getVersion: () => '9.9.9' },@@ -431,6 +433,7 @@ async function writeBundleFile(bytes: Buffer, password?: string): Promise<stringdescribe('sessionShareImport', () => {beforeEach(async () => {+ closeSharedTaskForTask.mockReset().mockResolvedValue(undefined);dbMock.conflictRow = null;dbMock.conflictForResumeId = null;dbMock.conflictGraphRows = [];@@ -843,6 +846,7 @@ describe('sessionShareImport', () => {replaceSessions?: Array<{ id: string; status: 'active' | 'archived' }>;};expect(txArgs.replaceSessions).toEqual([{ id: 'existing-session', status: 'active' }]);+ expect(closeSharedTaskForTask).toHaveBeenCalledExactlyOnceWith('existing-session', expect.objectContaining({ tx: expect.any(Function) }));});it('overwrite failure leaves replacement entirely to the failed transaction', async () => {@@ -862,6 +866,7 @@ describe('sessionShareImport', () => {).rejects.toMatchObject({ code: 'SHARE_IMPORT_FAILED' });// tx mock 在失败时不记录调用;编排层没有提前 patch/清理旧 session。expect(dbMock.txCalls).toHaveLength(0);+ expect(closeSharedTaskForTask).not.toHaveBeenCalled();});it('overwrite flag is a no-op when there is no conflict', async () => {@@ -879,6 +884,7 @@ describe('sessionShareImport', () => {expect(dbMock.txCalls).toHaveLength(1);const txArgs = dbMock.txCalls[0].args as { replaceSessions?: Array<{ id: string; status: string }> };expect(txArgs.replaceSessions).toBeUndefined();+ expect(closeSharedTaskForTask).not.toHaveBeenCalled();});it('reuses pre-existing transcript on disk without overwriting (deleted-session re-import)', async () => {diff --git a/apps/desktop/src/main/session-share/sessionShareImport.ts b/apps/desktop/src/main/session-share/sessionShareImport.tsindex b0b27d5faa..9fe089b3c6 100644--- a/apps/desktop/src/main/session-share/sessionShareImport.ts+++ b/apps/desktop/src/main/session-share/sessionShareImport.ts@@ -932,6 +932,15 @@ export async function commitShareImport(// revalidating the owner so a stale completion cannot be retried into// another profile and duplicate the already committed import.drafts.delete(opts.draftId);+ // The transaction already persisted closure intent for the old graph.+ // Revoke this process's live Host too; another owner consumes the journal.+ if (conflictExisting.length > 0) {+ const { closeSharedTaskForTask } = await import('../device-link/sharedTaskRuntime.js');+ for (const replaced of conflictExisting) {+ try { await closeSharedTaskForTask(replaced.id, dbClient); }+ catch { log.warn('shared task runtime cleanup pending after committed import'); }+ }+ }assertStillValid();},);diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.mdindex b254bfcd12..8a739576a1 100644--- a/docs/product-rules/shared-task-mode.md+++ b/docs/product-rules/shared-task-mode.md@@ -51,6 +51,8 @@- Desktop 与 Mobile 复用现有任务页面;房主在手机上通过既有同账号远控管理共享。网页端和匿名访客不在范围内。- 新协议以能力协商开放;缺少能力提示升级。两区域独立,不默认跨区域加入。- 关闭记录必须落入原 profile 的 journal 后才能释放数据库;本地同步撤权,服务端失败下次恢复重试。+- 同一 profile 的非 relay 持有实例归档/删除任务,也必须写入该 profile 的共享关闭记录,并以操作开始时捕获的账号凭证尝试关闭服务端共享。Host 在既有 5 秒刷新周期先消化本地关闭记录、使现有授权捕获失效,再查询服务端;relay 离线或服务端读取失败不能跳过本地撤权。此机制只关闭对应共享,不重启 relay 或影响其他任务。+- 覆盖式任务文件导入属于旧任务的终态变更:被替换的旧任务图及其共享关闭记录在同一数据库事务提交,失败一起回滚;成功后再通知本机共享运行时撤权。即使成功回执丢失或进程切换,持有 relay 的实例仍可从持久记录完成关闭,新导入任务不继承旧共享。- 登出时等待已发出的创建请求收尾,迟到的创建 ID 也必须先落关闭记录;在线关闭仅使用退出账号的固定凭证与端点,不刷新或影响新账号。- 移除请求未获确认前暂停该成员访问;网络失败须以服务端状态恢复。临时暂停或同账号新增设备造成的旧授权失效返回可重试错误,只有确认撤权才从访客端移除任务。- 本仓只改客户端;服务端实现位于独立 cindy-server 的本任务 worktree。两仓协议需一致。