From da184e82684bb1ae82db7657aaa914c8b912591f Mon Sep 17 00:00:00 2001 From: Ales Rechtorik Date: Sat, 10 Oct 2026 15:24:49 +0200 Subject: [PATCH 01/14] feat(assets): the Mate's asset store keeps a page an agent published A page is the one kind of original besides a picture: kept as its bytes came through ingestPage, never read as a picture even when it opens with an SVG, and served at its address under default-src 'none'; sandbox, so it runs nothing there. Its conversation's frame reads it; nothing opens it. --- .../src/assets/ContentAssetHttp.test.ts | 34 +++++++++++++++++++ apps/server/src/assets/ContentAssetHttp.ts | 5 +++ apps/server/src/assets/ContentAssets.ts | 20 ++++++++--- packages/contracts/src/assetReference.ts | 3 +- 4 files changed, 57 insertions(+), 5 deletions(-) diff --git a/apps/server/src/assets/ContentAssetHttp.test.ts b/apps/server/src/assets/ContentAssetHttp.test.ts index a643640ddd..ac22d1f28a 100644 --- a/apps/server/src/assets/ContentAssetHttp.test.ts +++ b/apps/server/src/assets/ContentAssetHttp.test.ts @@ -138,3 +138,37 @@ it.effect.each([ expect(resolutions).toBe(1); }), ); + +it.effect("serves a published page as a document that runs nothing at its own address", () => + Effect.gen(function* () { + const root = yield* Effect.promise(() => + NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "mate-http-page-")), + ); + roots.push(root); + const store = new ContentAssets(root); + // A page that opens with an SVG still is a page, never a picture. + const html = ''; + const page = yield* Effect.promise(() => + store.ingestPage(Buffer.from(html), { + threadId: ThreadId.make("thread"), + ownerId: "call", + name: "page-1.html", + provenance: "capture", + }), + ); + const original = page.original; + if (original.status !== "ready") throw new Error(`page refused: ${original.code}`); + const object = yield* Effect.promise(() => store.object(original.digest)); + const response = yield* protectedContentAsset(Effect.succeed(null), Effect.succeed(object), { + method: "GET", + headers: {}, + }); + expect(response.status).toBe(200); + expect(response.headers["content-type"]).toBe("text/html"); + expect(response.headers["content-security-policy"]).toBe("default-src 'none'; sandbox"); + const bytes = yield* Effect.promise(async () => + Buffer.from(await HttpServerResponse.toWeb(response).arrayBuffer()).toString(), + ); + expect(bytes).toBe(html); + }), +); diff --git a/apps/server/src/assets/ContentAssetHttp.ts b/apps/server/src/assets/ContentAssetHttp.ts index 67395262ff..ac07104811 100644 --- a/apps/server/src/assets/ContentAssetHttp.ts +++ b/apps/server/src/assets/ContentAssetHttp.ts @@ -2,6 +2,7 @@ import type { AssetRepresentation } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { HttpServerResponse } from "effect/http"; +import { PAGE_MIME_TYPE } from "./ContentAssets.ts"; import { openMediaFile, streamMediaFile } from "./MediaFile.ts"; export const contentAssetFailure = (code: string, status: number) => @@ -32,6 +33,10 @@ export const contentAssetResponse = Effect.fn("contentAssetResponse")(function* ...(object.mimeType === "image/svg+xml" ? { "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" } : {}), + // A page is read by its conversation's frame, never opened here: at this address it runs nothing. + ...(object.mimeType === PAGE_MIME_TYPE + ? { "Content-Security-Policy": "default-src 'none'; sandbox" } + : {}), }; if ( request.headers["if-none-match"] diff --git a/apps/server/src/assets/ContentAssets.ts b/apps/server/src/assets/ContentAssets.ts index 76731a2be2..9df33f6e6e 100644 --- a/apps/server/src/assets/ContentAssets.ts +++ b/apps/server/src/assets/ContentAssets.ts @@ -56,6 +56,8 @@ export function isStorageFull(error: unknown): boolean { return false; } type Owner = Omit & { readonly mimeType?: string }; +/** The one kind of original besides a picture: a page an agent published. */ +export const PAGE_MIME_TYPE = "text/html"; type StoredObject = AssetRepresentation & { readonly path: string }; const stores = new Map(); export const contentAssetsAt = (stateDir: string) => { @@ -142,15 +144,19 @@ export class ContentAssets { bytes: Uint8Array, preview = false, mimeHint?: string, + page = false, ): Promise { let info: Partial = {}; + // A page an agent published is kept as it came: never read as a picture, even one that opens + // with an SVG, and served to no one as a document that runs (`ContentAssetHttp`). try { - info = await sharp(bytes).metadata(); + if (!page) info = await sharp(bytes).metadata(); } catch { if (preview || !mimeHint?.startsWith("image/")) throw new ContentAssetError("unsupported"); } - const mimeType = - info.format === "jpeg" + const mimeType = page + ? PAGE_MIME_TYPE + : info.format === "jpeg" ? "image/jpeg" : info.format === "svg" ? "image/svg+xml" @@ -179,7 +185,12 @@ export class ContentAssets { return representation; } - async ingestBytes(bytes: Uint8Array, owner: Owner): Promise { + /** A page an agent published, kept as its bytes came (`PAGE_MIME_TYPE`), never as a picture. */ + async ingestPage(bytes: Uint8Array, owner: Owner): Promise { + return this.ingestBytes(bytes, owner, true); + } + + async ingestBytes(bytes: Uint8Array, owner: Owner, page = false): Promise { const id = NodeCrypto.randomUUID(); let occurrence: ImageOccurrence; try { @@ -187,6 +198,7 @@ export class ContentAssets { bytes, false, owner.mimeType ?? mediaMimeTypeFromExtension(NodePath.extname(owner.name)) ?? undefined, + page, ); occurrence = { ...owner, id, original: { status: "ready", ...original } }; } catch (error) { diff --git a/packages/contracts/src/assetReference.ts b/packages/contracts/src/assetReference.ts index 8ae64b58b7..ea31bc791e 100644 --- a/packages/contracts/src/assetReference.ts +++ b/packages/contracts/src/assetReference.ts @@ -14,7 +14,8 @@ export const ImageOccurrence = Schema.Struct({ Schema.Struct({ status: Schema.Literal("ready"), digest: AssetDigest, - mimeType: Schema.String.check(Schema.isPattern(/^image\//)), + // A picture, or the one other kind the store keeps: a page an agent published (`text/html`). + mimeType: Schema.String.check(Schema.isPattern(/^(?:image\/|text\/html$)/)), sizeBytes: PositiveInt, width: Schema.optionalKey(PositiveInt), height: Schema.optionalKey(PositiveInt), From c6eed4da0962b2166a3e4245a817bcaf8ae24ab6 Mon Sep 17 00:00:00 2001 From: Ales Rechtorik Date: Sat, 10 Oct 2026 15:24:50 +0200 Subject: [PATCH 02/14] feat(engine): a page the Mate publishes is recorded on its call by reference zcp's zerops_publish_page names the file it kept the page in. As the pump records the call it reads that file once into the Mate's asset store, as it stores a result's pictures, and the call's result carries the page by reference with its title, size and time: the same record live and after a reload, however long zcp keeps its copy. Only a regular file named like zcp's pages in a .zcp/state/pages directory, under 8 MiB, is ever read. The page rides the call it came from rather than an item of its own: one call is one item, pictures take the same path, and the state's shape is unchanged, so STATE_VERSION stays. --- .../src/engine/pump/SessionHost.test.ts | 56 ++++++++++++ apps/server/src/engine/pump/SessionHost.ts | 19 +++- .../src/engine/pump/callPictures.test.ts | 87 ++++++++++++++++++- apps/server/src/engine/pump/callPictures.ts | 59 +++++++++++-- packages/contracts/src/engineCall.ts | 18 ++++ 5 files changed, 231 insertions(+), 8 deletions(-) diff --git a/apps/server/src/engine/pump/SessionHost.test.ts b/apps/server/src/engine/pump/SessionHost.test.ts index ef04d4efa3..1177d1ba71 100644 --- a/apps/server/src/engine/pump/SessionHost.test.ts +++ b/apps/server/src/engine/pump/SessionHost.test.ts @@ -12,6 +12,14 @@ import { hostEvent, makeHostHarness } from "../testing/pump/hostHarness.ts"; import type { CallPictures } from "./callPictures.ts"; const S1 = SessionId.make("mate/s/1.1"); +const PAGE_ASSET = { + id: "asset-3", + threadId: "mate/s/1", + ownerId: "call-1", + name: "page-0123456789abcdef.html", + provenance: "capture", + original: { status: "ready", digest: "b".repeat(64), mimeType: "text/html", sizeBytes: 13 }, +} as never; const H1 = "mate/r/1" as TurnHandle; describe("SessionHost", () => { @@ -140,6 +148,11 @@ describe("SessionHost", () => { stored.push(`${key}: ${path}`); return { imagePath: "mate-asset:asset-2", imageName: "home.png" }; }), + page: (_thread, key, file) => + Effect.sync(() => { + stored.push(`${key}: page ${file}`); + return { asset: PAGE_ASSET, bytes: 13 }; + }), }; const { host, told } = yield* makeHostHarness({ pictures }); yield* host.begin(S1); @@ -219,6 +232,49 @@ describe("SessionHost", () => { ), ); + it.effect( + "a page the Mate publishes is recorded on its call by reference, with its title, size and time", + () => + Effect.scoped( + Effect.gen(function* () { + const file = "/var/www/.zcp/state/pages/page-0123456789abcdef.html"; + const { call, stored } = yield* turnWith({ + itemType: "mcp_tool_call", + title: "zerops_publish_page", + data: { + item: { + type: "mcpToolCall", + id: "call-1", + server: "zerops", + tool: "zerops_publish_page", + status: "completed", + arguments: { title: "Plan", path: "plan.html" }, + result: { + content: [ + { + type: "text", + text: JSON.stringify({ + page: { id: "page-0123456789abcdef", title: "Plan", file, bytes: 13 }, + message: "Published", + }), + }, + ], + }, + }, + }, + }); + assert.deepStrictEqual(stored, [`mate/r/1.i1: page ${file}`]); + const result = call?.body.kind === "call" ? call.body.result : undefined; + assert.deepStrictEqual(result?.page, { + asset: PAGE_ASSET, + title: "Plan", + bytes: 13, + publishedAt: call?.body.kind === "call" ? call.body.endedAt! : -1, + }); + }), + ), + ); + it.effect("a workspace picture a call looked at is named by its asset", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/engine/pump/SessionHost.ts b/apps/server/src/engine/pump/SessionHost.ts index bd5800ba81..35baaafa80 100644 --- a/apps/server/src/engine/pump/SessionHost.ts +++ b/apps/server/src/engine/pump/SessionHost.ts @@ -49,7 +49,7 @@ import type { ConversationsShape } from "../Conversations.ts"; import type { ProviderSignal } from "../domain/command.ts"; import { signalsCommandId } from "../domain/ids.ts"; import type { LiveBusShape } from "../LiveBus.ts"; -import type { CallPictures } from "./callPictures.ts"; +import { publishedPage, type CallPictures } from "./callPictures.ts"; import { makeToCore, type SendEvidence } from "./toCore.ts"; /** How an unasked session reads in the record. */ @@ -260,6 +260,23 @@ export const makeSessionHost = Effect.fnUntraced(function* ( }, }; } + // A page it published goes to the asset store too: the record holds it by reference, the + // same live and after a reload, however long zcp keeps its own copy. + const published = + body.state === "done" && body.result !== undefined ? publishedPage(body.result) : null; + if (published !== null && deps.pictures !== undefined) { + const kept = yield* deps.pictures.page(input.thread, signal.key, published.file); + if (kept !== null && body.result !== undefined) { + const publishedAt = body.endedAt ?? (yield* Clock.currentTimeMillis); + body = { + ...body, + result: { + ...body.result, + page: { asset: kept.asset, title: published.title, bytes: kept.bytes, publishedAt }, + }, + }; + } + } const looked = body.shows?.imagePath; if ( deps.pictures !== undefined && diff --git a/apps/server/src/engine/pump/callPictures.test.ts b/apps/server/src/engine/pump/callPictures.test.ts index 393a2399e9..20e932b097 100644 --- a/apps/server/src/engine/pump/callPictures.test.ts +++ b/apps/server/src/engine/pump/callPictures.test.ts @@ -3,12 +3,12 @@ import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; -import { ThreadId } from "@t3tools/contracts"; +import { PAGE_MAX_BYTES, ThreadId } from "@t3tools/contracts"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import { PIXEL } from "../testing/bridge/callHeavy.ts"; -import { makeCallPictures } from "./callPictures.ts"; +import { makeCallPictures, publishedPage } from "./callPictures.ts"; const thread = ThreadId.make("mate/s/1"); @@ -45,3 +45,86 @@ describe("a call's pictures in the Mate's asset store", () => { }), ); }); + +describe("a page the Mate publishes, in its asset store", () => { + const pagesOf = () => { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "call-pages-")); + const pages = NodePath.join(root, "work", ".zcp", "state", "pages"); + NodeFS.mkdirSync(pages, { recursive: true }); + const outside = NodePath.join(root, "secret.html"); + NodeFS.writeFileSync(outside, "

not a page

"); + NodeFS.writeFileSync(NodePath.join(pages, "page-0123456789abcdef.html"), "

Plan

"); + NodeFS.symlinkSync(outside, NodePath.join(pages, "page-1111111111111111.html")); + NodeFS.writeFileSync( + NodePath.join(pages, "page-2222222222222222.html"), + Buffer.alloc(PAGE_MAX_BYTES + 1, 0x61), + ); + NodeFS.mkdirSync(NodePath.join(pages, "page-3333333333333333.html")); + return { + pages, + outside, + store: makeCallPictures(NodePath.join(root, "state"), () => + Effect.succeed(NodePath.join(root, "work")), + ), + }; + }; + + it.effect("keeps a published page once, by reference, with its size", () => + Effect.gen(function* () { + const { pages, store } = pagesOf(); + const file = NodePath.join(pages, "page-0123456789abcdef.html"); + const first = yield* store.page(thread, "call-4", file); + const again = yield* store.page(thread, "call-4", file); + assert.strictEqual(first?.asset.original.status, "ready"); + assert.include(first?.asset.original, { mimeType: "text/html", sizeBytes: 13 }); + assert.strictEqual(first?.bytes, 13); + assert.strictEqual(again?.asset.id, first?.asset.id); + }), + ); + + it.effect.each([ + ["a file outside zcp's pages", "outside"], + ["a page that links elsewhere", "page-1111111111111111.html"], + ["a page over the cap", "page-2222222222222222.html"], + ["a directory", "page-3333333333333333.html"], + ["a page that is not there", "page-4444444444444444.html"], + ["a relative name", "relative"], + ] as const)("never reads %s", ([_what, name]) => + Effect.gen(function* () { + const { pages, outside, store } = pagesOf(); + const file = + name === "outside" + ? outside + : name === "relative" + ? ".zcp/state/pages/page-0123456789abcdef.html" + : NodePath.join(pages, name); + assert.isNull(yield* store.page(thread, "call-5", file)); + }), + ); +}); + +describe("the page a call published", () => { + it.each([ + [ + "zcp's result", + { + toolName: "zerops_publish_page", + resultText: JSON.stringify({ + page: { id: "page-1", title: "Plan", file: "/w/.zcp/state/pages/page-1.html", bytes: 9 }, + message: "Published", + }), + }, + { title: "Plan", file: "/w/.zcp/state/pages/page-1.html" }, + ], + ["another tool's", { toolName: "zerops_browser", resultText: '{"page":{}}' }, null], + ["a refusal", { toolName: "zerops_publish_page", resultText: '{"code":"X"}' }, null], + ["a result over the wire's limit", { toolName: "zerops_publish_page", truncated: true }, null], + [ + "a page with no title", + { toolName: "zerops_publish_page", resultText: '{"page":{"file":"/w/p.html"}}' }, + null, + ], + ] as const)("is read from %s", (_what, result, want) => { + assert.deepStrictEqual(publishedPage(result), want); + }); +}); diff --git a/apps/server/src/engine/pump/callPictures.ts b/apps/server/src/engine/pump/callPictures.ts index 54b36317e6..8452ea5530 100644 --- a/apps/server/src/engine/pump/callPictures.ts +++ b/apps/server/src/engine/pump/callPictures.ts @@ -8,13 +8,16 @@ * * @module engine/pump/callPictures */ +import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; -import type { - CallResultPicture, - ImageOccurrence, - SpiToolCallImage, - ThreadId, +import { + PAGE_MAX_BYTES, + type CallResult, + type CallResultPicture, + type ImageOccurrence, + type SpiToolCallImage, + type ThreadId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; @@ -44,6 +47,38 @@ export interface CallPictures { key: string, path: string, ) => Effect.Effect; + /** A page a call published, by the file zcp kept it in; one it cannot take is none. */ + readonly page: ( + thread: ThreadId, + key: string, + file: string, + ) => Effect.Effect<{ readonly asset: ImageOccurrence; readonly bytes: number } | null>; +} + +/** The tool a Mate's agent publishes a page with (zcp's `zerops_publish_page`). */ +export const PUBLISH_PAGE_TOOL = "zerops_publish_page"; + +/** + * Where zcp keeps a page it published, as its result names it: a file named by its content in + * the `pages` directory of a `.zcp/state` (`docs/spec-mate.md` §5.9 in zcp). Nothing else is read. + */ +const PAGE_FILE = /\/\.zcp\/state\/pages\/page-[0-9a-f]{16}\.html$/; + +/** The page a call's result says it published: its file and title, else none. */ +export function publishedPage( + result: Pick, +): { readonly file: string; readonly title: string } | null { + if (result.toolName !== PUBLISH_PAGE_TOOL || result.resultText === undefined) return null; + try { + const page = (JSON.parse(result.resultText) as { readonly page?: unknown }).page; + if (typeof page !== "object" || page === null) return null; + const { file, title } = page as { readonly file?: unknown; readonly title?: unknown }; + return typeof file === "string" && typeof title === "string" && title.length > 0 + ? { file, title } + : null; + } catch { + return null; + } } /** @@ -117,5 +152,19 @@ export const makeCallPictures = ( : {}), }; }).pipe(Effect.orElseSucceed(() => null)), + page: (thread, key, file) => + Effect.tryPromise(async () => { + // A regular file where zcp keeps pages, under the cap: never a link out of there. + if (!NodePath.isAbsolute(file) || !PAGE_FILE.test(file)) return null; + const stat = await NodeFSP.lstat(file); + if (!stat.isFile() || stat.size > PAGE_MAX_BYTES) return null; + const bytes = await NodeFSP.readFile(file); + if (bytes.byteLength > PAGE_MAX_BYTES) return null; + const store = assets(); + const asset = (await store.legacy([thread, key, file], () => + store.ingestPage(bytes, { ...owner(thread, key), name: NodePath.basename(file) }), + )) as ImageOccurrence; + return asset.original.status === "ready" ? { asset, bytes: bytes.byteLength } : null; + }).pipe(Effect.orElseSucceed(() => null)), }; }; diff --git a/packages/contracts/src/engineCall.ts b/packages/contracts/src/engineCall.ts index 6211efefa3..7566a8e91b 100644 --- a/packages/contracts/src/engineCall.ts +++ b/packages/contracts/src/engineCall.ts @@ -25,6 +25,22 @@ export const CallResultPicture = Schema.Struct({ }); export type CallResultPicture = typeof CallResultPicture.Type; +/** The largest page a call records: zcp's own cap on a published page (`ops.PageMaxBytes`). */ +export const PAGE_MAX_BYTES = 8 * 1024 * 1024; + +/** + * A page the agent published (`zerops_publish_page`) for the person to see above its reply: a + * self-contained HTML document kept in the Mate's asset store, by reference as a picture is, with + * its title, its size in bytes and when the call that published it ended. + */ +export const CallResultPage = Schema.Struct({ + asset: ImageOccurrence, + title: Schema.String, + bytes: Schema.Number, + publishedAt: Schema.Number, +}); +export type CallResultPage = typeof CallResultPage.Type; + /** * A `zerops_*` call's result, as V1's activity carries it (`ZeropsActivityResult`): the tool's * name, its text verbatim — absent while it runs, or when it was over the server's limit @@ -36,6 +52,8 @@ export const CallResult = Schema.Struct({ truncated: Schema.optionalKey(Schema.Boolean), images: Schema.optionalKey(Schema.Array(CallResultPicture)), imagesDropped: Schema.optionalKey(Schema.Boolean), + /** The page it published, on the engine only. */ + page: Schema.optionalKey(CallResultPage), }); export type CallResult = typeof CallResult.Type; From 5c69787a6983ed15d0e9d74d3ba988a71efa951f Mon Sep 17 00:00:00 2001 From: Ales Rechtorik Date: Sat, 10 Oct 2026 15:28:38 +0200 Subject: [PATCH 03/14] feat(engine): a reload's window holds every page its runs published A reload reads a closed run's person message, requests and answer, never the rest of its work, so a page above the answer vanished on reload. Each call that carries a page now rides the window with the answer, the same record the client got live. The test world takes an asset store on request so a page's file reaches it. --- .../src/engine/testing/pump/engineWorld.ts | 11 ++++ .../server/src/engine/wire/EngineWire.test.ts | 64 +++++++++++++++++++ apps/server/src/engine/wire/records.ts | 4 +- 3 files changed, 78 insertions(+), 1 deletion(-) diff --git a/apps/server/src/engine/testing/pump/engineWorld.ts b/apps/server/src/engine/testing/pump/engineWorld.ts index 47cb7ada90..4afaa8b39e 100644 --- a/apps/server/src/engine/testing/pump/engineWorld.ts +++ b/apps/server/src/engine/testing/pump/engineWorld.ts @@ -13,6 +13,8 @@ import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; +import * as NodeServices from "@effect/platform-node/NodeServices"; + import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -31,6 +33,7 @@ import { type RunState, } from "@t3tools/contracts"; +import * as ServerConfigModule from "../../../config.ts"; import * as NodeSqliteClient from "../../../persistence/NodeSqliteClient.ts"; import type { BridgeDriver } from "../../bridge/spi3.ts"; import { Conversations } from "../../Conversations.ts"; @@ -94,6 +97,8 @@ export interface WorldOptions { readonly thread: string; readonly instanceId: string; }) => unknown; + /** The server's config, so a call's pictures and pages reach an asset store; none by default. */ + readonly assets?: boolean; } let lives = 0; @@ -178,6 +183,11 @@ export const makeEngineWorld = (options: WorldOptions) => ), ); + const config = options.assets + ? ServerConfigModule.layerTest(dir, { prefix: "engine-assets-" }).pipe( + Layer.provide(NodeServices.layer), + ) + : Layer.empty; const lifeLayer = (scripted: ScriptedProvider) => liveEngineLayer({ worker: { pollMillis: 1_000 } }).pipe( Layer.provideMerge( @@ -185,6 +195,7 @@ export const makeEngineWorld = (options: WorldOptions) => scriptedProviderLayer(scripted), history.layer, ports, + config, NodeSqliteClient.layer({ filename }), ), ), diff --git a/apps/server/src/engine/wire/EngineWire.test.ts b/apps/server/src/engine/wire/EngineWire.test.ts index 57d4cf6764..fff21682e0 100644 --- a/apps/server/src/engine/wire/EngineWire.test.ts +++ b/apps/server/src/engine/wire/EngineWire.test.ts @@ -1,5 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -693,6 +694,69 @@ describe("a client reading an engine call", () => { ); }); +describe("a page the Mate publishes", () => { + it.effect("reaches the client on its call by reference, the same live and after a reload", () => + Effect.scoped( + Effect.gen(function* () { + const w = yield* makeEngineWorld({ driver: "claudeAgent", assets: true }); + yield* w.boot; + yield* w.tell({ + _tag: "AssignAgent", + agent: { + instanceId: "claudeAgent", + driver: "claudeAgent", + model: "m1", + profile: { kind: "mate" }, + }, + }); + const pages = NodePath.join( + NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "engine-page-")), + ".zcp", + "state", + "pages", + ); + NodeFS.mkdirSync(pages, { recursive: true }); + const file = NodePath.join(pages, "page-0123456789abcdef.html"); + NodeFS.writeFileSync(file, "

The plan

"); + const wire = yield* wireOf(w); + const live = yield* watch(w, wire); + yield* send(wire, "Plan the launch"); + yield* w.settle; + yield* w.agent((agent, thread) => + agent.zerops( + thread, + "zerops_publish_page", + { title: "Launch plan", path: "plan.html" }, + '{"title":"Launch plan"}', + JSON.stringify({ + page: { id: "page-0123456789abcdef", title: "Launch plan", file, bytes: 17 }, + message: "Published", + }), + ), + ); + yield* w.agent((agent, thread) => agent.say(thread, "The plan is above.")); + yield* w.agent((agent, thread) => agent.finish(thread)); + const liveCall = live + .flatMap((frame) => (frame.type === "changes" ? frame.items : [])) + .findLast((item) => item.kind === "call"); + const [reload] = yield* Effect.scoped(watch(w, wire)); + if (reload?.type !== "snapshot") throw new Error("no snapshot"); + const reloadCall = reload.items.find((item) => item.kind === "call"); + const page = liveCall?.kind === "call" ? liveCall.result?.page : undefined; + assert.include(page, { title: "Launch plan", bytes: 17 }); + assert.include(page?.asset.original, { status: "ready", mimeType: "text/html" }); + assert.deepStrictEqual(reloadCall?.kind === "call" ? reloadCall.result?.page : null, page); + // A reload's window holds the page with the answer, never the rest of the run's work. + assert.deepStrictEqual( + reload.items.map((item) => item.kind), + ["person", "call", "note"], + ); + yield* w.shutdown; + }), + ), + ); +}); + describe("a client subscribed to a Mate's conversation rows", () => { it.effect("gets each conversation's row with its agent, then the row again as it changes", () => Effect.scoped( diff --git a/apps/server/src/engine/wire/records.ts b/apps/server/src/engine/wire/records.ts index 8927aa39ff..b13e998c66 100644 --- a/apps/server/src/engine/wire/records.ts +++ b/apps/server/src/engine/wire/records.ts @@ -326,7 +326,8 @@ export const makeRecords = Effect.gen(function* () { /** * What a window shows of its runs: the runs, every person message, request and answer, every - * open request (wherever it was asked), and the newest items of each run not ended. + * page published above an answer, every open request (wherever it was asked), and the newest + * items of each run not ended. */ const windowOf = ( conversation: ConversationId, @@ -358,6 +359,7 @@ export const makeRecords = Effect.gen(function* () { SELECT * FROM engine_item WHERE conversation_id = ${conversation} AND ${sql.in("run_id", runIds)} AND (kind IN ('person', 'request') + OR (kind = 'call' AND json_extract(body_json, '$.result.page') IS NOT NULL) ${answers.length === 0 ? sql`` : sql`OR ${sql.in("item_id", answers)}`}) `; const asked = From 3959def6f4435cdb05b4cac3457ae2b08703c26f Mon Sep 17 00:00:00 2001 From: Ales Rechtorik Date: Sat, 10 Oct 2026 15:36:59 +0200 Subject: [PATCH 04/14] feat(client-runtime): a page the engine recorded carries into its Zerops call The call's result names the page it published by reference to the Mate's assets; the call ledger reads it once per row, so a row read again gives the page it gave before, and a page without an asset of its own is none. --- .../src/zerops/model/calls.test.ts | 49 +++++++++++++++++++ .../client-runtime/src/zerops/model/calls.ts | 19 ++++++- .../client-runtime/src/zerops/model/types.ts | 4 +- 3 files changed, 70 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/zerops/model/calls.test.ts b/packages/client-runtime/src/zerops/model/calls.test.ts index 9d76e6aca9..914f98d956 100644 --- a/packages/client-runtime/src/zerops/model/calls.test.ts +++ b/packages/client-runtime/src/zerops/model/calls.test.ts @@ -297,6 +297,55 @@ describe("collectZeropsCalls — the lattice properties", () => { expect(calls[0]!.id).toBe("anon:solo"); }); + it.each([ + { + title: "a page the engine recorded carries into its call by reference", + page: { + asset: { + id: "6f1c2b9e-0000-4000-8000-000000000001", + threadId: "thread", + ownerId: "call", + name: "page-0123456789abcdef.html", + provenance: "capture", + original: { + status: "ready", + digest: "b".repeat(64), + mimeType: "text/html", + sizeBytes: 17, + }, + }, + title: "Launch plan", + bytes: 17, + publishedAt: 1_760_000_000_000, + }, + carried: true, + }, + { + title: "a page with no asset of its own is no page", + page: { title: "Launch plan", bytes: 17, publishedAt: 1 }, + carried: false, + }, + ])("$title", ({ page, carried }) => { + const activities = [ + started({ + id: "a1", + payload: { toolCallId: "p1", data: { toolName: "mcp__zerops__zerops_publish_page" } }, + }), + completed({ + id: "a2", + payload: { + toolCallId: "p1", + data: { + toolName: "mcp__zerops__zerops_publish_page", + zerops: { toolName: "zerops_publish_page", resultText: "{}", page }, + }, + }, + }), + ]; + const [call] = collectZeropsCalls(activities, "t1"); + expect(call!.page).toEqual(carried ? page : undefined); + }); + it("a non-zerops call never appears in the ledger", () => { const activities = [ started({ diff --git a/packages/client-runtime/src/zerops/model/calls.ts b/packages/client-runtime/src/zerops/model/calls.ts index 10b7072eb8..93ffae98cb 100644 --- a/packages/client-runtime/src/zerops/model/calls.ts +++ b/packages/client-runtime/src/zerops/model/calls.ts @@ -1,4 +1,4 @@ -import { ImageOccurrence } from "@t3tools/contracts"; +import { CallResultPage, ImageOccurrence } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; import * as Option from "effect/Option"; /** @@ -160,6 +160,19 @@ function readZeropsImages( return images; } +const decodePage = Schema.decodeUnknownOption(CallResultPage); +/** Each row's page, read once: a row read again gives the page it gave before (as `imagesRead`). */ +const pagesRead = new WeakMap(); +/** The page a row's result says its call published; one that does not decode is none. */ +function readZeropsPage(payload: Record): CallResultPage | undefined { + const data = readRecord(payload.data); + const zerops = data !== undefined ? readRecord(data.zerops) : undefined; + const raw = zerops?.page; + if (typeof raw !== "object" || raw === null) return undefined; + if (!pagesRead.has(raw)) pagesRead.set(raw, Option.getOrUndefined(decodePage(raw))); + return pagesRead.get(raw); +} + const decodeImageOccurrence = Schema.decodeUnknownOption(ImageOccurrence); function readImages(raw: ReadonlyArray): ReadonlyArray | undefined { const images: ZeropsCallImage[] = []; @@ -353,6 +366,9 @@ function buildCall(group: CallGroup, runningTurnId: string | null): ZeropsCall { } } + let page: CallResultPage | undefined; + for (const row of rows) page = readZeropsPage(row.payload) ?? page; + // The start says the response it was written in; its other rows never do. let responseId: string | undefined; for (const row of rows) { @@ -372,6 +388,7 @@ function buildCall(group: CallGroup, runningTurnId: string | null): ZeropsCall { ...(resultText !== undefined ? { resultText } : {}), truncated, ...(images !== undefined ? { images } : {}), + ...(page !== undefined ? { page } : {}), startedAt: first.createdAt, anchorActivityId: first.id, ...(settledRow !== undefined ? { settledAt: settledRow.createdAt } : {}), diff --git a/packages/client-runtime/src/zerops/model/types.ts b/packages/client-runtime/src/zerops/model/types.ts index d0becf186a..25eb4a1f80 100644 --- a/packages/client-runtime/src/zerops/model/types.ts +++ b/packages/client-runtime/src/zerops/model/types.ts @@ -1,5 +1,5 @@ import type { RestartReading } from "../../data/projections/restart.ts"; -import type { ImageOccurrence } from "@t3tools/contracts"; +import type { CallResultPage, ImageOccurrence } from "@t3tools/contracts"; /** * The session and operation model — one object per thing Mate does to the * project, identity a domain fact (the provider's tool-call id) rather than a @@ -50,6 +50,8 @@ export interface ZeropsCall { readonly truncated: boolean; /** Image content blocks the result carried (e.g. a `zerops_browser` screenshot), carried forward like `resultText` (§2.3 R3). */ readonly images?: ReadonlyArray; + /** The page it published (`zerops_publish_page`), by reference: an engine record carries it. */ + readonly page?: CallResultPage; /** `min createdAt` over the call's rows. */ readonly startedAt: string; /** The row whose `createdAt` is `startedAt` — tiebreak only, never identity. */ From fe6770f8bd97e7d34c736734ba726a7930dcf102 Mon Sep 17 00:00:00 2001 From: Ales Rechtorik Date: Sat, 10 Oct 2026 15:36:59 +0200 Subject: [PATCH 05/14] feat(web): a page the Mate publishes stands in its run above the answer Each page a run's calls published is a row of its own, after the run's card and right above its answer, live as soon as the call ends and after a reload from the window that now holds it. It is a part of the turn, as the answer is, and the answer under it no longer eases up from the card. --- .../components/chat/MessagesTimeline.logic.ts | 37 ++++++++- .../chat/engineRunCard.pipeline.test.ts | 79 ++++++++++++++++++- apps/web/src/session-logic.ts | 4 + 3 files changed, 118 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index f34c623186..863e3b702b 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -18,6 +18,7 @@ import type { ChangeLandedEvent } from "@t3tools/client-runtime/zerops"; import type { ZeropsOperation } from "@t3tools/client-runtime/zerops/model"; import type { AgentPanelModel } from "@t3tools/client-runtime/state/subagentRuntime"; import { + type CallResultPage, type CrewSeam, type MessageId, type OrchestrationLatestTurn, @@ -714,6 +715,13 @@ type MessagesTimelineRowBody = held: number; } | { kind: "outcome"; id: string; createdAt: string; outcome: OutcomeModel } + | { + /** A page the Mate published for the person: above its answer, live and after a reload. */ + kind: "page"; + id: string; + createdAt: string; + page: CallResultPage; + } | { /** * A value the Mate asked the person for (`zerops_env action=request`): theirs to answer, so @@ -1009,6 +1017,8 @@ export function rowGap( return isPersonRow(previous) || opensRun(previous) ? "part" : turnAfter(previous); } if (opensRun(row)) return isPersonRow(previous) ? "part" : turnAfter(previous); + // A page the Mate published is a part of its turn, as its answer under it is. + if (row.kind === "page") return previous.kind === "page" ? "block" : "part"; if (closesTurn(previous)) return row.kind === "outcome" ? "line" : "block"; // The result hangs from its heading or its record: they read as one. if (row.kind === "outcome" && (previous.kind === "work-line" || previous.kind === "record")) @@ -1162,6 +1172,28 @@ function approvalPending(stretch: Stretch): Extract> { + const pages: Array> = []; + for (const stretch of turn.stretches) + for (const candidate of stretch.entries) { + if (candidate.kind !== "generic-call" && candidate.kind !== "work") continue; + const page = candidate.entry.publishedPage; + if (page === undefined || pages.some((shown) => shown.page.asset.id === page.asset.id)) + continue; + pages.push({ + kind: "page", + id: `page:${candidate.entry.toolCallId ?? candidate.id}`, + createdAt: new Date(page.publishedAt).toISOString(), + page, + }); + } + return pages; +} + /** * How long a run waited, which is not the Mate's work: on the person, from * each question or approval it asked to their answer, and on its helpers, @@ -3057,8 +3089,9 @@ export function deriveMessagesTimelineRows(input: { // With nothing to report, the Mate's last word under the run eases up // from where what ran alongside it stood. + const pages = turnPages(turn); const foldsFrom: FoldsFrom | undefined = - result !== null || (turn.live && !answeredAlone) + result !== null || pages.length > 0 || (turn.live && !answeredAlone) ? undefined : { turnKey: turn.key, @@ -3067,6 +3100,8 @@ export function deriveMessagesTimelineRows(input: { }; // A provider pause owns its stage, outside the work card it follows. if (pause !== null) rows.push(pause); + // What the Mate published for the person stands right above its answer, outside the card. + for (const page of pages) rows.push(page); // Each earlier run's answer stays under the card where it stood; the latest follows them. for (const earlier of turn.earlierAnswers) rows.push({ diff --git a/apps/web/src/components/chat/engineRunCard.pipeline.test.ts b/apps/web/src/components/chat/engineRunCard.pipeline.test.ts index a1399d1bae..d9cb59debc 100644 --- a/apps/web/src/components/chat/engineRunCard.pipeline.test.ts +++ b/apps/web/src/components/chat/engineRunCard.pipeline.test.ts @@ -24,6 +24,7 @@ import { import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; +import { deriveZeropsThreadModel } from "@t3tools/client-runtime/zerops/model"; import { deriveTimelineEntries, deriveWorkLogEntries } from "../../session-logic"; import type { ChatMessage } from "../../types"; import { backgroundLineOf, jobItems } from "./backgroundLine.logic"; @@ -142,6 +143,8 @@ function render(input: { helpers?: boolean; /** The Mate is out of reach: since when, in its notice's words. */ away?: { readonly since: string; readonly words: string }; + /** Its Zerops calls drawn from their own model, as the conversation draws them. */ + zerops?: boolean; }) { const records = { runs: input.runs.map((run) => decode(run)), @@ -151,12 +154,20 @@ function render(input: { ...(input.paged ? { spans: [{ runId: run1, from: null, to: 0, reading: null }] } : {}), }; const thread = engineThreadOfRecords(key, records)!; + const zerops = input.zerops + ? deriveZeropsThreadModel({ activities: thread.activities, runningTurnId: null }) + : null; return deriveMessagesTimelineRows({ runCards: engineRunCardsOfRecords(key, records)!, timelineEntries: deriveTimelineEntries( thread.messages as ReadonlyArray, [], - deriveWorkLogEntries(thread.activities), + deriveWorkLogEntries( + thread.activities, + zerops === null ? undefined : { exclude: zerops.zeropsActivityIds }, + ), + [], + zerops?.entries ?? [], ), latestTurn: thread.latestTurn, isWorking: input.isWorking ?? false, @@ -1016,3 +1027,69 @@ it.each([ }; expect(summaryOf(true)).toEqual(summaryOf(false)); }); + +describe("a page the Mate publishes", () => { + const page = { + asset: { + id: "6f1c2b9e-0000-4000-8000-000000000001", + threadId: "conversation", + ownerId: `${run1}/i/2`, + name: "page-0123456789abcdef.html", + provenance: "capture", + original: { status: "ready", digest: "b".repeat(64), mimeType: "text/html", sizeBytes: 17 }, + }, + title: "Launch plan", + bytes: 17, + publishedAt: t0 + 40_500, + }; + const publish = call(2, 40_000, { + step: "mcp", + tool: { name: "mcp__zerops__zerops_publish_page", server: "zerops" }, + words: "MCP tool call", + input: 'mcp__zerops__zerops_publish_page: {"title":"Launch plan"}', + result: { toolName: "zerops_publish_page", resultText: '{"page":{}}', page }, + } as never); + const answer = noteItem(run1, 3, "Week one is the hardest.", { at: t0 + 41_000, answer: true }); + const summary = { + items: 3, + calls: { mcp: 1 }, + tools: { mcp__zerops__zerops_publish_page: 1 }, + answerItemId: `${run1}/i/3`, + lastItemSeq: 3, + }; + + it.each([ + { held: "live, before its answer", live: true, paged: false }, + { held: "settled, every item held", live: false, paged: false }, + { held: "after a reload, its page and answer held", live: false, paged: true }, + ])( + "a page the Mate publishes stands in its run above the answer, the same live and after a reload: $held", + ({ live, paged }) => { + const rows = render({ + runs: [ + stressRun( + live + ? ({ state: "running", turnState: "running", endedAt: null, end: null } as never) + : ({ endedAt: t0 + 42_000, summary } as never), + ), + ], + items: [ + personItem(run1, 1, "Plan the launch", { at: t0 }), + publish, + ...(live ? [] : [answer]), + ], + paged, + isWorking: live, + zerops: true, + }); + const pageRow = rows.findIndex((row) => row.kind === "page"); + const shown = rows[pageRow]; + expect(shown?.kind === "page" ? shown.page : null).toEqual(page); + expect(pageRow).toBeGreaterThan(rows.findIndex((row) => row.kind === "record")); + const reply = rows.findIndex((row) => row.kind === "message" && row.id === answer.id); + if (live) expect(reply).toBe(-1); + else expect(reply).toBe(pageRow + 1); + expect(rows.filter((row) => row.kind === "page")).toHaveLength(1); + }, + ); +}); diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index bce3de1356..b35ae81590 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -23,6 +23,7 @@ import { extractCommandOutputText, } from "@t3tools/client-runtime/work-log/presentation"; import { + type CallResultPage, CREW_SEAM_ACTIVITY_KIND, MateInterruption, CrewSeam, @@ -178,6 +179,8 @@ function readCallInput(input: Record | null): WorkCallInput | u export interface WorkLogEntry { interruption?: MateInterruption; + /** A page the call published for the person (`zerops_publish_page`), by reference. */ + publishedPage?: CallResultPage; /** * `runtime.error`: how the server says its turn ended — its agent died * (`crash`), it failed (`failed`), or the usage limit refused it @@ -1951,6 +1954,7 @@ export function zeropsCallToWorkLogEntry(call: ZeropsCall): WorkLogEntry { toolInput: call.input, toolLifecycleStatus: zeropsCallToolLifecycleStatus(call.status), ...(call.resultText !== undefined ? { detail: call.resultText } : {}), + ...(call.page !== undefined ? { publishedPage: call.page } : {}), }; } From 7025af0565f5764c1484aaed3fdb7dba8f47a65a Mon Sep 17 00:00:00 2001 From: Ales Rechtorik Date: Sat, 10 Oct 2026 15:37:00 +0200 Subject: [PATCH 06/14] feat(web): a published page is drawn in place, sandboxed from everything The page runs in an iframe sandboxed with scripts alone, never the same origin, from srcdoc that opens with a Content-Security-Policy allowing no network at all, ahead of anything the page writes. It reaches neither the network, the Mate's server nor the person's session, so it needs no proxy and no origin of its own, as upstream's preview browser does. The frame holds its height from its first paint: the height this browser last measured the page at, else the shared item cap, which also caps it, the page scrolling inside. A tiny bootstrap reports the page's height, hands a clicked http(s) link to the conversation, which opens it in a new tab only on the person's own click, and takes the app's colour tokens as CSS variables, light or dark. Open full shows it larger in a dialog. The measured heights are this browser's own layout, so their module joins the browser-storage rule's layout allowances. --- .../src/components/chat/MessagesTimeline.tsx | 15 ++ .../components/chat/PublishedPage.test.tsx | 47 ++++ .../web/src/components/chat/PublishedPage.tsx | 205 ++++++++++++++++++ apps/web/src/components/chat/pageHeights.ts | 43 ++++ .../chat/publishedPage.logic.test.ts | 162 ++++++++++++++ .../components/chat/publishedPage.logic.ts | 150 +++++++++++++ apps/web/src/index.css | 62 ++++++ .../no-remote-data-in-browser-storage.ts | 2 + 8 files changed, 686 insertions(+) create mode 100644 apps/web/src/components/chat/PublishedPage.test.tsx create mode 100644 apps/web/src/components/chat/PublishedPage.tsx create mode 100644 apps/web/src/components/chat/pageHeights.ts create mode 100644 apps/web/src/components/chat/publishedPage.logic.test.ts create mode 100644 apps/web/src/components/chat/publishedPage.logic.ts diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index c0343ab8a7..375a8feb11 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -186,6 +186,7 @@ import { } from "./userMessageTerminalContexts"; import { SkillInlineText } from "./SkillInlineText"; import { LAST_WORDS_GRACE_MS, latestFinishedWordsAt } from "./conversation.logic"; +import { PublishedPage } from "./PublishedPage"; import { TurnReport } from "./TurnReport"; import { ConversationAfterWork, ConversationWorking, dockDraws } from "./ConversationWorking"; import { useEndingsHeld } from "./useEndingsHeld"; @@ -2479,6 +2480,7 @@ function TimelineRowBody({ row }: { row: TimelineRow }) { ) : null} {row.kind === "pause" ? : null} {row.kind === "outcome" ? : null} + {row.kind === "page" ? : null} {row.kind === "vault-request" ? : null} {row.kind === "seam" ? : null} {row.kind === "crew-seam" ? : null} @@ -2868,6 +2870,19 @@ function PauseTimelineRow({ row }: { row: Extract }) { + const ctx = use(TimelineRowCtx); + if (ctx.threadRef === null) return null; + return ( + + ); +} + function OutcomeTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); const [settling] = useState(() => watchedTurnKeys.delete(row.outcome.turnKey)); diff --git a/apps/web/src/components/chat/PublishedPage.test.tsx b/apps/web/src/components/chat/PublishedPage.test.tsx new file mode 100644 index 0000000000..da5917a4fa --- /dev/null +++ b/apps/web/src/components/chat/PublishedPage.test.tsx @@ -0,0 +1,47 @@ +import { markupDom } from "../../../test/markupDom"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vite-plus/test"; + +import { PublishedPageFrame } from "./PublishedPage"; +import { PAGE_POLICY } from "./publishedPage.logic"; + +const theme = { scheme: "light" as const, vars: { "--background": "#fff" } }; +/** A page that tries every way out: the Mate's own API, the network, the person's session. */ +const prying = `
`; + +const frameOf = (html: string | null, failed = false) => + markupDom( + renderToStaticMarkup( + , + ), + ).querySelector("iframe"); + +describe("a published page in the conversation", () => { + it("a published page cannot reach the network or the Mate's files", () => { + const frame = frameOf(prying); + expect(frame).not.toBeNull(); + // Scripts alone: no same origin (the Mate's server, the session), no popups, forms or top navigation. + expect(frame!.getAttribute("sandbox")).toBe("allow-scripts"); + expect(frame!.getAttribute("src")).toBeNull(); + const doc = frame!.getAttribute("srcdoc")!; + const policy = doc.indexOf(`content="${PAGE_POLICY}"`); + expect(policy).toBeGreaterThan(-1); + expect(policy).toBeLessThan(doc.indexOf("fetch(")); + expect(PAGE_POLICY).toContain("default-src 'none'"); + expect(frame!.getAttribute("title")).toBe("Launch plan"); + }); + + it.each([ + { title: "while it is read", html: null, failed: false }, + { title: "when it could not be read", html: null, failed: true }, + ])("holds no frame $title", ({ html, failed }) => { + expect(frameOf(html, failed)).toBeNull(); + }); +}); diff --git a/apps/web/src/components/chat/PublishedPage.tsx b/apps/web/src/components/chat/PublishedPage.tsx new file mode 100644 index 0000000000..9b8b9698ae --- /dev/null +++ b/apps/web/src/components/chat/PublishedPage.tsx @@ -0,0 +1,205 @@ +import type { CallResultPage, EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { Maximize2Icon } from "lucide-react"; +import { useEffect, useMemo, useRef, useState } from "react"; + +import { useMateImage } from "~/assets/MateImages"; +import { useTheme } from "~/hooks/useTheme"; +import { Button } from "../ui/button"; +import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; +import { + PAGE_THEME_VARS, + linkToOpen, + pageDocument, + pageFrameHeight, + readPageMessage, + themeRule, + type PageTheme, +} from "./publishedPage.logic"; +import { rememberPageHeight, rememberedPageHeight } from "./pageHeights"; + +/** The conversation's colours as a page reads them, read off the app's own tokens. */ +function usePageTheme(): PageTheme { + const { resolvedTheme } = useTheme(); + return useMemo(() => { + const style = + typeof document === "undefined" ? null : getComputedStyle(document.documentElement); + const vars: Record = {}; + for (const name of PAGE_THEME_VARS) { + const value = style?.getPropertyValue(name).trim(); + if (value) vars[name] = value; + } + return { scheme: resolvedTheme, vars }; + }, [resolvedTheme]); +} + +/** A blob's text, once it is read; null until then. */ +function useBlobText(blob: Blob | null): string | null { + const [read, setRead] = useState<{ blob: Blob; text: string } | null>(null); + useEffect(() => { + if (blob === null) return; + let live = true; + void blob.text().then((text) => { + if (live) setRead({ blob, text }); + }); + return () => { + live = false; + }; + }, [blob]); + return read !== null && read.blob === blob ? read.text : null; +} + +export interface PublishedPageFrameProps { + /** The page's asset: what its height is remembered by. */ + readonly id: string; + readonly title: string; + /** The page's HTML; null while it is read. */ + readonly html: string | null; + readonly theme: PageTheme; + /** It could not be read. */ + readonly failed?: boolean; + /** Drawn full size: the frame takes its box's height, not the page's. */ + readonly full?: boolean; +} + +/** + * The page in its frame: sandboxed with scripts alone, behind a policy that allows no network + * (`publishedPage.logic.ts`). The frame stands at the page's remembered height from its first paint + * — at the shared cap while that is unknown — and follows the height the page says, at most the + * cap: a taller page scrolls inside it. + */ +export function PublishedPageFrame(props: PublishedPageFrameProps) { + const { id, title, html, theme, failed = false, full = false } = props; + const frameRef = useRef(null); + const [content, setContent] = useState(() => rememberedPageHeight(id)); + // The page is written once, in the colours it opened with; later colours reach it as a message. + const [opened] = useState(theme); + const document_ = useMemo( + () => (html === null ? null : pageDocument(html, opened)), + [html, opened], + ); + + useEffect(() => { + const listen = (event: MessageEvent) => { + const frame = frameRef.current; + if (frame === null || event.source !== frame.contentWindow) return; + const message = readPageMessage(event.data); + if (message === null) return; + if (message.kind === "height") { + setContent(message.height); + // Full size, the page lays out wider: its height in the conversation is another. + if (!full) rememberPageHeight(id, message.height); + return; + } + const url = linkToOpen(message, { + fromFrame: true, + focused: document.activeElement === frame, + activated: navigator.userActivation?.isActive ?? true, + }); + if (url !== null) window.open(url, "_blank", "noopener,noreferrer"); + }; + window.addEventListener("message", listen); + return () => window.removeEventListener("message", listen); + }, [id, full]); + + useEffect(() => { + if (theme === opened) return; + frameRef.current?.contentWindow?.postMessage( + { mate: "page-theme", rule: themeRule(theme) }, + "*", + ); + }, [theme, opened]); + + const height = full ? null : pageFrameHeight(content); + return ( +
+ {document_ !== null ? ( + ` + + `` + ); +} + +/** The page inside the wrapper, as its frame's `srcdoc` holds it (for a test to read). */ +export function innerDocumentOf(document: string): string | null { + const match = /