TypeScript
fix: guests see the screenshots the agent shows in its replies (#26323)
Theo Browne50d3a31ffd8a
diff --git a/apps/server/src/guest/GuestShareService.test.ts b/apps/server/src/guest/GuestShareService.test.tsindex 2f0366d4d2d..31acd7bdb60 100644--- a/apps/server/src/guest/GuestShareService.test.ts+++ b/apps/server/src/guest/GuestShareService.test.ts@@ -5,22 +5,26 @@ import {CommandId,EventId,GuestShareId,+ type GuestStreamEvent,MessageId,type OrchestrationV2TurnItem,ProjectId,ProviderDriverKind,ProviderInstanceId,+ RunId,ThreadId,TurnItemId,} from "@t3tools/contracts";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";+import * as Deferred from "effect/Deferred";import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";import * as FileSystem from "effect/FileSystem";import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";+import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";import * as Stream from "effect/Stream";import * as TestClock from "effect/testing/TestClock";@@ -842,3 +846,270 @@ it.effect("serves the shared thread's files to its guest, never another thread'sassert.isDefined(shareId);}).pipe(Effect.scoped, Effect.provide(layerTest)),);++it.effect("serves an image on the host only when an agent reply the guest sees shows it", () =>+ Effect.gen(function* () {+ const { orchestrator, guestShares } = yield* shareThread;+ const runId = yield* ownerRun;+ const fileSystem = yield* FileSystem.FileSystem;+ const directory = yield* fileSystem.makeTempDirectoryScoped();+ const shot = `${directory}/my shot.png`;+ const fileUrl = `${directory}/file-url.png`;+ const page = `${directory}/page.png`;+ const fromUser = `${directory}/from-user.png`;+ const unnamed = `${directory}/unnamed.png`;+ const later = `${directory}/later.png`;+ for (const path of [shot, fileUrl, fromUser, unnamed, later]) {+ yield* fileSystem.writeFile(path, PNG);+ }+ yield* fileSystem.writeFileString(page, "<script>alert(1)</script>");+ const eventSink = yield* EventSink.EventSinkV2;+ const now = yield* DateTime.now;+ const run = (yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs[0];+ const item = (+ id: string,+ ordinal: number,+ fields:+ | { readonly type: "assistant_message"; readonly text: string }+ | { readonly type: "user_message"; readonly text: string },+ target: { readonly threadId: ThreadId; readonly runId: RunId } = { threadId, runId },+ ) => ({+ id: EventId.make(`event:${id}`),+ type: "turn-item.updated" as const,+ threadId: target.threadId,+ driver: ProviderDriverKind.make("codex"),+ providerInstanceId: instanceId,+ occurredAt: now,+ payload: {+ id: TurnItemId.make(id),+ threadId: target.threadId,+ runId: target.runId,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal,+ title: null,+ status: "completed" as const,+ startedAt: now,+ completedAt: now,+ updatedAt: now,+ messageId: MessageId.make(id),+ ...(fields.type === "assistant_message"+ ? { ...fields, streaming: false }+ : {+ ...fields,+ createdBy: "user" as const,+ creationSource: "web" as const,+ inputIntent: "turn_start" as const,+ attachments: [],+ }),+ },+ });+ yield* eventSink.write({+ events: [+ item("item:agent-images", 1, {+ type: "assistant_message",+ text: `Done:  }) `,+ }),+ // A guest's sent message is a user message; it must not open files on the host.+ item("item:guest-image", 2, { type: "user_message", text: `` }),+ {+ id: EventId.make("event:run-done"),+ type: "run.updated" as const,+ threadId,+ runId,+ providerInstanceId: instanceId,+ occurredAt: now,+ payload: { ...run!, status: "completed" as const, completedAt: now },+ },+ ],+ });+ // The guest watches a fork, which shows these replies as inherited history.+ const forkId = ThreadId.make("thread:guest-share-fork");+ yield* orchestrator.dispatch({+ type: "thread.fork",+ commandId: CommandId.make("fork"),+ sourceThreadId: threadId,+ targetThreadId: forkId,+ sourcePoint: { type: "run", runId },+ createdBy: "user",+ creationSource: "web",+ });+ const { url } = yield* guestShares.create({ threadId: forkId });+ const { token: session } = yield* guestShares.redeem({+ credential: url.slice(url.indexOf("#") + 1),+ name: "Sam",+ });++ // The guest's page opens, and its stream sends the replies the fork inherits.+ const sent = yield* Queue.unbounded<GuestStreamEvent>();+ yield* Stream.runForEach(yield* guestShares.stream(session), (event) =>+ Queue.offer(sent, event),+ ).pipe(Effect.forkScoped);+ const sentItem = Effect.fn(function* (id: string) {+ for (;;) {+ const event = yield* Queue.take(sent);+ if (+ event.type === "thread" &&+ event.item.kind === "event" &&+ event.item.event.type === "turn-item.updated" &&+ event.item.event.payload.id === id+ ) {+ return;+ }+ }+ });++ // The agent shows another screenshot live, then enough rows to push the first reply out of+ // the window, before the page asks for any image.+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("fork-message"),+ threadId: forkId,+ messageId: MessageId.make("message:fork"),+ text: "One more",+ attachments: [],+ dispatchMode: { type: "defer_start" },+ createdBy: "user",+ creationSource: "web",+ });+ const forkRun = (yield* orchestrator.getThreadRecords(forkId, ["runs"])).runs.at(-1)!;+ const inFork = { threadId: forkId, runId: forkRun.id };+ yield* eventSink.write({+ events: [+ item(+ "item:later-image",+ 1,+ { type: "assistant_message", text: `` },+ inFork,+ ),+ ...Array.from({ length: 600 }, (_, index) =>+ item(+ `item:filler-${index}`,+ index + 2,+ { type: "assistant_message", text: "Working." },+ inFork,+ ),+ ),+ ],+ });+ yield* sentItem("item:later-image");++ // The page still shows every reply it was sent, so each image loads.+ for (const path of [shot, fileUrl, later]) {+ assert.deepStrictEqual(yield* guestShares.media(session, path), {+ path,+ mimeType: "image/png",+ });+ }+ for (const path of [page, fromUser, unnamed, `${directory}/missing.png`]) {+ assert.equal((yield* Effect.flip(guestShares.media(session, path))).reason, "unavailable");+ }++ // A reply edited to drop its image stops allowing it.+ yield* eventSink.write({+ events: [+ {+ ...item("item:later-image", 1, { type: "assistant_message", text: "Gone." }, inFork),+ id: EventId.make("event:later-image-edited"),+ },+ ],+ });+ yield* sentItem("item:later-image");+ assert.equal((yield* Effect.flip(guestShares.media(session, later))).reason, "unavailable");+ }).pipe(Effect.scoped, Effect.provide(layerTest)),+);++it.effect("keeps a connected guest's images while other shares come and go", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const directory = yield* fileSystem.makeTempDirectoryScoped();+ const shot = `${directory}/shot.png`;+ yield* fileSystem.writeFile(shot, PNG);+ const eventSink = yield* EventSink.EventSinkV2;+ const now = yield* DateTime.now;+ /** A shared thread whose agent reply shows the screenshot, and its guest's session. */+ const sharedWithImage = Effect.fn(function* (id: ThreadId) {+ const { orchestrator, guestShares, credential } = yield* shareThreadFor(id);+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make(`message:${id}`),+ threadId: id,+ messageId: MessageId.make(`message:${id}`),+ text: "Show me",+ attachments: [],+ dispatchMode: { type: "defer_start" },+ createdBy: "user",+ creationSource: "web",+ });+ const runId = (yield* orchestrator.getThreadRecords(id, ["runs"])).runs[0]!.id;+ yield* eventSink.write({+ events: [+ {+ id: EventId.make(`event:reply:${id}`),+ type: "turn-item.updated",+ threadId: id,+ driver: ProviderDriverKind.make("codex"),+ providerInstanceId: instanceId,+ occurredAt: now,+ payload: {+ id: TurnItemId.make(`item:reply:${id}`),+ threadId: id,+ runId,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 1,+ title: null,+ status: "completed",+ startedAt: now,+ completedAt: now,+ updatedAt: now,+ type: "assistant_message",+ messageId: MessageId.make(`item:reply:${id}`),+ text: ``,+ streaming: false,+ },+ },+ ],+ });+ const { token } = yield* guestShares.redeem({ credential, name: "Sam" });+ return { guestShares, token };+ });++ // This guest's page stays open while more guests than the record keeps open and close theirs.+ const { guestShares, token } = yield* sharedWithImage(threadId);+ const opened = yield* Deferred.make<void>();+ yield* Stream.runForEach(yield* guestShares.stream(token), () =>+ Deferred.succeed(opened, undefined),+ ).pipe(Effect.forkScoped);+ yield* Deferred.await(opened);+ const closedTokens: Array<string> = [];+ for (let index = 0; index < 65; index++) {+ const other = yield* sharedWithImage(ThreadId.make(`thread:other-${index}`));+ const events = yield* guestShares.stream(other.token);+ // The first is built but never read, as for a HEAD request; the rest open and close.+ if (index > 0) yield* Stream.runDrain(Stream.take(events, 2));+ closedTokens.push(other.token);+ }+ assert.equal((yield* guestShares.media(token, shot)).mimeType, "image/png");+ // Records of guests with no open page were dropped to make room.+ for (const closed of closedTokens.slice(0, 2)) {+ assert.equal((yield* Effect.flip(guestShares.media(closed, shot))).reason, "unavailable");+ }++ // A new link on the thread starts empty: its guest gets nothing the last guest was sent.+ const { url } = yield* guestShares.create({ threadId });+ const next = yield* guestShares.redeem({+ credential: url.slice(url.indexOf("#") + 1),+ name: "Kim",+ });+ assert.equal((yield* Effect.flip(guestShares.media(next.token, shot))).reason, "unavailable");+ yield* Stream.runDrain(Stream.take(yield* guestShares.stream(next.token), 2));+ assert.equal((yield* guestShares.media(next.token, shot)).mimeType, "image/png");+ }).pipe(Effect.scoped, Effect.provide(layerTest)),+);diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.tsindex 1f65217e452..0346068bc54 100644--- a/apps/server/src/guest/GuestShareService.ts+++ b/apps/server/src/guest/GuestShareService.ts@@ -15,9 +15,11 @@ import {type OrchestrationV2CommandOutputFrame,type OrchestrationV2DomainEvent,type OrchestrationV2GetTurnItemResult,+ type OrchestrationV2TurnItem,ThreadId,TurnItemId,} from "@t3tools/contracts";+import { chatMarkdownImageSources } from "@t3tools/shared/markdownPipeline";import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";import * as Context from "effect/Context";import * as Crypto from "effect/Crypto";@@ -63,7 +65,10 @@ import { guestShareView, guestThreadModel } from "./guestView.ts";import {classifyGuestUploads,GUEST_UPLOAD_HEADER_BYTES,+ guestHostImageType,type GuestUpload,+ matchesImageSignature,+ repliesShowImage,} from "./guestAttachments.ts";const SIGNING_SECRET_NAME = "guest-share-signing-key";@@ -71,6 +76,8 @@ const SHARE_ID_BYTES = 16;const INVITE_SIGNATURE_BYTES = 16;const SNAPSHOT_ROW_LIMIT = 600;const SNAPSHOT_USER_TURN_LIMIT = 20;+// Shares with no open guest stream whose sent image replies are still kept.+const SHARED_THREAD_REPLIES_LIMIT = 64;// How soon an open read notices that its link stopped working, such as Connect no longer serving// the host. Closing or replacing the link ends the main stream at once.const ACCESS_RECHECK_INTERVAL = Duration.seconds(30);@@ -190,9 +197,20 @@ export class GuestShareService extends Context.Service<{ readonly path: string; readonly attachment: ChatAttachment },GuestShareAccessError>;+ /** An image on the host that an agent reply the guest sees shows, and its type. */+ readonly media: (+ session: string,+ path: string,+ ) => Effect.Effect<{ readonly path: string; readonly mimeType: string }, GuestShareAccessError>;}>()("t3/guest/GuestShareService") {}+/** A reply a guest's stream sent, with its image sources once a media request parsed them. */+interface SentReply {+ readonly text: string;+ sources?: ReadonlyArray<string>;+}+/** The thread record an event carries, for the share and the view. */const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | null => {switch (event.type) {@@ -464,6 +482,40 @@ const make = Effect.gen(function* () {Effect.ignore,);+ // The image replies each share's guest stream has sent, in its opening snapshot or live, so an+ // image loads while the guest's page can show its reply, inherited ones included. Keyed by+ // share, so a new link on the thread starts empty. A share with an open stream keeps its+ // record; past the limit, closed ones are dropped.+ const sentImageReplies = new Map<+ GuestShareId,+ { openStreams: number; readonly replies: Map<string, SentReply> }+ >();+ const sentRecord = (shareId: GuestShareId) => {+ let record = sentImageReplies.get(shareId);+ if (record === undefined) {+ record = { openStreams: 0, replies: new Map() };+ sentImageReplies.set(shareId, record);+ for (const [id, other] of sentImageReplies) {+ if (sentImageReplies.size <= SHARED_THREAD_REPLIES_LIMIT) break;+ if (other.openStreams === 0 && id !== shareId) sentImageReplies.delete(id);+ }+ }+ return record;+ };+ const rememberSent = (shareId: GuestShareId, items: Iterable<OrchestrationV2TurnItem>) => {+ for (const item of items) {+ if (item.type !== "assistant_message") continue;+ const key = `${item.threadId}\u0000${item.id}`;+ // Only replies with image syntax can show an image. One edited to drop its images stops+ // allowing them.+ if (item.text.includes("![") || /<img/i.test(item.text)) {+ sentRecord(shareId).replies.set(key, { text: item.text });+ } else {+ sentImageReplies.get(shareId)?.replies.delete(key);+ }+ }+ };+/*** The thread as the owner's thread subscription sends it: a bounded snapshot, then the same* wire events, batched the same way. Only the share's own state is added.@@ -511,6 +563,7 @@ const make = Effect.gen(function* () {Stream.map((item): ReadonlyArray<GuestStreamEvent> => {if (item.kind !== "event") return [];if (endsShare(item.event)) return [ended];+ if (item.event.type === "turn-item.updated") rememberSent(share.id, [item.event.payload]);const updated = threadOf(item.event);const view = updated === null ? null : viewOf(updated);return view === null@@ -528,17 +581,15 @@ const make = Effect.gen(function* () {const untilExpiry = Effect.sleep(Math.max(0, Date.parse(share.expiresAt) - DateTime.toEpochMillis(yield* DateTime.now)),);+ const openingSnapshot = buildBoundedThreadStreamSnapshot({+ snapshotSequence: snapshot.snapshotSequence,+ projection: snapshot.projection,+ });const opening: ReadonlyArray<GuestStreamEvent> = [{ type: "view", view: initialView },- {- type: "thread",- item: buildBoundedThreadStreamSnapshot({- snapshotSequence: snapshot.snapshotSequence,- projection: snapshot.projection,- }),- },+ { type: "thread", item: openingSnapshot },];- return Stream.fromIterable(opening).pipe(+ const events = Stream.fromIterable(opening).pipe(Stream.concat(Stream.merge(live, Stream.fromEffect(Effect.as(untilExpiry, ended)), {haltStrategy: "either",@@ -557,6 +608,25 @@ const make = Effect.gen(function* () {),),);+ // The record is opened and counted when the stream runs, paired with its release, so a+ // response whose body never runs (HEAD) touches nothing.+ return Stream.unwrap(+ Effect.acquireRelease(+ Effect.sync(() => {+ const record = sentRecord(share.id);+ record.openStreams += 1;+ rememberSent(+ share.id,+ openingSnapshot.projection.visibleTurnItems.map((row) => row.item),+ );+ return record;+ }),+ (record) =>+ Effect.sync(() => {+ record.openStreams -= 1;+ }),+ ).pipe(Effect.as(events)),+ );});const unavailable = new GuestShareAccessError({ reason: "unavailable" });@@ -630,6 +700,33 @@ const make = Effect.gen(function* () {return exists ? { path, attachment: found } : yield* unavailable;});+ const media = Effect.fn("GuestShareService.media")(function* (session: string, path: string) {+ const { share } = yield* authorize(session, "session");+ const mimeType = guestHostImageType(path);+ if (mimeType === null) return yield* unavailable;+ const sent = sentImageReplies.get(share.id)?.replies.values() ?? [];+ // Each sent reply is parsed once, on the first request that needs it.+ if (+ !repliesShowImage(+ path,+ [...sent],+ (reply) => (reply.sources ??= chatMarkdownImageSources(reply.text)),+ )+ ) {+ return yield* unavailable;+ }+ // The bytes must be the image the name says, as for a guest's own upload.+ const header = yield* fileSystem.open(path, { flag: "r" }).pipe(+ Effect.flatMap((file) => file.readAlloc(GUEST_UPLOAD_HEADER_BYTES)),+ Effect.scoped,+ Effect.mapError(() => unavailable),+ );+ if (Option.isNone(header) || !matchesImageSignature(mimeType, header.value)) {+ return yield* unavailable;+ }+ return { path, mimeType };+ });+return GuestShareService.of({create,redeem,@@ -640,6 +737,7 @@ const make = Effect.gen(function* () {item,commandOutput,attachment,+ media,});});diff --git a/apps/server/src/guest/guestAttachments.test.ts b/apps/server/src/guest/guestAttachments.test.tsnew file mode 100644index 00000000000..c65dd1364c2--- /dev/null+++ b/apps/server/src/guest/guestAttachments.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vite-plus/test";++import { guestHostImageType, repliesShowImage } from "./guestAttachments.ts";++describe("guest host images", () => {+ it.each([+ ["", "/w/a.png", "image/png"],+ ["", "/w/my shot.jpg", "image/jpeg"],+ [".png)", "/w/shot(1).png", "image/png"],+ [" ", "/w/shot_1.png", "image/png"],+ [" ", "/w/a&b.png", "image/png"],+ ["", "/w/café.png", "image/png"],+ [" ", "/w/shot.png", "image/png"],+ [" ", "/w/shot2.png", "image/png"],+ ["![a][r]\n\n[r]: /w/ref.png", "/w/ref.png", "image/png"],+ ["", "/w/url form.png", "image/png"],+ ["", "C:\\w\\win.png", "image/png"],+ ["![a][r]\n\n[r]: C:\\w\\ref.png", "C:/w/ref.png", "image/png"],+ // Shown as a link, in code, or not at all: the guest sees no image, so none loads.+ ["[a](/w/link.png)", "/w/link.png", null],+ ["```\n\n```", "/w/code.png", null],+ ["``", "/w/span.png", null],+ ["<!--  -->", "/w/comment.png", null],+ ["", "/a.png", null],+ ["", "//host/s/x.png", null],+ ["", "\\\\host\\s\\x.png", null],+ ["", "/w/a.svg", null],+ ["", "/w/a.constructor", null],+ ])("%j serves %j as %j", (text, path, type) => {+ const served = guestHostImageType(path) !== null && repliesShowImage(path, [{ text }]);+ expect(served ? guestHostImageType(path) : null).toBe(type);+ });+});diff --git a/apps/server/src/guest/guestAttachments.ts b/apps/server/src/guest/guestAttachments.tsindex ab7bd1a78b8..5118899620d 100644--- a/apps/server/src/guest/guestAttachments.ts+++ b/apps/server/src/guest/guestAttachments.ts@@ -3,6 +3,9 @@ import {GUEST_MESSAGE_MAX_ATTACHMENTS,isProviderSendTurnSupportedImageMimeType,} from "@t3tools/contracts";+import { markdownDestinationHostPath } from "@t3tools/shared/markdownLinks";+import { chatMarkdownImageSources } from "@t3tools/shared/markdownPipeline";+import { isAbsolutePath, isNetworkPath } from "@t3tools/shared/path";/** A file from a guest's message request, saved by the multipart parser to a temporary path. */export interface GuestUpload {@@ -46,6 +49,44 @@ const IMAGE_SIGNATURES: Readonly<Record<string, (header: Uint8Array) => boolean>startsWith(header, ascii("RIFF")) && startsWith(header, ascii("WEBP"), 8),};+export const matchesImageSignature = (mimeType: string, header: Uint8Array) =>+ IMAGE_SIGNATURES[mimeType]?.(header) === true;++const IMAGE_TYPE_BY_EXTENSION: ReadonlyMap<string, string> = new Map([+ ["png", "image/png"],+ ["jpg", "image/jpeg"],+ ["jpeg", "image/jpeg"],+ ["gif", "image/gif"],+ ["webp", "image/webp"],+]);++/**+ * The type of a host image a guest may ask for by path, or null. A network path never qualifies:+ * it would make the host reach out to another machine.+ */+export function guestHostImageType(path: string): string | null {+ if (!isAbsolutePath(path) || isNetworkPath(path)) return null;+ return IMAGE_TYPE_BY_EXTENSION.get(path.split(".").at(-1)!.toLowerCase()) ?? null;+}++/**+ * Whether an agent reply shows the image at `path`, so the guest already sees it. `imageSources`+ * lets the caller reuse a reply's parse across requests.+ */+export function repliesShowImage<Reply extends { readonly text: string }>(+ path: string,+ replies: ReadonlyArray<Reply>,+ imageSources: (reply: Reply) => ReadonlyArray<string> = (reply) =>+ chatMarkdownImageSources(reply.text),+) {+ // Parsing is the slow part; a reply with no image syntax shows no image.+ return replies.some(+ (reply) =>+ (reply.text.includes("![") || /<img/i.test(reply.text)) &&+ imageSources(reply).some((source) => markdownDestinationHostPath(source) === path),+ );+}+/*** Control characters and separators would break the name in headers and on disk, and direction* overrides would let `invoice\u202Efdp.exe` show as a PDF.@@ -76,11 +117,9 @@ export function classifyGuestUploads(upload.contentType.split(";", 1)[0]!.trim().toLowerCase() || "application/octet-stream";if (upload.sizeBytes === 0) return { ok: false, reason: "unsupported_file" };if (mimeType.startsWith("image/")) {- const signatureMatches = IMAGE_SIGNATURES[mimeType];if (!isProviderSendTurnSupportedImageMimeType(mimeType) ||- signatureMatches === undefined ||- !signatureMatches(upload.header)+ !matchesImageSignature(mimeType, upload.header)) {return { ok: false, reason: "unsupported_file" };}diff --git a/apps/server/src/guest/http.ts b/apps/server/src/guest/http.tsindex 7c8356119de..bf368ac884d 100644--- a/apps/server/src/guest/http.ts+++ b/apps/server/src/guest/http.ts@@ -2,6 +2,7 @@ import {GUEST_ATTACHMENT_ROUTE,GUEST_COMMAND_OUTPUT_ROUTE,GUEST_ITEM_ROUTE,+ GUEST_MEDIA_ROUTE,GUEST_RENDER_ROUTE,GUEST_ROUTE_PREFIX,GUEST_SHARE_PARAM,@@ -34,6 +35,12 @@ import { GuestShareAccessError, GuestShareService } from "./GuestShareService.ts// Cloudflare closes idle streams after about 100 seconds.const HEARTBEAT_INTERVAL = Duration.seconds(20);const NO_STORE = { "cache-control": "no-store" };+// A file never runs as a page on this origin, whatever its bytes.+const FILE_HEADERS = {+ ...NO_STORE,+ "x-content-type-options": "nosniff",+ "content-security-policy": "default-src 'none'; sandbox",+};const decodeRedeem = Schema.decodeUnknownEffect(GuestRedeemRequest);const decodeSubmit = Schema.decodeUnknownEffect(GuestSubmitRequest);@@ -315,9 +322,7 @@ const attachmentRoute = HttpRouter.add(Effect.flatMap(({ path, attachment }) =>HttpServerResponse.file(path, {headers: {- ...NO_STORE,- "x-content-type-options": "nosniff",- "content-security-policy": "default-src 'none'; sandbox",+ ...FILE_HEADERS,...(attachment.type === "image" &&isProviderSendTurnSupportedImageMimeType(attachment.mimeType)? { "content-type": attachment.mimeType }@@ -334,6 +339,25 @@ const attachmentRoute = HttpRouter.add(}),);+// Only an image an agent reply shows loads; anything else on the host is refused.+const mediaRoute = HttpRouter.add(+ "GET",+ GUEST_MEDIA_ROUTE,+ Effect.gen(function* () {+ const request = yield* HttpServerRequest.HttpServerRequest;+ const path = new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("path");+ if (!path) return yield* badRequest;+ const guestShares = yield* GuestShareService;+ return yield* guestShares.media(yield* sessionToken, path).pipe(+ Effect.flatMap(({ path, mimeType }) =>+ HttpServerResponse.file(path, { headers: { ...FILE_HEADERS, "content-type": mimeType } }),+ ),+ Effect.catchTags({ GuestShareAccessError: errorResponse }),+ Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 500, headers: NO_STORE })),+ );+ }),+);+export const layer = Layer.mergeAll(redeemRoute,sessionRoute,@@ -343,4 +367,5 @@ export const layer = Layer.mergeAll(itemRoute,commandOutputRoute,attachmentRoute,+ mediaRoute,);diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsxindex d67803a6399..345bde84976 100644--- a/apps/web/src/components/ChatMarkdown.browser.test.tsx+++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx@@ -10,6 +10,7 @@ import "../index.css";import { filesystemEnvironment } from "../state/filesystem";import { useRightPanelStore } from "../rightPanelStore";import { setMarkdownTaskChecked } from "./files/filePreviewMode";+import { HostImageUrlContext } from "./chat/hostImageUrl";const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({workspaceSearch: vi.fn(),@@ -122,6 +123,22 @@ it("shows unavailable audio when a workspace embed has no thread", async () => {expect(screen.container.querySelector("audio")).toBeNull();});+it("loads a host image through the page's own route when there is no environment", async () => {+ setup();+ const pixel =+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";+ const hostImageUrl = vi.fn((_path: string) => pixel);+ await using screen = await render(+ <HostImageUrlContext value={hostImageUrl}>+ <ChatMarkdown cwd={undefined} text="" />+ </HostImageUrlContext>,+ );+ await expect.element(screen.getByAltText("Shot")).toHaveAttribute("src", pixel);+ expect(new Set(hostImageUrl.mock.calls.map(([path]) => path))).toEqual(+ new Set(["/work/my shot.png"]),+ );+});+describe("ChatMarkdown favicon privacy", () => {it("suppresses private link images while preserving public links across updates", async () => {setup();diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex 2ae3e8d9f97..32f15bcf542 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -65,6 +65,7 @@ import {import { mediaUrlReference } from "@t3tools/client-runtime/media-reference";import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/mediaPreview";import { InlineAudioPreview } from "./files/InlineAudioPreview";+import { HostImageUrlContext } from "./chat/hostImageUrl";import * as Cause from "effect/Cause";import * as Option from "effect/Option";import * as Schema from "effect/Schema";@@ -1483,6 +1484,24 @@ const CHAT_MARKDOWN_COMPONENTS = {/>);}+ const hostImageUrl = use(HostImageUrlContext);+ if (imageSource._tag === "WorkspaceFile" && kind === "image" && hostImageUrl !== null) {+ const hostSrc = hostImageUrl(imageSource.path);+ return (+ <ChatMarkdownImage+ key={hostSrc}+ src={hostSrc}+ alt={altText}+ copyMarkdown={copyMarkdown}+ standalone={standalone}+ className={className}+ style={authoredSizeStyle}+ imageProps={imageProps}+ actionsSource={{ kind, name: altText || kind, src: hostSrc }}+ onImageExpand={imageExpand}+ />+ );+ }if (imageSource._tag === "WorkspaceFile" && threadRef) {return (<ChatMarkdownAssetImagediff --git a/apps/web/src/components/chat/hostImageUrl.ts b/apps/web/src/components/chat/hostImageUrl.tsnew file mode 100644index 00000000000..2078d40ff4f--- /dev/null+++ b/apps/web/src/components/chat/hostImageUrl.ts@@ -0,0 +1,7 @@+import { createContext } from "react";++/**+ * Where markdown loads an image file on the host by its absolute path, when the page has no+ * environment to ask. The guest page sets it to its own route.+ */+export const HostImageUrlContext = createContext<((path: string) => string) | null>(null);diff --git a/apps/web/src/components/guest/GuestPage.tsx b/apps/web/src/components/guest/GuestPage.tsxindex 3ec7b2d5423..6d72741691f 100644--- a/apps/web/src/components/guest/GuestPage.tsx+++ b/apps/web/src/components/guest/GuestPage.tsx@@ -45,6 +45,7 @@ import type { ChatComposerHandle } from "../chat/ChatComposer";import { ComposerControl, ComposerControlIcon } from "../chat/ComposerControl";import type { ExpandedImagePreview } from "../chat/ExpandedImagePreview";import { GuestMessageAttachments } from "../chat/GuestMessageAttachments";+import { HostImageUrlContext } from "../chat/hostImageUrl";import { PierreEntryIcon } from "../chat/PierreEntryIcon";import { GuestMessageName, guestBubbleClassName } from "../chat/guestMessageStyle";import { MessagesTimeline } from "../chat/MessagesTimeline";@@ -60,6 +61,7 @@ import {applyGuestStreamEvent,formatGuestExpiry,guestAttachmentUrl,+ guestMediaUrl,createGuestAttachmentUrls,guestFilesProblem,initialGuestStreamState,@@ -387,6 +389,7 @@ function GuestThread({const openFile = useStableCallback((file: { readonly id: string }) =>openInNewTab(guestAttachmentUrl(shareId, file.id)),);+ const hostImageUrl = useStableCallback((path: string) => guestMediaUrl(shareId, path));const activityRun = deriveThreadActivityRun(projection);const runtime = deriveThreadStructureRuntime(projection);const runlessWorkStartedAt = deriveRunlessWorkStartedAt(projection);@@ -448,50 +451,52 @@ function GuestThread({<ExpiryLabel expiresAt={expiresAt} /></header><div className="relative min-h-0 flex-1">- <MessagesTimeline- listRef={listRef}- timelineEntries={entries}- isWorking={isWorking}- activeTurnStartedAt={workStartedAt}- latestRun={activityRun}- runningRunId={runningRunId}- turnDiffSummaries={NO_TURN_DIFFS}- runs={projection.runs}- routeThreadKey={threadKey}- onOpenThread={ignore}- supportsConversationRollback={false}- onRevertToTurnCount={ignore}- isRevertingCheckpoint={false}- onImageExpand={openExpandedImage}- onFileOpen={openFile}- onFileDownload={openFile}- renderHtmlRender={renderHtmlRender}- turnItemSource={turnItemSource}- activeThreadEnvironmentId={GUEST_ENVIRONMENT_ID}- markdownCwd={undefined}- resolvedTheme={resolvedTheme}- timestampFormat="locale"- workspaceRoot={undefined}- anchorMessageId={null}- onAnchorReady={ignore}- onAnchorSizeChanged={ignore}- contentInsetEndAdjustment={0}- emptyPlaceholderInset={0}- liveFollowEnabled={follow.timelineLiveFollowEnabled}- onIsAtEndChange={follow.onIsAtEndChangeStable}- onViewportAttach={follow.attachTimelineViewport}- footer={- unplaced.length === 0 ? null : (- <ol ref={footerRef} className="chat-content-lane flex flex-col gap-4 pb-4">- {unplaced.map((message) => (- <li key={message.id}>- <UnplacedGuestMessage shareId={shareId} message={message} />- </li>- ))}- </ol>- )- }- />+ <HostImageUrlContext value={hostImageUrl}>+ <MessagesTimeline+ listRef={listRef}+ timelineEntries={entries}+ isWorking={isWorking}+ activeTurnStartedAt={workStartedAt}+ latestRun={activityRun}+ runningRunId={runningRunId}+ turnDiffSummaries={NO_TURN_DIFFS}+ runs={projection.runs}+ routeThreadKey={threadKey}+ onOpenThread={ignore}+ supportsConversationRollback={false}+ onRevertToTurnCount={ignore}+ isRevertingCheckpoint={false}+ onImageExpand={openExpandedImage}+ onFileOpen={openFile}+ onFileDownload={openFile}+ renderHtmlRender={renderHtmlRender}+ turnItemSource={turnItemSource}+ activeThreadEnvironmentId={GUEST_ENVIRONMENT_ID}+ markdownCwd={undefined}+ resolvedTheme={resolvedTheme}+ timestampFormat="locale"+ workspaceRoot={undefined}+ anchorMessageId={null}+ onAnchorReady={ignore}+ onAnchorSizeChanged={ignore}+ contentInsetEndAdjustment={0}+ emptyPlaceholderInset={0}+ liveFollowEnabled={follow.timelineLiveFollowEnabled}+ onIsAtEndChange={follow.onIsAtEndChangeStable}+ onViewportAttach={follow.attachTimelineViewport}+ footer={+ unplaced.length === 0 ? null : (+ <ol ref={footerRef} className="chat-content-lane flex flex-col gap-4 pb-4">+ {unplaced.map((message) => (+ <li key={message.id}>+ <UnplacedGuestMessage shareId={shareId} message={message} />+ </li>+ ))}+ </ol>+ )+ }+ />+ </HostImageUrlContext>{follow.showScrollToBottom ? (<ScrollToEndButtonsummary={null}diff --git a/apps/web/src/components/guest/guestStream.logic.ts b/apps/web/src/components/guest/guestStream.logic.tsindex a424cf04721..0b37d66eeec 100644--- a/apps/web/src/components/guest/guestStream.logic.ts+++ b/apps/web/src/components/guest/guestStream.logic.ts@@ -1,5 +1,6 @@import {GUEST_ATTACHMENT_ROUTE,+ GUEST_MEDIA_ROUTE,GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,GUEST_MESSAGE_MAX_ATTACHMENTS,GUEST_SHARE_PARAM,@@ -184,6 +185,10 @@ export function inviteShareId(credential: string): string | null {export const guestAttachmentUrl = (shareId: string, attachmentId: string) =>`${GUEST_ATTACHMENT_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&id=${encodeURIComponent(attachmentId)}`;+/** Where the guest page loads an image file on the host that an agent message embeds. */+export const guestMediaUrl = (shareId: string, path: string) =>+ `${GUEST_MEDIA_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&path=${encodeURIComponent(path)}`;+/*** Why these files cannot go with one message, or null. The server checks the same limits; this* only says so before the upload.diff --git a/docs/user/guest-links.md b/docs/user/guest-links.mdindex b97e400c651..a8631a6c93b 100644--- a/docs/user/guest-links.md+++ b/docs/user/guest-links.md@@ -26,9 +26,9 @@ unlinking the machine from T3 Connect also ends it. You can send or dismiss gues## What the guest seesThe guest sees the thread's recent history and everything after, in the same timeline you see, as-it streams: messages and their files, the agent's replies and reasoning, plans, questions, and its-work, with command output when they expand a command. Their composer shows the thread's model, but-they cannot change it. They do not see diffs, and they cannot act on the thread: no forking,+it streams: messages and their files, the agent's replies with the images they show from your+machine, its reasoning, plans, questions, and its work, with command output when they expand a+command. Their composer shows the thread's model, but they cannot change it. They do not see diffs, and they cannot act on the thread: no forking,reverting, opening files on your machine, or answering the agent for you.Anything the agent read or printed can show, such as a value from a file. Share only threads youdiff --git a/packages/client-runtime/src/markdownImages.ts b/packages/client-runtime/src/markdownImages.tsindex 924220ec27c..94cba5c9f84 100644--- a/packages/client-runtime/src/markdownImages.ts+++ b/packages/client-runtime/src/markdownImages.ts@@ -1,16 +1,14 @@import {isNetworkPath,isWindowsAbsolutePath,- stripSlashPrefixedWindowsDrive,workspaceRelativeFilePath,} from "@t3tools/shared/path";import {+ markdownDestinationHostPath,normalizeMarkdownLinkDestination,- safeDecodeURIComponent,splitMarkdownLinkSearchAndHash,} from "@t3tools/shared/markdownLinks";-import { parseFileUrlHref } from "@t3tools/shared/fileLinks";const DIRECT_IMAGE_SOURCE_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i;const URI_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;@@ -59,19 +57,9 @@ export function classifyMarkdownImageSource(return { _tag: "Direct", uri: source };}- if (/^file:/i.test(source)) {- const target = parseFileUrlHref(source);- return target === null- ? { _tag: "Blocked" }- : hostFileSource(- stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path)),- workspaceRoot,- );- }-- const path = stripSlashPrefixedWindowsDrive(- safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path),- );+ const path = markdownDestinationHostPath(source);+ if (path === null) return { _tag: "Blocked" };+ if (/^file:/i.test(source)) return hostFileSource(path, workspaceRoot);if (path.length === 0) return { _tag: "Blocked" };if (path.startsWith("/") || isWindowsAbsolutePath(path)) {return hostFileSource(path, workspaceRoot);diff --git a/packages/contracts/src/guestShare.ts b/packages/contracts/src/guestShare.tsindex fa4b3a256f0..fd991fe1e4c 100644--- a/packages/contracts/src/guestShare.ts+++ b/packages/contracts/src/guestShare.ts@@ -136,3 +136,8 @@ export const GUEST_COMMAND_OUTPUT_ROUTE = `${GUEST_ROUTE_PREFIX}/command-output`* Images load inline; other files download.*/export const GUEST_ATTACHMENT_ROUTE = `${GUEST_ROUTE_PREFIX}/attachment`;+/**+ * An image file on the host that an agent message in the shared thread embeds:+ * `?share=<share id>&path=<absolute path>`.+ */+export const GUEST_MEDIA_ROUTE = `${GUEST_ROUTE_PREFIX}/media`;diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.tsindex 0445fa42d8a..177e6fcbf50 100644--- a/packages/shared/src/markdownLinks.ts+++ b/packages/shared/src/markdownLinks.ts@@ -227,6 +227,22 @@ export function splitMarkdownLinkSearchAndHash(value: string): {};}+/**+ * The decoded path a markdown destination names on the host, before any workspace resolution, or+ * null for a `file:` URL that does not parse. Clients and the guest media route both read it here.+ */+export function markdownDestinationHostPath(source: string): string | null {+ if (/^file:/i.test(source)) {+ const target = parseFileUrlHref(source);+ return target === null+ ? null+ : stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path));+ }+ return stripSlashPrefixedWindowsDrive(+ safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path),+ );+}+export function isMarkdownFileLinkLabel(label: string, href: string): boolean {const destination = parseMarkdownFileLink(href);if (!destination) return false;diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.tsindex 275b93b562f..fe3d73ddac6 100644--- a/packages/shared/src/markdownPipeline.ts+++ b/packages/shared/src/markdownPipeline.ts@@ -1,6 +1,8 @@import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast";import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts";-import type { PluggableList } from "unified";+import { type PluggableList, unified } from "unified";+import remarkParse from "remark-parse";+import remarkRehype from "remark-rehype";import rehypeRaw from "rehype-raw";import rehypeSanitize, { defaultSchema } from "rehype-sanitize";import remarkBreaks from "remark-breaks";@@ -11,7 +13,7 @@ import {CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,remarkCodexDirectives,} from "./codexMarkdownDirectives.ts";-import { isWindowsDrivePathHref } from "./markdownLinks.ts";+import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts";import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";type MarkdownImageHastNode = {@@ -304,3 +306,38 @@ function remarkNormalizeLinksAndTagInlineCode() {export function shouldPreserveAssistantLineBreaks(text: string): boolean {return /^★ Insight(?:\s|─)/mu.test(text);}++const imageSourceProcessor = unified()+ .use(remarkParse)+ .use(CHAT_MARKDOWN_REMARK_PLUGINS)+ .use(remarkRehype, { allowDangerousHtml: true })+ .use(CHAT_MARKDOWN_REHYPE_PLUGINS);++interface ImageSourceNode {+ readonly type: string;+ readonly tagName?: string;+ readonly properties?: { readonly src?: unknown; readonly dataLocalSrc?: unknown };+ readonly children?: ReadonlyArray<ImageSourceNode>;+}++/**+ * The sources of the images chat markdown shows, read as ChatMarkdown's `img` renderer reads+ * them. Code, comments, and plain links show no image, so they add none.+ */+export function chatMarkdownImageSources(markdown: string): Array<string> {+ const sources: Array<string> = [];+ const visit = (node: ImageSourceNode) => {+ if (node.type === "element" && node.tagName === "img") {+ const { src, dataLocalSrc } = node.properties ?? {};+ // The sanitizer drops a Windows drive path from `src`; the renderer reads it from here.+ if (typeof dataLocalSrc === "string") {+ sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/"));+ } else if (typeof src === "string") {+ sources.push(normalizeMarkdownLinkDestination(src));+ }+ }+ node.children?.forEach(visit);+ };+ visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode);+ return sources;+}