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(desktop): keep disposed MCP App frames from quitting the app

kingwindang22496429a058
diff --git a/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts
index fffbd22035..6129077a6a 100644
--- a/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts
+++ b/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts
@@ -186,6 +186,41 @@ describe('MCP App local protocol isolation', () => {
contents.emit('before-input-event', event, { type: 'keyDown', key: 'Escape' });
expect(sandbox.executeJavaScript).toHaveBeenCalledOnce();
});
+ it('keeps a disposed render frame from escaping WebContents callbacks and quitting the app', () => {
+ registerMcpAppProtocol();
+ const disposed = () => {
+ throw new Error('Render frame was disposed before WebFrameMain could be accessed');
+ };
+ const contents = new EventEmitter();
+ app.emit('web-contents-created', {}, contents);
+ const input = { preventDefault: vi.fn() };
+ const escape = { type: 'keyDown', key: 'Escape' };
+ Object.defineProperty(contents, 'focusedFrame', { configurable: true, get: disposed });
+ expect(() => contents.emit('before-input-event', input, escape)).not.toThrow();
+ Object.defineProperty(contents, 'focusedFrame', {
+ configurable: true,
+ value: { get url() { return disposed(); }, parent: null },
+ });
+ expect(() => contents.emit('before-input-event', input, escape)).not.toThrow();
+ expect(input.preventDefault).not.toHaveBeenCalled();
+ // A frame that disappears cannot be authorised, so its navigation is refused.
+ const gone = { get frame() { return disposed(); }, url: 'https://example.org', preventDefault: vi.fn() };
+ expect(() => contents.emit('will-frame-navigate', gone)).not.toThrow();
+ expect(gone.preventDefault).toHaveBeenCalledOnce();
+ const ancestorGone = {
+ frame: { url: 'cindy-mcp-app://example-view/resource', get parent() { return disposed(); } },
+ url: 'https://example.org',
+ preventDefault: vi.fn(),
+ };
+ expect(() => contents.emit('will-frame-navigate', ancestorGone)).not.toThrow();
+ expect(ancestorGone.preventDefault).toHaveBeenCalledOnce();
+ // Failures that are not a disposed frame are still reported.
+ Object.defineProperty(contents, 'focusedFrame', {
+ configurable: true,
+ get() { throw new Error('boom'); },
+ });
+ expect(() => contents.emit('before-input-event', input, escape)).toThrow('boom');
+ });
it('rebuilds remote CSP and serves only the current owner through distinct origins', async () => {
let handler!: (request: Request) => Promise<Response> | Response;
vi.spyOn(protocol, 'handle').mockImplementation((_scheme, callback) => {
diff --git a/apps/desktop/src/main/mcp-apps/sandboxProtocol.ts b/apps/desktop/src/main/mcp-apps/sandboxProtocol.ts
index f74be7d8ba..8b89271825 100644
--- a/apps/desktop/src/main/mcp-apps/sandboxProtocol.ts
+++ b/apps/desktop/src/main/mcp-apps/sandboxProtocol.ts
@@ -26,6 +26,13 @@ const documents = new Map<
bridge?: { key: string; frame?: WebFrameMain; invoke(input: unknown): Promise<unknown> };
}
>();
+// Electron throws this from any WebFrameMain getter (`contents.focusedFrame`, `frame.url`,
+// `frame.parent`, `event.frame`) once the render frame is gone, which is routine while an
+// App iframe is being torn down or recreated. It must not escape a WebContents event
+// callback: that surfaces as a top-level uncaughtException and quits the whole app.
+function isDisposedFrameError(error: unknown): boolean {
+ return error instanceof Error && error.message.includes('Render frame was disposed');
+}
async function readBridgeBody(request: Request): Promise<string> {
const reader = request.body?.getReader();
if (!reader) throw new Error('MCP_APP_INVALID_REQUEST');
@@ -152,37 +159,50 @@ export function registerMcpAppProtocol(): void {
input.shift
)
return;
- for (let frame = contents.focusedFrame; frame; frame = frame.parent) {
- if (!frame.url.startsWith('cindy-mcp-app:')) continue;
- const url = new URL(frame.url);
- if (url.pathname !== '/sandbox' || url.hostname.endsWith('-view')) continue;
- const entry = documents.get(url.hostname);
- if (!entry || entry.owner !== getCurrentDbClientSnapshot()) return;
- event.preventDefault();
- void frame
- .executeJavaScript("window.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape'}))")
- .catch(() => {});
- return;
+ try {
+ for (let frame = contents.focusedFrame; frame; frame = frame.parent) {
+ if (!frame.url.startsWith('cindy-mcp-app:')) continue;
+ const url = new URL(frame.url);
+ if (url.pathname !== '/sandbox' || url.hostname.endsWith('-view')) continue;
+ const entry = documents.get(url.hostname);
+ if (!entry || entry.owner !== getCurrentDbClientSnapshot()) return;
+ event.preventDefault();
+ void frame
+ .executeJavaScript("window.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape'}))")
+ .catch(() => {});
+ return;
+ }
+ } catch (error) {
+ // The focused frame vanished mid-walk: there is nothing left to relay Escape to.
+ if (!isDisposedFrameError(error)) throw error;
}
});
contents.on('will-frame-navigate', (event) => {
- const source = event.frame?.url || event.initiator?.url || '';
- // A declared nested iframe is allowed to load its approved origin. Only
- // descendants of the actual App resource get this grant, never the App
- // itself or its trusted sandbox proxy.
- let nestedDomains: readonly string[] | undefined;
- for (let ancestor = event.frame?.parent; ancestor; ancestor = ancestor.parent) {
- if (!ancestor.url.startsWith('cindy-mcp-app:')) continue;
- const url = new URL(ancestor.url);
- if (!url.hostname.endsWith('-view') || url.pathname !== '/resource') continue;
- const entry = documents.get(url.hostname.slice(0, -5));
- nestedDomains =
- entry?.owner === getCurrentDbClientSnapshot()
- ? (entry.document.policy?.frameDomains ?? [])
- : [];
- break;
+ try {
+ const source = event.frame?.url || event.initiator?.url || '';
+ // A declared nested iframe is allowed to load its approved origin. Only
+ // descendants of the actual App resource get this grant, never the App
+ // itself or its trusted sandbox proxy.
+ let nestedDomains: readonly string[] | undefined;
+ for (let ancestor = event.frame?.parent; ancestor; ancestor = ancestor.parent) {
+ if (!ancestor.url.startsWith('cindy-mcp-app:')) continue;
+ const url = new URL(ancestor.url);
+ if (!url.hostname.endsWith('-view') || url.pathname !== '/resource') continue;
+ const entry = documents.get(url.hostname.slice(0, -5));
+ nestedDomains =
+ entry?.owner === getCurrentDbClientSnapshot()
+ ? (entry.document.policy?.frameDomains ?? [])
+ : [];
+ break;
+ }
+ if (!isMcpAppFrameNavigationAllowed(source, event.url, nestedDomains))
+ event.preventDefault();
+ } catch (error) {
+ if (!isDisposedFrameError(error)) throw error;
+ // Source and ancestry can no longer be established, so the navigation policy
+ // cannot approve it. Fail closed rather than let it bypass the checks.
+ event.preventDefault();
}
- if (!isMcpAppFrameNavigationAllowed(source, event.url, nestedDomains)) event.preventDefault();
});
});
protocol.handle('cindy-mcp-app', async (request) => {