Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .agents/skills/verify-screens/features/app-bridge.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ A stand-in host relays MCP Apps messages to the real adapter while the canvas ru

- `bridge-claude`: the Claude adapter opens the same interactive library and Screen, relays edits and events, and returns a working browser fallback.

- `bridge-no-relay`: a host that shows the view but delivers none of its tool calls, as the Claude desktop Code tab does for servers that Claude Code starts. The view shows the local URL from the tool result, even when the host sends only its text, and "Open in browser" asks the host to open that URL, which opens the same Screen in the browser canvas.

## How to get to it (user POV)

- Open the canvas in an MCP Apps host, open a Screen and work with an agent.
Expand All @@ -24,6 +26,11 @@ probe bridge-claude
expect last.resource=true last.libraryInput=true last.annotations=true last.browserTabIgnored=true last.live=true last.teardown=true last.localRequests=0
```

```screens id=bridge-no-relay
probe bridge-no-relay
expect last.fallback=true last.openLink=true last.browserOpened=true last.localRequests=0
```

## Gotchas

- The CLI uses a stand-in host for automated relay checks. In Codex, open Screens from the sidebar or as a chat tab.
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,13 @@ claude plugin install screens@screens-local
node release/claude-desktop.mjs
```

Restart Claude Desktop after registration, then ask Claude Code to open Screens. In the desktop Code tab, `open_screen` opens the interactive canvas. It opens the library by default or a specific Screen when given its ID.
Restart Claude Desktop after registration. In a Claude Desktop chat, `open_screen` opens the interactive canvas. It opens the library by default or a specific Screen when given its ID.

Claude Desktop registers the interactive `open_screen` tool. Its connection forwards actions from the widget to the local service. The Claude Code marketplace plugin supplies agent tools and `open_screen_in_browser` for terminal sessions or browser fallback. The local release installer (`--install`) also updates the Desktop registration.
Claude Desktop registers the interactive `open_screen` tool. Its connection forwards actions from the widget to the local service. Code tab sessions do not receive this registration. The Claude Code marketplace plugin supplies agent tools and `open_screen_in_browser` for the Code tab, terminal sessions or browser fallback. The local release installer (`--install`) also updates the Desktop registration.

In either host, use the returned local URL when a browser is needed. Pass `openBrowser: true` to launch the system browser explicitly.
The Code tab can show a widget from a server that Claude Code starts, but it does not deliver the widget's actions to that server. In that case the widget shows the local URL and an Open in browser button.

In Claude Code, use the returned local URL when a browser is needed. Pass `openBrowser: true` to launch the system browser explicitly. In Codex, the agent works in the Screens view that you open from the sidebar or a chat tab.

Try this prompt:

