diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index d921045eda..3b0aaa8223 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -410,22 +410,20 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i : /^mate-asset:([a-f0-9-]{36})$/.exec(input.resource.path)?.[1]; if (occurrenceId) { const config = yield* ServerConfig.ServerConfig; + const store = contentAssetsAt(config.stateDir); + // A page a call published is kept apart from the pictures, under the same reference. const occurrence = yield* Effect.tryPromise({ - try: () => contentAssetsAt(config.stateDir).occurrence(occurrenceId), + try: () => store.occurrence(occurrenceId).catch(() => store.pageOccurrence(occurrenceId)), catch: (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }), }); - if (occurrence.original.status !== "ready") + const original = occurrence.original; + if (original.status !== "ready") return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource }); return { - relativeUrl: `/api/assets/objects/${occurrence.original.digest}/original`, + relativeUrl: `/api/assets/objects/${original.digest}/original`, expiresAt: 0, - ...(occurrence.original.width && occurrence.original.height - ? { - imageDimensions: { - width: occurrence.original.width, - height: occurrence.original.height, - }, - } + ...("width" in original && original.width && original.height + ? { imageDimensions: { width: original.width, height: original.height } } : {}), }; } diff --git a/apps/server/src/assets/ContentAssetHttp.test.ts b/apps/server/src/assets/ContentAssetHttp.test.ts index a643640ddd..c55a033ae3 100644 --- a/apps/server/src/assets/ContentAssetHttp.test.ts +++ b/apps/server/src/assets/ContentAssetHttp.test.ts @@ -138,3 +138,34 @@ 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(["call"], Buffer.from(html), { + threadId: ThreadId.make("thread"), + ownerId: "call", + name: "page-1.html", + }), + ); + const object = yield* Effect.promise(() => store.object(page.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.test.ts b/apps/server/src/assets/ContentAssets.test.ts index c4f4fc6045..73d1814c24 100644 --- a/apps/server/src/assets/ContentAssets.test.ts +++ b/apps/server/src/assets/ContentAssets.test.ts @@ -6,7 +6,7 @@ import * as NodePath from "node:path"; import { ThreadId } from "@t3tools/contracts"; import sharp from "sharp"; -import { afterEach, expect, it } from "vite-plus/test"; +import { afterEach, describe, expect, it } from "vite-plus/test"; import { ContentAssets } from "./ContentAssets.ts"; @@ -240,3 +240,55 @@ it("a pressure retry of the preview recipe never publishes a reference to reclai await NodeFSP.rm(directory, { recursive: true, force: true }); } }); + +describe("a page an agent published, in the asset store", () => { + const pageOwner = { threadId: ThreadId.make("thread"), ownerId: "call", name: "page-1.html" }; + + it("is kept apart from the pictures, so a build that reads only pictures never meets it", async () => { + const { root, store } = await fixture(); + const picture = await store.ingestBytes(await image(), owner); + const page = await store.ingestPage(["call"], Buffer.from("

Plan

"), pageOwner); + const pictures = await NodeFSP.readdir(NodePath.join(root, "home", "occurrences")); + expect(pictures).toEqual([`${picture.id}.json`]); + expect(await store.pageOccurrence(page.id)).toEqual(page); + expect(await store.pageOwners(page.original.digest)).toEqual([page]); + expect(await store.owners(page.original.digest)).toEqual([]); + }); + + it("is kept once for the same call, however often it is told", async () => { + const { store } = await fixture(); + const first = await store.ingestPage(["call"], Buffer.from("

Plan

"), pageOwner); + const again = await store.ingestPage(["call"], Buffer.from("

Plan

"), pageOwner); + expect(again.id).toBe(first.id); + }); + + it("is never the same object as the same bytes kept as a picture", async () => { + const { store } = await fixture(); + const svg = Buffer.from(''); + const picture = await store.ingestBytes(svg, { ...owner, name: "dot.svg" }); + const page = await store.ingestPage(["call"], svg, pageOwner); + if (picture.original.status !== "ready") throw new Error("picture refused"); + expect(page.original.digest).not.toBe(picture.original.digest); + expect((await store.object(picture.original.digest)).mimeType).toBe("image/svg+xml"); + expect((await store.object(page.original.digest)).mimeType).toBe("text/html"); + }); +}); + +it("an occurrence this build cannot read never hides every other picture's readers", async () => { + const { root, store } = await fixture(); + const picture = await store.ingestBytes(await image(), owner); + if (picture.original.status !== "ready") throw new Error("picture refused"); + await NodeFSP.writeFile( + NodePath.join(root, "home", "occurrences", "00000000-0000-4000-8000-000000000000.json"), + JSON.stringify({ + ...picture, + id: "x", + original: { ...picture.original, mimeType: "text/x-newer" }, + }), + ); + expect( + (await new ContentAssets(NodePath.join(root, "home")).owners(picture.original.digest)).map( + (each) => each.id, + ), + ).toEqual([picture.id]); +}); diff --git a/apps/server/src/assets/ContentAssets.ts b/apps/server/src/assets/ContentAssets.ts index 76731a2be2..bbaedccc2d 100644 --- a/apps/server/src/assets/ContentAssets.ts +++ b/apps/server/src/assets/ContentAssets.ts @@ -4,9 +4,10 @@ import * as NodeFS from "node:fs"; import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; -import type { AssetRepresentation, ImageOccurrence } from "@t3tools/contracts"; +import type { AssetRepresentation, ImageOccurrence, PageOccurrence } from "@t3tools/contracts"; import { ImageOccurrence as OccurrenceSchema, + PageOccurrence as PageOccurrenceSchema, AssetRepresentation as RepresentationSchema, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; @@ -14,8 +15,12 @@ import { mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview"; import sharp, { type Metadata } from "sharp"; const decodeOccurrence = Schema.decodeUnknownSync(OccurrenceSchema); +const decodePageOccurrence = Schema.decodeUnknownSync(PageOccurrenceSchema); const decodeRepresentation = Schema.decodeUnknownSync(RepresentationSchema); const digestOf = (bytes: Uint8Array) => NodeCrypto.createHash("sha256").update(bytes).digest("hex"); +/** A page's object identity: its bytes as a page, never the same object as the same bytes as a picture. */ +const pageDigestOf = (bytes: Uint8Array) => + NodeCrypto.createHash("sha256").update("mate-page\0").update(bytes).digest("hex"); const hasCode = (error: unknown, code: string) => typeof error === "object" && error !== null && "code" in error && error.code === code; export class ContentAssetError extends Error { @@ -56,6 +61,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) => { @@ -72,6 +79,7 @@ export const contentAssetsAt = (stateDir: string) => { export class ContentAssets { private mutation: Promise = Promise.resolve(); private ownership: Promise> | undefined; + private pageOwnership: Promise> | undefined; private previewOwnership: Promise>> | undefined; private readonly backfilling = new Map>(); private readonly encoding = new Map>(); @@ -374,6 +382,93 @@ export class ContentAssets { ); } + /** + * A page an agent published, kept as its bytes came and never read as a picture, even one that + * opens with an SVG. It is kept apart from the pictures: its object's identity says it is a page + * (`pageDigestOf`), and its occurrence lives in `pages/`, an index a build that reads only + * pictures never opens. Kept once per `key`: the same call told again keeps nothing twice. + */ + async ingestPage( + key: ReadonlyArray, + bytes: Uint8Array, + owner: Omit, + ): Promise { + const binding = NodePath.join( + this.directory, + "pages", + "bindings", + `${digestOf(Buffer.from(JSON.stringify(key)))}.json`, + ); + const bound = await NodeFSP.readFile(binding, "utf8") + .then((text) => this.pageOccurrence((JSON.parse(text) as { id: string }).id)) + .catch(() => null); + if (bound !== null) return bound; + const digest = pageDigestOf(bytes); + const file = NodePath.join(this.directory, "originals", digest); + const exists = await this.object(digest).then( + (object) => object.mimeType === PAGE_MIME_TYPE, + () => false, + ); + if (!exists) { + await this.atomic(file, bytes); + await NodeFSP.chmod(file, 0o444); + const representation: AssetRepresentation = { + digest, + mimeType: PAGE_MIME_TYPE, + sizeBytes: bytes.byteLength, + relativeUrl: `/api/assets/objects/${digest}/original`, + }; + await this.atomic(`${file}.json`, Buffer.from(JSON.stringify(representation))); + } + const occurrence: PageOccurrence = { + ...owner, + id: NodeCrypto.randomUUID(), + provenance: "capture", + original: { status: "ready", digest, mimeType: PAGE_MIME_TYPE, sizeBytes: bytes.byteLength }, + }; + await this.atomic( + NodePath.join(this.directory, "pages", `${occurrence.id}.json`), + Buffer.from(JSON.stringify(occurrence)), + ); + await this.atomic(binding, Buffer.from(JSON.stringify({ id: occurrence.id }))); + if (this.pageOwnership) { + const owners = await this.pageOwnership.catch(() => null); + owners?.set(digest, [...(owners.get(digest) ?? []), occurrence]); + } + return occurrence; + } + + async pageOccurrence(id: string): Promise { + if (!/^[a-f0-9-]{36}$/.test(id)) throw new ContentAssetError("object-missing"); + try { + return decodePageOccurrence( + JSON.parse( + await NodeFSP.readFile(NodePath.join(this.directory, "pages", `${id}.json`), "utf8"), + ), + ); + } catch { + throw new ContentAssetError("object-missing"); + } + } + + /** The pages whose object is `digest`: who may read it. */ + async pageOwners(digest: string): Promise> { + this.pageOwnership ??= (async () => { + const owners = new Map(); + const files = await NodeFSP.readdir(NodePath.join(this.directory, "pages")).catch(() => []); + for (const file of files.filter((name) => name.endsWith(".json"))) { + const page = await this.pageOccurrence(file.slice(0, -5)).catch(() => null); + if (page === null) continue; + owners.set(page.original.digest, [...(owners.get(page.original.digest) ?? []), page]); + } + return owners; + })().catch((error) => { + this.pageOwnership = undefined; + throw error; + }); + return (await this.pageOwnership).get(digest) ?? []; + } + async occurrence(id: string): Promise { if (!/^[a-f0-9-]{36}$/.test(id)) throw new ContentAssetError("object-missing"); try { @@ -421,8 +516,9 @@ export class ContentAssets { const owners = new Map(); const files = await NodeFSP.readdir(NodePath.join(this.directory, "occurrences")); for (const file of files.filter((name) => name.endsWith(".json"))) { - const occurrence = await this.occurrence(file.slice(0, -5)); - if (occurrence.original.status !== "ready") continue; + // Each on its own: one occurrence this build cannot read never hides every other. + const occurrence = await this.occurrence(file.slice(0, -5)).catch(() => null); + if (occurrence === null || occurrence.original.status !== "ready") continue; const values = owners.get(occurrence.original.digest) ?? []; values.push(occurrence); owners.set(occurrence.original.digest, values); diff --git a/apps/server/src/assets/ImageAsset.ts b/apps/server/src/assets/ImageAsset.ts index b58e71c904..0c2be64f54 100644 --- a/apps/server/src/assets/ImageAsset.ts +++ b/apps/server/src/assets/ImageAsset.ts @@ -57,6 +57,27 @@ export const resolveImageAsset = Effect.fn("resolveImageAsset")(function* ( : /^mate-asset:[a-f0-9-]{36}:(source-missing|source-changed|storage-full|unsupported|persistence-failed)$/.exec( resource.path, )?.[1]; + // A page a call published, under the same reference as a picture: its document, no picture's + // occurrence, to its own conversation alone. + const page = + occurrenceId && resource._tag !== "attachment" && resource._tag !== "project-favicon" + ? yield* Effect.promise(() => store.pageOccurrence(occurrenceId).catch(() => null)) + : null; + if (page !== null) { + if (!(input.ownsThread ? input.ownsThread(page.threadId) : page.threadId === threadId)) + return yield* Effect.fail(new ContentAssetError("object-missing")); + const relativeUrl = `/api/assets/objects/${page.original.digest}/original`; + return { + relativeUrl, + expiresAt: 0, + representation: { + digest: page.original.digest, + mimeType: page.original.mimeType, + sizeBytes: page.original.sizeBytes, + relativeUrl, + }, + } satisfies AssetCreateUrlResult; + } let occurrence; if (occurrenceId) { occurrence = yield* Effect.tryPromise({ diff --git a/apps/server/src/engine/pump/SessionHost.test.ts b/apps/server/src/engine/pump/SessionHost.test.ts index ef04d4efa3..a290d1f2f6 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,54 @@ 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..c4b235f34b 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,28 @@ 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..b3db9db499 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,94 @@ 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")); + // Another session's pages: named as zcp names them, not this session's. + const theirs = NodePath.join(root, "other", ".zcp", "state", "pages"); + NodeFS.mkdirSync(theirs, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(theirs, "page-5555555555555555.html"), "

theirs

"); + return { + pages, + outside, + theirs, + 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"], + ["another session's page", "theirs"], + ] as const)("never reads %s", ([_what, name]) => + Effect.gen(function* () { + const { pages, outside, theirs, store } = pagesOf(); + const file = + name === "outside" + ? outside + : name === "relative" + ? ".zcp/state/pages/page-0123456789abcdef.html" + : name === "theirs" + ? NodePath.join(theirs, "page-5555555555555555.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..eaf1d422ff 100644 --- a/apps/server/src/engine/pump/callPictures.ts +++ b/apps/server/src/engine/pump/callPictures.ts @@ -8,13 +8,19 @@ * * @module engine/pump/callPictures */ +import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; -import type { - CallResultPicture, - ImageOccurrence, - SpiToolCallImage, - ThreadId, +import * as NodeFS from "node:fs"; + +import { + PAGE_MAX_BYTES, + type CallResult, + type CallResultPicture, + type ImageOccurrence, + type PageOccurrence, + type SpiToolCallImage, + type ThreadId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; @@ -44,6 +50,69 @@ 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: PageOccurrence; 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 session's own `.zcp/state/pages` (`docs/spec-mate.md` §5.9 in zcp). Nothing else is read. + */ +const PAGE_NAME = /^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; + } +} + +/** + * A page file's bytes, read as a picture the call looked at is (`ContentAssets.ingestFile`): only + * a regular file named like zcp's pages, directly in the session's own `.zcp/state/pages`, opened + * without following a link and without waiting on a FIFO, checked on the open handle, at most the + * cap. Anything else is none. + */ +async function readPage(cwd: string, file: string): Promise { + if (!NodePath.isAbsolute(file) || !PAGE_NAME.test(NodePath.basename(file))) return null; + const pages = await NodeFSP.realpath(NodePath.join(cwd, ".zcp", "state", "pages")); + if ((await NodeFSP.realpath(NodePath.dirname(file))) !== pages) return null; + const handle = await NodeFSP.open( + NodePath.join(pages, NodePath.basename(file)), + NodeFS.constants.O_RDONLY | NodeFS.constants.O_NOFOLLOW | NodeFS.constants.O_NONBLOCK, + ); + try { + const stat = await handle.stat(); + if (!stat.isFile() || stat.size > PAGE_MAX_BYTES) return null; + const buffer = Buffer.alloc(PAGE_MAX_BYTES + 1); + let read = 0; + for (;;) { + const { bytesRead } = await handle.read(buffer, read, buffer.length - read, read); + if (bytesRead === 0) break; + read += bytesRead; + if (read > PAGE_MAX_BYTES) return null; + } + return buffer.subarray(0, read); + } finally { + await handle.close(); + } } /** @@ -117,5 +186,20 @@ export const makeCallPictures = ( : {}), }; }).pipe(Effect.orElseSucceed(() => null)), + page: (thread, key, file) => + Effect.gen(function* () { + const cwd = yield* cwdOf(thread); + if (cwd === undefined) return null; + return yield* Effect.tryPromise(async () => { + const bytes = await readPage(cwd, file); + if (bytes === null || bytes.byteLength === 0) return null; + const asset = await assets().ingestPage(["page", thread, key, file], bytes, { + threadId: thread, + ownerId: key, + name: NodePath.basename(file), + }); + return { asset, bytes: bytes.byteLength }; + }); + }).pipe(Effect.orElseSucceed(() => null)), }; }; 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/testing/pump/scriptedProvider.ts b/apps/server/src/engine/testing/pump/scriptedProvider.ts index da02236e49..16e4c05f29 100644 --- a/apps/server/src/engine/testing/pump/scriptedProvider.ts +++ b/apps/server/src/engine/testing/pump/scriptedProvider.ts @@ -55,6 +55,8 @@ interface Session { held: Deferred.Deferred | null; readonly requests: Map; model: string | undefined; + /** Where the session runs, as it was started: where a call's files resolve. */ + cwd: string | undefined; } /** Claude names its session with a UUID: one per provider thread here. */ @@ -189,6 +191,7 @@ export const makeScriptedProvider = (options: ScriptedProviderOptions) => threadId: session.thread as ThreadId, resumeCursor: cursorOf(session), ...(session.model === undefined ? {} : { model: session.model }), + ...(session.cwd === undefined ? {} : { cwd: session.cwd }), createdAt: NOW, updatedAt: NOW, }) as ProviderSession; @@ -261,6 +264,7 @@ export const makeScriptedProvider = (options: ScriptedProviderOptions) => held: null, requests: new Map(), model: input.modelSelection?.model, + cwd: input.cwd, }; sessions.set(threadId, session); yield* emit("session.started", threadId); diff --git a/apps/server/src/engine/wire/EngineWire.test.ts b/apps/server/src/engine/wire/EngineWire.test.ts index 57d4cf6764..803905904c 100644 --- a/apps/server/src/engine/wire/EngineWire.test.ts +++ b/apps/server/src/engine/wire/EngineWire.test.ts @@ -693,6 +693,70 @@ 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" }, + }, + }); + // zcp keeps it in the session's own workspace, where the pump reads it. + const pages = NodePath.join(w.dir, ".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 = diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 653c7fa2f0..e14b329a9a 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -422,7 +422,11 @@ export const assetRouteLayer = HttpRouter.add( return yield* Effect.fail(contentAssetFailure("access-unverified", 503)); const preview = match[2] === "preview"; const owners = yield* Effect.tryPromise({ - try: () => store.owners(match[1]!, preview), + // A page's readers are its own index's: pages are kept apart from pictures. + try: async () => [ + ...(await store.owners(match[1]!, preview)), + ...(preview ? [] : await store.pageOwners(match[1]!)), + ], catch: () => contentAssetFailure("access-unverified", 503), }); let readable = false; 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/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..ed9d4b9e9d --- /dev/null +++ b/apps/web/src/components/chat/PublishedPage.test.tsx @@ -0,0 +1,43 @@ +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, WRAPPER_POLICY, innerDocumentOf } 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 wrapper = frame!.getAttribute("srcdoc")!; + expect(wrapper).toContain(`content="${WRAPPER_POLICY}"`); + const doc = innerDocumentOf(wrapper)!; + 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..c248257d1b --- /dev/null +++ b/apps/web/src/components/chat/PublishedPage.tsx @@ -0,0 +1,269 @@ +import type { CallResultPage, EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { Maximize2Icon } from "lucide-react"; +import { useCallback, 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, + themeMessage, + type PageTheme, +} from "./publishedPage.logic"; + +/** The conversation's colours as the app's own tokens hold them now. */ +function readTheme(scheme: PageTheme["scheme"]): PageTheme { + 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, vars }; +} + +/** + * The conversation's colours as a page reads them, read again on any change of the app's theme — + * light or dark, a palette, a contrast — that the root element's attributes carry. + */ +function usePageTheme(): PageTheme { + const { resolvedTheme } = useTheme(); + const [theme, setTheme] = useState(() => readTheme(resolvedTheme)); + useEffect(() => { + const refresh = () => + setTheme((held) => { + const now = readTheme(resolvedTheme); + return JSON.stringify(now) === JSON.stringify(held) ? held : now; + }); + refresh(); + const observer = new MutationObserver(refresh); + observer.observe(document.documentElement, { attributes: true }); + return () => observer.disconnect(); + }, [resolvedTheme]); + return theme; +} + +/** 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; +} + +/** The element's nearest scrolling ancestor: the conversation's list, where it has one. */ +function scrollParentOf(element: HTMLElement): HTMLElement | null { + for (let parent = element.parentElement; parent !== null; parent = parent.parentElement) { + const overflow = getComputedStyle(parent).overflowY; + if (overflow === "auto" || overflow === "scroll" || overflow === "overlay") return parent; + } + return null; +} + +/** + * Whether the element is near the view of the list it scrolls in: a page's frame runs only there, + * so pages far off-screen — a spinning one among them — never hold the conversation, and the list's + * own clipping never unmounts one in sight. A page spinning in view holds the browser as any page + * would: a browser's limit, not this frame's. Without an observer (a server render), it always is. + */ +function useNearView(ref: React.RefObject): boolean { + const [near, setNear] = useState(() => typeof IntersectionObserver === "undefined"); + useEffect(() => { + const element = ref.current; + if (element === null || typeof IntersectionObserver === "undefined") return; + const observer = new IntersectionObserver( + (entries) => setNear(entries.some((entry) => entry.isIntersecting)), + { root: scrollParentOf(element), rootMargin: "100% 0px" }, + ); + observer.observe(element); + return () => observer.disconnect(); + }, [ref]); + return near; +} + +export interface PublishedPageFrameProps { + 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 frames: two deep, sandboxed with scripts alone, its navigation refused before + * it leaves (`publishedPage.logic.ts`). The frame stands at the shared cap from its first paint + * until the page says its height, then eases to it, at most the cap: a taller page scrolls inside + * it. A page whose frame loads again — a navigation the wrapper refused, a reload — is taken down + * at once and never heard from again; the person may show the published page again. + */ +export function PublishedPageFrame(props: PublishedPageFrameProps) { + const { title, html, theme, failed = false, full = false } = props; + const boxRef = useRef(null); + const frameRef = useRef(null); + const near = useNearView(boxRef); + const [content, setContent] = useState(null); + const [left, setLeft] = useState(false); + /** Each showing of the page is a frame of its own: its loads are counted from none. */ + const [showing, setShowing] = useState(0); + const loads = useRef(0); + // Each frame element counts its own loads: one mounted again as it nears the view starts at none. + const attach = useCallback((frame: HTMLIFrameElement | null) => { + frameRef.current = frame; + loads.current = 0; + }, []); + // 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 || loads.current > 1) return; + const message = readPageMessage(event.data, event.origin); + if (message === null) return; + if (message.kind === "left") { + setLeft(true); + return; + } + if (message.kind === "height") { + setContent(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); + }, []); + + useEffect(() => { + if (theme === opened) return; + frameRef.current?.contentWindow?.postMessage(themeMessage(theme), "*"); + }, [theme, opened]); + + const height = full ? null : pageFrameHeight(content); + const shown = document_ !== null && !left && near; + return ( +
+ {shown ? ( + ` + + `` + ); +} + +/** 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 = /