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(browser-extension): close a stopping bridge at once; keep pairings to the package source; bound uploads

Dashbfff423e388b
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/browserExtensionSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/browserExtensionSlot.test.ts
index 37c16f6ccb..82bb322c45 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/browserExtensionSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/browserExtensionSlot.test.ts
@@ -333,7 +333,7 @@ describe('browserExtensionSlot · 管子上行', () => {
});
expect(
JSON.parse(await fs.readFile(path.join(dir, encodeURIComponent(id) + '.json'), 'utf8')),
- ).toEqual({ version: 1, trustedClients: [] });
+ ).toEqual({ version: 1, source: '[null,null]', trustedClients: [] });
expect(await slot.handleRequest(id, { kind: 'relayActive', id: 'r1' })).toEqual({
ok: true,
active: true,
@@ -368,6 +368,37 @@ describe('browserExtensionSlot · 管子上行', () => {
expect(again.sent.some(([, payload]) => (payload as { name?: string }).name === 'browser-extension-policy-request')).toBe(false);
});
+ // Review 2026-10-29 (Codex P1): a package from another source reused the old package's pairings.
+ it('换成其它来源的包时不沿用旧配对', async () => {
+ const { slot, bridges, sent, dir } = await makeSlot();
+ const clients = [{ id: 'c1', origin: 'chrome-extension://' + CHROME_ID, extensionId: CHROME_ID, publicKey: 'k' }];
+ await fs.writeFile(
+ path.join(dir, encodeURIComponent('_root__my-browser') + '.json'),
+ JSON.stringify({ version: 1, source: JSON.stringify([{ kind: 'local', source: 'manual' }, null]), trustedClients: clients }),
+ );
+ slot.reconcile([extGhost()]);
+ await vi.waitFor(() => expect(bridges[0]?.started).toBe(true));
+ expect(bridges[0].calls.some(([name]) => name === 'setTrustedClients')).toBe(false);
+ expect(sent).toContainEqual(['_root__my-browser', { type: 'event', name: 'browser-extension-policy-request' }]);
+ });
+
+ // Review 2026-10-29 (Codex P2): disabling the plugin while its bridge was still starting left queued
+ // jobs deliverable until startup finished.
+ it('启动未完成就停用时立即关闭桥接', async () => {
+ let finishStart: () => void = () => undefined;
+ const { slot, bridges } = await makeSlot();
+ const ghost = extGhost();
+ slot.reconcile([ghost]);
+ await vi.waitFor(() => expect(bridges).toHaveLength(1));
+ bridges[0].start = () => new Promise<void>((resolve) => (finishStart = resolve));
+ // The slot awaits the cached read before start; give it time to reach the held start.
+ await new Promise((r) => setTimeout(r, 25));
+ const stopping = slot.reconcile([]);
+ expect(bridges[0].closed).toBe(true);
+ finishStart();
+ await stopping;
+ });
+
it('没有配对缓存时向插件索要一次;配对单独落盘', async () => {
const { slot, bridges, sent, dir } = await makeSlot();
slot.reconcile([extGhost()]);
@@ -377,7 +408,7 @@ describe('browserExtensionSlot · 管子上行', () => {
expect(await slot.handleRequest('_root__my-browser', { kind: 'setTrustedClients', clients })).toEqual({ ok: true });
expect(
JSON.parse(await fs.readFile(path.join(dir, encodeURIComponent('_root__my-browser') + '.json'), 'utf8')),
- ).toEqual({ version: 1, trustedClients: clients });
+ ).toEqual({ version: 1, source: '[null,null]', trustedClients: clients });
});
});
diff --git a/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts b/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts
index 28c136a42a..28fd22485c 100644
--- a/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts
@@ -108,6 +108,8 @@ interface Entry {
closing: boolean;
/** Paired clients as last persisted. */
saved: SavedBrowserExtensionState;
+ /** Where the installed package came from; pairings never carry over to a package from elsewhere. */
+ source: string;
/** Serialises cache writes so an older write cannot land after a newer one. */
writes: Promise<void>;
/**
@@ -129,6 +131,11 @@ function fail(
return { ok: false, errorCode, message };
}
+/** Install provenance of a package: a replacement from another source starts without saved pairings. */
+function packageSource(ghost: InstalledGhost): string {
+ return JSON.stringify([ghost.publishingSource ?? null, ghost.namespace ?? null]);
+}
+
function entrySignature(ghost: InstalledGhost, ownerScopeKey: string): string {
return JSON.stringify([
ownerScopeKey,
@@ -199,6 +206,7 @@ export class GhostBrowserExtensionSlot {
ready: Promise.resolve(),
closing: false,
saved: { trustedClients: [] },
+ source: packageSource(ghost),
writes: Promise.resolve(),
cacheDir,
};
@@ -206,7 +214,7 @@ export class GhostBrowserExtensionSlot {
entry.ready = (async () => {
// The old bridge must release its port and native registration before this one claims them.
await previous?.catch(() => undefined);
- const saved = await this.readSaved(cacheDir, instanceId);
+ const saved = await this.readSaved(cacheDir, instanceId, entry.source);
if (saved) {
entry.saved = saved;
try {
@@ -252,6 +260,9 @@ export class GhostBrowserExtensionSlot {
entry.closing = true;
this.entries.delete(instanceId);
const stopped = (async () => {
+ // Close first: queued jobs end and new ones are refused at once, even while startup (native
+ // registration can take seconds) is still finishing. Closing again after it is harmless.
+ await entry.bridge.close();
await entry.ready;
await entry.bridge.close();
await entry.native?.close();
@@ -415,14 +426,28 @@ export class GhostBrowserExtensionSlot {
return path.join(cacheDir, encodeURIComponent(instanceId) + '.json');
}
- /** Saved pairings; null when missing or unreadable. A site list saved by older versions is ignored. */
- private async readSaved(cacheDir: string, instanceId: string): Promise<SavedBrowserExtensionState | null> {
+ /**
+ * Saved pairings; null when missing, unreadable or saved for a package from another source. A file
+ * without a source predates this check and is taken once. A site list saved by older versions is ignored.
+ */
+ private async readSaved(
+ cacheDir: string,
+ instanceId: string,
+ source: string,
+ ): Promise<SavedBrowserExtensionState | null> {
try {
const raw = JSON.parse(await fs.readFile(this.policyFile(cacheDir, instanceId), 'utf8')) as {
version?: unknown;
+ source?: unknown;
trustedClients?: unknown;
};
if (raw?.version !== 1) return null;
+ if (raw.source !== undefined && raw.source !== source) {
+ this.deps.log?.warn('browser extension pairings ignored: the package came from another source', {
+ instanceId,
+ });
+ return null;
+ }
return {
trustedClients: Array.isArray(raw.trustedClients) ? raw.trustedClients : [],
};
@@ -434,13 +459,16 @@ export class GhostBrowserExtensionSlot {
private persist(entry: Entry, change: Partial<SavedBrowserExtensionState>): Promise<void> {
entry.saved = { ...entry.saved, ...change };
const snapshot = entry.saved;
- entry.writes = entry.writes.then(() => this.writeSaved(entry.cacheDir, entry.instanceId, snapshot));
+ entry.writes = entry.writes.then(() =>
+ this.writeSaved(entry.cacheDir, entry.instanceId, entry.source, snapshot),
+ );
return entry.writes;
}
private async writeSaved(
cacheDir: string,
instanceId: string,
+ source: string,
saved: SavedBrowserExtensionState,
): Promise<void> {
const file = this.policyFile(cacheDir, instanceId);
@@ -449,7 +477,7 @@ export class GhostBrowserExtensionSlot {
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
await fs.writeFile(
tmp,
- JSON.stringify({ version: 1, trustedClients: saved.trustedClients }),
+ JSON.stringify({ version: 1, source, trustedClients: saved.trustedClients }),
{ mode: 0o600 },
);
await fs.rename(tmp, file);
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/user-browser-backend.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/user-browser-backend.test.ts
index 74b3b0f03f..d7241c084d 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/user-browser-backend.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/user-browser-backend.test.ts
@@ -635,6 +635,15 @@ describe('UserBrowserBackend · 读取与动作', () => {
ref: 'r9',
files: [{ name: 'a.png', data: 'AQID', mimeType: 'image/png' }],
});
+ // Review 2026-10-29: a batch over the extension's ~30 MB limit is refused before any file is read.
+ const big = pathMod.join(root, 'big.bin');
+ await fsp.writeFile(big, '');
+ await fsp.truncate(big, 31_000_000);
+ const jobsBefore = fake.jobs.length;
+ expect(
+ await call(b, { action: 'upload', targetId: 't1', paths: [big], __mcpSessionId: 's1' }),
+ ).toMatchObject({ ok: false, message: expect.stringContaining('30 MB') });
+ expect(fake.jobs.length).toBe(jobsBefore);
expect(
await call(b, {
action: 'upload',
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/user-browser-backend.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/user-browser-backend.ts
index 76c5c24430..675c12ccb4 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/user-browser-backend.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/user-browser-backend.ts
@@ -26,7 +26,7 @@ import type {
BrowserExtensionClientInfo,
BrowserExtensionJobResult,
} from '../../browser-extension/bridge.js';
-import { resolveUploadFiles } from './rsb-webview-upload-policy.js';
+import { readRecipeInputFileSync, resolveUploadFiles } from './rsb-webview-upload-policy.js';
import type { BackendRequest, BackendResult, BrowserBackend } from './types.js';
export interface UserBrowserPageControl {
@@ -151,6 +151,16 @@ function outdated(action: BackendRequest['action'], what: string): BackendResult
);
}
+/** Bytes per upload the extension accepts (its job validation caps base64 at 40 million characters). */
+const UPLOAD_BATCH_BYTES_MAX = 30_000_000;
+function uploadTooLarge(action: BackendRequest['action']): BackendResult {
+ return actionFailed(
+ action,
+ '上传文件总大小超过约 30 MB:浏览器扩展一次只能接收这么多,请分批上传',
+ 'BROWSER_RUNTIME_INVALID_REQUEST',
+ );
+}
+
const UPLOAD_MIME: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
@@ -1263,13 +1273,24 @@ export class UserBrowserBackend implements BrowserBackend {
? await this.opts.resolveUploadRoots(sessionId)
: [];
const paths = await resolveUploadFiles(req.paths, roots);
- const files = await Promise.all(
- paths.map(async (file) => ({
+ // The extension takes about 30 MB per upload (its base64 limit); refuse before reading anything.
+ let total = 0;
+ for (const file of paths) total += (await fs.stat(file)).size;
+ if (total > UPLOAD_BATCH_BYTES_MAX) return uploadTooLarge(req.action);
+ const files: Array<{ name: string; data: string; mimeType: string }> = [];
+ let read = 0;
+ for (const file of paths) {
+ // Read from the descriptor that was checked, so a file swapped for a link after the check
+ // cannot pull bytes from outside the allowed roots. One file at a time bounds memory.
+ const bytes = readRecipeInputFileSync(file, roots);
+ read += bytes.length;
+ if (read > UPLOAD_BATCH_BYTES_MAX) return uploadTooLarge(req.action);
+ files.push({
name: path.basename(file),
- data: (await fs.readFile(file)).toString('base64'),
+ data: bytes.toString('base64'),
mimeType: UPLOAD_MIME[path.extname(file).toLowerCase()] ?? '',
- })),
- );
+ });
+ }
const ref = req.inputRef ?? req.ref;
const job = await this.pageJob(gate.control, record, 'upload', {
...(ref ? { ref } : req.selector ? { selector: req.selector } : { selector: 'input[type=file]' }),