Skip to content

Commit b8d9a67

Browse files
cliffhallclaude
andcommitted
refactor(apps): address PR review — theme stability, onError, validation polish
Responds to the automated PR review on #1403. - Theme toggle no longer rebuilds a running app's bridge. createAppBridgeFactory reads the resolved theme from the DOM (Mantine's data-mantine-color-scheme) at bridge-build time instead of capturing isDark in the factory deps, so the factory identity is stable across theme flips. (#1) - Wire AppRenderer's onError through AppsScreen -> InspectorView -> App.tsx, surfacing bridge/runtime failures (no client, late rejection, failed tools/call) as a red toast instead of a silent blank iframe. (#2) - Extract validateToolOutput into a pure, unit-tested helper covering the matching / extra-property / missing-structuredContent / error / bad-schema cases (the no-structuredContent branch can't be produced via the SDK server, which rejects it before sending). (#4) - useSandboxUrl aborts its in-flight fetch on unmount (cancelled flag) to avoid setState after unmount. (#5) - Schema-mismatch toast: autoClose:false (details modal is one click away). (note) - AppRenderer: add a state-machine comment block documenting the bridge lifecycle refs. (#6) - inspectorClient: note why the `as CallToolResult` casts are safe. (note) Tests: AppsScreen onError surface; validateToolOutput unit suite; factory theme read from DOM. validate + test:storybook green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 6376c6b commit b8d9a67

13 files changed

Lines changed: 298 additions & 83 deletions

File tree

‎clients/web/src/App.tsx‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -265,9 +265,8 @@ function App() {
265265
const invocation = await inspectorClient.readResource(uri);
266266
return invocation.result;
267267
},
268-
theme: isDark ? "dark" : "light",
269268
}),
270-
[inspectorClient, isDark],
269+
[inspectorClient],
271270
);
272271

273272
const [managedToolsState, setManagedToolsState] =
@@ -923,6 +922,17 @@ function App() {
923922
// these route the tool input/result into the running app via the renderer's
924923
// imperative handle. ---
925924

925+
// Surfaces bridge/runtime failures (factory throw — e.g. no client after a
926+
// disconnect — late bridge rejection, or a failed tools/call) that would
927+
// otherwise leave a silently blank app iframe.
928+
const onAppError = useCallback((err: Error) => {
929+
notifications.show({
930+
title: "MCP App error",
931+
message: err.message,
932+
color: "red",
933+
});
934+
}, []);
935+
926936
// Selection is owned by AppsScreen's local state; App.tsx has nothing to do
927937
// on select, but the prop is required so the screen stays prop-driven.
928938
const onSelectApp = useCallback(() => {}, []);
@@ -965,23 +975,25 @@ function App() {
965975
message: invocation.outputValidationError,
966976
};
967977
notifications.show({
978+
// Don't auto-dismiss: the message is advisory and the details modal
979+
// is one click away — let the user close it when they've read it.
980+
autoClose: false,
968981
title: "App output doesn't match its schema",
969982
color: "yellow",
970-
autoClose: 12000,
971983
message: (
972984
<OutputValidationToastMessage
973985
onViewDetails={() => setOutputValidationDetails(details)}
974986
/>
975987
),
976988
});
977989
}
978-
} catch {
979-
// Transport-level failure — the app already received its input; there
980-
// is no per-app error surface yet, so swallow to avoid an unhandled
981-
// rejection from the `void onOpenApp(...)` call site.
990+
} catch (err) {
991+
// Transport-level failure (the call never returned a result). Surface it
992+
// so the user isn't left staring at a blank/partial app frame.
993+
onAppError(err instanceof Error ? err : new Error(String(err)));
982994
}
983995
},
984-
[inspectorClient, tools],
996+
[inspectorClient, tools, onAppError],
985997
);
986998

987999
const onCloseApp = useCallback(() => {
@@ -1393,6 +1405,7 @@ function App() {
13931405
void onOpenApp(name, args);
13941406
}}
13951407
onCloseApp={onCloseApp}
1408+
onAppError={onAppError}
13961409
onRefreshApps={onRefreshTools}
13971410
/>
13981411
<ServerConfigModal

‎clients/web/src/components/elements/AppRenderer/AppRenderer.tsx‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,26 @@ async function disposeBridge(bridge: AppBridge): Promise<void> {
5454
}
5555
}
5656

