Skip to content

Commit 51dce16

Browse files
authored
fix(dashboard): renew a saved App's expired launch instead of failing (#6743)
A saved dashboard tile held one App launch. The host expires a launch after 30 minutes and treats it as stale when its connection settings change, as after a Cloud credential renewal or a server restart. Nothing replaced it: the App's own calls failed with "This App launch has expired, closed, or changed. Reopen the App in its original conversation", and the background refresh turned the same failure into an error on the tile. - When a saved view's call is rejected for a stale or missing launch, the frame asks the tile for a new lease and runs the call once more. The host rejects a stale launch before the tool runs, so nothing runs twice. - The tile renews an expired or reported-stale lease with one refresh and hands out the new lease. - The refresh reuse path relaunches on a stale launch, as it already does for an expired one. The frame test file turns on happy-dom's iframe page loading, which happy-dom 21 switched off by default, so its iframes have a window again. Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent a0a72c4 commit 51dce16

3 files changed

Lines changed: 124 additions & 32 deletions

File tree

‎apps/app/src/components/chat/mcp-app-frame.tsx‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -324,9 +324,10 @@ export type McpAppSandboxViewProps = {
324324
/**
325325
* A cached Dashboard may paint now, but its tools must await a fresh,
326326
* access-checked lease. Called again for each call, so a host that keeps
327-
* this view open across launches can hand it each newer lease.
327+
* this view open across launches can hand it each newer lease. Given the
328+
* lease a call just found stale, it renews that lease or throws.
328329
*/
329-
resolveLiveActions?: () => Promise<{ origin: McpAppOrigin; app: OpenworkMcpAppResource }>
330+
resolveLiveActions?: (staleLaunchId?: string) => Promise<{ origin: McpAppOrigin; app: OpenworkMcpAppResource }>
330331
/**
331332
* With resolveLiveActions: this saved view goes live in place, so the App
332333
* may ask for its kept read-only results. Like every call, such a read
@@ -430,9 +431,9 @@ export function McpAppSandboxView({ origin, app, resolveLiveActions, goesLiveInP
430431
const loads = createMcpAppOpenLoads(openKey === undefined ? undefined : JSON.stringify([openKey, retryAttempt]))
431432
// The lease the current actions use, once a cached view has one.
432433
let liveLaunchId: string | undefined
433-
const bindLiveActions = async () => {
434+
const bindLiveActions = async (staleLaunchId?: string) => {
434435
if (!resolveLiveActions) return
435-
const live = await resolveLiveActions()
436+
const live = await resolveLiveActions(staleLaunchId)
436437
if (disposed || failed) throw new Error("This artifact view has closed or changed.")
437438
if (live.origin.readOnly || !live.app.launchId || live.app.serverName !== app.serverName
438439
|| live.app.toolName !== app.toolName || live.app.resourceUri !== app.resourceUri) {
@@ -599,9 +600,24 @@ export function McpAppSandboxView({ origin, app, resolveLiveActions, goesLiveInP
599600
return cached.result
600601
}
601602
const userInteraction = _meta?.["openwork/userInteraction"] === true
602-
const callNow = async () => connectionController
603+
const callOnce = async () => connectionController
603604
? await connectionController.callTool(actions, app, name, args, userInteraction)
604605
: standardMcpToolResult(await actions.callTool(name, args, userInteraction))
606+
// A saved Dashboard view outlives each lease: a call that finds its
607+
// lease expired or replaced renews it and runs once more. The host
608+
// rejects a stale lease before the tool runs, so nothing runs twice.
609+
const callNow = async () => {
610+
const leaseId = liveLaunchId
611+
try {
612+
return await callOnce()
613+
} catch (cause) {
614+
if (!savedLive || !leaseId || !(cause instanceof OpenworkServerError)
615+
|| !["missing_launch_context", "stale_launch_context"].includes(cause.code)) throw cause
616+
await bindLiveActions(leaseId)
617+
if (liveLaunchId === leaseId) throw cause
618+
return await callOnce()
619+
}
620+
}
605621
let toolResult: CallToolResult
606622
let reused = false
607623
if (userInteraction) {

‎apps/app/src/react-app/domains/dashboard/mcp-app-tile.tsx‎

Lines changed: 46 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -279,24 +279,9 @@ function McpAppTileContent({
279279
const onAutoLaunchDisabledRef = useRef(onAutoLaunchDisabled);
280280
onAutoLaunchDisabledRef.current = onAutoLaunchDisabled;
281281
const launchRef = useRef<TileAttempt | null>(null);
282-
const resolveLiveActions = useCallback(async (): Promise<LiveTarget> => {
283-
const document = stateRef.current.phase === "ready" ? stateRef.current.lifetime : null;
284-
for (;;) {
285-
const attempt = launchRef.current;
286-
// The launch's own handler settles the tile first, so the state read below is its outcome.
287-
if (attempt?.promise) await attempt.promise.catch(() => undefined);
288-
const current = stateRef.current;
289-
// A launch for a different document retires this one; only its replacement may use the new lease.
290-
if (!document?.active || current.phase !== "ready" || current.lifetime !== document) {
291-
throw new Error("This artifact view has closed or changed.");
292-
}
293-
const live = liveTargetOf(current);
294-
if (live?.app.launchId) return live;
295-
if (launchRef.current === attempt) {
296-
throw new Error("This artifact's workspace is still unavailable. Refresh the tile to reconnect.");
297-
}
298-
}
299-
}, []);
282+
// Wakes callers waiting for a launch they requested, or for their document to close.
283+
const launchWaiters = useRef<Array<() => void>>([]);
284+
const wakeLaunchWaiters = useCallback(() => { for (const wake of launchWaiters.current.splice(0)) wake(); }, []);
300285
const lifetime = useRef({ active: true });
301286
const endpointsRef = useRef(launchEndpoints);
302287
endpointsRef.current = launchEndpoints;
@@ -320,7 +305,8 @@ function McpAppTileContent({
320305
}
321306
removeDashboardTileCache(cacheScopeKey, entry.id);
322307
updateState(next);
323-
}, [cacheScopeKey, entry.id, releaseLaunch, updateState]);
308+
wakeLaunchWaiters();
309+
}, [cacheScopeKey, entry.id, releaseLaunch, updateState, wakeLaunchWaiters]);
324310
const requestRefresh = useCallback((userInitiated: boolean) => {
325311
if (!lifetime.current.active || refreshStateRef.current === "refreshing") return;
326312
updateRefresh("refreshing");
@@ -330,6 +316,35 @@ function McpAppTileContent({
330316
setStarted(true);
331317
setNonce(next);
332318
}, [updateRefresh]);
319+
const resolveLiveActions = useCallback(async (staleLaunchId?: string): Promise<LiveTarget> => {
320+
const document = stateRef.current.phase === "ready" ? stateRef.current.lifetime : null;
321+
let renewing = false;
322+
for (;;) {
323+
const attempt = launchRef.current;
324+
// The launch's own handler settles the tile first, so the state read below is its outcome.
325+
if (attempt?.promise) await attempt.promise.catch(() => undefined);
326+
const current = stateRef.current;
327+
// A launch for a different document retires this one; only its replacement may use the new lease.
328+
if (!document?.active || current.phase !== "ready" || current.lifetime !== document) {
329+
throw new Error("This artifact view has closed or changed.");
330+
}
331+
const live = liveTargetOf(current);
332+
const leaseId = live?.app.launchId;
333+
const expired = live?.app.refresh ? live.app.refresh.expiresAt <= Date.now() : false;
334+
if (live && leaseId && leaseId !== staleLaunchId && !expired) return live;
335+
if (launchRef.current !== attempt) continue;
336+
// A lease that expired or that the host reported stale is renewed by one
337+
// refresh of this tile, never handed out again.
338+
if (leaseId && !renewing) {
339+
renewing = true;
340+
const launched = new Promise<void>((resolve) => { launchWaiters.current.push(resolve); });
341+
requestRefresh(false);
342+
await launched;
343+
continue;
344+
}
345+
throw new Error("This artifact's workspace is still unavailable. Refresh the tile to reconnect.");
346+
}
347+
}, [requestRefresh]);
333348
useLayoutEffect(() => {
334349
lifetime.current.active = true;
335350
if (launchRef.current?.controller.signal.aborted && !launchRef.current.admitted) launchRef.current = null;
@@ -340,8 +355,9 @@ function McpAppTileContent({
340355
launchRef.current?.controller.abort();
341356
if (stateRef.current.phase === "ready") stateRef.current.lifetime.active = false;
342357
releaseLaunches();
358+
wakeLaunchWaiters();
343359
};
344-
}, [releaseLaunches]);
360+
}, [releaseLaunches, wakeLaunchWaiters]);
345361
useLayoutEffect(() => {
346362
if (savedCache && (!cached || !cachedEndpoint)) removeDashboardTileCache(cacheScopeKey, entry.id);
347363
const current = stateRef.current;
@@ -445,10 +461,14 @@ function McpAppTileContent({
445461
reused = current;
446462
} catch (cause) {
447463
assertActive();
448-
if (!(cause instanceof OpenworkServerError) || cause.status !== 422 || !["mcp_app_resource_changed", "mcp_app_refresh_denied"].includes(cause.code)) throw cause;
449-
fallbackEndpoint = current.endpoint;
450-
clearDocument({ phase: "loading" });
451-
attempt.document = undefined;
464+
if (!(cause instanceof OpenworkServerError) || cause.status !== 422) throw cause;
465+
if (["mcp_app_resource_changed", "mcp_app_refresh_denied"].includes(cause.code)) {
466+
fallbackEndpoint = current.endpoint;
467+
clearDocument({ phase: "loading" });
468+
attempt.document = undefined;
469+
// Only the lease went stale (expired, or its connection settings changed):
470+
// launch again for the same document, as an expired lease does.
471+
} else if (!["stale_launch_context", "missing_launch_context"].includes(cause.code)) throw cause;
452472
}
453473
}
454474
if (!target) {
@@ -531,6 +551,7 @@ function McpAppTileContent({
531551
},
532552
});
533553
attempt.promise = promise;
554+
wakeLaunchWaiters();
534555
const markSettled = () => { if (launchRef.current === attempt) attempt.promise = null; };
535556
void promise.then(markSettled, markSettled);
536557
void promise.then(next => {
@@ -609,7 +630,7 @@ function McpAppTileContent({
609630
attempt.controller.signal.addEventListener("abort", stopCredentialRetry, { once: true });
610631
}
611632
});
612-
}, [cacheScopeKey, entry, launchArguments, argumentsSignature, manualLaunch, nonce, started, geometry.ref, clearDocument, releaseLaunch, releaseLaunches, updateState, updateRefresh, requestRefresh]);
633+
}, [cacheScopeKey, entry, launchArguments, argumentsSignature, manualLaunch, nonce, started, geometry.ref, clearDocument, releaseLaunch, releaseLaunches, updateState, updateRefresh, requestRefresh, wakeLaunchWaiters]);
613634

614635
useEffect(() => {
615636
if (manualLaunch) return;

‎apps/app/tests/mcp-app-frame.test.ts‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,16 @@ import type { McpAppSandboxViewProps } from "../src/components/chat/mcp-app-fram
1919
import * as mcpAppOrigin from "../src/components/chat/mcp-app-origin"
2020
import { markCloudCredentialRefreshed } from "../src/react-app/domains/connections/cloud-credential-revision"
2121

22-
GlobalRegistrator.register({ url: "https://web.example/" })
22+
// happy-dom 21 loads no iframe page by default, so frames would have no window to talk to.
23+
GlobalRegistrator.register({ url: "https://web.example/", settings: { enableIframePageLoading: true } })
2324
afterAll(() => GlobalRegistrator.unregister())
2425
const { MessageListProvider } = await import("../src/components/chat/message-list-provider")
2526
const { WorkspaceProvider } = await import("../src/react-app/shell/workspace-provider")
2627
const { useUiStateStore } = await import("../src/react-app/shell/ui-state-store")
2728
const { usePanelTabStore } = await import("../src/react-app/domains/session/panel/panel-tab-store")
2829
const { useSessionActivityStore } = await import("../src/react-app/domains/session/status/session-activity-store")
2930
const { McpAppTile } = await import("../src/react-app/domains/dashboard/mcp-app-tile")
30-
const { removeDashboardTileCache } = await import("../src/react-app/domains/dashboard/dashboard-tile-cache")
31+
const { removeDashboardTileCache, writeDashboardTileCache } = await import("../src/react-app/domains/dashboard/dashboard-tile-cache")
3132
const { flushDashboardTileCacheStorage } = await import("../src/app/lib/dashboard-cache-storage")
3233
const {
3334
buildMcpAppCsp,
@@ -542,6 +543,60 @@ describe("MCP App retry ownership", () => {
542543
}
543544
expect([...released].sort()).toEqual(["render-0-1", "render-0-2", "render-1-1"])
544545
})
546+
547+
test("a saved dashboard view relaunches when its lease goes stale and keeps the App on screen", async () => {
548+
const host = await startupFixture()
549+
const scope = "stale-lease"
550+
const launches: string[] = []
551+
const calls: Array<Parameters<OpenworkServerClient["callMcpAppTool"]>[1]> = []
552+
const resolveSpy = spyOn(host.client, "resolveMcpApp").mockImplementation(async () => {
553+
launches.push(`lease-${launches.length + 1}`)
554+
return { app: fixture({ toolName: "render-0", launchId: launches.at(-1) }) }
555+
})
556+
const releaseSpy = spyOn(host.client, "releaseMcpApp").mockResolvedValue({ released: true })
557+
const callSpy = spyOn(host.client, "callMcpAppTool").mockImplementation(async (_workspace, request) => {
558+
calls.push(request)
559+
// The host replaced the first lease, as a credential renewal or server restart does.
560+
if (request.launchId === "lease-1" && request.name === "read_detail") {
561+
throw new OpenworkServerError(422, "stale_launch_context", "This App launch has expired, closed, or changed.")
562+
}
563+
return { content: [] }
564+
})
565+
writeDashboardTileCache(scope, "stale-0", {
566+
argumentsSignature: "{}", cachedAt: Date.now(), workspaceId: "fixture",
567+
app: fixture({ toolName: "render-0", launchId: undefined }), result: { content: [] },
568+
})
569+
const actionContext = { requestId: 1, signal: new AbortController().signal,
570+
sendNotification: async () => {}, sendRequest: async () => { throw new Error("Unexpected request") } }
571+
try {
572+
await host.renderElement(createElement(WorkspaceProvider, {
573+
client: null, openworkServerClient: host.client, workspaceId: "fixture", selectedWorkspaceRoot: "/fixture",
574+
}, createElement(McpAppTile, {
575+
entry: { kind: "mcp", id: "stale-0", title: "Stale 0", serverName: "fixture", toolName: "render-0",
576+
projectedToolName: "render-0", resourceUri: fixture().resourceUri, autoLaunch: true },
577+
cacheScopeKey: scope,
578+
})))
579+
await host.notify(0, "ui/notifications/sandbox-proxy-ready")
580+
await act(async () => { host.bridges[0].oninitialized?.() })
581+
expect(launches).toEqual(["lease-1"])
582+
const answer = host.bridges[0].oncalltool?.({ name: "read_detail" }, actionContext)
583+
// The stale call asks the tile to refresh; let React run that launch.
584+
await act(async () => { await new Promise(resolve => setImmediate(resolve)) })
585+
await expect(answer).resolves.toEqual({ content: [] })
586+
await act(async () => {})
587+
expect(launches).toEqual(["lease-1", "lease-2"])
588+
expect(calls.filter(call => call.name === "read_detail").map(call => call.launchId)).toEqual(["lease-1", "lease-2"])
589+
expect(releaseSpy.mock.calls.map(([, id]) => id)).toEqual(["lease-1"])
590+
expect(host.bridges).toHaveLength(1)
591+
expect(host.failures).toEqual([])
592+
} finally {
593+
removeDashboardTileCache(scope, "stale-0")
594+
flushDashboardTileCacheStorage()
595+
try { await host.dispose() } finally {
596+
for (const spy of [resolveSpy, releaseSpy, callSpy]) spy.mockRestore()
597+
}
598+
}
599+
})
545600
})
546601

547602
describe("MCP App data continuity", () => {

0 commit comments

Comments
 (0)