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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/server/src/guide/topics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,7 @@ The ↓ count is only as fresh as the last fetch, and {place:sourceControl.fetch
id: "pages-and-command-requests",
title: "Agent pages and command requests",
keywords: ["page", "chart", "diagram", "mockup", "run command", "card", "artifact"],
body: `With {place:threads.agentPages} on, an agent can show a chart, diagram, mockup or document as a page in its reply. {place:threads.claudeArtifacts} lets Claude also publish one to claude.ai for a link you can share.
body: `With {place:threads.agentPages} on, an agent can show a chart, diagram, mockup or document as a page in its reply. Select text in a page to copy it or add a note on it for your next message, as in the chat's own text. {place:threads.claudeArtifacts} lets Claude also publish one to claude.ai for a link you can share.

With {place:threads.commandRequests} on, an agent can ask you to run a command it can't run itself (one that needs your password or sign-in, or a long-running server): a card in the chat with Run, Put in terminal and Skip, and the output comes back to the agent.`,
},
Expand Down
174 changes: 174 additions & 0 deletions apps/web/src/components/chat/AgentPageFrame.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ import {
import { AGENT_PAGE_MIN_HEIGHT, type AgentPageContentSize } from "@threadlines/shared/agentPages";
import { page, userEvent } from "vite-plus/test/browser";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { useRef } from "react";
import { render } from "vitest-browser-react";

import { AgentPageFrame } from "./AgentPageFrame";
import { AgentPageRow } from "./AgentPageRow";
import { ExpandedImageViewerHost } from "./ExpandedImageViewerHost";
import { TranscriptSelectionLayer } from "./TranscriptSelectionPopover";

// Stored pages by version id: what `pages.read` would return.
const storedPages = vi.hoisted(() => new Map<string, string>());
Expand Down Expand Up @@ -69,6 +71,13 @@ const picture = (color: string) =>
/** The frame decides what a load means as it happens; this is time for the answer to show. */
const settled = () => new Promise((resolve) => setTimeout(resolve, 150));

/**
* Focus landing in a page soon after typing in the app counts as the page
* taking it (AgentPageFrame's focus guard): a reader who just typed clicks
* into a page a moment later.
*/
const pastTypingWindow = () => new Promise((resolve) => setTimeout(resolve, 1_600));

/** Which of a frame's edges fade out, read from its mask. */
function fadedEdges(frame: HTMLElement) {
const mask = frame.style.maskImage;
Expand Down Expand Up @@ -283,4 +292,169 @@ describe("AgentPageRow", () => {
window.removeEventListener("message", onReport);
}
});

it("offers copy and add-note on text the reader selects in a page, as in the chat", async () => {
const version = versionOf(
"selectable",
`<p>Part 2: the products</p><p id="row">edwards-est-vigilant-gsa-ct2.html</p>` +
// A page cannot raise the actions by itself, without the reader in it.
`<script>addEventListener("load", function () { parent.postMessage({ jsonrpc: "2.0", method: "threadlines/selection-changed", params: { text: "forged", top: 0, left: 0, bottom: 10, right: 10 } }, "*"); });</script>`,
);
const other = versionOf("other", "<p>Another page</p>");
const onAddHighlight = vi.fn();
const pageProps = (ref: typeof version, title: string) => ({
pageId: ref.pageId,
versionId: ref.versionId,
version: 1,
turnId: TurnId.make("turn-1"),
participantId: null,
title,
kind: "html" as const,
height: 120,
createdAt: "2026-10-23T12:00:00.000Z",
updatedAt: "2026-10-23T12:00:00.000Z",
});
function Timeline() {
const containerRef = useRef<HTMLDivElement>(null);
return (
<div ref={containerRef} style={{ position: "relative", width: 600, height: 400 }}>
<AgentPageRow
environmentId={version.environmentId}
threadId={version.threadId}
page={pageProps(version, "Fixes")}
updated={false}
/>
<AgentPageRow
environmentId={other.environmentId}
threadId={other.threadId}
page={{ ...pageProps(other, "Other"), pageId: AgentPageId.make("page-2") }}
updated={false}
/>
<TranscriptSelectionLayer containerRef={containerRef} onAddHighlight={onAddHighlight} />
</div>
);
}
let forged = false;
const onForged = (event: MessageEvent) => {
if (event.data?.params?.text === "forged") forged = true;
};
window.addEventListener("message", onForged);
await render(<Timeline />);
const addNote = page.getByRole("button", { name: "Add note" });
const pageText = page
.frameLocator(page.getByTitle("Fixes"))
.getByText("edwards-est-vigilant-gsa-ct2.html");
await vi.waitFor(() => expect(forged).toBe(true));
window.removeEventListener("message", onForged);
await settled();
expect(addNote.elements()).toHaveLength(0);

await pageText.tripleClick();
await expect.element(addNote).toBeVisible();
// Beside the selected line, not somewhere else on the page.
const line = page.getByTitle("Fixes").element().getBoundingClientRect();
const actions = addNote.element().getBoundingClientRect();
expect(actions.top).toBeGreaterThan(line.top);
expect(actions.top).toBeLessThan(line.top + 120);

// A click into another page leaves this page's selection behind, and its actions.
await page.frameLocator(page.getByTitle("Other")).getByText("Another page").click();
await page.frameLocator(page.getByTitle("Other")).getByText("Another page").click();
await expect.poll(() => addNote.elements()).toHaveLength(0);

await pageText.tripleClick();
await expect.element(addNote).toBeVisible();

await addNote.click();
await userEvent.keyboard("This one failed");
await page.getByRole("button", { name: "Add", exact: true }).click();
expect(onAddHighlight).toHaveBeenCalledWith({
sourceMessageId: version.pageId,
sourceRole: "page",
selectedText: "edwards-est-vigilant-gsa-ct2.html",
note: "This one failed",
});
});

it("offers the same actions in the full-size view, beside the text at any zoom", async () => {
const version = versionOf(
"full-size",
`<p style="margin:0;position:absolute;top:200px;left:20px">fire-lite-ann-rly.html</p>`,
);
const onAddHighlight = vi.fn();
await render(
<AgentPageRow
environmentId={version.environmentId}
threadId={version.threadId}
page={{
pageId: version.pageId,
versionId: version.versionId,
version: 1,
turnId: TurnId.make("turn-1"),
participantId: null,
title: "Products",
kind: "html",
height: 120,
createdAt: "2026-10-23T12:00:00.000Z",
updatedAt: "2026-10-23T12:00:00.000Z",
}}
updated={false}
onAddHighlight={onAddHighlight}
/>,
);
await page.getByRole("button", { name: "Open Products full size" }).click();
const dialog = page.getByRole("dialog");
const addNote = dialog.getByRole("button", { name: "Add note" });
const frame = dialog.getByTitle("Products");
const line = page.frameLocator(frame).getByText("fire-lite-ann-rly.html");
const actionsBelowFrameTop = () =>
addNote.element().getBoundingClientRect().top - frame.element().getBoundingClientRect().top;
const zoomIn = dialog.getByRole("button", { name: "Zoom in" });
// The view has loaded the page and settled its focus.
await expect.element(zoomIn).toBeEnabled();
// The test before typed its note just now.
await pastTypingWindow();
await line.tripleClick();
await expect.element(addNote).toBeVisible();
// The line sits 200px down the page.
expect(actionsBelowFrameTop()).toBeGreaterThan(210);
expect(actionsBelowFrameTop()).toBeLessThan(260);

// Zoomed to 125% it is drawn 250px down, and the actions follow it.
await zoomIn.click();
await zoomIn.click();
await expect.element(dialog.getByText("125%")).toBeVisible();
await expect.poll(actionsBelowFrameTop).toBeGreaterThan(265);

// Escape in the note, even on its buttons, closes the note, not the full-size view.
await addNote.click();
await userEvent.keyboard("Discontinued");
await userEvent.keyboard("{Tab}");
await expect.element(dialog.getByRole("button", { name: "Cancel" })).toHaveFocus();
await userEvent.keyboard("{Escape}");
await expect
.poll(() => dialog.getByRole("button", { name: "Add", exact: true }).elements())
.toHaveLength(0);
await expect.element(dialog).toBeVisible();

await dialog.getByRole("button", { name: /^Zoom 125%/ }).click();
await pastTypingWindow();
await line.tripleClick();
await addNote.click();
await userEvent.keyboard("Discontinued");
// A look at the source keeps the note being written.
const source = dialog.getByRole("button", { name: "Source" });
await source.click();
await source.click();
await expect
.element(dialog.getByPlaceholder("Add context for this highlight"))
.toHaveValue("Discontinued");
await dialog.getByRole("button", { name: "Add", exact: true }).click();
expect(onAddHighlight).toHaveBeenCalledWith({
sourceMessageId: version.pageId,
sourceRole: "page",
selectedText: "fire-lite-ann-rly.html",
note: "Discontinued",
});
});
});
1 change: 1 addition & 0 deletions apps/web/src/components/chat/AgentPageFrame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ export function AgentPageFrame(props: {
<iframe
ref={frameRef}
title={title}
data-agent-page-id={pageId}
srcDoc={pageDocument}
sandbox={AGENT_PAGE_FRAME_SANDBOX}
referrerPolicy="no-referrer"
Expand Down
33 changes: 28 additions & 5 deletions apps/web/src/components/chat/AgentPageRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,14 @@ import {

import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { openExternalUrl } from "../../lib/externalLinks";
import type { TranscriptHighlightContextSelection } from "../../lib/transcriptHighlightContext";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { ThemeOfferRow } from "../theme/ui/ThemeOfferRow";
import { AgentPageFrame } from "./AgentPageFrame";
import { TranscriptSelectionLayer } from "./TranscriptSelectionPopover";

// Which pages the reader minimized, for this app session. Held outside the
// row: the timeline unmounts rows that scroll away, and a page must stay as
Expand Down Expand Up @@ -87,6 +89,11 @@ export function AgentPageRow(props: {
readonly page: OrchestrationAgentPage;
/** A later turn's version of a page an earlier turn showed. */
readonly updated: boolean;
/**
* Adds a note on text selected in the page to the composer. The chat's own
* selection layer covers the inline page; the full-size view has its own.
*/
readonly onAddHighlight?: ((selection: TranscriptHighlightContextSelection) => void) | undefined;
}) {
// A theme an agent offered is a page too, shown as a theme row.
return props.page.kind === "theme" ? <ThemeOfferRow {...props} /> : <FramedPageRow {...props} />;
Expand Down Expand Up @@ -198,6 +205,7 @@ function FramedPageRow(props: Parameters<typeof AgentPageRow>[0]) {
version={version}
page={page}
share={share}
onAddHighlight={props.onAddHighlight}
onClose={() => setFullSize(false)}
/>
) : null}
Expand Down Expand Up @@ -265,9 +273,11 @@ function FullSizePage(props: {
readonly version: Parameters<typeof AgentPageFrame>[0]["version"];
readonly page: OrchestrationAgentPage;
readonly share: ReturnType<typeof agentPageShareLink>;
readonly onAddHighlight: ((selection: TranscriptHighlightContextSelection) => void) | undefined;
readonly onClose: () => void;
}) {
const { share } = props;
const { share, onAddHighlight } = props;
const pageBoxRef = useRef<HTMLDivElement>(null);
const { copyToClipboard, isCopied } = useCopyToClipboard();
const [loaded, setLoaded] = useState<AgentPageReadResult | null>(null);
const [showSource, setShowSource] = useState(false);
Expand Down Expand Up @@ -378,9 +388,19 @@ function FullSizePage(props: {
<pre className="min-h-0 flex-1 overflow-auto px-5 pb-5 font-mono text-xs leading-5 whitespace-pre-wrap text-foreground">
{loaded.content}
</pre>
) : (
// The page has no side padding of its own, so full size gives it a
// gutter, painted in the page's own background: its panel's fill.
) : null}
{/* Text selected in the page gets the chat's copy and add-note actions
here too, placed inside this box. It stays mounted while the source
shows, so the page and a note being written keep. */}
<div
ref={pageBoxRef}
className={cn(
"relative flex min-h-0 flex-1 flex-col",
showSource && loaded !== null && "hidden",
)}
>
{/* The page has no side padding of its own, so full size gives it a
gutter, painted in the page's own background: its panel's fill. */}
<AgentPageFrame
key={props.version.versionId}
version={props.version}
Expand All @@ -389,7 +409,10 @@ function FullSizePage(props: {
onLoaded={onLoaded}
zoom={zoom}
/>
)}
{onAddHighlight ? (
<TranscriptSelectionLayer containerRef={pageBoxRef} onAddHighlight={onAddHighlight} />
) : null}
</div>
</DialogPopup>
</Dialog>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { SquarePenIcon, Trash2Icon, XIcon } from "lucide-react";

import { cn } from "~/lib/utils";
import type { TranscriptHighlightContextDraft } from "~/lib/transcriptHighlightContext";
import { formatTranscriptHighlightContextPreview } from "~/lib/transcriptHighlightContext";
import {
formatTranscriptHighlightContextPreview,
transcriptHighlightRoleWord,
} from "~/lib/transcriptHighlightContext";
import { COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME } from "../composerInlineChip";
import { Button } from "../ui/button";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
Expand Down Expand Up @@ -67,7 +70,7 @@ function TranscriptHighlightChip({
const [noteDraft, setNoteDraft] = useState(context.note);

const preview = formatTranscriptHighlightContextPreview(context);
const roleWord = context.sourceRole === "assistant" ? "assistant" : "your";
const roleWord = transcriptHighlightRoleWord(context.sourceRole);

// Keep the editable draft aligned with the stored note when it changes elsewhere.
useEffect(() => {
Expand Down
14 changes: 12 additions & 2 deletions apps/web/src/components/chat/MessagesTimeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,10 @@ import type {
TranscriptHighlightContextSelection,
TranscriptHighlightSourceRole,
} from "~/lib/transcriptHighlightContext";
import { formatTranscriptHighlightContextPreview } from "~/lib/transcriptHighlightContext";
import {
formatTranscriptHighlightContextPreview,
transcriptHighlightRoleWord,
} from "~/lib/transcriptHighlightContext";
import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
import {
type AgentModelLabeler,
Expand Down Expand Up @@ -340,6 +343,10 @@ interface TimelineRowSharedState {
onResolveNoteSuggestion?: NoteSuggestionResolver | undefined;
/** Puts a message an MCP app asked to send into the composer. */
onPutMcpAppMessage?: ((text: string) => void) | undefined;
/** Adds a note on selected text to the composer; a page's full-size view offers it too. */
onAddTranscriptHighlightContext?:
| ((selection: TranscriptHighlightContextSelection) => void)
| undefined;
/** Opens or closes a side answer's one-line status to watch it written. */
onToggleSideAnswer: (sideTurnId: SideTurnId) => void;
/** Scrolls to a message: a side answer posted below, or its question. */
Expand Down Expand Up @@ -2136,6 +2143,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onCancelCheckBack,
onResolveNoteSuggestion,
onPutMcpAppMessage,
onAddTranscriptHighlightContext,
threadStartCallsByTurn,
runMessage,
anchorOwnsLiveAgents,
Expand Down Expand Up @@ -2182,6 +2190,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onCancelCheckBack,
onResolveNoteSuggestion,
onPutMcpAppMessage,
onAddTranscriptHighlightContext,
threadStartCallsByTurn,
runMessage,
anchorOwnsLiveAgents,
Expand Down Expand Up @@ -4297,6 +4306,7 @@ function PageTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "page" }>
threadId={ctx.activeThreadId}
page={row.page}
updated={row.updated}
onAddHighlight={ctx.onAddTranscriptHighlightContext}
/>
</>
);
Expand Down Expand Up @@ -5786,7 +5796,7 @@ const UserMessageTranscriptHighlightInlineLabel = memo(
context: ParsedTranscriptHighlightContextEntry;
}) {
const preview = formatTranscriptHighlightContextPreview(props.context);
const roleWord = props.context.sourceRole === "assistant" ? "assistant" : "your";
const roleWord = transcriptHighlightRoleWord(props.context.sourceRole);

return (
<Popover>
Expand Down
Loading
Loading