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): 修复 MCP App 卡片卸载时的顶层崩溃 (#6488)

FicoWang86c53b902804
diff --git a/apps/desktop/scripts/fixtures/mcp-app-card/mcp-app-card-fixture.tsx b/apps/desktop/scripts/fixtures/mcp-app-card/mcp-app-card-fixture.tsx
new file mode 100644
index 0000000000..83f072c556
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/mcp-app-card/mcp-app-card-fixture.tsx
@@ -0,0 +1,27 @@
+import { McpAppCard } from '../../../src/renderer/components/chat/McpAppCard';
+import { AppFrame, mountPage } from '../../ui-page/harness';
+
+// The page runner intentionally forbids guest frames. Exercise the actual error
+// and retry surface here; connected guest teardown is a separate browser check.
+let opens = 0;
+void mountPage({
+ host: {
+ maker: {
+ mcpApps: async (_sessionId: string, input: { op: string }) => {
+ if (input.op === 'open') {
+ document.documentElement.dataset.fixtureOpens = String(++opens);
+ throw new Error('MCP_APP_CARD_UNAVAILABLE');
+ }
+ return {};
+ },
+ },
+ },
+ render: () => (
+ <AppFrame>
+ <div className="p-4">
+ <McpAppCard sessionId="fixture-task" clientId="fixture-card" title="MCP App"
+ fallbackText="Saved result: the form response remains available after the App closes." />
+ </div>
+ </AppFrame>
+ ),
+});
diff --git a/apps/desktop/scripts/fixtures/mcp-app-card/ui-page.mjs b/apps/desktop/scripts/fixtures/mcp-app-card/ui-page.mjs
new file mode 100644
index 0000000000..043eed47ec
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/mcp-app-card/ui-page.mjs
@@ -0,0 +1,26 @@
+import assert from 'node:assert/strict';
+
+export default {
+ name: 'mcp-app-card',
+ entry: './mcp-app-card-fixture.tsx',
+ viewport: { width: 800, height: 520 },
+ real: 'McpAppCard, McpAppController, Button, saved fallback text, theme and translations',
+ notCovered: 'Live cross-origin App, teardown handshake, fullscreen and full Cindy session switching; verified separately from this error-surface screenshot',
+ stubs: {
+ 'src/renderer/features/device-link/stickySessionOrigin':
+ 'export const getStickySessionDeviceId = () => undefined;',
+ 'src/renderer/features/device-link/remoteProjectsStore':
+ 'export const remoteProjectsStore = { subscribe: () => () => {} };',
+ },
+ cases: { default: { about: 'Failed App retains saved text and offers retry' } },
+ async ready(page) { await page.getByRole('alert').waitFor(); },
+ async check(page, ui) {
+ assert.equal(await page.locator('iframe').count(), 0);
+ const retry = page.getByRole('button', { name: await ui.t('mcpApps.retry'), exact: true });
+ await retry.click();
+ await page.waitForFunction(() => document.documentElement.dataset.fixtureOpens === '2');
+ await page.getByRole('alert').waitFor();
+ assert.ok(await page.getByText('Saved result:', { exact: false }).isVisible());
+ assert.ok(await retry.isVisible());
+ },
+};
diff --git a/apps/desktop/src/main/bot-import/__tests__/host.test.ts b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
index e933fb7110..736abe55a9 100644
--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
@@ -266,9 +266,13 @@ it('keeps an already installed teammate working after its package leaves the cat
const first = await nativeFinished(await inviteNativeBotPackage(entry, 'renderer:1'));
// The receipt of a package that is no longer bundled (a teammate retired from the catalog).
const file = path.join(h.root, 'companion-imports', `${first.requestId}.json`);
- const receipt = JSON.parse(await fs.readFile(file, 'utf8'));
- receipt.nativePackage.packageId = 'retired-example';
- await fs.writeFile(file, JSON.stringify(receipt));
+ // A complete result can precede checkpoint cleanup. Join its lifecycle lock so
+ // the trailing receipt save cannot overwrite this retired-package fixture.
+ await withBotProfileLocks([first.botId], async () => {
+ const receipt = JSON.parse(await fs.readFile(file, 'utf8'));
+ receipt.nativePackage.packageId = 'retired-example';
+ await fs.writeFile(file, JSON.stringify(receipt));
+ });
const catalog = await listNativeBotPackages();
expect(catalog.map(item => item.packageId)).not.toContain('retired-example');
expect(catalog.every(item => item.installation === undefined)).toBe(true);
diff --git a/apps/desktop/src/renderer/components/chat/McpAppCard.tsx b/apps/desktop/src/renderer/components/chat/McpAppCard.tsx
index 80ea6df0fe..8cc5ada836 100644
--- a/apps/desktop/src/renderer/components/chat/McpAppCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/McpAppCard.tsx
@@ -114,7 +114,7 @@ function InteractiveMcpAppCard({ sessionId, clientId, title, fallbackText, devic
};
}, []);
- useEffect(() => {
+ useLayoutEffect(() => {
const element = root.current;
if (!element || !visible) return;
let disposed = false;
@@ -127,8 +127,8 @@ function InteractiveMcpAppCard({ sessionId, clientId, title, fallbackText, devic
if (!disposed) {
setLoading(false);
setError(mcpAppFailureKey(error));
- frame?.remove();
setMode('inline');
+ dispose();
}
};
const controller = new McpAppController(
@@ -182,7 +182,6 @@ function InteractiveMcpAppCard({ sessionId, clientId, title, fallbackText, devic
})
.catch((error) => {
fail(error);
- void controller.close().catch(() => {});
});
const update = () => {
void controller.context(hostContext(localeRef.current, element)).catch(() => {});
@@ -194,7 +193,8 @@ function InteractiveMcpAppCard({ sessionId, clientId, title, fallbackText, devic
});
const sizeObserver = new ResizeObserver(update);
sizeObserver.observe(element);
- return () => {
+ function dispose() {
+ if (disposed) return;
disposed = true;
controllerRef.current = undefined;
// Notify before hiding the frame; close() retains the View until the
@@ -202,24 +202,33 @@ function InteractiveMcpAppCard({ sessionId, clientId, title, fallbackText, devic
controller.prepareNativeClose();
themeObserver.disconnect();
sizeObserver.disconnect();
- // Atomic move preserves the Chromium frame during its bounded teardown handshake.
+ // Layout cleanup runs before React removes the ancestor message tree.
+ // Keep a live frame connected for the bounded teardown, including on failure.
if (frame) {
frame.style.cssText =
'position:fixed;width:1px;height:1px;visibility:hidden;pointer-events:none';
const body = document.body as HTMLElement & {
moveBefore?: (node: Node, child: Node | null) => void;
};
- if (body.moveBefore) body.moveBefore(frame, null);
- else controller.prepareNativeClose();
+ if (frame.isConnected && body.isConnected && frame.ownerDocument === body.ownerDocument) {
+ try {
+ body.moveBefore?.(frame, null);
+ } catch {
+ // A rejected atomic move must not prevent close/listener cleanup.
+ // Never reinsert a disconnected frame: that would reload the App.
+ }
+ }
}
void controller
.close()
.catch(() => {})
.finally(() => {
frame?.remove();
+ frame = undefined;
window.removeEventListener('message', receive);
});
- };
+ }
+ return dispose;
}, [sessionId, clientId, attempt, appTitle, visible, deviceId]);
useEffect(() => {
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/McpAppCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/McpAppCard.test.tsx
index 7ad9f7c596..32751e41a6 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/McpAppCard.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/McpAppCard.test.tsx
@@ -67,6 +67,83 @@ afterEach(() => {
state.openError = undefined;
state.originListeners.clear();
});
+
+// #6432: the real card must release a mounted View without letting cleanup
+// escape React. Existing jsdom tests lack moveBefore and close immediately.
+// Unit tier models its connected-node constraint and delays close; the browser
+// experiment separately verifies Chromium preserves the actual App document.
+it.each(['unmount', 'failure-retry', 'disconnected', 'rejected-move', 'no-move-api'])(
+ 'finishes bounded View cleanup after %s', async (scenario) => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');
+ vi.stubGlobal('matchMedia', () => ({ matches: false }));
+ vi.stubGlobal('IntersectionObserver', class {
+ constructor(private callback: (entries: Array<{ isIntersecting: boolean }>) => void) {}
+ observe(element: Element) { state.intersections.set(element, this.callback); }
+ disconnect() {}
+ });
+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
+ const added = vi.spyOn(window, 'addEventListener');
+ const removed = vi.spyOn(window, 'removeEventListener');
+ const move = vi.fn((node: Node, child: Node | null) => {
+ if (!node.isConnected || scenario === 'rejected-move')
+ throw new DOMException('Atomic move requires a connected node', 'HierarchyRequestError');
+ document.body.insertBefore(node, child);
+ });
+ Object.defineProperty(document.body, 'moveBefore', {
+ configurable: true, value: scenario === 'no-move-api' ? undefined : move,
+ });
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ let finish!: () => void;
+ const closed = new Promise<void>((resolve) => { finish = resolve; });
+ try {
+ await act(async () => root.render(<article><div>
+ <McpAppCard sessionId="task" clientId="card" title="App" fallbackText="Saved result" />
+ </div></article>));
+ await act(async () => [...state.intersections.values()][0]([{ isIntersecting: true }]));
+ const controller = state.controllers[0];
+ controller.close.mockReturnValue(closed);
+ const receive = added.mock.calls.find(([type]) => type === 'message')![1];
+ const frame = container.querySelector('iframe')!;
+ if (scenario === 'disconnected') frame.remove();
+ if (scenario === 'failure-retry') {
+ await act(async () => controller.fail(new Error('MCP_APP_FAILED')));
+ expect(container.querySelector('[role="alert"]')).not.toBeNull();
+ expect(container.textContent).toContain('Saved result');
+ expect(frame.isConnected).toBe(true);
+ await act(async () => container.querySelector('button')!.click());
+ expect(state.controllers).toHaveLength(2);
+ expect(container.querySelector('iframe')).not.toBe(frame);
+ expect(container.querySelector('[role="alert"]')).toBeNull();
+ } else {
+ // Delete the ancestor message tree, as session switching/virtualization does.
+ await act(async () => root.render(null));
+ }
+ expect(controller.close).toHaveBeenCalledOnce();
+ expect(removed).not.toHaveBeenCalledWith('message', receive);
+ if (scenario === 'unmount' || scenario === 'failure-retry') {
+ expect(frame.parentElement).toBe(document.body);
+ expect(frame.isConnected).toBe(true);
+ }
+ if (scenario === 'disconnected') expect(move).not.toHaveBeenCalled();
+ await act(async () => { finish(); await closed; });
+ expect(frame.isConnected).toBe(false);
+ expect(removed).toHaveBeenCalledWith('message', receive);
+ if (scenario === 'failure-retry') {
+ expect(container.querySelector('iframe')?.isConnected).toBe(true);
+ expect(state.controllers[1].close).not.toHaveBeenCalled();
+ }
+ } finally {
+ finish();
+ await act(async () => root.unmount());
+ container.remove();
+ Reflect.deleteProperty(document.body, 'moveBefore');
+ }
+ },
+);
+
it('reopens when device ownership is restored but ignores unchanged ownership', async () => {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');