57+
/**
58+
* Bridge lifecycle (the interlocking refs below):
59+
*
60+
* mount ─▶ build (buildId++) ─▶ factory(iframe,tool) ─async─▶ bridgeRef set
61+
* │ on "initialized"
62+
* ▼ → flushPending
63+
* cleanup ─▶ scheduleDispose() ──microtask──▶ dispose (unless cancelled)
64+
* ▲ │
65+
* └── re-setup with SAME inputs ─────┘ cancel + REUSE bridge
66+
*
67+
* - `buildId` (monotonic): a bridge resolved from an older build self-disposes.
68+
* - `disposeScheduled`: a dispose is queued (microtask); a synchronous re-setup
69+
* (StrictMode double-invoke, or a transient re-render) cancels it and reuses
70+
* the live bridge instead of rebuilding (rebuild double-loads the sandbox and
71+
* races the app handshake). A re-setup with CHANGED inputs disposes + rebuilds.
72+
* - `lastDeps`: distinguishes "same inputs → reuse" from "changed → rebuild".
73+
* - `initialized`: gates flushing buffered input/result until the view is ready.
74+
* - `pendingInput`/`pendingResult`: latest-wins buffer for host-initiated open.
75+
* - `teardownStarted`: makes the imperative teardown() idempotent vs unmount.
76+
*/
5777
export function AppRenderer({
5878
sandboxPath,
5979
tool,

‎clients/web/src/components/elements/AppRenderer/createAppBridgeFactory.test.ts‎

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,6 @@ describe("createAppBridgeFactory", () => {
106106
const factory = createAppBridgeFactory({
107107
getClient: () => null,
108108
readResource: vi.fn(),
109-
theme: "dark",
110109
});
111110
await expect(factory(makeIframe(), tool)).rejects.toThrow(
112111
/no connected MCP client/,
@@ -117,25 +116,29 @@ describe("createAppBridgeFactory", () => {
117116
const factory = createAppBridgeFactory({
118117
getClient: () => fakeClient,
119118
readResource: vi.fn(),
120-
theme: "light",
121119
});
122120
await expect(factory(makeIframe(false), tool)).rejects.toThrow(/no window/);
123121
});
124122

125123
it("constructs the bridge with the client, host info, capabilities and theme, then connects", async () => {
126-
const factory = createAppBridgeFactory({
127-
getClient: () => fakeClient,
128-
readResource: vi.fn().mockResolvedValue(uiResource("<h1>hi</h1>")),
129-
theme: "dark",
130-
});
131-
await factory(makeIframe(), tool);
132-
expect(bridgeInstances).toHaveLength(1);
133-
const bridge = bridgeInstances[0];
134-
expect(bridge.ctorArgs[0]).toBe(fakeClient);
135-
expect(bridge.ctorArgs[1]).toMatchObject({ name: "MCP Inspector" });
136-
expect(bridge.ctorArgs[2]).toMatchObject({ serverTools: {} });
137-
expect(bridge.ctorArgs[3]).toEqual({ hostContext: { theme: "dark" } });
138-
expect(bridge.connect).toHaveBeenCalledTimes(1);
124+
// Theme is read from the DOM (Mantine's resolved color-scheme attribute).
125+
document.documentElement.setAttribute("data-mantine-color-scheme", "dark");
126+
try {
127+
const factory = createAppBridgeFactory({
128+
getClient: () => fakeClient,
129+
readResource: vi.fn().mockResolvedValue(uiResource("<h1>hi</h1>")),
130+
});
131+
await factory(makeIframe(), tool);
132+
expect(bridgeInstances).toHaveLength(1);
133+
const bridge = bridgeInstances[0];
134+
expect(bridge.ctorArgs[0]).toBe(fakeClient);
135+
expect(bridge.ctorArgs[1]).toMatchObject({ name: "MCP Inspector" });
136+
expect(bridge.ctorArgs[2]).toMatchObject({ serverTools: {} });
137+
expect(bridge.ctorArgs[3]).toEqual({ hostContext: { theme: "dark" } });
138+
expect(bridge.connect).toHaveBeenCalledTimes(1);
139+
} finally {
140+
document.documentElement.removeAttribute("data-mantine-color-scheme");
141+
}
139142
});
140143

141144
it("on sandboxready, reads the UI resource and pushes html + meta to the sandbox", async () => {
@@ -148,7 +151,6 @@ describe("createAppBridgeFactory", () => {
148151
const factory = createAppBridgeFactory({
149152
getClient: () => fakeClient,
150153
readResource,
151-
theme: "light",
152154
});
153155
await factory(makeIframe(), tool);
154156
const bridge = bridgeInstances[0];
@@ -169,7 +171,6 @@ describe("createAppBridgeFactory", () => {
169171
const factory = createAppBridgeFactory({
170172
getClient: () => fakeClient,
171173
readResource,
172-
theme: "light",
173174
});
174175
await factory(makeIframe(), {
175176
name: "plain",
@@ -186,7 +187,6 @@ describe("createAppBridgeFactory", () => {
186187
const factory = createAppBridgeFactory({
187188
getClient: () => fakeClient,
188189
readResource,
189-
theme: "light",
190190
});
191191
await factory(makeIframe(), tool);
192192
const bridge = bridgeInstances[0];
@@ -200,7 +200,6 @@ describe("createAppBridgeFactory", () => {
200200
const factory = createAppBridgeFactory({
201201
getClient: () => fakeClient,
202202
readResource,
203-
theme: "light",
204203
});
205204
await factory(makeIframe(), tool);
206205
const bridge = bridgeInstances[0];
@@ -216,7 +215,6 @@ describe("createAppBridgeFactory", () => {
216215
const factory = createAppBridgeFactory({
217216
getClient: () => fakeClient,
218217
readResource: vi.fn().mockResolvedValue(uiResource("<h1>x</h1>")),
219-
theme: "light",
220218
});
221219
await factory(makeIframe(), tool);
222220
const bridge = bridgeInstances[0];

‎clients/web/src/components/elements/AppRenderer/createAppBridgeFactory.ts‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,32 @@ export interface AppBridgeFactoryDeps {
4242
getClient: () => Client | null;
4343
/** Reads a UI resource (resources/read) and returns the SDK result. */
4444
readResource: (uri: string) => Promise<ReadResourceResult>;
45-
/** Initial host theme passed to the app via hostContext. */
46-
theme: "light" | "dark";
45+
}
46+
47+
/**
48+
* Resolve the host theme from the DOM at bridge-build time. Mantine writes the
49+
* resolved color scheme to `<html data-mantine-color-scheme>`. Reading it here
50+
* (rather than capturing React state in the factory deps) keeps the factory's
51+
* identity stable across theme toggles — the AppRenderer treats a new factory
52+
* identity as "rebuild the bridge", which would reload a running app's iframe on
53+
* every theme flip. The theme is read once per bridge build (the value at open
54+
* time); pushing live theme updates to an already-open app would need an
55+
* AppBridge.setHostContext follow-up.
56+
*/
57+
function currentTheme(): "light" | "dark" {
58+
if (typeof document !== "undefined") {
59+
const attr = document.documentElement.getAttribute(
60+
"data-mantine-color-scheme",
61+
);
62+
if (attr === "dark" || attr === "light") return attr;
63+
}
64+
if (
65+
typeof window !== "undefined" &&
66+
window.matchMedia?.("(prefers-color-scheme: dark)").matches
67+
) {
68+
return "dark";
69+
}
70+
return "light";
4771
}
4872

4973
/** First text content block of a UI resource, plus its `_meta` (sandbox hints). */
@@ -95,7 +119,7 @@ export function createAppBridgeFactory(
95119
}
96120

97121
const bridge = new AppBridge(client, HOST_INFO, HOST_CAPABILITIES, {
98-
hostContext: { theme: deps.theme },
122+
hostContext: { theme: currentTheme() },
99123
});
100124

101125
// The double-iframe proxy posts `sandboxready` once it can receive content.

‎clients/web/src/components/screens/AppsScreen/AppsScreen.test.tsx‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,27 @@ describe("AppsScreen", () => {
9494
expect(screen.queryByText("MCP Apps (3)")).not.toBeInTheDocument();
9595
});
9696

97+
it("surfaces a bridge factory failure via onError", async () => {
98+
const user = userEvent.setup();
99+
const onError = vi.fn();
100+
const throwingFactory: BridgeFactory = () => {
101+
throw new Error("no connected MCP client");
102+
};
103+
renderWithMantine(
104+
<AppsScreen
105+
{...buildProps({ bridgeFactory: throwingFactory, onError })}
106+
/>,
107+
);
108+
// The no-fields app auto-launches on selection, mounting the renderer,
109+
// whose effect invokes the factory (which throws → routes to onError).
110+
await user.click(screen.getByText("Ops Dashboard"));
111+
await vi.waitFor(() => expect(onError).toHaveBeenCalledTimes(1));
112+
expect(onError.mock.calls[0][0]).toBeInstanceOf(Error);
113+
expect((onError.mock.calls[0][0] as Error).message).toContain(
114+
"no connected MCP client",
115+
);
116+
});
117+
97118
it("filters the list via the search input", async () => {
98119
const user = userEvent.setup();
99120
renderWithMantine(<AppsScreen {...buildProps()} />);

‎clients/web/src/components/screens/AppsScreen/AppsScreen.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ export interface AppsScreenProps {
4242
onSelectApp: (name: string) => void;
4343
onOpenApp: (name: string, args: Record<string, unknown>) => void;
4444
onCloseApp: () => void;
45+
/** Surfaces bridge/runtime failures from the renderer (e.g. no client). */
46+
onError?: (err: Error) => void;
4547
}
4648

4749
const ScreenLayout = Flex.withProps({
@@ -128,6 +130,7 @@ export function AppsScreen({
128130
onSelectApp,
129131
onOpenApp,
130132
onCloseApp,
133+
onError,
131134
}: AppsScreenProps) {
132135
const [selectedAppName, setSelectedAppName] = useState<string | undefined>(
133136
undefined,
@@ -268,6 +271,7 @@ export function AppsScreen({
268271
sandboxPath={sandboxPath}
269272
tool={selectedTool}
270273
bridgeFactory={bridgeFactory}
274+
onError={onError}
271275
ref={rendererRef}
272276
/>
273277
</RendererFrame>

‎clients/web/src/components/views/InspectorView/InspectorView.stories.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,7 @@ const meta: Meta<typeof InspectorView> = {
359359
onSelectApp: fn(),
360360
onOpenApp: fn(),
361361
onCloseApp: fn(),
362+
onAppError: fn(),
362363
onRefreshApps: fn(),
363364
},
364365
};

‎clients/web/src/components/views/InspectorView/InspectorView.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ function makeProps(
8888
onSelectApp: vi.fn(),
8989
onOpenApp: vi.fn(),
9090
onCloseApp: vi.fn(),
91+
onAppError: vi.fn(),
9192
onRefreshApps: vi.fn(),
9293
...overrides,
9394
};

‎clients/web/src/components/views/InspectorView/InspectorView.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ export interface InspectorViewProps {
274274
onSelectApp: (name: string) => void;
275275
onOpenApp: (name: string, args: Record<string, unknown>) => void;
276276
onCloseApp: () => void;
277+
onAppError: (err: Error) => void;
277278
onRefreshApps: () => void;
278279
}
279280

@@ -341,6 +342,7 @@ export function InspectorView({
341342
onSelectApp,
342343
onOpenApp,
343344
onCloseApp,
345+
onAppError,
344346
onRefreshApps,
345347
}: InspectorViewProps) {
346348
// UI-only state. Connection state, primitive lists, and all action
@@ -482,6 +484,7 @@ export function InspectorView({
482484
onSelectApp={onSelectApp}
483485
onOpenApp={onOpenApp}
484486
onCloseApp={onCloseApp}
487+
onError={onAppError}
485488
/>
486489
</ScreenStage>
487490
<ScreenStage active={activeTab === "Prompts"}>

0 commit comments

Comments
 (0)