Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
fix(mcp): initialize page previews and verify embedded app readiness
Rahmane46c417b74db
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 44575e86..0acf1992 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -123,7 +123,7 @@ MSO exposes exactly two user-visible MCP App classes instead:- `render_mso_block` binds `ui://mso/block-v2.html` for compact validation, action buttons, andCRUD input-output. A button returns a user-approved follow-up message; it does not execute amutation inside the widget, so ordinary scope, approval, audit, and workflow rules still apply.-- `render_mso_page` binds `ui://mso/page-v2.html` for native `/`, `/monitor`, `/project`, `/diff`,+- `render_mso_page` binds `ui://mso/page-v3.html` for native `/`, `/monitor`, `/project`, `/diff`,`/browser`, and `/apps/<reviewed-id>` views. Native Page views call the same bounded MSO tools.`workflow_start` is orchestration-only and headless: it still owns workflow isolation, skill/recipediff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 4dd03a72..8cc751a3 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,12 @@+## 2026-09-05 — MCP Page preview lifecycle++Fixed a missing MCP Apps host initialization handshake, wrapped tool-result handling and+repeated iframe remounts on unchanged globals. Page v3 now waits for an origin/source-checked+app readiness message, displays bounded retry/direct-production actions, and preserves the+cached v2 URI as a read-only alias. The exact reviewed iframe registry and Block-only approval+contract remain unchanged. Targeted contracts and a desktop/mobile browser harness validate+both standard MCP and legacy ChatGPT host paths. Toolset: `2026.09.05.1`.+# mso — Progress Log- **Rahmanef-aligned MCP widget palette / Block + Page v2 (2026-09-04):** MCP server `1.10.0` / toolset `2026.09.04.7` moves the two canonical ChatGPT resources to `ui://mso/block-v2.html` and `ui://mso/page-v2.html` so hosts do not reuse the old purple CSS cache key. Block and Page now share one visual-token source aligned with `rahmanef.com`: light `#f4f4f7` / `#1c1c1f`, dark `#1b1b20` / `#f2f2f5`, accent `#1f6df0`, Plus Jakarta Sans display copy, Inter body copy, fine separators, and editorial foreground/background primary-action inversion. ChatGPT theme changes propagate through `window.openai.theme` with a color-scheme fallback. Block/Page v1 and the earlier workflow/surface URIs remain readable but unlisted compatibility aliases; the headless workflow and two-surface/security contracts are unchanged.- **Headless workflows + two-surface MCP UI contract (2026-09-04):** MCP server `1.10.0` / toolset `2026.09.04.6` removes the automatic UI binding from `workflow_start`: orchestration, collision checks, tracing, evidence, and learning continue in the background without consuming the answer with a progress card. ChatGPT now has exactly two canonical MCP App resources: `ui://mso/block-v1.html` through `render_mso_block` for compact validation/action/CRUD input-output, and `ui://mso/page-v1.html` through `render_mso_page` for native operator views plus reviewed development/preview/production embeds. Block buttons send a user-approved follow-up and never execute mutations inside the widget, preserving normal scope, approval, audit, and workflow boundaries. The prior workflow/surface URIs remain non-advertised read aliases, while `workflow_status` and `render_mso_surface` remain app-only compatibility shims for cached clients. The ChatGPT transport profile is 66 tools: 64 model-visible actions (35 read / 17 write / 12 exec) plus two app-only shims; the full catalog is 90. Only Block and Page advertise a resource URI.diff --git a/docs/TESTING-HANDOFF.md b/docs/TESTING-HANDOFF.mdindex ea5c1309..8cc3d637 100644--- a/docs/TESTING-HANDOFF.md+++ b/docs/TESTING-HANDOFF.md@@ -5,11 +5,11 @@ Update this file at the end of every manual or automated test session. Keep it f## Current status-The current release target is **MSO CLI 1.12.1**, MCP server `1.10.0`, toolset `2026.09.04.7`; use `mso --version` plus `/api/health` for the exact Git build because documentation-only release commits also advance that identity. The v1.10/v1.11 findings and the v1.12 sectioned-terminal/recoverable-error work below are resolved and retained as historical test evidence. Do not re-open a resolved finding from prose alone: reproduce it against the current build first. There is no known 1.12 release blocker in this handoff.+The current release target is **MSO CLI 1.12.1**, MCP server `1.10.0`, toolset `2026.09.05.1`; use `mso --version` plus `/api/health` for the exact Git build because documentation-only release commits also advance that identity. The v1.10/v1.11 findings and the v1.12 sectioned-terminal/recoverable-error work below are resolved and retained as historical test evidence. Do not re-open a resolved finding from prose alone: reproduce it against the current build first. There is no known 1.12 release blocker in this handoff.Current verified behavior:- **2026-09-04 Cognitive Runtime public-claim audit:** source/main/origin + loopback/public production were revalidated on the latest concurrent baseline. Fresh reruns pass `bench:cognitive`, `bench:memory`, P9 200-correction calibration, P10 lifecycle, and P10 retrieval calibration. Current deterministic evidence: 100% required-tool recall, 96.6% active-schema reduction, memory 8/8, P9 6/6, P10 lifecycle 8/8, lexical/local-semantic 4/6 vs 3/6, graph fixture 3/3. Canonical raw comparison artifacts were re-hashed: P6 `e0b5e1e30a9f1e5b34624e42d4bb5195792e50129b74de7d4006906a99716ba5`, P7 two-run `a0c12961d142420f6ac334ff021bde7ab82faa89f9294107d3bd46823606a530`, P8 three-run `f70e2f5e8132f0808976ed69e2cb6769d2cec861d58612a8cca2ef5d80a7d838`, P8 cache `b4a2b1be5dc6edfb2ce8282eae64e3a4fc206cd043ecb825a1eae6a617c9f871`. The canonical P7 file is `mso-p7-repeat-full-2x9.json`; the similarly named `mso-p7-repeat-full-2runs.json` is a different, non-canonical run. Recomputed P7+P8 evidence is 5/5 perfect for both MSO and Hermes with 74.7% fewer normalized tokens/attempt, 12.8% lower mean average latency, and 34.1% lower mean per-run p50 for MSO on that exact matched nine-scenario corpus. P4/P5 exact numeric tables are historical-only because their exact raw artifacts were not independently revalidated in this audit. Cost/cache/OpenClaw remain unranked. Tool Forge source/non-Docker tests pass, but the local Forge Docker image was absent, so three Docker-only tests were correctly skipped and executable evaluation fails closed until explicitly provisioned.-- Fresh 3 current MCP contract: server `1.10.0` / toolset `2026.09.04.7`; ChatGPT receives **66 transport tools = 64 model-visible actions (35 read / 17 write / 12 exec) + app-only `workflow_status` and `render_mso_surface` compatibility shims**, while the full transport catalog is 90 tools. Every ChatGPT action advertises `outputSchema`, and the dedicated MCP Apps origin remains `https://mso-ui.rahmanef.com`. Exactly two canonical resources are published: `ui://mso/block-v2.html` for validation/action/CRUD input-output and `ui://mso/page-v2.html` for native views plus reviewed dev/preview/prod embeds. `workflow_start` is headless and has no UI template. Only `render_mso_block` and `render_mso_page` bind resources. Block/Page v1 and previous workflow/surface URIs remain readable but unlisted; the two app-only actions keep cached clients functional. Page framing remains exact-origin under `https://game.rahmanef.com/embed`, while Block has no frame domains and cannot execute a mutation directly.+- Fresh 3 current MCP contract: server `1.10.0` / toolset `2026.09.05.1`; ChatGPT receives **66 transport tools = 64 model-visible actions (35 read / 17 write / 12 exec) + app-only `workflow_status` and `render_mso_surface` compatibility shims**, while the full transport catalog is 90 tools. Every ChatGPT action advertises `outputSchema`, and the dedicated MCP Apps origin remains `https://mso-ui.rahmanef.com`. Exactly two canonical resources are published: `ui://mso/block-v2.html` for validation/action/CRUD input-output and `ui://mso/page-v3.html` for native views plus reviewed dev/preview/prod embeds. `workflow_start` is headless and has no UI template. Only `render_mso_block` and `render_mso_page` bind resources. Block/Page v1 and previous workflow/surface URIs remain readable but unlisted; the two app-only actions keep cached clients functional. Page framing remains exact-origin under `https://game.rahmanef.com/embed`, while Block has no frame domains and cannot execute a mutation directly.- MCP App acceptance: starting a workflow must produce structured workflow identity without opening an App. A Block must render bounded validation/CRUD data and return a user-approved follow-up when its action is pressed; it must not call a mutation itself. A Page must render native `/monitor`/`/project`/`/diff` views through `tools/call` and frame Play Together only from `https://game.rahmanef.com/embed`. The old Block/Page v1 and workflow/surface URIs must resolve only as non-advertised compatibility aliases. Block v2 and Page v2 are cache-busting visual-resource changes, so ChatGPT must re-scan Fresh 3 after deployment.- Alfa Cockpit acceptance: Assistant → Chat shows a compact project/model/activity bar; Cockpit opens as a desktop panel and mobile drawer; project search can select a project outside the first bounded page; selected project metadata reaches the next Alfa system prompt but raw `KNOWLEDGE.md`/repo-memory bodies do not; private typed-memory keys/values render as `Private memory`; Host Skills lazy-load from `/api/skills`; model switch stays within the configured provider; Activity & Runs shows local Alfa tool state alongside MCP workflow activity without treating the browser run as MCP `workflow_finish`.- Alfa Automation acceptance: a saved recipe's Run action switches to its configured persona and submits the ordered recipe through normal Alfa execution. Read steps may execute directly; write/exec steps must still park on the existing approval card. Playbook starter prompts appear as bounded empty-chat quick actions.diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.mdindex 3bdfbd99..9931409e 100644--- a/docs/generated/MCP-CATALOG.md+++ b/docs/generated/MCP-CATALOG.md@@ -4,12 +4,12 @@## Full MSO catalog-<!-- mcp-toolset: server=1.10.0 version=2026.09.04.7 tools=88 read=44 write=25 exec=19 -->+<!-- mcp-toolset: server=1.10.0 version=2026.09.05.1 tools=88 read=44 write=25 exec=19 -->| Fact | Current source value ||---|---:|| MCP server | `1.10.0` |-| Toolset | `2026.09.04.7` |+| Toolset | `2026.09.05.1` || Toolset changed at | `2026-09-04T10:25:00Z` || Transport tools | **90** || Model/operator tools | **88** |@@ -122,7 +122,7 @@## ChatGPT static profile-<!-- mcp-chatgpt-profile: server=1.10.0 version=2026.09.04.7 tools=64 read=35 write=17 exec=12 app-only=2 total=66 -->+<!-- mcp-chatgpt-profile: server=1.10.0 version=2026.09.05.1 tools=64 read=35 write=17 exec=12 app-only=2 total=66 -->The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_NAMES`. OAuth scope is still enforced independently; project-owned MCP tool names remain dynamic data behind the generic project bridge.diff --git a/docs/integrations/CHATGPT-UI.md b/docs/integrations/CHATGPT-UI.mdindex ca3083f3..485bd0ad 100644--- a/docs/integrations/CHATGPT-UI.md+++ b/docs/integrations/CHATGPT-UI.md@@ -9,7 +9,7 @@ The user-visible contract has exactly two canonical MCP App resources:| Surface | Entry tool | Resource | Intended use || --- | --- | --- | --- || **Block** | `render_mso_block` | `ui://mso/block-v2.html` | Compact validation, action buttons, and CRUD input-output |-| **Page** | `render_mso_page` | `ui://mso/page-v2.html` | Full native operator views and reviewed development, preview, or production app embeds |+| **Page** | `render_mso_page` | `ui://mso/page-v3.html` | Full native operator views and reviewed development, preview, or production app embeds |`workflow_start` is now headless. It remains the required orchestration bootstrap for multi-step work, including skill/recipe lookup, collision checks, workflow isolation, tracing, evidence, and learning, but it has no `_meta.ui.resourceUri` and no `openai/outputTemplate`. Starting background work therefore does not consume the answer with an unrelated workflow card.@@ -133,10 +133,31 @@ ChatGPT modelAfter changing UI resources or tool metadata:1. run targeted tests, `bun run verify`, and the official production release path;-2. verify `initialize` reports MCP server `1.10.0` and toolset `2026.09.04.7`;+2. verify `initialize` reports MCP server `1.10.0` and toolset `2026.09.05.1`;3. verify `tools/list` exposes 66 ChatGPT transport tools, keeps `workflow_start` headless, marks the two compatibility actions app-only, and binds only `render_mso_block` / `render_mso_page`;-4. verify `resources/list` contains exactly `ui://mso/block-v2.html` and `ui://mso/page-v2.html`, both with `text/html;profile=mcp-app`;+4. verify `resources/list` contains exactly `ui://mso/block-v2.html` and `ui://mso/page-v3.html`, both with `text/html;profile=mcp-app`;5. verify Block has no frame domain and Page has only reviewed exact origins;6. refresh/re-scan the ChatGPT development app so its cached action/resource snapshot is replaced.A widget already rendered in an old conversation cannot be removed retroactively. After the server deployment, a stale workflow card indicates a cached ChatGPT connector snapshot, not a new `workflow_start` binding.++## Page initialization and readiness (v3)++Page sends the MCP Apps `ui/initialize` request with `appInfo`, `appCapabilities` and+protocol version `2026-01-26`, then acknowledges with `ui/notifications/initialized`.+Host result notifications and wrapped legacy `window.openai.toolOutput` use the same validated+route interpreter. Unchanged results or host globals do not remount a running embedded app.+The cached `ui://mso/page-v2.html` URI is a read-only alias for current Page bytes.++A reviewed game sends a versioned readiness acknowledgement; Page validates its exact origin+and iframe source. An iframe load event does not prove readiness. The bounded timeout shows+Retry preview and Open production controls instead of a permanent skeleton. The production+link is user-initiated through the host, and the Page redirect allowlist contains only MSO and+the reviewed game origin. Normal host tools and headless workflows are unchanged.++Verification: `node scripts/e2e/mcp-page.mjs` exercises a pure MCP host without `window.openai`,+legacy wrapped output, readiness/source checks, timeout/retry and no duplicate iframe reloads.+For Play Together, the independent game server must allow every reviewed ancestor on `/embed`+and keep the inner cartridge at `/embed/game-frame.html`; root app framing stays restricted.++Page reports measured dimensions through `ui/notifications/size-changed`; its layout avoids viewport-relative height feedback when the host resizes the component.diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.tsindex 693953e7..e7bdb08c 100644--- a/lib/config/env-example.test.ts+++ b/lib/config/env-example.test.ts@@ -41,6 +41,7 @@ const NOT_A_KNOB: Record<string, string> = {WATCHDOG_USEC: "systemd's",// Test + tooling only, never part of a deployment.E2E_BASE_URL: "test harness",+ CHROME_PATH: "MCP Page browser contract harness executable override, not production configuration",E2E_PASSWORD: "test harness",E2E_DEVICE: "test harness",E2E_HEADED: "test harness",diff --git a/lib/mcp/surface-catalog.test.ts b/lib/mcp/surface-catalog.test.tsindex 8f700f47..7a37f4ba 100644--- a/lib/mcp/surface-catalog.test.ts+++ b/lib/mcp/surface-catalog.test.ts@@ -50,7 +50,7 @@ describe("MSO Page trusted app catalog", () => {expect(MSO_SURFACE_SCRIPT).not.toContain("innerHTML");expect(MSO_SURFACE_SCRIPT).not.toContain("insertAdjacentHTML");expect(MSO_SURFACE_SCRIPT).not.toContain("document.write");- expect(MSO_SURFACE_SCRIPT).toContain('method:"tools/call"');+ expect(MSO_SURFACE_SCRIPT).toContain('rpcRequest("tools/call"');expect(MSO_SURFACE_SCRIPT).toContain('rpcCall("render_mso_page"');expect(MSO_SURFACE_SCRIPT).not.toContain("window.openai.callTool");expect(MSO_SURFACE_SCRIPT).toContain("url.origin!==safe.origin");diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.tsindex caefbc83..c2d22e74 100644--- a/lib/mcp/toolset.ts+++ b/lib/mcp/toolset.ts@@ -4,7 +4,7 @@ import type { McpTool } from "./tool-kit";import { toolDescriptor, type McpToolProfile } from "./tool-contract";export const MCP_SERVER_VERSION = "1.10.0";-export const MCP_TOOLSET_VERSION = "2026.09.04.7";+export const MCP_TOOLSET_VERSION = "2026.09.05.1";export const MCP_TOOLSET_CHANGED_AT = "2026-09-04T10:25:00Z";export type McpToolsetInfo = {diff --git a/lib/mcp/ui-config.ts b/lib/mcp/ui-config.tsindex 9d7f5b2c..97ace731 100644--- a/lib/mcp/ui-config.ts+++ b/lib/mcp/ui-config.ts@@ -3,7 +3,7 @@ export const MSO_ORIGIN = "https://mso.rahmanef.com";// below mso.rahmanef.com, whose session cookie may be scoped to that hostname.export const MCP_UI_DOMAIN = "https://mso-ui.rahmanef.com";-export function widgetResourceMeta(description: string, options?: { frameDomains?: readonly string[]; connectDomains?: readonly string[]; resourceDomains?: readonly string[] }): Record<string, unknown> {+export function widgetResourceMeta(description: string, options?: { frameDomains?: readonly string[]; connectDomains?: readonly string[]; resourceDomains?: readonly string[]; redirectDomains?: readonly string[] }): Record<string, unknown> {const frameDomains = [...(options?.frameDomains ?? [])];const connectDomains = [...(options?.connectDomains ?? [])];const resourceDomains = [...(options?.resourceDomains ?? [])];@@ -18,6 +18,6 @@ export function widgetResourceMeta(description: string, options?: { frameDomains"openai/widgetDomain": MCP_UI_DOMAIN,// Standard CSP fields live only in `ui.csp`. OpenAI documents this legacy// key as still required for trusted `openExternal` redirect destinations.- "openai/widgetCSP": { redirect_domains: [MSO_ORIGIN] },+ "openai/widgetCSP": { redirect_domains: [MSO_ORIGIN, ...(options?.redirectDomains ?? [])] },};}diff --git a/lib/mcp/ui-page-bridge.ts b/lib/mcp/ui-page-bridge.tsnew file mode 100644index 00000000..1a138d34--- /dev/null+++ b/lib/mcp/ui-page-bridge.ts@@ -0,0 +1,61 @@+// Browser-side MCP Apps lifecycle. Source-checked postMessage remains inside the host bridge.+export const MSO_PAGE_BRIDGE_SCRIPT = String.raw`+let hostConnected=false, hostContext={}, lastOutputKey="", viewCleanup=()=>{};+let lastPageSize="";+function reportPageSize(){+ if(!hostConnected)return;const root=document.querySelector(".surface");if(!root)return;+ const rect=root.getBoundingClientRect(),style=getComputedStyle(document.body);+ const height=Math.ceil(rect.height+(parseFloat(style.paddingTop)||0)+(parseFloat(style.paddingBottom)||0));+ const width=Math.ceil(document.documentElement.clientWidth),key=width+","+height;+ if(height<1||height>1600||key===lastPageSize)return;lastPageSize=key;+ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/size-changed",params:{width,height}},"*");+}+const pageResizeObserver=typeof ResizeObserver==="function"?new ResizeObserver(()=>requestAnimationFrame(reportPageSize)):null;++function rpcRequest(method,params){+ const id=nextRpcId++;+ return new Promise((resolve,reject)=>{+ const timer=setTimeout(()=>{pending.delete(id);reject(new Error("Host request timed out"))},10000);+ pending.set(id,{resolve,reject,timer});+ window.parent.postMessage({jsonrpc:"2.0",id,method,params},"*");+ });+}+function acceptPageResult(result){+ const value=unbox(result);+ if(!value||typeof value!=="object"||!validRoute(value.route)||!["home","monitor","project","diff","browser","app"].includes(value.kind))return false;+ if(value.kind==="app"&&!safeAppResult(value.app))return false;+ const key=JSON.stringify([value.route,value.kind,value.project,value.sha,value.app?.url]);+ if(key===lastOutputKey)return true;+ lastOutputKey=key;current=value;render();return true;+}+function acceptPageInput(params){+ if(lastOutputKey)return;+ const args=params&¶ms.arguments;+ if(args&&validRoute(args.route)){routeEl.textContent=args.route;body.replaceChildren(el("div","loading","Waiting for page data…"))}+}+function onHostMessage(event){+ if(event.source!==window.parent)return;+ const msg=event.data;if(!msg||msg.jsonrpc!=="2.0")return;+ if(msg.id!==undefined&&pending.has(msg.id)){+ const request=pending.get(msg.id);pending.delete(msg.id);clearTimeout(request.timer);+ msg.error?request.reject(new Error(text(msg.error.message,"Host request failed"))):request.resolve(msg.result);return;+ }+ if(msg.method==="ui/notifications/tool-result"){if(msg.params?.isError)showError(new Error("The page tool reported an error. Retry from chat."));else if(!acceptPageResult(msg.params))showError(new Error("The host returned invalid page data."))}+ if(msg.method==="ui/notifications/tool-input")acceptPageInput(msg.params);+ if(msg.method==="ui/notifications/host-context-changed"){hostContext={...hostContext,...msg.params};applyHostGlobals()}+ if(msg.method==="ui/resource-teardown"&&msg.id!==undefined){viewCleanup();pageResizeObserver?.disconnect();window.parent.postMessage({jsonrpc:"2.0",id:msg.id,result:{}},"*")}+}+async function initializeMcpPage(){+ try{+ const result=await rpcRequest("ui/initialize",{+ protocolVersion:"2026-01-26",+ appInfo:{name:"MSO Page",version:"3.0.0"},+ appCapabilities:{availableDisplayModes:["inline","fullscreen","pip"]}+ });+ if(!result||typeof result.protocolVersion!=="string")throw new Error("Invalid host initialization response");+ hostConnected=true;hostContext=result.hostContext||{};applyHostGlobals();+ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/initialized",params:{}},"*");+ const root=document.querySelector(".surface");if(root)pageResizeObserver?.observe(root);reportPageSize();+ }catch(error){if(!lastOutputKey)showError(new Error("The chat host did not initialize the page. Reopen the preview or refresh the connector."))}+}+`;diff --git a/lib/mcp/ui-page-frame.ts b/lib/mcp/ui-page-frame.tsnew file mode 100644index 00000000..f38c2866--- /dev/null+++ b/lib/mcp/ui-page-frame.ts@@ -0,0 +1,31 @@+// A reviewed app must acknowledge readiness; iframe load alone also fires for blocked pages.+export const MSO_PAGE_FRAME_SCRIPT = String.raw`+function mountReviewedFrame(safe,stage){+ const wrap=el("div","frame-wrap"),frame=document.createElement("iframe");+ const status=el("div","frame-status"),message=el("span","","Connecting to live production…");+ status.setAttribute("role","status");status.setAttribute("aria-live","polite");+ const retry=button("Retry preview",()=>loadFrame());retry.hidden=true;+ const external=button("Open production ↗",()=>openProduction());+ status.append(message,retry,external);stage.content.append(status,wrap);+ frame.title=safe.title+" live demo";frame.setAttribute("sandbox",safe.sandbox);+ frame.referrerPolicy="no-referrer";frame.allow="fullscreen; autoplay; gamepad; accelerometer; gyroscope";+ wrap.append(frame);let timer=0,disposed=false;+ function unavailable(){if(disposed)return;wrap.dataset.state="unavailable";message.textContent="Preview did not confirm readiness. Retry or open production directly.";retry.hidden=false}+ function loadFrame(){clearTimeout(timer);wrap.dataset.state="loading";message.textContent="Connecting to live production…";retry.hidden=true;frame.src=safe.url;timer=setTimeout(unavailable,12000)}+ function ready(event){+ if(event.source!==frame.contentWindow||event.origin!==safe.origin)return;+ const data=event.data;if(!data||data.type!=="play-together:embed-ready"||data.schemaVersion!==1)return;+ clearTimeout(timer);wrap.dataset.state="ready";message.textContent="Production app ready";retry.hidden=true;+ }+ async function openProduction(){+ try{+ if(hostConnected)await rpcRequest("ui/open-link",{url:safe.origin});+ else if(window.openai&&typeof window.openai.openExternal==="function")await window.openai.openExternal({href:safe.origin});+ else throw new Error("Host external navigation is unavailable");+ }catch(_){message.textContent="Open production in your browser: "+safe.origin}+ }+ window.addEventListener("message",ready);frame.addEventListener("error",unavailable);+ viewCleanup=()=>{disposed=true;clearTimeout(timer);window.removeEventListener("message",ready);frame.removeEventListener("error",unavailable)};+ loadFrame();+}+`;diff --git a/lib/mcp/ui-page-lifecycle.test.ts b/lib/mcp/ui-page-lifecycle.test.tsnew file mode 100644index 00000000..fd757c3e--- /dev/null+++ b/lib/mcp/ui-page-lifecycle.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from "vitest";+import { LEGACY_PAGE_V2_URI, MSO_PAGE_URI, listUiResources, readUiResource } from "./ui-resources";++describe("MCP Page lifecycle and cached resource migration", () => {+ it("serves current bytes to cached v2 clients without advertising a third UI", () => {+ const page = readUiResource(MSO_PAGE_URI);+ expect(readUiResource(LEGACY_PAGE_V2_URI)).toMatchObject({ uri: LEGACY_PAGE_V2_URI, text: page?.text });+ expect(listUiResources()).toHaveLength(2);+ expect(listUiResources().some((resource) => resource.uri === LEGACY_PAGE_V2_URI)).toBe(false);+ });+ it("includes the Apps handshake and readiness contract in valid self-contained JavaScript", () => {+ const html = readUiResource(MSO_PAGE_URI)?.text ?? "";+ const script = html.match(/<script>([\s\S]*)<\/script>/)?.[1];+ expect(script).toBeTruthy();+ expect(() => new Function(script ?? "")).not.toThrow();+ for (const marker of [+ 'rpcRequest("ui/initialize"',+ 'appInfo:{name:"MSO Page",version:"3.0.0"}',+ 'method:"ui/notifications/initialized"',+ 'event.source!==window.parent',+ 'event.source!==frame.contentWindow||event.origin!==safe.origin',+ 'data.type!=="play-together:embed-ready"||data.schemaVersion!==1',+ 'if(key===lastOutputKey)return true',+ 'setTimeout(unavailable,12000)',+ ]) expect(script).toContain(marker);+ });+});diff --git a/lib/mcp/ui-resources.test.ts b/lib/mcp/ui-resources.test.tsindex 112d0480..a8385067 100644--- a/lib/mcp/ui-resources.test.ts+++ b/lib/mcp/ui-resources.test.ts@@ -115,7 +115,7 @@ describe("MCP Apps Block and Page contract", () => {expect(script).toBeTruthy();expect(() => new Function(script!)).not.toThrow();expect(content.text).not.toContain("fetch(");- expect(content.text).not.toContain('method:"tools/call"');+ expect(content.text).not.toContain('rpcRequest("tools/call"');expect(content.text).not.toContain("dangerouslySetInnerHTML");expect(content._meta).toMatchObject({ui: { domain: MCP_UI_DOMAIN, prefersBorder: true, csp: { connectDomains: [], resourceDomains: [] } },@@ -146,8 +146,8 @@ describe("MCP Apps Block and Page contract", () => {resourceDomains: [],frameDomains: ["https://game.rahmanef.com"],});- expect(content._meta["openai/widgetCSP"]).toEqual({ redirect_domains: [MSO_ORIGIN] });- expect(MSO_PAGE_URI).toContain("page-v2.html");+ expect(content._meta["openai/widgetCSP"]).toEqual({ redirect_domains: [MSO_ORIGIN, "https://game.rahmanef.com"] });+ expect(MSO_PAGE_URI).toContain("page-v3.html");});it("returns only redacted structured workflow state and keeps status polling out of workflow memory", async () => {@@ -235,7 +235,7 @@ describe("MCP Apps Block and Page contract", () => {expect(page).toContain('route:"/project"');expect(page).toContain('route:"/diff"');expect(page).toContain('route:"/browser"');- expect(page).toContain('method:"tools/call"');+ expect(page).toContain('rpcRequest("tools/call"');});it("rejects unknown UI resource URIs", async () => {diff --git a/lib/mcp/ui-resources.ts b/lib/mcp/ui-resources.tsindex 8ab68931..4f2ffeaf 100644--- a/lib/mcp/ui-resources.ts+++ b/lib/mcp/ui-resources.ts@@ -8,6 +8,7 @@ export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";// across the UI-contract migration. They are intentionally not advertised by// resources/list: the public product contract has exactly Block and Page.export const LEGACY_BLOCK_V1_URI = "ui://mso/block-v1.html";+export const LEGACY_PAGE_V2_URI = "ui://mso/page-v2.html";export const LEGACY_PAGE_V1_URI = "ui://mso/page-v1.html";export const LEGACY_WORKFLOW_PROGRESS_URI = "ui://mso/workflow-progress-v3.html";export const LEGACY_SURFACE_URI = "ui://mso/surface-v5.html";@@ -25,6 +26,7 @@ const RESOURCES: readonly McpUiResource[] = [MSO_BLOCK_RESOURCE, MSO_PAGE_RESOURconst LEGACY_ALIASES = new Map<string, McpUiResource>([[LEGACY_BLOCK_V1_URI, MSO_BLOCK_RESOURCE],[LEGACY_PAGE_V1_URI, MSO_PAGE_RESOURCE],+ [LEGACY_PAGE_V2_URI, MSO_PAGE_RESOURCE],[LEGACY_WORKFLOW_PROGRESS_URI, MSO_BLOCK_RESOURCE],[LEGACY_SURFACE_URI, MSO_PAGE_RESOURCE],]);diff --git a/lib/mcp/ui-surface-script.ts b/lib/mcp/ui-surface-script.tsindex 72486df4..cb9333eb 100644--- a/lib/mcp/ui-surface-script.ts+++ b/lib/mcp/ui-surface-script.ts@@ -1,3 +1,5 @@+import { MSO_PAGE_BRIDGE_SCRIPT } from "./ui-page-bridge";+import { MSO_PAGE_FRAME_SCRIPT } from "./ui-page-frame";import { SURFACE_APPS } from "./surface-catalog";import { MSO_WIDGET_THEME_SCRIPT } from "./ui-widget-tokens";@@ -27,6 +29,8 @@ const body=$("surface-body"), titleEl=$("surface-title"), routeEl=$("surface-rouconst fsBtn=$("surface-fullscreen"), pipBtn=$("surface-pip"), homeBtn=$("surface-home");let current={route:"/",kind:"home",title:"MSO",openPath:"/assistant/mcp",catalog:[]};const pending=new Map();let nextRpcId=5000;+${MSO_PAGE_BRIDGE_SCRIPT}+${MSO_PAGE_FRAME_SCRIPT}function text(value,fallback="—"){return typeof value==="string"&&value.trim()?value.trim():fallback}function clear(node){while(node.firstChild)node.removeChild(node.firstChild)}@@ -44,30 +48,27 @@ function safeAppResult(raw){}function openPath(path){setMsoTarget(validRoute(path)?path:"/assistant/mcp")}function applyHostGlobals(){- const api=window.openai||{};+ const api={...hostContext,...(window.openai||{})};applyHostTheme();const max=Number(api.maxHeight);document.documentElement.style.setProperty("--host-max-h",Number.isFinite(max)&&max>180?Math.floor(max)+"px":"680px");const safe=api.safeArea||{};for(const [key,value] of [["top",safe.top],["right",safe.right],["bottom",safe.bottom],["left",safe.left]]){const n=Number(value);document.documentElement.style.setProperty("--safe-"+key,Number.isFinite(n)?Math.max(0,n)+"px":"0px")}modeEl.textContent=text(api.displayMode,"inline");}async function displayMode(mode){- try{if(!window.openai||typeof window.openai.requestDisplayMode!=="function")throw new Error("unsupported");await window.openai.requestDisplayMode({mode})}catch(_){modeEl.textContent=mode+" unavailable"}+ try{if(hostConnected){await rpcRequest("ui/request-display-mode",{mode})}else{if(!window.openai||typeof window.openai.requestDisplayMode!=="function")throw new Error("unsupported");await window.openai.requestDisplayMode({mode})}}catch(_){modeEl.textContent=mode+" unavailable"}}function persistRoute(){try{if(window.openai&&typeof window.openai.setWidgetState==="function")window.openai.setWidgetState({modelContent:"MSO Page: "+current.route,privateContent:{route:current.route},imageIds:[]})}catch(_){}}-function rpcCall(name,args){- const id=nextRpcId++;window.parent.postMessage({jsonrpc:"2.0",id,method:"tools/call",params:{name,arguments:args}},"*");- return new Promise((resolve,reject)=>{pending.set(id,{resolve,reject});setTimeout(()=>{if(pending.has(id)){pending.delete(id);reject(new Error("tool timeout"))}},10000)})-}-function unbox(result){return result&&result.structuredContent?result.structuredContent:result}+function rpcCall(name,args){return rpcRequest("tools/call",{name,arguments:args})}+function unbox(result){if(!result||typeof result!=="object")return result;if(result.structuredContent)return result.structuredContent;if(result.result)return unbox(result.result);return result}function nav(route,extra={}){if(!validRoute(route))return;- current={route,kind:route==="/"?"home":"loading",title:"MSO",openPath:"/assistant/mcp",catalog:current.catalog,...extra};render();+ lastOutputKey="";current={route,kind:route==="/"?"home":"loading",title:"MSO",openPath:"/assistant/mcp",catalog:current.catalog,...extra};render();if(route==="/")return;- rpcCall("render_mso_page",{route,...(extra.project?{project:extra.project}:{}),...(extra.sha?{sha:extra.sha}:{})}).then(result=>{const value=unbox(result);if(value&&typeof value==="object"){current=value;render()}}).catch(showError)+ rpcCall("render_mso_page",{route,...(extra.project?{project:extra.project}:{}),...(extra.sha?{sha:extra.sha}:{})}).then(result=>{if(!acceptPageResult(result))throw new Error("Invalid page result")}).catch(showError)}-function showError(error){clear(body);const box=el("div","notice");const inner=el("div");inner.append(el("h3","","Page unavailable"),el("p","error",error&&error.message?error.message:"The requested page could not be loaded."));box.append(inner);body.append(box)}+function showError(error){viewCleanup();viewCleanup=()=>{};clear(body);const box=el("div","notice");const inner=el("div");inner.append(el("h3","","Page unavailable"),el("p","error",error&&error.message?error.message:"The requested page could not be loaded."));box.append(inner);body.append(box)}function renderHome(){const root=el("div","home");const hero=el("section","hero");hero.append(el("h2","","MSO Page"),el("p","","ChatGPT is another MSO presentation target. Open a native operator view or a reviewed live demo without leaving the conversation."));root.append(hero);root.append(el("div","section-title","Native pages"));const native=el("div","grid");@@ -88,14 +89,14 @@ function appendLine(list,label,value){const row=el("div","line");row.append(el("function stageBase(subtitle){const root=el("div","stage"),head=el("div","stage-head"),content=el("div");head.append(button("←",()=>nav("/"),"back"));const t=el("div","stage-title");t.append(el("strong","",current.title),el("span","",subtitle));head.append(t);root.append(head,content);return{root,content}}function renderApp(){const raw=current.app,safe=safeAppResult(raw);if(!safe){showError(new Error("The app result is not in the reviewed MSO Page registry."));return}const stage=stageBase(safe.renderer==="iframe"?"Live app demo":"Remote-browser fallback");body.append(stage.root);openPath(safe.renderer==="remote"?"/browser":"/assistant/mcp");- if(safe.renderer==="iframe"){const wrap=el("div","frame-wrap"),frame=document.createElement("iframe");frame.title=safe.title+" live demo";frame.src=safe.url;frame.setAttribute("sandbox",safe.sandbox);frame.referrerPolicy="no-referrer";frame.allow="fullscreen";wrap.append(frame);stage.content.append(wrap);return}+ if(safe.renderer==="iframe"){mountReviewedFrame(safe,stage);return}const box=el("div","notice"),inner=el("div");inner.append(el("h3","",safe.title+" protects itself from framing"),el("p","",safe.reason||"This app is not allowlisted for nested framing. MSO preserves the app's own frame policy instead of stripping it."));const row=el("div","row");row.append(button("Open Remote Browser",()=>openMso(),"primary"));if(window.openai&&typeof window.openai.sendFollowUpMessage==="function")row.append(button("Ask ChatGPT to continue",()=>window.openai.sendFollowUpMessage({prompt:"Continue this demo using the MSO remote-browser fallback for "+safe.title+"."})));inner.append(row);box.append(inner);stage.content.append(box);if(safe.presentation==="pip")pipBtn.hidden=false}function renderBrowser(){const box=el("div","notice"),inner=el("div");inner.append(el("h3","","Remote Browser seam"),el("p","","Sites that deny iframe embedding stay isolated. MSO can continue them through Camoufox without exposing its VNC password or authenticated viewer URL to this widget."));const row=el("div","row");row.append(button("Open MSO Browser",()=>openMso(),"primary"));inner.append(row);box.append(inner);body.append(box);openPath("/browser")}-function render(){clear(body);titleEl.textContent=text(current.title,"MSO Page");routeEl.textContent=text(current.route,"/");openPath(text(current.openPath,"/assistant/mcp"));persistRoute();if(current.kind==="home")renderHome();else if(current.kind==="monitor")renderMonitor();else if(current.kind==="project")renderProject("project");else if(current.kind==="diff")renderProject("diff");else if(current.kind==="app")renderApp();else if(current.kind==="browser")renderBrowser();else body.append(el("div","loading","Loading MSO Page…"))}-function readOutput(){const value=window.openai&&window.openai.toolOutput;if(value&&typeof value==="object"){current=value;render()}}-window.addEventListener("message",event=>{if(event.source!==window.parent)return;const msg=event.data;if(!msg||msg.jsonrpc!=="2.0")return;if(msg.id!==undefined&&pending.has(msg.id)){const req=pending.get(msg.id);pending.delete(msg.id);msg.error?req.reject(msg.error):req.resolve(msg.result);return}if(msg.method==="ui/notifications/tool-result"&&msg.params&&msg.params.structuredContent){current=msg.params.structuredContent;render()}},{passive:true});+function render(){viewCleanup();viewCleanup=()=>{};clear(body);titleEl.textContent=text(current.title,"MSO Page");routeEl.textContent=text(current.route,"/");openPath(text(current.openPath,"/assistant/mcp"));persistRoute();if(current.kind==="home")renderHome();else if(current.kind==="monitor")renderMonitor();else if(current.kind==="project")renderProject("project");else if(current.kind==="diff")renderProject("diff");else if(current.kind==="app")renderApp();else if(current.kind==="browser")renderBrowser();else body.append(el("div","loading","Loading MSO Page…"))}+function readOutput(){return acceptPageResult(window.openai&&window.openai.toolOutput)}+window.addEventListener("message",onHostMessage,{passive:true});window.addEventListener("openai:set_globals",()=>{applyHostGlobals();readOutput()},{passive:true});fsBtn.addEventListener("click",()=>displayMode("fullscreen"));pipBtn.addEventListener("click",()=>displayMode("pip"));homeBtn.addEventListener("click",()=>nav("/"));-applyHostGlobals();readOutput();render();+applyHostGlobals();if(!readOutput())render();initializeMcpPage();`;diff --git a/lib/mcp/ui-surface-style.ts b/lib/mcp/ui-surface-style.tsindex 1278acc6..b9b35d5e 100644--- a/lib/mcp/ui-surface-style.ts+++ b/lib/mcp/ui-surface-style.ts@@ -2,7 +2,8 @@ import { MSO_WIDGET_TOKENS } from "./ui-widget-tokens";export const MSO_SURFACE_STYLE = String.raw`${MSO_WIDGET_TOKENS}-:root{font-family:var(--font-body);--line:var(--sep);--muted:var(--text-dim);--soft:var(--field);--accent:var(--os-accent);--safe-top:0px;--safe-right:0px;--safe-bottom:0px;--safe-left:0px;--host-max-h:680px}*{box-sizing:border-box}html,body{margin:0;min-width:0;background:transparent;color:var(--text)}body{padding:8px;font-family:var(--font-body)}.surface{display:flex;min-height:260px;max-height:min(var(--host-max-h),78vh);overflow:hidden;flex-direction:column;border:1px solid var(--sep-strong);border-radius:18px;background:var(--surface);box-shadow:var(--shadow-pop)}.bar{display:flex;min-height:48px;align-items:center;gap:8px;padding:8px 10px;border-bottom:1px solid var(--sep);padding-left:max(10px,var(--safe-left));padding-right:max(10px,var(--safe-right))}.brand{display:grid;place-items:center;width:30px;height:30px;flex:0 0 30px;border-radius:9px;background:var(--text);color:var(--surface);font-family:var(--font-display);font-size:12px;font-weight:850}.heading{min-width:0;flex:1}.heading strong{display:block;font-family:var(--font-display);font-size:12px;line-height:1.2;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.heading span{display:block;margin-top:2px;font-size:9px;color:var(--text-dim);font-family:var(--font-mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tools{display:flex;align-items:center;gap:5px;flex-wrap:wrap;justify-content:flex-end}button,.button{appearance:none;border:1px solid var(--sep-strong);background:var(--field);color:var(--text);border-radius:9px;padding:6px 8px;min-height:30px;font:inherit;font-size:10px;font-weight:650;cursor:pointer;text-decoration:none}button:hover,.button:hover{background:var(--hover-strong)}button:focus-visible,.button:focus-visible{outline:2px solid var(--os-accent);outline-offset:2px}.primary{border-color:var(--text);background:var(--text);color:var(--surface)}.primary:hover{background:var(--text);box-shadow:0 8px 22px color-mix(in srgb,var(--text) 15%,transparent)}.open-direct{font-size:9px;color:inherit}.open-feedback{display:none}.body{min-height:0;flex:1;overflow:auto;padding:12px;padding-bottom:max(12px,var(--safe-bottom));scrollbar-gutter:stable}.home{display:grid;gap:12px}.hero{padding:14px;border:1px solid var(--sep-strong);border-radius:15px;background:linear-gradient(135deg,color-mix(in srgb,var(--os-accent) 9%,var(--surface)),var(--surface))}.hero h2{margin:0;font-family:var(--font-display);font-size:17px}.hero p{max-width:680px;margin:5px 0 0;font-size:11px;line-height:1.5;color:var(--text-dim)}.section-title{margin:2px 0 7px;font-family:var(--font-mono);font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-dim)}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}.card{min-width:0;text-align:left;padding:11px;border:1px solid var(--sep-strong);border-radius:13px;background:var(--field)}.card:hover{background:var(--hover)}.card strong{display:block;font-family:var(--font-display);font-size:11px}.card span{display:block;margin-top:4px;font-size:9px;line-height:1.4;color:var(--text-dim)}.tag{display:inline-flex!important;width:auto!important;margin-top:8px!important;padding:2px 6px;border-radius:999px;border:1px solid var(--sep-strong);font-family:var(--font-mono);font-size:8px!important;text-transform:uppercase;letter-spacing:.06em}.stage{display:flex;min-height:330px;height:100%;flex-direction:column}.stage-head{display:flex;align-items:center;gap:8px;margin-bottom:8px}.back{flex:0 0 auto}.stage-title{min-width:0;flex:1}.stage-title strong{display:block;font-family:var(--font-display);font-size:12px}.stage-title span{display:block;margin-top:2px;font-size:9px;color:var(--text-dim)}.frame-wrap{position:relative;min-height:280px;flex:1;overflow:hidden;border:1px solid var(--sep-strong);border-radius:13px;background:var(--inset)}.frame-wrap iframe{display:block;width:100%;height:100%;min-height:360px;border:0;background:#fff}.notice{display:grid;min-height:280px;place-items:center;border:1px solid var(--sep-strong);border-radius:13px;background:var(--field);padding:24px;text-align:center}.notice>div{max-width:520px}.notice h3{margin:0;font-family:var(--font-display);font-size:14px}.notice p{margin:7px 0 0;color:var(--text-dim);font-size:10px;line-height:1.5}.notice .row{justify-content:center;margin-top:12px}.metrics{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:7px}.metric{padding:12px;border:1px solid var(--sep-strong);border-radius:12px;background:var(--field)}.metric span{display:block;font-family:var(--font-mono);font-size:8px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-dim)}.metric strong{display:block;margin-top:4px;font-family:var(--font-display);font-size:13px}.list{margin-top:8px;border:1px solid var(--sep-strong);border-radius:12px;overflow:hidden}.line{display:flex;align-items:center;gap:10px;min-height:34px;padding:7px 9px;border-top:1px solid var(--sep);font-size:10px}.line:first-child{border-top:0}.line span{color:var(--text-dim)}.line strong{margin-left:auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mono{font-family:var(--font-mono)}.loading{display:grid;min-height:240px;place-items:center;color:var(--text-dim);font-size:11px}.error{color:var(--destructive-text)}.mode-badge{padding:3px 6px;border-radius:999px;background:var(--field);font-family:var(--font-mono);font-size:8px;color:var(--text-dim)}-@media(max-width:660px){body{padding:5px}.surface{max-height:min(var(--host-max-h),82vh);border-radius:14px}.bar{align-items:flex-start;min-height:46px}.tools{max-width:50%}.tools button,.tools .button{padding:5px 7px}.grid{grid-template-columns:1fr 1fr}.frame-wrap iframe{min-height:430px}.metrics{grid-template-columns:1fr 1fr}.body{padding:9px}}+:root{font-family:var(--font-body);--line:var(--sep);--muted:var(--text-dim);--soft:var(--field);--accent:var(--os-accent);--safe-top:0px;--safe-right:0px;--safe-bottom:0px;--safe-left:0px;--host-max-h:680px}*{box-sizing:border-box}html,body{margin:0;min-width:0;background:transparent;color:var(--text)}body{padding:8px;font-family:var(--font-body)}.surface{display:flex;min-height:260px;max-height:var(--host-max-h);overflow:hidden;flex-direction:column;border:1px solid var(--sep-strong);border-radius:18px;background:var(--surface);box-shadow:var(--shadow-pop)}.bar{display:flex;min-height:48px;align-items:center;gap:8px;padding:8px 10px;border-bottom:1px solid var(--sep);padding-left:max(10px,var(--safe-left));padding-right:max(10px,var(--safe-right))}.brand{display:grid;place-items:center;width:30px;height:30px;flex:0 0 30px;border-radius:9px;background:var(--text);color:var(--surface);font-family:var(--font-display);font-size:12px;font-weight:850}.heading{min-width:0;flex:1}.heading strong{display:block;font-family:var(--font-display);font-size:12px;line-height:1.2;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.heading span{display:block;margin-top:2px;font-size:9px;color:var(--text-dim);font-family:var(--font-mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tools{display:flex;align-items:center;gap:5px;flex-wrap:wrap;justify-content:flex-end}button,.button{appearance:none;border:1px solid var(--sep-strong);background:var(--field);color:var(--text);border-radius:9px;padding:6px 8px;min-height:30px;font:inherit;font-size:10px;font-weight:650;cursor:pointer;text-decoration:none}button:hover,.button:hover{background:var(--hover-strong)}button:focus-visible,.button:focus-visible{outline:2px solid var(--os-accent);outline-offset:2px}.primary{border-color:var(--text);background:var(--text);color:var(--surface)}.primary:hover{background:var(--text);box-shadow:0 8px 22px color-mix(in srgb,var(--text) 15%,transparent)}.open-direct{font-size:9px;color:inherit}.open-feedback{display:none}.body{min-height:0;flex:1;overflow:auto;padding:12px;padding-bottom:max(12px,var(--safe-bottom));scrollbar-gutter:stable}.home{display:grid;gap:12px}.hero{padding:14px;border:1px solid var(--sep-strong);border-radius:15px;background:linear-gradient(135deg,color-mix(in srgb,var(--os-accent) 9%,var(--surface)),var(--surface))}.hero h2{margin:0;font-family:var(--font-display);font-size:17px}.hero p{max-width:680px;margin:5px 0 0;font-size:11px;line-height:1.5;color:var(--text-dim)}.section-title{margin:2px 0 7px;font-family:var(--font-mono);font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-dim)}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}.card{min-width:0;text-align:left;padding:11px;border:1px solid var(--sep-strong);border-radius:13px;background:var(--field)}.card:hover{background:var(--hover)}.card strong{display:block;font-family:var(--font-display);font-size:11px}.card span{display:block;margin-top:4px;font-size:9px;line-height:1.4;color:var(--text-dim)}.tag{display:inline-flex!important;width:auto!important;margin-top:8px!important;padding:2px 6px;border-radius:999px;border:1px solid var(--sep-strong);font-family:var(--font-mono);font-size:8px!important;text-transform:uppercase;letter-spacing:.06em}.stage{display:flex;min-height:330px;height:100%;flex-direction:column}.stage-head{display:flex;align-items:center;gap:8px;margin-bottom:8px}.back{flex:0 0 auto}.stage-title{min-width:0;flex:1}.stage-title strong{display:block;font-family:var(--font-display);font-size:12px}.stage-title span{display:block;margin-top:2px;font-size:9px;color:var(--text-dim)}.frame-wrap{position:relative;min-height:280px;flex:1;overflow:hidden;border:1px solid var(--sep-strong);border-radius:13px;background:var(--inset)}.frame-wrap iframe{display:block;width:100%;height:100%;min-height:360px;border:0;background:#fff}.notice{display:grid;min-height:280px;place-items:center;border:1px solid var(--sep-strong);border-radius:13px;background:var(--field);padding:24px;text-align:center}.notice>div{max-width:520px}.notice h3{margin:0;font-family:var(--font-display);font-size:14px}.notice p{margin:7px 0 0;color:var(--text-dim);font-size:10px;line-height:1.5}.notice .row{justify-content:center;margin-top:12px}.metrics{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:7px}.metric{padding:12px;border:1px solid var(--sep-strong);border-radius:12px;background:var(--field)}.metric span{display:block;font-family:var(--font-mono);font-size:8px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-dim)}.metric strong{display:block;margin-top:4px;font-family:var(--font-display);font-size:13px}.list{margin-top:8px;border:1px solid var(--sep-strong);border-radius:12px;overflow:hidden}.line{display:flex;align-items:center;gap:10px;min-height:34px;padding:7px 9px;border-top:1px solid var(--sep);font-size:10px}.line:first-child{border-top:0}.line span{color:var(--text-dim)}.line strong{margin-left:auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mono{font-family:var(--font-mono)}.loading{display:grid;min-height:240px;place-items:center;color:var(--text-dim);font-size:11px}.error{color:var(--destructive-text)}.mode-badge{padding:3px 6px;border-radius:999px;background:var(--field);font-family:var(--font-mono);font-size:8px;color:var(--text-dim)}+.frame-status{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:6px 2px 10px;font-size:10px;color:var(--text-dim)}.frame-status span{flex:1;min-width:120px}.frame-status button{min-height:34px}.stage>div:last-child{min-height:0;display:flex;flex-direction:column;flex:1}.frame-wrap[data-state="unavailable"]{border-color:var(--destructive-text)}+@media(max-width:660px){body{padding:5px}.surface{max-height:var(--host-max-h);border-radius:14px}.bar{align-items:flex-start;min-height:46px}.tools{max-width:50%}.tools button,.tools .button{padding:5px 7px}.grid{grid-template-columns:1fr 1fr}.frame-wrap iframe{min-height:430px}.metrics{grid-template-columns:1fr 1fr}.body{padding:9px}}@media(max-width:420px){.grid{grid-template-columns:1fr}.heading span{max-width:150px}.tools .optional{display:none}.metrics{grid-template-columns:1fr}.frame-wrap iframe{min-height:480px}}`;diff --git a/lib/mcp/ui-surface.ts b/lib/mcp/ui-surface.tsindex 671afc0f..e50e5a36 100644--- a/lib/mcp/ui-surface.ts+++ b/lib/mcp/ui-surface.ts@@ -4,7 +4,7 @@ import { surfaceFrameDomains } from "./surface-catalog";import { MSO_SURFACE_SCRIPT } from "./ui-surface-script";import { MSO_SURFACE_STYLE } from "./ui-surface-style";-export const MSO_PAGE_URI = "ui://mso/page-v2.html";+export const MSO_PAGE_URI = "ui://mso/page-v3.html";const MIME = "text/html;profile=mcp-app";const html = String.raw`<main class="surface" aria-label="MSO Page">@@ -32,6 +32,6 @@ export const MSO_PAGE_RESOURCE = {text: html,_meta: widgetResourceMeta("Interactive MSO Page. It renders native operator views and exact-origin reviewed development or production targets. Nested frames are limited to explicit CSP frame domains and dedicated embed routes; arbitrary HTML and URLs are never accepted from the model.",- { frameDomains: surfaceFrameDomains() },+ { frameDomains: surfaceFrameDomains(), redirectDomains: surfaceFrameDomains() },),} as const;diff --git a/scripts/e2e/mcp-page.mjs b/scripts/e2e/mcp-page.mjsnew file mode 100644index 00000000..b4e7647f--- /dev/null+++ b/scripts/e2e/mcp-page.mjs@@ -0,0 +1,79 @@+#!/usr/bin/env node+// Browser contract for the portable MCP host, readiness, timeout and legacy cached output.+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import { createRequire } from "node:module";+import path from "node:path";+const require = createRequire(import.meta.url);+const { chromium } = require(path.join(process.cwd(), "os-browser/node_modules/playwright"));+const resource = JSON.parse(execFileSync("bun", ["-e", 'import { MSO_PAGE_RESOURCE } from "./lib/mcp/ui-surface"; console.log(JSON.stringify(MSO_PAGE_RESOURCE))'], { encoding: "utf8" }));+const output = {+ route: "/apps/play-together", kind: "app", title: "Play Together", openPath: "/assistant/mcp", catalog: [],+ app: { id: "play-together", url: "https://game.rahmanef.com/embed" },+};+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH ?? "/usr/bin/google-chrome", args: ["--no-sandbox", "--disable-dev-shm-usage"] });+let assertions = 0;+try {+ for (const legacy of [false, true]) {+ const page = await browser.newPage({ viewport: { width: legacy ? 390 : 1280, height: 800 } });+ await page.clock.install();+ let childLoads = 0;+ await page.route("https://game.rahmanef.com/embed", (route) => {+ childLoads++;+ return route.fulfill({ contentType: "text/html", body: "<!doctype html><title>Controlled game readiness fixture</title><main>Fixture game shell</main>" });+ });+ await page.route("https://mso-ui.rahmanef.com/qa", (route) => route.fulfill({ contentType: "text/html", body: `${legacy ? `<script>window.openai={toolOutput:${JSON.stringify({ structuredContent: output })}}</script>` : ""}${resource.text}` }));+ await page.route("https://chatgpt.com/qa", (route) => route.fulfill({ contentType: "text/html", body: `<!doctype html><script>+ window.calls=[];window.result=${JSON.stringify(output)};+ window.addEventListener("message",event=>{+ const msg=event.data;if(!msg||msg.jsonrpc!=="2.0")return;calls.push(msg);+ const frame=document.querySelector("iframe").contentWindow;+ if(msg.method==="ui/initialize"&&!${legacy})frame.postMessage({jsonrpc:"2.0",id:msg.id,result:{protocolVersion:"2026-01-26",hostCapabilities:{serverTools:{},openLinks:{}},hostContext:{displayMode:"inline"}}},"https://mso-ui.rahmanef.com");+ if(msg.method==="ui/notifications/initialized"){+ frame.postMessage({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:{route:result.route}}},"https://mso-ui.rahmanef.com");+ frame.postMessage({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:{structuredContent:result}},"https://mso-ui.rahmanef.com");+ }+ if(msg.method==="ui/notifications/size-changed")document.querySelector("iframe").style.height=msg.params.height+"px";+ if(msg.method==="ui/open-link")frame.postMessage({jsonrpc:"2.0",id:msg.id,result:{}},"https://mso-ui.rahmanef.com");+ });</script><iframe src="https://mso-ui.rahmanef.com/qa" style="width:100%;height:740px"></iframe>` }));+ await page.goto("https://chatgpt.com/qa");+ const component = page.frameLocator('iframe[src="https://mso-ui.rahmanef.com/qa"]');+ await component.locator('.frame-wrap[data-state="loading"]').waitFor();+ assert.equal(childLoads, 1); assertions++;+ const widget = page.frames().find((frame) => frame.url() === "https://mso-ui.rahmanef.com/qa");+ const game = page.frames().find((frame) => frame.url() === "https://game.rahmanef.com/embed");+ assert(widget && game);+ if (!legacy) {+ const calls = await page.evaluate(() => window.calls);+ assert.equal(calls[0].method, "ui/initialize");+ assert.equal(calls[0].params.appInfo.name, "MSO Page");+ assert.deepEqual(calls[0].params.appCapabilities.availableDisplayModes, ["inline", "fullscreen", "pip"]);+ assert(calls.some((call) => call.method === "ui/notifications/initialized")); assertions++;+ }+ await widget.evaluate(() => window.dispatchEvent(new MessageEvent("message", { origin: "https://game.rahmanef.com", source: window, data: { type: "play-together:embed-ready", schemaVersion: 1 } })));+ assert.equal(await component.locator(".frame-wrap").getAttribute("data-state"), "loading"); assertions++;+ await game.evaluate(() => parent.postMessage({ type: "play-together:embed-ready", schemaVersion: 99 }, "https://mso-ui.rahmanef.com"));+ assert.equal(await component.locator(".frame-wrap").getAttribute("data-state"), "loading"); assertions++;+ await page.clock.fastForward(13000);+ await component.locator('.frame-wrap[data-state="unavailable"]').waitFor();+ await component.getByRole("button", { name: "Retry preview" }).click();+ await component.locator('.frame-wrap[data-state="loading"]').waitFor();+ await page.waitForTimeout(50);+ const reloaded = page.frames().find((frame) => frame.url() === "https://game.rahmanef.com/embed");+ assert(reloaded); assertions++;+ await reloaded.evaluate(() => parent.postMessage({ type: "play-together:embed-ready", schemaVersion: 1 }, "https://mso-ui.rahmanef.com"));+ await component.locator('.frame-wrap[data-state="ready"]').waitFor(); assertions++;+ const previousLoads = childLoads;+ await page.evaluate(() => document.querySelector("iframe").contentWindow.postMessage({ jsonrpc: "2.0", method: "ui/notifications/tool-result", params: { structuredContent: window.result } }, "https://mso-ui.rahmanef.com"));+ await widget.evaluate(() => window.dispatchEvent(new Event("openai:set_globals")));+ await page.waitForTimeout(50);+ assert.equal(childLoads, previousLoads, "Unchanged results and host globals must not restart the game"); assertions++;+ if (!legacy) {+ await component.getByRole("button", { name: "Open production" }).click();+ assert((await page.evaluate(() => window.calls)).some((call) => call.method === "ui/open-link" && call.params.url === "https://game.rahmanef.com")); assertions++;+ }+ console.log(`PASS ${legacy ? "legacy wrapped toolOutput / mobile" : "pure MCP Apps host / desktop"}: init, source validation, timeout, retry, ready, no repeated reload`);+ await page.close();+ }+ console.log(`MCP Page browser checks: ${assertions} assertions passed`);+} finally { await browser.close(); }