Expand Down
1 change: 1 addition & 0 deletions packages/canvas/src/shell/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -431,3 +431,4 @@ body { background: var(--window); color: var(--text); font: var(--text-md) / var
@media (max-width: 700px) {
.screens-comment-popover { left: auto; right: var(--chrome-inset); top: 52px; max-height: calc(100dvh - 52px - var(--shell-height) - 2 * var(--chrome-inset)); }
}
.screens-relay-url { pointer-events: auto; user-select: text; -webkit-user-select: text; overflow-wrap: anywhere; }
27 changes: 25 additions & 2 deletions packages/canvas/src/shell/main.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { connectLocalService, connectService } from "@screens/client";
import { connectAppTransport } from "../../../client/src/bridge.ts";
import { AppRelayError, connectAppTransport } from "../../../client/src/bridge.ts";
import { runBench } from "./bench.ts";
import { installTestHook } from "./testHook.ts";
import { LibraryApp } from "./library/LibraryApp.tsx";
Expand All @@ -26,7 +27,14 @@ async function boot() {
const observer = configureOpening();
const root = createRoot(document.getElementById("root")!);
observer?.mark("transport.connect.start");
const svc = window.__SCREENS_APP__ ? connectService(await connectAppTransport()) : await connectLocalService({ origin: location.origin, token: window.__SCREENS__.token, instanceId: window.__SCREENS__.instanceId, role: "canvas", sessionId: sessionId() });
let svc;
try {
svc = window.__SCREENS_APP__ ? connectService(await connectAppTransport()) : await connectLocalService({ origin: location.origin, token: window.__SCREENS__.token, instanceId: window.__SCREENS__.instanceId, role: "canvas", sessionId: sessionId() });
} catch (e) {
if (!(e instanceof AppRelayError)) throw e;
root.render(<RelayFallback relay={e} />);
return;
}
observer?.mark("transport.connected");
if (window.__SCREENS_APP__) configureAppContent(svc);
if (observer && !window.__SCREENS_APP__) {
Expand All @@ -45,4 +53,19 @@ async function boot() {
observer?.mount((path) => navigate(path));
}

/** The host shows this view but cannot relay its calls: offer the same canvas in the browser. */
function RelayFallback({ relay }: { relay: AppRelayError }) {
const [url, setUrl] = useState<string | null | undefined>(undefined);
const [failed, setFailed] = useState(false);
useEffect(() => { void relay.browserUrl().then(setUrl); }, [relay]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update the fallback when a delayed tool result arrives

If the host delivers ui/notifications/tool-result more than three seconds after the relay fails, browserUrl() resolves to null and RelayFallback permanently renders “Ask the agent for the local Screens URL” without an Open in browser button. The message listener subsequently records the correct URL, but the component calls browserUrl() only once and never receives that update. This can occur when the view initializes before open_screen completes, particularly with openBrowser: true, whose launcher can wait up to five seconds. Keep the fallback subscribed to URL notifications after the initial timeout so a late result can populate the address and button.

Useful? React with 👍 / 👎.

if (url === undefined) return null;
return <div className="screens-center"><div className="empty-state" data-relay-fallback="">
<h2>Screens can’t connect in this view</h2>
<p>This host shows Screens but doesn’t pass its changes to the local service. Open the canvas in your browser to keep working.</p>
{url && <button type="button" className="button primary" onClick={() => { relay.openLink(url).catch(() => setFailed(true)); }}>Open in browser</button>}
{url && failed && <p>The host didn’t open the link. Copy this address into your browser:</p>}
<p className="screens-relay-url">{url ?? "Ask the agent for the local Screens URL."}</p>
</div></div>;
}

boot().catch((e) => { document.body.textContent = `Screens could not start: ${e instanceof Error ? e.message : e}.${window.__SCREENS_APP__ ? " Open the local browser URL returned by open_screen to continue." : ""}`; });
64 changes: 62 additions & 2 deletions packages/cli/src/bridge-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,15 @@ export async function verifyBridge(browser: Browser, home: string, screenId: str
if (!uri || !Array.isArray(entries) || !["global", "thread"].every((type) => entries.some((entry) => entry.type === type))) throw new Error("open_screen must expose global and thread MCP App entrypoints");
const empty = await tool("open_screen", {});
if ((empty.structuredContent as { screenId?: unknown } | undefined)?.screenId !== null) throw new Error("open_screen with empty arguments must open the library");
// Codex agents work in the sidebar or thread-tab view, so its open_screen never points them at a browser.
if (adapterHost === "codex" && ((empty.structuredContent as Record<string, unknown> | undefined)?.url !== undefined || "openBrowser" in ((opener as { inputSchema?: { properties?: object } }).inputSchema?.properties ?? {})))
throw new Error("Codex open_screen must not offer a browser URL or launch");
const resource = (await adapter.readResource({ uri })).contents[0] as { text?: string; mimeType?: string; _meta?: Record<string, any> };
if (resource?.mimeType !== "text/html;profile=mcp-app" || !resource.text || !resource._meta?.ui?.csp) throw new Error("the canvas resource is not an MCP App page with a CSP");
const app = resource.text;
const opened = (await tool("open_screen", { screenId })).structuredContent as { url: string };
await tool("open_screen", { screenId });
// Codex's open_screen returns no browser URL: the browser-tab checks below use the service's canvas origin.
const opened = { url: `${origins[0]}/s/${screenId}` };
await page.exposeBinding("__appTool", async (_source, name: string, args: Record<string, unknown>) => {
if (name === "_screens_call" && args.kind === "chunk") uploadChunks++;
if (!["_screens_call", "_screens_events", "_screens_content"].includes(name)) throw new Error("unexpected app tool");
Expand Down Expand Up @@ -130,7 +135,7 @@ try{let result;if(m.method==='ui/initialize')result={protocolVersion:'2026-01-26
}, image.id, { timeout: 10000 });
// A browser tab on another Screen of this library does not redirect the embedded view lookup.
const other = (await tool("create_screen", { title: "Browser tab" })).structuredContent as { id: string };
const fallback = (await tool("open_screen", { screenId: other.id })).structuredContent as { url: string };
const fallback = { url: `${origins[0]}/s/${other.id}` };
const tab = await context.newPage();
await tab.goto(fallback.url);
for (let i = 0; i < 100 && !(await service.views()).some((v) => v.screenId === other.id && !v.app); i++) await new Promise((r) => setTimeout(r, 100));
Expand Down Expand Up @@ -223,3 +228,58 @@ try{let result;if(m.method==='ui/initialize')result={protocolVersion:'2026-01-26
throw new Error(`${(e as Error).message}; images: ${JSON.stringify(images)}; page errors: ${errors.join(" | ")}`);
} finally { await context.close(); await adapter.close(); }
}

/** A host that shows the view but delivers none of its tool calls, as the Claude desktop Code tab does for servers that
* Claude Code starts. The view must offer the local browser canvas from the tool result, and opening it must work. */
export async function verifyRelayFallback(browser: Browser, home: string, screenId: string, service: Service, origins: readonly string[]): Promise<Record<string, unknown>> {
const adapter = new Client({ name: "screens-no-relay-host", version: "1" });
await adapter.connect(new StdioClientTransport({ command: process.execPath, args: [path.resolve("packages/mcp/src/main.ts"), "--host", "claude"], env: { ...process.env, SCREENS_HOME: home } as Record<string, string>, stderr: "ignore" }));
const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, reducedMotion: "reduce" });
const page = await context.newPage();
const requests: string[] = [];
page.on("request", (req) => { if (origins.some((o) => req.url().startsWith(o)) || /^https?:\/\/(?:127\.0\.0\.1|localhost)(?::|\/)/i.test(req.url())) requests.push(req.url()); });
try {
const opener = (await adapter.listTools()).tools.find((t) => t.name === "open_screen") as { _meta?: Record<string, any> } | undefined;
const uri = opener?._meta?.ui?.resourceUri as string | undefined;
if (!uri) throw new Error("open_screen does not name an MCP App resource");
const opened = await adapter.callTool({ name: "open_screen", arguments: { screenId } });
const url = (opened.structuredContent as { url?: string } | undefined)?.url;
if (!url) throw new Error("open_screen returned no local URL");
const app = ((await adapter.readResource({ uri })).contents[0] as { text?: string }).text;
if (!app) throw new Error("the canvas resource has no page");
// Some hosts drop structuredContent from the tool result, so this one sends only the text content.
const toolResult = { content: opened.content };
const host = `<!doctype html><html><head><style>html,body,iframe{margin:0;width:100%;height:100%;border:0}</style></head><body><iframe id="app"></iframe><script>
window.__calls=0;window.__links=[];const app=document.getElementById('app');app.srcdoc=${JSON.stringify(app).replace(/</g, "\\u003c")};
addEventListener('message',(e)=>{if(e.source!==app.contentWindow||!e.data||e.data.jsonrpc!=='2.0')return;const m=e.data;const reply=(r)=>e.source.postMessage({jsonrpc:'2.0',id:m.id,...r},'*');
if(m.method==='ui/notifications/initialized'){e.source.postMessage({jsonrpc:'2.0',method:'ui/notifications/tool-input',params:{arguments:{screenId:${JSON.stringify(screenId)}}}},'*');e.source.postMessage({jsonrpc:'2.0',method:'ui/notifications/tool-result',params:${JSON.stringify(toolResult).replace(/</g, "\\u003c")}},'*');return;}
if(m.id===undefined||!m.method)return;
if(m.method==='ui/initialize')reply({result:{protocolVersion:'2026-01-26',hostCapabilities:{openLinks:{}},hostInfo:{name:'screens-no-relay',version:'1'}}});
else if(m.method==='tools/call'){window.__calls++;reply({error:{code:-32603,message:'MCP error -32603: IPC not available for MCP tool call'}});}
else if(m.method==='ui/open-link'){window.__links.push(m.params.url);reply({result:{}});}
else reply({error:{code:-32601,message:'Method not found'}});});
</script></body></html>`;
await page.route("https://screens.test/**", (route) => route.fulfill({ status: 200, contentType: "text/html", body: host }));
await page.goto("https://screens.test/");
await page.waitForFunction(() => document.querySelector("iframe")?.contentWindow?.document.querySelector("#root"));
const appFrame = page.frames().find((f) => f !== page.mainFrame())!;
await appFrame.locator("[data-relay-fallback]").waitFor({ timeout: 15000 });
const shownUrl = await appFrame.locator(".screens-relay-url").textContent();
if (shownUrl !== url) throw new Error(`the fallback shows ${shownUrl}, not the URL open_screen returned`);
await appFrame.getByRole("button", { name: "Open in browser", exact: true }).click();
await page.waitForFunction(() => (window as any).__links.length > 0, null, { timeout: 5000 });
const links = await page.evaluate(() => (window as any).__links as string[]);
if (links.length !== 1 || links[0] !== url) throw new Error(`the view asked the host to open ${JSON.stringify(links)}, not ${url}`);
const calls = await page.evaluate(() => (window as any).__calls as number);
if (requests.length) throw new Error(`the embedded view requested local origins: ${requests.join(", ")}`);
// The link the view hands the host opens the same Screen in the browser canvas.
const tab = await context.newPage();
await tab.goto(links[0]!);
for (let i = 0; i < 100 && !(await service.views()).some((v) => v.screenId === screenId && !v.app); i++) await new Promise((r) => setTimeout(r, 100));
if (!(await service.views()).some((v) => v.screenId === screenId && !v.app)) throw new Error("the browser canvas at the fallback URL never opened the Screen");
return { fallback: true, urlFromText: true, openLink: true, browserOpened: true, relayCalls: calls, localRequests: requests.length };
} catch (e) {
await page.screenshot({ path: path.join(home, "..", "evidence", "relay-fallback.png") }).catch(() => {});
throw e;
} finally { await context.close(); await adapter.close(); }
}
7 changes: 6 additions & 1 deletion packages/cli/src/driver.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { verifyFrameMessages } from "./frame-messages.ts";
import { verifyBridge } from "./bridge-host.ts";
import { verifyBridge, verifyRelayFallback } from "./bridge-host.ts";
// The one executor. A session's daemon hosts exactly one Driver, which owns the dev service process, the MCP
// adapter, an observer connection, the browser and its views, handles, marks, the journal and evidence.
// Steps run one at a time. Mutations go through MCP or real browser input, never storage.
Expand Down Expand Up @@ -452,6 +452,11 @@ export class Driver {
const data = await verifyBridge(this.browser, this.spec.home, this.screen, this.observer, this.devSecret, [this.reg.canvasOrigin, this.reg.frameOrigin], false, s.suite === "bridge-claude" ? "claude" : "codex");
return { text: `probe ${s.suite} ${JSON.stringify(data)}`, data };
}
if (s.suite === "bridge-no-relay") {
if (!this.screen) throw new StepError("open a Screen before the relay fallback probe");
const data = await verifyRelayFallback(this.browser, this.spec.home, this.screen, this.observer, [this.reg.canvasOrigin, this.reg.frameOrigin]);
return { text: `probe ${s.suite} ${JSON.stringify(data)}`, data };
}
if (s.suite === "thumbnails") {
const doc = this.doc(); if (!doc) throw new StepError("open a Screen before requesting thumbnails");
const hashes = [...new Set(Object.values(doc.items).map((i) => i.kind === "reference-image" ? i.assetHash : i.posterHash).filter((h): h is string => !!h))];
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export type Step =
| { readonly kind: "service"; readonly action: "restart" | "reset" | "kill" | "terminate" | "log"; readonly lines: number }
/** Kill and respawn the MCP adapter, as when an agent host restarts it. */
| { readonly kind: "adapter"; readonly action: "restart" | "open" | "close"; readonly name: string }
| { readonly kind: "probe"; readonly suite: "security" | "discovery" | "identity" | "idle" | "port" | "results" | "thumbnails" | "bridge" | "bridge-claude" | "frame-messages" | "history-replay" | "history-invariants"; readonly tool?: string }
| { readonly kind: "probe"; readonly suite: "security" | "discovery" | "identity" | "idle" | "port" | "results" | "thumbnails" | "bridge" | "bridge-claude" | "bridge-no-relay" | "frame-messages" | "history-replay" | "history-invariants"; readonly tool?: string }
| { readonly kind: "doctor" }
| { readonly kind: "tools" };

Expand Down Expand Up @@ -272,7 +272,7 @@ export const VERBS: Readonly<Record<string, Verb>> = {
service: { group: "session", summary: "service restart|reset|kill|terminate|log [N] (reset: an empty library)", parse: (c) => ({ kind: "service", action: one(c.words[0], ["restart", "reset", "kill", "terminate", "log"], "service"), lines: c.words[1] ? num(c.words[1], "lines") : 20 }) },
agent: { group: "session", summary: "agent restart | open NAME | close NAME", parse: (c) => { const action = one(c.words[0], ["restart", "open", "close"], "agent"); return { kind: "adapter", action, name: c.words[1] ?? "main" }; } },
fault: { group: "session", summary: "fault delay-commit MS [count=N] | fail-commit storage|conflict [count=N] | drop-result [count=N] | crash before-write|after-content-flush|after-temp-write|after-temp-flush|after-rename|after-write | disk-full content|poster|document | corrupt-document @S [json|schema|threads] | disconnect | no-browser [count=N] | drop-upload after=N [count=N] | fail-upload after=N | corrupt-upload [count=N] | expire-uploads | expire-presence | clear", parse: (c) => ({ kind: "fault", fault: parseFault(c) }) },
probe: { group: "session", summary: "probe security|discovery|identity|idle|port|results|thumbnails|bridge|bridge-claude|frame-messages|history-replay|history-invariants [tool=TOOL]", parse: (c) => { return { kind: "probe", suite: one(c.words[0], ["security", "discovery", "identity", "idle", "port", "results", "thumbnails", "bridge", "bridge-claude", "frame-messages", "history-replay", "history-invariants"], "probe"), tool: c.kv.get("tool") }; } },
probe: { group: "session", summary: "probe security|discovery|identity|idle|port|results|thumbnails|bridge|bridge-claude|bridge-no-relay|frame-messages|history-replay|history-invariants [tool=TOOL]", parse: (c) => { return { kind: "probe", suite: one(c.words[0], ["security", "discovery", "identity", "idle", "port", "results", "thumbnails", "bridge", "bridge-claude", "bridge-no-relay", "frame-messages", "history-replay", "history-invariants"], "probe"), tool: c.kv.get("tool") }; } },
doctor: { group: "session", summary: "doctor", parse: () => ({ kind: "doctor" }) },
tools: { group: "session", summary: "tools (MCP tools and their arguments; * marks required)", parse: () => ({ kind: "tools" }) },
shot: { group: "evidence", summary: "shot [T] [as=NAME]", parse: (c) => ({ kind: "shot", target: c.words[0] ? parseTarget(c.words[0]) : null, name: c.bind, view: c.view }) },
Expand Down
Loading