Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(cindy-make): stop hidden task delivery and sharing
MagicLizi7536a6fa7334
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.tsindex 5de3465b0f..6d920587bc 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { createSharedTaskApi, parseSharedTaskSnapshot, type SharedTaskDetail } from '@cindy/device-link';import type { SharedTaskJournalEntry } from '../../localDb/sharedTasks.js';import { SharedTaskHost, type SharedTaskHostOptions } from '../sharedTaskHost.js';-import { executeSharedTaskHostCommand } from '../sharedTaskCommands.js';+import { executeSharedTaskAccountCommand, executeSharedTaskHostCommand } from '../sharedTaskCommands.js';import { createIpcError } from '../../../shared/ipc-errors.js';const detail = (revision = 1): SharedTaskDetail => ({@@ -54,6 +54,66 @@ beforeEach(() => {host = new SharedTaskHost(options);});describe('task host sharedTask lifecycle', () => {+ it.each(['cindy-make', 'cindy-make-merge'])('closes an upgraded %s share and removes it from owner and guest directories', async (source) => {+ records.set('sharedTask', { sharedTaskId: 'sharedTask', sessionId: 'session', terminal: false, snapshot: parseSharedTaskSnapshot(detail()) });+ options.readSession = vi.fn(async id => ({ id, title: 'Task', status: 'active', source }));+ api.close.mockImplementation(async () => { serverDetail = { ...detail(2), status: 'closed', guests: [] }; });+ await host.restore();+ expect(records.get('sharedTask')?.terminal).toBe(true);+ expect(api.close).toHaveBeenCalledExactlyOnceWith('sharedTask');+ expect(api.get).not.toHaveBeenCalled();+ expect(canRead()).toBe(false);+ expect(host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))).toBeNull();+ await expect(executeSharedTaskAccountCommand({ action: 'owned' }, api, 'owner')).resolves.toEqual([]);+ await expect(executeSharedTaskAccountCommand({ action: 'list' }, api, 'guest-a')).resolves.toEqual([]);+ await expect(api.list()).resolves.toEqual([]);+ await expect(host.open('session')).rejects.toThrow('unavailable');+ expect(api.create).not.toHaveBeenCalled();+ });++ it.each(['cindy-make', 'cindy-make-merge'])('closes an unjournaled legacy %s share without restoring access', async (source) => {+ options.readSession = vi.fn(async id => ({ id, title: 'Task', status: 'active', source }));+ await host.restore();+ expect(records.get('sharedTask')?.terminal).toBe(true);+ expect(api.close).toHaveBeenCalledExactlyOnceWith('sharedTask');+ expect(api.get).not.toHaveBeenCalled();+ });++ it('revokes only a hidden share offline and retries server closure after restart', async () => {+ await host.open('session');+ const hiddenCapture = host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))!;+ const otherDetail = { ...detail(), sharedTaskId: 'other-share', sessionId: 'other-session' };+ api.create.mockResolvedValueOnce({ sharedTaskId: 'other-share', revision: 1 });+ api.get.mockResolvedValueOnce(otherDetail);+ await host.open('other-session');+ const otherCapture = host.capturePeer(sharedTaskGuestPeer('other-share', 'member-b', 'phone-b'))!;+ api.list.mockResolvedValue([detail(), otherDetail]);+ api.get.mockImplementation(async sharedTaskId => sharedTaskId === 'other-share' ? otherDetail : detail());+ options.readSession = vi.fn(async id => ({ id, title: 'Task', status: 'active', source: id === 'session' ? 'cindy-make' : 'cc' }));+ await host.restore(false);+ expect(hiddenCapture.isCurrent()).toBe(false);+ expect(otherCapture.isCurrent()).toBe(true);+ expect(records.get('sharedTask')?.terminal).toBe(true);+ expect(records.get('other-share')?.terminal).toBe(false);+ expect(api.close).not.toHaveBeenCalled();+ api.close.mockRejectedValueOnce(new Error('offline'));+ await expect(host.restore()).rejects.toThrow('offline');+ expect(hiddenCapture.isCurrent()).toBe(false);+ const restarted = new SharedTaskHost(options);+ await restarted.restore();+ expect(api.close.mock.calls).toEqual([['sharedTask'], ['sharedTask']]);+ expect(records.get('other-share')?.terminal).toBe(false);+ expect(restarted.capturePeer(sharedTaskGuestPeer('other-share', 'member-b', 'phone-b'))?.isCurrent()).toBe(true);+ expect(restarted.authorize('sharedTask', { accountId: 'guest-a', deviceId: 'phone-a' }, 'session', 'history.read').allowed).toBe(false);+ });++ it('does not grant an already-shared hidden task through a direct refresh', async () => {+ options.readSession = vi.fn(async id => ({ id, title: 'Task', status: 'active', source: 'cindy-make' }));+ await expect(host.refresh('sharedTask')).rejects.toThrow('unavailable');+ expect(records.size).toBe(0);+ expect(canRead()).toBe(false);+ });+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'))!;diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.tsindex dccc5fa66d..d9d6a66cd5 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts@@ -1,7 +1,8 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';type HostRecord = {- options: { creationState: unknown; isCurrent(): boolean; revoke(sharedTaskId: string, memberId?: string): void };+ options: { creationState: unknown; isCurrent(): boolean; revoke(sharedTaskId: string, memberId?: string): void;+ readSession(sessionId: string): Promise<{ id: string; source?: string | null } | null> };restore: ReturnType<typeof vi.fn>;dispose: ReturnType<typeof vi.fn>;closeLocallyForBoundary: ReturnType<typeof vi.fn>;@@ -78,6 +79,16 @@ afterEach(async () => {});describe('shared runtime stable owner recommit', () => {+ it('preserves the raw task source for shared-task restoration without changing the database', async () => {+ const session = { id: 'session', title: 'Legacy Make', status: 'active', source: 'cindy-make-merge' };+ state.db.client.query.mockResolvedValue([session]);+ start();+ await expect(state.hosts[0].options.readSession('session')).resolves.toEqual(session);+ expect(state.db.client.query).toHaveBeenCalledExactlyOnceWith(+ 'SELECT id, title, status, source FROM sessions WHERE id = ? LIMIT 1', ['session']);+ expect(state.db.client.exec).not.toHaveBeenCalled();+ });+it('prepares and rolls back a terminal journal only in the captured profile database', async () => {const db = state.db.client;const prepared = await prepareSharedTaskClosureForTask('session', db);diff --git a/apps/desktop/src/main/device-link/sharedTaskHost.ts b/apps/desktop/src/main/device-link/sharedTaskHost.tsindex a30fa73518..6a9be098c0 100644--- a/apps/desktop/src/main/device-link/sharedTaskHost.ts+++ b/apps/desktop/src/main/device-link/sharedTaskHost.ts@@ -2,6 +2,7 @@ import {parseSharedTaskSnapshot, parseSharedTaskPeer, type SharedTaskApi, type SharedTaskCaller,type SharedTaskDetail, type SharedTaskIdentity, type SharedTaskQueueItem,} from '@cindy/device-link';+import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';import type { SharedTaskJournal } from '../localDb/sharedTasks.js';import { isIpcError } from '../../shared/ipc-errors.js';import { SharedTaskAccess } from './sharedTaskAccess.js';@@ -27,7 +28,7 @@ export interface SharedTaskHostOptions {creationState?: SharedTaskCreationState;/** Bound at construction to this profile/auth/region generation. */isCurrent(): boolean;- readSession(sessionId: string): Promise<{ id: string; title: string; status: string } | null>;+ readSession(sessionId: string): Promise<{ id: string; title: string; status: string; source?: string | null } | null>;/** Teardown only the affected sharedTask/member, not the shared relay connection. */revoke(sharedTaskId: string, memberId?: string): void;changed(sharedTaskId: string): void;@@ -91,7 +92,8 @@ export class SharedTaskHost {if (this.closed.has(snapshot.sharedTaskId)) throw new Error('SharedTask is closed locally');const session = await this.options.readSession(snapshot.sessionId);this.assertSessionOpen(snapshot.sessionId, generation);- if (!session || session.id !== snapshot.sessionId || session.status !== 'active') throw new Error('SharedTask task is unavailable');+ if (!session || session.id !== snapshot.sessionId || session.status !== 'active'+ || !CINDY_MAKE_ENABLED && isCindyMakeSource(session.source)) throw new Error('SharedTask task is unavailable');const persisted = (await this.options.journal.latest()).find((item) => item.sharedTaskId === snapshot.sharedTaskId);this.assertSessionOpen(snapshot.sessionId, generation);if (persisted?.terminal || this.closed.has(snapshot.sharedTaskId)) throw new Error('SharedTask is closed locally');@@ -158,7 +160,8 @@ export class SharedTaskHost {this.assertSessionGeneration(sessionId, generation);const session = await this.options.readSession(sessionId);this.assertSessionGeneration(sessionId, generation);- if (!session || session.id !== sessionId || session.status !== 'active') throw new Error('SharedTask task is unavailable');+ if (!session || session.id !== sessionId || session.status !== 'active'+ || !CINDY_MAKE_ENABLED && isCindyMakeSource(session.source)) throw new Error('SharedTask task is unavailable');const journal = await this.options.journal.latest();this.assertSessionGeneration(sessionId, generation);// Server create is idempotent for an active task: close the previous IDs@@ -216,12 +219,16 @@ export class SharedTaskHost {// 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 item of journal) if (!item.terminal && item.snapshot+ && item.snapshot.ownerAccountId === this.options.ownerAccountId+ && item.snapshot.hostDeviceId === this.options.hostDeviceId) sessions.add(item.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)) {+ if ((!session || session.status !== 'active'+ || !CINDY_MAKE_ENABLED && isCindyMakeSource(session.source)) && !this.closedSessions.has(sessionId)) {await this.closeLocallyForBoundary(sessionId);this.assertCurrent();}@@ -246,7 +253,7 @@ export class SharedTaskHost {// 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') {+ if (!session || session.status !== 'active' || !CINDY_MAKE_ENABLED && isCindyMakeSource(session.source)) {this.revokeLocally(item.sharedTaskId);await this.options.journal.close(item);this.assertCurrent();diff --git a/apps/desktop/src/main/device-link/sharedTaskRuntime.ts b/apps/desktop/src/main/device-link/sharedTaskRuntime.tsindex d4eabdd6fb..e0e120fd43 100644--- a/apps/desktop/src/main/device-link/sharedTaskRuntime.ts+++ b/apps/desktop/src/main/device-link/sharedTaskRuntime.ts@@ -58,8 +58,8 @@ export function startSharedTaskRuntime(options: {api: sharedTaskApi, journal: createSharedTaskJournal(db.client),ownerAccountId, hostDeviceId: getDeviceId(), creationState, isCurrent: current,async readSession(sessionId) {- const rows = await db.client.query<{ id: string; title: string; status: string }>(- 'SELECT id, title, status FROM sessions WHERE id = ? LIMIT 1', [sessionId]);+ const rows = await db.client.query<{ id: string; title: string; status: string; source: string | null }>(+ 'SELECT id, title, status, source FROM sessions WHERE id = ? LIMIT 1', [sessionId]);return rows[0] ?? null;},revoke: (sharedTaskId, memberId) => {diff --git a/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts b/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.tsnew file mode 100644index 0000000000..ca7db5d963--- /dev/null+++ b/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts@@ -0,0 +1,93 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';+import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';+import { cindyMakeOutboxPolicy } from '@/session/cindyMakeOutboxPolicy';+import { isDurableOutboxHandedOff, isDurableOutboxSettled, type DurableOutboxRecord } from '@/session/durableOutbox';+import type { OutboxSessionPolicy } from '@/session/durableOutboxDelivery';++const source = ts.createSourceFile('MobileOutboxBridge.tsx', readFileSync(resolve(+ process.cwd(), 'src/session/MobileOutboxBridge.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const expressions = new Map<string, string>();+const names = ['knownSession', 'hidden', 'invokeOwned', 'canRun', 'sessionPolicy'];+function visit(node: ts.Node) {+ if ((ts.isVariableDeclaration(node) || ts.isPropertyAssignment(node)+ && ['canRun', 'sessionPolicy'].includes(node.name.getText(source))) && node.initializer+ && names.includes(node.name.getText(source))) expressions.set(node.name.getText(source), node.initializer.getText(source));+ ts.forEachChild(node, visit);+}+visit(source);+for (const name of names) if (!expressions.has(name)) throw new Error('Missing outbox callback: ' + name);+const compiled = ts.transpileModule(+ 'function create(deps) { const { remoteSessionStore, mobileDurableOutbox, latest, guard, AppState, CINDY_MAKE_ENABLED, isCindyMakeSource, isDurableOutboxSettled, isDurableOutboxHandedOff, cindyMakeOutboxPolicy, isCurrent } = deps;'+ + ['knownSession', 'hidden', 'invokeOwned'].map(name => 'const ' + name + ' = ' + expressions.get(name) + ';').join('')+ + 'const needsReconciliation = () => true; const isDurableOutboxCreationHeld = () => false; const getNewSessionCreationTask = () => null;'+ + 'const maker = (record) => ({ getSession: (sessionId) => invokeOwned(record)(record.deviceId, "local-db:sessions:get", [sessionId]) });'+ + 'return { hidden, invokeOwned, canRun: ' + expressions.get('canRun') + ', sessionPolicy: ' + expressions.get('sessionPolicy') + ' }; }',+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },+).outputText;++function harness(sessions: Array<{ id: string; source?: string; deviceLinkDeviceId: string }>) {+ const record = { deviceId: 'desktop', state: 'queued', uploads: [],+ item: { sessionId: 'session', clientId: 'client', attachmentSlots: [] } } as unknown as DurableOutboxRecord;+ const invoke = vi.fn(async (_device: string, _channel: string, _args: unknown[], options: { preSend(): void }) => {+ options.preSend(); return { id: 'session', source: 'cc' };+ });+ const latest = { current: { link: { status: 'online', getPresenceAvailability: () => true, invoke } } };+ const deps = { remoteSessionStore: { getSessions: () => sessions }, mobileDurableOutbox: { getSnapshot: () => [record] },+ latest, guard: () => {}, AppState: { currentState: 'active' }, CINDY_MAKE_ENABLED, isCindyMakeSource,+ isDurableOutboxSettled, isDurableOutboxHandedOff, cindyMakeOutboxPolicy, isCurrent: () => true };+ const callbacks = new Function(compiled + '; return create;')()(deps) as {+ hidden(record: DurableOutboxRecord): boolean;+ canRun(record: DurableOutboxRecord): boolean;+ sessionPolicy(record: DurableOutboxRecord): Promise<OutboxSessionPolicy>;+ invokeOwned(record: DurableOutboxRecord): (device: string, channel: string, args: unknown[]) => Promise<unknown>;+ };+ return { record, callbacks, invoke, latest, deps };+}++describe('Cindy Make outbox bridge guards', () => {+ it.each(['cindy-make', 'cindy-make-merge'])('selects a suspended hidden %s record for local cleanup even offline', async source => {+ const { record, callbacks, invoke, latest } = harness([{ id: 'session', source, deviceLinkDeviceId: 'desktop' }]);+ record.suspended = true;+ latest.current.link.status = 'offline';+ expect(callbacks.hidden(record)).toBe(true);+ expect(callbacks.canRun(record)).toBe(true);+ await expect(callbacks.sessionPolicy(record)).resolves.toBe('discard');+ expect(invoke).not.toHaveBeenCalled();+ });++ it('does not confuse the same session ID on another computer with a hidden task', async () => {+ const { record, callbacks, invoke } = harness([{ id: 'session', source: 'cindy-make', deviceLinkDeviceId: 'other-desktop' }]);+ expect(callbacks.hidden(record)).toBe(false);+ await expect(callbacks.sessionPolicy(record)).resolves.toBe('deliver');+ expect(invoke).toHaveBeenCalledWith('desktop', 'local-db:sessions:get', ['session'], expect.anything());+ });++ it.each(['cindy-make', 'cindy-make-merge'])('checks raw metadata again before enqueue when %s arrives late', async source => {+ const sessions = [{ id: 'session', source: 'cc', deviceLinkDeviceId: 'desktop' }];+ const { record, callbacks, invoke } = harness(sessions);+ await expect(callbacks.sessionPolicy(record)).resolves.toBe('deliver');+ const sent = vi.fn();+ invoke.mockImplementationOnce(async (_device, _channel, _args, options) => {+ sessions[0].source = source;+ options.preSend();+ sent();+ return { id: 'session', source };+ });+ await expect(callbacks.invokeOwned(record)('desktop', 'maker:input:enqueue', ['session'])).rejects.toThrow('OUTBOX_SESSION_DISABLED');+ expect(sent).not.toHaveBeenCalled();+ await expect(callbacks.sessionPolicy(record)).resolves.toBe('discard');+ });++ it('keeps ordinary offline records suspended instead of deleting or delivering them', () => {+ const { record, callbacks, latest } = harness([{ id: 'session', source: 'cc', deviceLinkDeviceId: 'desktop' }]);+ latest.current.link.status = 'offline';+ expect(callbacks.hidden(record)).toBe(false);+ expect(callbacks.canRun(record)).toBe(false);+ latest.current.link.status = 'online';+ record.suspended = true;+ expect(callbacks.canRun(record)).toBe(false);+ });+});diff --git a/apps/mobile/src/__tests__/durableOutbox.test.ts b/apps/mobile/src/__tests__/durableOutbox.test.tsindex 79441f476f..763f3dc813 100644--- a/apps/mobile/src/__tests__/durableOutbox.test.ts+++ b/apps/mobile/src/__tests__/durableOutbox.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from "vitest";import { accountVaultKey } from '@cindy/auth-client';import { cancelledCreationDraft, outboxCreationRetryIdentity } from '../session/cancelledCreationDraft';+import { cindyMakeOutboxPolicy } from '../session/cindyMakeOutboxPolicy';import {createDurableOutbox,isDurableOutboxUnsent,@@ -190,6 +191,117 @@ async function setup(storage = disk()) {};}+describe('disabled Cindy Make outbox recovery', () => {+ it.each(['cindy-make', 'cindy-make-merge'])('cleans upgraded %s records before contacting a legacy host', async (source) => {+ const { store, storage, deps } = await setup();+ await store.add(message());+ const restarted = createDurableOutbox(storage);+ await restarted.activate('alice');+ const readSession = vi.fn(async () => ({ id: 'session-a', source }));+ const delivery = createDurableOutboxDelivery({ ...deps, store: restarted,+ sessionPolicy: (record) => cindyMakeOutboxPolicy(record, {+ knownSession: () => ({ id: 'session-a', source }), readSession, isCurrent: () => true,+ }),+ });+ await delivery.run();+ delivery.wake();+ await delivery.run();+ expect(readSession).not.toHaveBeenCalled();+ expect(deps.projection).not.toHaveBeenCalled();+ expect(deps.prepare).not.toHaveBeenCalled();+ expect(deps.upload).not.toHaveBeenCalled();+ expect(deps.enqueue).not.toHaveBeenCalled();+ expect(deps.cancel).not.toHaveBeenCalled();+ expect(deps.cleanup).toHaveBeenCalledWith(expect.objectContaining({ cleanupOutcome: 'cancelled' }), true);+ const coldStart = createDurableOutbox(storage);+ await coldStart.activate('alice');+ expect(coldStart.getSnapshot()).toEqual([]);+ });++ it.each(['cindy-make', 'cindy-make-merge'])('reads missing metadata before discarding a legacy %s task', async (source) => {+ const { store, deps } = await setup();+ await store.add(message());+ const readSession = vi.fn(async () => ({ id: 'session-a', source }));+ await createDurableOutboxDelivery({ ...deps,+ sessionPolicy: (record) => cindyMakeOutboxPolicy(record, {+ knownSession: () => undefined, readSession, isCurrent: () => true,+ }),+ }).run();+ expect(readSession).toHaveBeenCalledOnce();+ expect(deps.projection).not.toHaveBeenCalled();+ expect(deps.enqueue).not.toHaveBeenCalled();+ expect(store.getSnapshot()).toEqual([]);+ });++ it.each(['offline', 'missing', 'mismatch'])('retains an unknown record on %s and resumes ordinary delivery after recovery', async (failure) => {+ const { store, storage, deps } = await setup();+ await store.add(message());+ const readSession = vi.fn<() => Promise<{ id: string; source?: string } | null>>()+ .mockResolvedValue({ id: 'session-a', source: 'cc' });+ if (failure === 'offline') readSession.mockRejectedValueOnce(new Error('offline'));+ else readSession.mockResolvedValueOnce(failure === 'missing' ? null : { id: 'another', source: 'cc' });+ const delivery = createDurableOutboxDelivery({ ...deps,+ sessionPolicy: (record) => cindyMakeOutboxPolicy(record, {+ knownSession: () => undefined, readSession, isCurrent: () => true,+ }),+ });+ await delivery.run();+ expect(store.getSnapshot()).toEqual([message()]);+ expect(deps.projection).not.toHaveBeenCalled();+ expect(deps.cleanup).not.toHaveBeenCalled();+ const coldStart = createDurableOutbox(storage);+ await coldStart.activate('alice');+ expect(coldStart.getSnapshot()).toEqual([message()]);+ delivery.wake();+ await delivery.run();+ expect(deps.enqueue).toHaveBeenCalledOnce();+ });++ it('does not delete uploads possibly owned by a legacy host or block another task', async () => {+ const { store, deps } = await setup();+ await store.add({ ...message(), state: 'confirming', enqueueStarted: true, sendAtMs: 1 });+ await store.add(message('id-2', 'ordinary'));+ await createDurableOutboxDelivery({ ...deps,+ sessionPolicy: (record) => cindyMakeOutboxPolicy(record, {+ knownSession: () => ({ id: record.item.sessionId, source: record.item.sessionId === 'ordinary' ? 'cc' : 'cindy-make' }),+ readSession: async () => null, isCurrent: () => true,+ }),+ }).run();+ expect(deps.cleanup).toHaveBeenCalledWith(expect.objectContaining({ cleanupOutcome: 'accepted' }), false);+ expect(deps.enqueue).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ item: expect.objectContaining({ sessionId: 'ordinary' }) }));+ expect(store.getSnapshot().every(record => record.item.sessionId === 'ordinary')).toBe(true);+ });++ it('keeps a disabled terminal record retryable after local cleanup fails', async () => {+ const { store, storage, deps } = await setup();+ await store.add(message());+ deps.cleanup.mockRejectedValueOnce(new Error('files unavailable'));+ const delivery = createDurableOutboxDelivery({ ...deps, sessionPolicy: async () => 'discard' });+ await delivery.run();+ const coldStart = createDurableOutbox(storage);+ await coldStart.activate('alice');+ expect(coldStart.getSnapshot()[0]).toMatchObject({ cleanupOutcome: 'cancelled' });+ await createDurableOutboxDelivery({ ...deps, store: coldStart, sessionPolicy: async () => 'discard' }).run();+ expect(coldStart.getSnapshot()).toEqual([]);+ expect(deps.enqueue).not.toHaveBeenCalled();+ });++ it('does not consume a record after the owner changes during metadata lookup', async () => {+ const { store, deps, deactivate } = await setup();+ await store.add(message());+ await createDurableOutboxDelivery({ ...deps,+ sessionPolicy: (record) => cindyMakeOutboxPolicy(record, {+ knownSession: () => undefined,+ readSession: async () => { deactivate(); return { id: 'session-a', source: 'cindy-make' }; },+ isCurrent: deps.isCurrent,+ }),+ }).run();+ expect(store.getSnapshot()).toEqual([message()]);+ expect(deps.cleanup).not.toHaveBeenCalled();+ expect(deps.enqueue).not.toHaveBeenCalled();+ });+});+describe("durable mobile outbox ownership", () => {it.each([Object.assign(new Error('Message 不存在'), { code: 'NOT_FOUND' }),diff --git a/apps/mobile/src/session/MobileOutboxBridge.tsx b/apps/mobile/src/session/MobileOutboxBridge.tsxindex e6e0330416..6746b80037 100644--- a/apps/mobile/src/session/MobileOutboxBridge.tsx+++ b/apps/mobile/src/session/MobileOutboxBridge.tsx@@ -8,6 +8,8 @@ import {} from "@/auth/authOwnerGeneration";import { useDeviceLink } from "@/device-link/DeviceLinkContext";import { parseSharedTaskPeer } from "@cindy/device-link";+import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';+import { cindyMakeOutboxPolicy } from './cindyMakeOutboxPolicy';import {createMobileMakerTransport,type RemoteInvoke,@@ -86,6 +88,11 @@ export function MobileOutboxBridge() {const guard = () => {if (!isCurrent()) throw new Error("OUTBOX_OWNER_CHANGED");};+ const knownSession = (record: DurableOutboxRecord) =>+ remoteSessionStore.getSessions().find(session =>+ session.id === record.item.sessionId && session.deviceLinkDeviceId === record.deviceId);+ const hidden = (record: DurableOutboxRecord) =>+ !CINDY_MAKE_ENABLED && isCindyMakeSource(knownSession(record)?.source);const invoke: RemoteInvoke = async (deviceId, channel, args) => {guard();const result = await latest.current.link.invoke(deviceId, channel, args, {@@ -101,6 +108,7 @@ export function MobileOutboxBridge() {guard();if (!mobileDurableOutbox.getSnapshot().includes(record))throw new Error("OUTBOX_STALE_WRITE");+ if (hidden(record)) throw new Error('OUTBOX_SESSION_DISABLED');};guardRecord();const result = await latest.current.link.invoke(@@ -133,7 +141,7 @@ export function MobileOutboxBridge() {if (!isCurrent()) return;const keys = new Set<string>();for (const record of mobileDurableOutbox.getSnapshot()) {- if (isDurableOutboxSettled(record)) continue;+ if (isDurableOutboxSettled(record) || hidden(record)) continue;if (record.creation?.cancelled) {dismissRecoveredPrecreatedSession({ sessionId: record.item.sessionId, deviceId: record.deviceId });continue;@@ -180,13 +188,18 @@ export function MobileOutboxBridge() {canRun: (r) =>AppState.currentState !== "background" &&AppState.currentState !== "inactive" &&- (isDurableOutboxSettled(r) ||+ (hidden(r) || isDurableOutboxSettled(r) ||(!r.suspended && !r.creation?.cancelled &&needsReconciliation(r) &&!isDurableOutboxCreationHeld(r.item.sessionId) &&latest.current.link.status === "online" &&latest.current.link.getPresenceAvailability(r.deviceId) !== false &&getNewSessionCreationTask(r.item.sessionId) === null)),+ sessionPolicy: (record) => cindyMakeOutboxPolicy(record, {+ knownSession: () => knownSession(record),+ readSession: () => maker(record).getSession(record.item.sessionId),+ isCurrent: () => isCurrent() && mobileDurableOutbox.getSnapshot().includes(record),+ }),projection: async (r) => {epochs.set(leaseKey(r), {authority: remoteSessionStore.captureInputProjectionAuthorityEpoch(@@ -372,6 +385,7 @@ export function MobileOutboxBridge() {if (isCurrent()) Alert.alert(i18n.t("session.outbox.restoreFailed"));});const off = mobileDurableOutbox.subscribe(run);+ const offSessions = remoteSessionStore.subscribe(run);const timer = setInterval(run, 2_000);const appState = AppState.addEventListener("change", (state) => {if (state === "active") {@@ -384,6 +398,7 @@ export function MobileOutboxBridge() {delivery.stop();if (runnerRef.current === delivery) runnerRef.current = null;off();+ offSessions();clearInterval(timer);appState.remove();for (const lease of leases.values()) lease.release();diff --git a/apps/mobile/src/session/cindyMakeOutboxPolicy.ts b/apps/mobile/src/session/cindyMakeOutboxPolicy.tsnew file mode 100644index 0000000000..e0c12e787f--- /dev/null+++ b/apps/mobile/src/session/cindyMakeOutboxPolicy.ts@@ -0,0 +1,23 @@+import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';+import type { DurableOutboxRecord } from './durableOutbox';+import type { OutboxSessionPolicy } from './durableOutboxDelivery';++type SessionSource = { id: string; source?: string | null };++export async function cindyMakeOutboxPolicy(record: DurableOutboxRecord, deps: {+ knownSession(): SessionSource | undefined;+ readSession(): Promise<SessionSource | null>;+ isCurrent(): boolean;+}): Promise<OutboxSessionPolicy> {+ if (CINDY_MAKE_ENABLED) return 'deliver';+ let session = deps.knownSession();+ if (session?.id !== record.item.sessionId || session.source === undefined) {+ try {+ session = await deps.readSession() ?? undefined;+ } catch {+ return 'wait';+ }+ }+ if (!deps.isCurrent() || session?.id !== record.item.sessionId) return 'wait';+ return isCindyMakeSource(session.source) ? 'discard' : 'deliver';+}diff --git a/apps/mobile/src/session/durableOutboxDelivery.ts b/apps/mobile/src/session/durableOutboxDelivery.tsindex 6b6304dfbe..d881b1f949 100644--- a/apps/mobile/src/session/durableOutboxDelivery.ts+++ b/apps/mobile/src/session/durableOutboxDelivery.ts@@ -16,10 +16,12 @@ import type {export type DeliveryProjection = InputProjection &InputDeliveryProjection & { clearBoundaryMs?: number | null };+export type OutboxSessionPolicy = 'deliver' | 'discard' | 'wait';export interface DurableOutboxDeliveryDeps {store: ReturnType<typeof createDurableOutbox>;isCurrent(): boolean;canRun(record: DurableOutboxRecord): boolean;+ sessionPolicy?(record: DurableOutboxRecord): Promise<OutboxSessionPolicy>;projection(record: DurableOutboxRecord): Promise<DeliveryProjection>;session(record: DurableOutboxRecord): Promise<{ id: string; status: string } | null>;prepare(record: DurableOutboxRecord): Promise<QueuedRemoteMessage>;@@ -100,6 +102,11 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {if (current(record)) await finish();};try {+ if (deps.sessionPolicy && !isDurableOutboxSettled(record)) {+ const policy = await deps.sessionPolicy(record);+ if (!current(record) || policy === 'wait') return;+ if (policy === 'discard') return await finish(isDurableOutboxUnsent(record));+ }if (record.draftHandoff) {await deps.store.reconcileDrafts(record.item.sessionId);const reconciled = deps.store.getSnapshot().find((r) => id(r) === id(record));diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.mdindex 13451803b2..f9f37e5fe5 100644--- a/docs/product-rules/shared-task-mode.md+++ b/docs/product-rules/shared-task-mode.md@@ -52,6 +52,7 @@- 房主使用自己的邀请不走访客加入流程,不创建访客或占用加入名额;服务端返回 HTTP 409 / `SHARED_TASK_SELF_JOIN`,两端提示“这是你发起的共享任务,无需加入。请从‘我发起的’打开”。同账号访问继续使用既有设备互联。旧服务端的通用 `CONFLICT` 仍显示兜底提示,不根据错误消息猜测是否为房主;旧客户端收到新错误码也沿用兜底提示。准确提示需服务端与客户端均升级,接口与成功响应结构不变。- 移除或退出立即撤权;原邀请不可重入,房主生成新邀请后才能再次加入。- 停止共享、归档、房主登出使旧邀请和成员关系失效。重新共享产生新的共享 ID。+- Cindy Make 停用时,房主 Desktop 按本机原始任务来源关闭已有的制作任务共享(含 `cindy-make-merge`),不恢复访客访问、不允许重新开启。复用原有关闭账本与服务端关闭接口,离线先撤销本机授权,联网后重试关闭并从房主、访客目录移除,旧邀请随共享关闭失效;普通任务共享不受影响,任务历史与工作目录保留。实现与回归见 `sharedTaskHost.ts`、`sharedTaskHost.test.ts` 和 `sharedTaskRuntime.test.ts`。- 归档后恢复为活动任务,可以显式重新开启共享;须先完成旧共享关闭,旧代次的请求仍然失效。- 房主设备的 relay 连接确认离线后有 60 秒重连宽限,期间重连保留共享、邀请与成员关系;持续离线超过宽限后由下一轮服务端扫描关闭(正常情况下确认离线后 60–90 秒)。关闭后重新上线不会恢复旧共享,需显式重新开启并发送新邀请。主动关闭与登出的显式关闭请求不等待宽限。已由新连接接管的旧连接退出不算离线;TTL 内短暂网络抖动不承诺立即判定。- 服务端是成员关系权威;主机保存恢复与关闭记录。迟到响应、旧快照、缓存和重连不能恢复已撤销访问。