Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(sharing): 区分断线状态并阻止失败归档

DavidShen945b904bae34
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index fa8e04582b..6537b99235 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -582,6 +582,7 @@ import { issueWritableDirectoryPickerGrant } from './maker-ipc/writableDirectory
// 设备互联(跨设备远程控制): relay 连接 host + 开关/设备列表 IPC
import {
initDeviceLinkService,
+ getDeviceLinkStatus,
isSharedTaskAvailable,
releaseDeviceLinkOwnershipBeforeLogout,
handleDeviceLinkSystemResume,
@@ -9527,7 +9528,7 @@ app.on('ready', async () => {
// owning modules above; future collections/actions do not add tunnel channels.
registerRemoteResourcesIpc();
registerDeviceLinkIpc();
- registerSharedTaskIpc(isSharedTaskAvailable);
+ registerSharedTaskIpc(isSharedTaskAvailable, () => getDeviceLinkStatus() === 'online');
registerFilePeerIpc();
registerRemoteDesktopIpc(isGlobalVoiceInputOverlaySender);
void startupPurgeDrain
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskIpc.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskIpc.test.ts
new file mode 100644
index 0000000000..5529eed25d
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskIpc.test.ts
@@ -0,0 +1,77 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { SHARED_TASK_ACCOUNT_CHANNEL, SHARED_TASK_HOST_CHANNEL } from '@cindy/device-link';
+import { registerSharedTaskIpc } from '../sharedTaskIpc.js';
+
+const h = vi.hoisted(() => ({
+ handlers: new Map<string, (event: unknown, raw: unknown) => Promise<unknown>>(),
+ context: null as null | { sharedTask?: object },
+ trusted: vi.fn(),
+ list: vi.fn(),
+ close: vi.fn(),
+ host: { activeSharedTaskIds: vi.fn(() => []), open: vi.fn(), close: vi.fn() },
+}));
+vi.mock('electron', () => ({ ipcMain: { handle: (channel: string, handler: (event: unknown, raw: unknown) => Promise<unknown>) => h.handlers.set(channel, handler) } }));
+vi.mock('../../authManager.js', () => ({ getCurrentUserId: () => 'owner' }));
+vi.mock('../../security/trustedAppRenderer.js', () => ({ assertTrustedAppRendererEvent: h.trusted }));
+vi.mock('../invoke-context.js', () => ({ getDeviceLinkInvokeContext: () => h.context }));
+vi.mock('../sharedTaskRuntime.js', () => ({ requireSharedTaskHost: () => h.host }));
+vi.mock('../sharedTaskApi.js', () => ({ sharedTaskApi: { list: h.list, close: h.close } }));
+
+const invoke = (channel: string, command: unknown) => h.handlers.get(channel)!({}, command);
+const commands = [
+ [SHARED_TASK_HOST_CHANNEL, { action: 'state', sessionId: 'task' }],
+ [SHARED_TASK_HOST_CHANNEL, { action: 'open', sessionId: 'task' }],
+ [SHARED_TASK_ACCOUNT_CHANNEL, { action: 'owned' }],
+ [SHARED_TASK_ACCOUNT_CHANNEL, { action: 'close', sharedTaskId: 'share' }],
+] as const;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.handlers.clear(); h.context = null;
+ h.list.mockResolvedValue([]);
+});
+
+describe('shared-task IPC availability', () => {
+ it.each(commands)('returns a retryable disconnect for %s %j without side effects', async (channel, command) => {
+ registerSharedTaskIpc(() => false, () => false);
+ await expect(invoke(channel, command)).rejects.toMatchObject({ code: 'DEVICE_LINK_NOT_CONNECTED' });
+ expect(h.host.open).not.toHaveBeenCalled();
+ expect(h.host.activeSharedTaskIds).not.toHaveBeenCalled();
+ expect(h.list).not.toHaveBeenCalled();
+ expect(h.close).not.toHaveBeenCalled();
+ });
+
+ it('keeps unsupported capability distinct when the relay is online', async () => {
+ registerSharedTaskIpc(() => false, () => true);
+ await expect(invoke(SHARED_TASK_HOST_CHANNEL, { action: 'state', sessionId: 'task' }))
+ .resolves.toEqual({ available: false, detail: null });
+ for (const [channel, command] of commands.slice(1)) {
+ await expect(invoke(channel, command)).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' });
+ }
+ expect(h.list).not.toHaveBeenCalled();
+ });
+
+ it('recovers after reconnection without re-registering handlers', async () => {
+ let online = true;
+ registerSharedTaskIpc(() => online, () => online);
+ const state = () => invoke(SHARED_TASK_HOST_CHANNEL, { action: 'state', sessionId: 'task' });
+ await expect(state()).resolves.toEqual({ available: true, detail: null });
+ online = false;
+ await expect(state()).rejects.toMatchObject({ code: 'DEVICE_LINK_NOT_CONNECTED' });
+ online = true;
+ await expect(state()).resolves.toEqual({ available: true, detail: null });
+ await expect(invoke(SHARED_TASK_ACCOUNT_CHANNEL, { action: 'owned' })).resolves.toEqual([]);
+ expect(h.list).toHaveBeenCalledTimes(1);
+ });
+
+ it('retains the guest and tunneled-account permission guards before availability', async () => {
+ registerSharedTaskIpc(() => false, () => false);
+ h.context = { sharedTask: {} };
+ for (const [channel, command] of commands) {
+ await expect(invoke(channel, command)).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ }
+ h.context = {};
+ await expect(invoke(SHARED_TASK_ACCOUNT_CHANNEL, { action: 'owned' }))
+ .rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ });
+});
diff --git a/apps/desktop/src/main/device-link/sharedTaskIpc.ts b/apps/desktop/src/main/device-link/sharedTaskIpc.ts
index 795367622d..c9720e417b 100644
--- a/apps/desktop/src/main/device-link/sharedTaskIpc.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskIpc.ts
@@ -9,17 +9,22 @@ import { sharedTaskApi } from './sharedTaskApi.js';
import { executeSharedTaskAccountCommand, executeSharedTaskHostCommand } from './sharedTaskCommands.js';
/** Narrow Renderer adapter; account operations cannot be tunneled on somebody else's login. */
-export function registerSharedTaskIpc(available: () => boolean): void {
+export function registerSharedTaskIpc(available: () => boolean, relayOnline: () => boolean): void {
+ const availableOnline = () => {
+ // A transient disconnect is not evidence of an unsupported server version.
+ if (!relayOnline()) throwIpcError('DEVICE_LINK_NOT_CONNECTED', 'SharedTask relay is not connected');
+ return available();
+ };
ipcMain.handle(SHARED_TASK_HOST_CHANNEL, async (event, raw: unknown) => {
const context = getDeviceLinkInvokeContext();
if (context?.sharedTask) throwIpcError('PERMISSION_DENIED', 'Only the sharedTask owner can manage members');
if (!context) assertTrustedAppRendererEvent(event);
- return executeSharedTaskHostCommand(raw, { available, host: requireSharedTaskHost });
+ return executeSharedTaskHostCommand(raw, { available: availableOnline, host: requireSharedTaskHost });
});
ipcMain.handle(SHARED_TASK_ACCOUNT_CHANNEL, async (event, raw: unknown) => {
if (getDeviceLinkInvokeContext()) throwIpcError('PERMISSION_DENIED', 'SharedTask account operations are local only');
assertTrustedAppRendererEvent(event);
- if (!available()) throwIpcError('UNSUPPORTED_CAPABILITY', 'SharedTask mode requires updated clients and server');
+ if (!availableOnline()) throwIpcError('UNSUPPORTED_CAPABILITY', 'SharedTask mode requires updated clients and server');
return executeSharedTaskAccountCommand(raw, sharedTaskApi, getCurrentUserId() ?? undefined, {
hostedIds: () => { try { return requireSharedTaskHost().activeSharedTaskIds(); } catch { return []; } },
closeHosted: (sharedTaskId) => requireSharedTaskHost().close(sharedTaskId),
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/sharedTaskArchiveGuard.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/sharedTaskArchiveGuard.test.ts
new file mode 100644
index 0000000000..68cf2cf3ce
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/sharedTaskArchiveGuard.test.ts
@@ -0,0 +1,84 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+
+// Execute the actual sidebar callbacks without mounting its unrelated stores.
+const source = ts.createSourceFile('sidebar.tsx', readFileSync(resolve(process.cwd(),
+ 'src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+function callback(name: string, bindings: Record<string, unknown>) {
+ let expression: ts.Node | undefined;
+ const visit = (node: ts.Node) => {
+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === name && node.initializer && ts.isCallExpression(node.initializer)) {
+ expression = node.initializer.arguments[0];
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ if (!expression) throw new Error('Missing sidebar callback: ' + name);
+ const js = ts.transpileModule('const callback = ' + expression.getText(source), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ return new Function(...Object.keys(bindings), js + '; return callback;')(...Object.values(bindings));
+}
+
+function harness(result: unknown, reject = false, sharedTaskId: string | undefined = 'share') {
+ const account = reject ? vi.fn().mockRejectedValue(result) : vi.fn().mockResolvedValue(result);
+ const runSessionAction = vi.fn();
+ const setConfirm = vi.fn();
+ const toast = { error: vi.fn(), warning: vi.fn() };
+ const session = { id: 'task' };
+ const bindings = {
+ window: { electronAPI: { sharedTask: { account }, binding: { resolveSession: async () => ({ attached: false }) } } },
+ toast, t: (key: string) => key, sharedTaskErrorKey: () => 'sharedTask.retry',
+ sessionsById: new Map([['task', session]]), sessionsByIdRef: { current: new Map([['task', session]]) },
+ runningSessionIds: new Set(), attachedSessionIdsRef: { current: new Set() },
+ isRemoteSessionWriteBlocked: () => false, resolveWorktreeRemovalPreflight: async () => 'clean',
+ viewedSessionIdRef: { current: 'other' }, viewedSessionId: 'other',
+ resolveSessionRemovalRedirect: vi.fn(), unarchiveSession: vi.fn(),
+ runSessionAction, setConfirm, CONFIRM_INITIAL: { open: false },
+ };
+ const closeOwnedSharedTask = callback('closeOwnedSharedTask', bindings);
+ return {
+ account, runSessionAction, toast, setConfirm,
+ archive: () => callback('handleActionClick', { ...bindings, closeOwnedSharedTask })('task', 'archive', sharedTaskId),
+ confirm: (action: string) => callback('handleConfirm', { ...bindings, closeOwnedSharedTask,
+ confirm: { sessionId: 'task', action, sharedTaskId },
+ })(),
+ };
+}
+
+describe('sidebar shared-task archive/delete guard', () => {
+ it.each(['archive', 'confirmed-archive', 'delete'])('blocks %s on a resolved close failure', async (action) => {
+ const h = harness({ closed: [], failed: [{ sharedTaskId: 'share' }] });
+ if (action === 'archive') await h.archive();
+ else await h.confirm(action === 'delete' ? 'delete' : 'archive');
+ expect(h.runSessionAction).not.toHaveBeenCalled();
+ expect(h.setConfirm).not.toHaveBeenCalled();
+ expect(h.toast.error).toHaveBeenCalledWith('sharedTask.closeFailedToast');
+ });
+ it.each([undefined, {}, { closed: ['other'], failed: [] }])('fails closed for an invalid or unrelated result %j', async (result) => {
+ const h = harness(result);
+ await h.archive();
+ expect(h.runSessionAction).not.toHaveBeenCalled();
+ });
+ it('blocks both paths when close rejects', async () => {
+ const h = harness(new Error('offline'), true);
+ await h.archive(); await h.confirm('delete');
+ expect(h.runSessionAction).not.toHaveBeenCalled();
+ expect(h.toast.error).toHaveBeenCalledWith('sharedTask.retry');
+ });
+ it('allows archive and confirmed delete only after the requested share closes', async () => {
+ const h = harness({ closed: ['share'], failed: [] });
+ await h.archive(); await h.confirm('delete');
+ expect(h.account).toHaveBeenCalledWith({ action: 'close', sharedTaskId: 'share' });
+ expect(h.runSessionAction.mock.calls.map((call) => call[1])).toEqual(['archive', 'delete']);
+ expect(h.toast.error).not.toHaveBeenCalled();
+ });
+ it('does not close any share for an ordinary task', async () => {
+ const h = harness(undefined, false, '');
+ await h.archive(); await h.confirm('delete');
+ expect(h.account).not.toHaveBeenCalled();
+ expect(h.runSessionAction).toHaveBeenCalledTimes(2);
+ });
+});