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(mcp): 限制项目操作广播到当前可信窗口

Dash9be03358d584
diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
index 5dbc03ab1e..8c2dc81a8d 100644
--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
@@ -50,6 +50,11 @@ vi.mock('electron', () => ({
getAllWindows: () => [{ isDestroyed: () => false, webContents: { send: h.webContentsSend } }],
},
}));
+// These broadcast fixtures represent mounted, trusted app windows.
+vi.mock('../security/trustedAppRenderer.js', () => ({
+ assertTrustedAppRendererEvent: vi.fn(),
+ isTrustedAppRendererWindow: (w: { isDestroyed: () => boolean }) => !w.isDestroyed(),
+}));
vi.mock('../logger', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
diff --git a/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
index f335e88a00..2b7783d7cb 100644
--- a/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
+++ b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
@@ -14,6 +14,7 @@ const harness = vi.hoisted(() => ({
generation: 1,
},
boundaryPending: false,
+ navigated: false,
handlers: new Map<string, (...args: unknown[]) => unknown>(),
listeners: new Map<string, (...args: unknown[]) => unknown>(),
send: vi.fn(),
@@ -87,6 +88,8 @@ vi.mock('../logger.js', () => ({
vi.mock('../security/trustedAppRenderer.js', () => ({
assertTrustedAppRendererEvent: (...args: unknown[]) => harness.assertTrusted(...args),
+ isTrustedAppRendererWindow: (w: { appContent?: boolean; isDestroyed: () => boolean }) =>
+ w.appContent === true && !w.isDestroyed() && !harness.navigated,
}));
vi.mock('../windowFocusClassifier.js', () => ({
@@ -172,6 +175,7 @@ describe('sidebarSettingsStore', () => {
harness.root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-sidebar-owner-state-'));
harness.session = { mode: 'cloud', dataOwnerId: 'owner-a', generation: 1 };
harness.boundaryPending = false;
+ harness.navigated = false;
harness.handlers.clear();
harness.listeners.clear();
harness.send.mockReset();
@@ -205,7 +209,11 @@ describe('sidebarSettingsStore', () => {
const owner = request({});
expect(await restoreLocalProjectVisibility('c:/WORKSPACE/alpha', owner)).toBe(true);
expect(loadSnapshot().hiddenProjectKeys).toEqual([]);
- expect(harness.send).toHaveBeenLastCalledWith('sidebar-settings:hidden-project-keys-changed', [], owner);
+ expect(harness.send).toHaveBeenLastCalledWith(
+ 'sidebar-settings:hidden-project-keys-changed',
+ [],
+ owner,
+ );
expect(await restoreLocalProjectVisibility('C:/workspace/Alpha', owner)).toBe(false);
setSession('cloud', 'owner-b');
await expect(restoreLocalProjectVisibility('C:/workspace/Alpha', owner)).rejects.toMatchObject({
@@ -213,6 +221,21 @@ describe('sidebarSettingsStore', () => {
});
});
+ it('does not send project paths after an app window navigates away', async () => {
+ const { restoreLocalProjectVisibility } = await import('../sidebarSettingsStore');
+ await hiddenHandler(request({ projectKey: 'C:/workspace/Alpha', hidden: true }));
+ expect(harness.send).toHaveBeenCalled();
+ harness.send.mockClear();
+ harness.sendSecond.mockClear();
+ harness.navigated = true;
+ await restoreLocalProjectVisibility('C:/workspace/Alpha', request({}));
+ await hiddenHandler(request({ projectKey: 'C:/workspace/Alpha', hidden: true }));
+ expect(harness.send).not.toHaveBeenCalled();
+ expect(harness.sendSecond).not.toHaveBeenCalled();
+ expect(harness.untrustedSend).not.toHaveBeenCalled();
+ expect(harness.destroyedSend).not.toHaveBeenCalled();
+ });
+
it('isolates pinned and hidden state by owner', async () => {
await pinnedHandler(
request({
@@ -670,9 +693,7 @@ describe('sidebarSettingsStore', () => {
'utf-8',
);
- const writing = mainViewHiddenHandler(
- request({ ghostId: 'xd-sites', hidden: true }),
- );
+ const writing = mainViewHiddenHandler(request({ ghostId: 'xd-sites', hidden: true }));
await new Promise((resolve) => setTimeout(resolve, 20));
setSession('cloud', 'owner-a');
fs.unlinkSync(`${file}.lock`);
diff --git a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts
index 537b04bf05..4e81c42f72 100644
--- a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts
+++ b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts
@@ -79,6 +79,11 @@ vi.mock('electron', () => ({
getAllWindows: () => [{ isDestroyed: () => false, webContents: { send: h.webContentsSend } }],
},
}));
+// These broadcast fixtures represent mounted, trusted app windows.
+vi.mock('../security/trustedAppRenderer.js', () => ({
+ assertTrustedAppRendererEvent: vi.fn(),
+ isTrustedAppRendererWindow: (w: { isDestroyed: () => boolean }) => !w.isDestroyed(),
+}));
vi.mock('../logger', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index 16c4584117..9eebf7a6c7 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -35,6 +35,7 @@ const h = vi.hoisted(() => ({
closeSession: vi.fn(async (_sessionId: string) => undefined),
tapWindowBroadcast: vi.fn(),
windows: [] as Array<{
+ trusted?: boolean;
isDestroyed: ReturnType<typeof vi.fn>;
webContents: { send: ReturnType<typeof vi.fn> };
}>,
@@ -123,6 +124,8 @@ vi.mock('../../../sessionTaskSummary.js', () => ({
}));
vi.mock('../../../security/trustedAppRenderer.js', () => ({
assertTrustedAppRendererEvent: vi.fn(),
+ isTrustedAppRendererWindow: (w: { trusted?: boolean; isDestroyed: () => boolean }) =>
+ !w.isDestroyed() && w.trusted !== false,
}));
vi.mock('../../agentIslandSessionPatch', () => ({ notifyAgentIslandSessionPatch: vi.fn() }));
vi.mock('../../../messagePersistBroadcaster', () => ({ noteSessionClearBoundary: vi.fn() }));
@@ -329,6 +332,40 @@ afterEach(async () => {
});
describe('local-db:sessions:update handler wiring', () => {
+ it('rechecks window trust for both movement broadcasts after navigation', async () => {
+ const trusted = {
+ trusted: true,
+ isDestroyed: vi.fn(() => false),
+ webContents: { send: vi.fn() },
+ };
+ const auxiliary = {
+ trusted: false,
+ isDestroyed: vi.fn(() => false),
+ webContents: { send: vi.fn() },
+ };
+ h.windows = [trusted, auxiliary];
+ await invokeUpdate('codex-local', { workingDir: '/new/dir', workspaceKind: 'project' });
+ expect(trusted.webContents.send).toHaveBeenCalledWith('local-db:recent-workdirs:changed', {
+ path: '/new/dir',
+ });
+ expect(trusted.webContents.send).toHaveBeenCalledWith(
+ 'local-db:sessions:patched',
+ expect.objectContaining({ sessionId: 'codex-local' }),
+ );
+ expect(auxiliary.webContents.send).not.toHaveBeenCalled();
+
+ trusted.webContents.send.mockClear();
+ trusted.trusted = false;
+ await invokeUpdate('codex-local', { workingDir: '/another/dir', workspaceKind: 'project' });
+ await invokeUpdate('codex-local', { workspaceKind: 'dialogue' });
+ expect(trusted.webContents.send).not.toHaveBeenCalled();
+ expect(auxiliary.webContents.send).not.toHaveBeenCalled();
+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith(
+ 'local-db:sessions:patched',
+ expect.objectContaining({ sessionId: 'codex-local' }),
+ );
+ });
+
it('isolates device-link and renderer failures while broadcasting a session patch', () => {
const failedWindowSend = vi.fn(() => {
throw new Error('window closed');
@@ -937,21 +974,33 @@ describe('local-db:sessions:update handler wiring', () => {
});
it.each([{ workingDir: '/new/dir', workspaceKind: 'project' }, { workspaceKind: 'dialogue' }])(
- 'runs MCP move checks inside the route lock before persisting %j', async (patch) => {
+ 'runs MCP move checks inside the route lock before persisting %j',
+ async (patch) => {
let locked = false;
h.routeLock.mockImplementation(async (_id, task) => {
locked = true;
- try { return await task(); } finally { locked = false; }
+ try {
+ return await task();
+ } finally {
+ locked = false;
+ }
});
const beforeUpdate = vi.fn(async () => {
expect(locked).toBe(true);
- throw Object.assign(new Error('[PRECONDITION_FAILED] move blocked'), { code: 'PRECONDITION_FAILED' });
+ throw Object.assign(new Error('[PRECONDITION_FAILED] move blocked'), {
+ code: 'PRECONDITION_FAILED',
+ });
});
- await expect(updateSessionInDb('cc-local', patch, undefined, {
- assertCurrent: () => undefined, beforeUpdate,
- })).rejects.toThrow('move blocked');
+ await expect(
+ updateSessionInDb('cc-local', patch, undefined, {
+ assertCurrent: () => undefined,
+ beforeUpdate,
+ }),
+ ).rejects.toThrow('move blocked');
expect(beforeUpdate).toHaveBeenCalledOnce();
- expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('cc-local')).toEqual({ working_dir: '/old/dir' });
+ expect(
+ h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('cc-local'),
+ ).toEqual({ working_dir: '/old/dir' });
expect(h.relocate).not.toHaveBeenCalled();
expect(h.tapWindowBroadcast).not.toHaveBeenCalled();
},
@@ -959,24 +1008,46 @@ describe('local-db:sessions:update handler wiring', () => {
it('checks the move account fence again after closing an idle runtime and before writing', async () => {
let current = true;
- h.closeIdleSessionForMove.mockImplementationOnce(async () => { current = false; return true; });
- await expect(updateSessionInDb('codex-local', { workingDir: '/new/dir' }, undefined, {
- beforeUpdate: async () => undefined,
- assertCurrent: () => { if (!current) throw Object.assign(new Error('[PRECONDITION_FAILED] account changed'), { code: 'PRECONDITION_FAILED' }); },
- })).rejects.toThrow('account changed');
- expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('codex-local')).toEqual({ working_dir: '/old/dir' });
+ h.closeIdleSessionForMove.mockImplementationOnce(async () => {
+ current = false;
+ return true;
+ });
+ await expect(
+ updateSessionInDb('codex-local', { workingDir: '/new/dir' }, undefined, {
+ beforeUpdate: async () => undefined,
+ assertCurrent: () => {
+ if (!current)
+ throw Object.assign(new Error('[PRECONDITION_FAILED] account changed'), {
+ code: 'PRECONDITION_FAILED',
+ });
+ },
+ }),
+ ).rejects.toThrow('account changed');
+ expect(
+ h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('codex-local'),
+ ).toEqual({ working_dir: '/old/dir' });
expect(h.tapWindowBroadcast).not.toHaveBeenCalled();
});
it('retains transcript relocation and returned resume identity for a guarded MCP move', async () => {
- const updated = await updateSessionInDb('cc-local', { workingDir: '/new/dir', workspaceKind: 'project' }, undefined, {
- beforeUpdate: async () => undefined, assertCurrent: () => undefined,
- });
+ const updated = await updateSessionInDb(
+ 'cc-local',
+ { workingDir: '/new/dir', workspaceKind: 'project' },
+ undefined,
+ {
+ beforeUpdate: async () => undefined,
+ assertCurrent: () => undefined,
+ },
+ );
expect(updated.workingDir).toBe('/new/dir');
expect(h.relocate).toHaveBeenCalledWith('cc-local', '/old/dir', '/new/dir', {
- client: h.client, assertCurrent: expect.any(Function),
+ client: h.client,
+ assertCurrent: expect.any(Function),
});
- expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', expect.objectContaining({ sessionId: 'cc-local' }));
+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith(
+ 'local-db:sessions:patched',
+ expect.objectContaining({ sessionId: 'cc-local' }),
+ );
});
it('returns and broadcasts the sdkSessionId persisted during relocation', async () => {
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 446a5cd06a..e6c877e7c0 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -27,7 +27,14 @@ import { getDbClient } from '../client/current';
import * as currentDb from '../client/current';
import type { DbClient } from '../client/DbClient';
import { sessions, messages } from '../schema';
-import { selectSessionListRows, selectSessionWithCount, selectSessionsByIds, flattenSessionReadRow, projectSessionReadResult, type SessionListRow } from '../sessionQueries';
+import {
+ selectSessionListRows,
+ selectSessionWithCount,
+ selectSessionsByIds,
+ flattenSessionReadRow,
+ projectSessionReadResult,
+ type SessionListRow,
+} from '../sessionQueries';
import { commitBotProfileDeletion } from '../botProfileDeletionStore.js';
import {
persistSessionListProjectionBatch,
@@ -85,7 +92,10 @@ import {
import { dismissErrorMessage, rebroadcastAgentSwitchBoundary } from './messages';
import { SESSION_READ_BATCH_LIMIT } from '../../../shared/sessionRead';
import { isDeviceLinkInvoke } from '../../device-link/invoke-context.js';
-import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer.js';
+import {
+ assertTrustedAppRendererEvent,
+ isTrustedAppRendererWindow,
+} from '../../security/trustedAppRenderer.js';
import { removeTurnChangeSetsForSession } from '../../turn-change-set/store.js';
import { quiesceSessionBeforeWorktreeRecycle } from './sessionRemovalOperations.js';
import { withSessionRouteLock, withSessionRouteLocks } from '../sessionRouteLock.js';
@@ -361,7 +371,7 @@ export function broadcastSessionPatched(
}
for (const w of windows) {
try {
- if (w.isDestroyed()) continue;
+ if (!isTrustedAppRendererWindow(w)) continue;
if (hasCapturedScope) {
w.webContents.send('local-db:sessions:patched', { sessionId, patch }, ownerStamp);
} else if (ownerStamp === undefined) {
@@ -383,7 +393,7 @@ function broadcastRecentWorkdirsChanged(path: string, ownerScope: OwnerScope): v
const hasCapturedScope = ownerScope !== null;
const ownerStamp = hasCapturedScope ? ownerScope.ownerStamp : getSafeOwnerPushStamp();
for (const window of BrowserWindow.getAllWindows()) {
- if (window.isDestroyed()) continue;
+ if (!isTrustedAppRendererWindow(window)) continue;
if (hasCapturedScope || ownerStamp !== undefined) {
window.webContents.send('local-db:recent-workdirs:changed', { path }, ownerStamp);
} else {
@@ -1226,7 +1236,9 @@ export function registerSessionIpc(
}
scheduleSessionListProjectionBackfill(mergedRows);
- return mergedRows.map((row) => projectSessionReadResult(flattenSessionReadRow(row), opts.resolveContextWindow));
+ return mergedRows.map((row) =>
+ projectSessionReadResult(flattenSessionReadRow(row), opts.resolveContextWindow),
+ );
};
const loadUsageHistoryRows = async () => {
// 用量历史的“最耗任务”必须覆盖整个会话表,再由 renderer 按所选日历范围
@@ -1516,7 +1528,10 @@ export function registerSessionIpc(
ipcMain.handle('local-db:sessions:get-many', async (event, value: unknown) => {
if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);
if (!Array.isArray(value) || value.length > SESSION_READ_BATCH_LIMIT) {
- throwIpcError('INVALID_PARAMS', `sessionIds must be an array of at most ${SESSION_READ_BATCH_LIMIT} ids`);
+ throwIpcError(
+ 'INVALID_PARAMS',
+ `sessionIds must be an array of at most ${SESSION_READ_BATCH_LIMIT} ids`,
+ );
}
const ids = [...new Set(value.map((id) => requireString(id, 'sessionId')))];
if (!ids.length) return [];
diff --git a/apps/desktop/src/main/sidebarSettingsStore.ts b/apps/desktop/src/main/sidebarSettingsStore.ts
index e746c9c943..96cd3b0511 100644
--- a/apps/desktop/src/main/sidebarSettingsStore.ts
+++ b/apps/desktop/src/main/sidebarSettingsStore.ts
@@ -44,7 +44,10 @@ import {
isLegacyOwnerNamespaceClaimOwnedBy,
isLegacyOwnerNamespaceClaimedByOtherOwner,
} from './ownerNamespaceMigration.js';
-import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer.js';
+import {
+ assertTrustedAppRendererEvent,
+ isTrustedAppRendererWindow,
+} from './security/trustedAppRenderer.js';
import { atomicWriteFileSync, readAtomicFileSync } from './utils/atomicWriteFile.js';
import { throwIpcError } from './utils/ipcValidate.js';
import { isAppContentWindow } from './windowFocusClassifier.js';
@@ -424,7 +427,7 @@ function broadcastHiddenProjectKeysChanged(
ownerStamp: DataOwnerPushStamp,
): void {
for (const window of BrowserWindow.getAllWindows()) {
- if (!isAppContentWindow(window)) continue;
+ if (!isTrustedAppRendererWindow(window)) continue;
window.webContents.send(
'sidebar-settings:hidden-project-keys-changed',
Array.from(projectKeys),