From 87a62c2b81ad318c2c6c7bbb93ae973457444dec Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 15:24:19 -0800 Subject: [PATCH] Make this an artifact, under an answer a Bot draws A drawn answer (a native interface, an HTML interface, or a gallery or Playground component that drew) gets "Make this an artifact" under it, in the toolbar style of Copy under a reply. Pressing it sends the Bot the person's ask as an ordinary message, naming the drawing by its title or its place when there are several, and the Bot makes the artifact with the artifact_create every Bot holds. The same for a Bot connected over plain AG-UI. Text answers and artifact cards get none. The offer in the Bot's prompt didn't reach people on GPT models; this is OpenBot's version of Claude's "Save as artifact" on its custom visuals. --- .github/workflows/ci.yml | 1 + .../components/channels/chat-transcript.tsx | 86 +- .../components/channels/conversation-view.tsx | 39 + app/src/components/channels/drawn-answers.ts | 218 ++++++ .../channels/telemetry-assistant-message.tsx | 24 + app/tests/drawn-answers.test.ts | 198 +++++ app/tests/make-artifact-browser.test.tsx | 736 ++++++++++++++++++ app/tests/make-artifact.fixture.tsx | 105 +++ 8 files changed, 1406 insertions(+), 1 deletion(-) create mode 100644 app/src/components/channels/drawn-answers.ts create mode 100644 app/tests/drawn-answers.test.ts create mode 100644 app/tests/make-artifact-browser.test.tsx create mode 100644 app/tests/make-artifact.fixture.tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fb8e72f4d3..1ffa73f59d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -756,6 +756,7 @@ jobs: app/tests/home-screen-connect-browser.test.tsx app/tests/long-names-layout.test.tsx app/tests/long-turn-reopen.test.tsx + app/tests/make-artifact-browser.test.tsx app/tests/member-rows-long-names.test.tsx app/tests/model-picker-touch.test.tsx app/tests/move-to-cloud-settings.test.tsx diff --git a/app/src/components/channels/chat-transcript.tsx b/app/src/components/channels/chat-transcript.tsx index b4230fc611..583662c2c6 100644 --- a/app/src/components/channels/chat-transcript.tsx +++ b/app/src/components/channels/chat-transcript.tsx @@ -187,6 +187,7 @@ import { import { splitChatOrigin } from "./chat-origin"; import type { QueuedMessage } from "./composer"; import { transcriptColumn } from "./conversation-columns"; +import { makeArtifactAsks } from "./drawn-answers"; import { FileTypeIcon } from "./file-icon"; import { FollowScroll, RESUME_PX, useFollowIntent } from "./follow-intent"; import { LateRenderersContext, LateRenderersWatch } from "./late-renderers"; @@ -194,7 +195,10 @@ import { usePacedReveal } from "./paced-reveal"; import { latestPlanPerTurn } from "./plan-turns"; import { ResearchResults } from "./research-results"; import { TeamBotConsentCard } from "./team-bot-consent"; -import { ReplyToolbar } from "./telemetry-assistant-message"; +import { + MakeArtifactToolbar, + ReplyToolbar, +} from "./telemetry-assistant-message"; import { ActivityAppMarks, attachmentReadName, @@ -286,6 +290,12 @@ type ChatTranscriptProps = { * a turn that ended for a reason carrying on would not fix (a refusal, a Bot no longer shared). */ onCarryOn?: () => void; + /** + * Send the Bot the person's ask to keep one drawn answer as an artifact, drawn as "Make this an + * artifact" under each answer the Bot drew (`drawn-answers.ts`). Absent where nothing can be + * sent: no button is drawn. + */ + onMakeArtifact?: (ask: string) => void; /** * The person dismissed `stopped` for this turn: it is not drawn, though the turn is still the one * that stopped (its work stays unfolded, as it was under the notice). @@ -310,6 +320,7 @@ type ChatTranscriptProps = { /** One shared empty array, so a screen without a queue does not hand down a new one per render. */ const EMPTY_QUEUE: readonly QueuedMessage[] = []; const NO_REFUSALS: ReadonlyMap = new Map(); +const NO_ARTIFACT_ASKS: ReadonlyMap = new Map(); /* * HELD, NOT INERT, AND PER ROW. A read-only row has to stop every press in it, including ones no @@ -1445,6 +1456,45 @@ const TranscriptMessage = memo(function TranscriptMessage({ ); }); +/** + * "Make this an artifact" under an answer the Bot drew, sending the person's ask for it. + * + * Laid out as the toolbar under a reply is, a little closer to what it is under: a drawn answer + * ends in its own frame, not in a last line of words. The newest drawn answer's stays shown, as the + * newest reply's Copy does; an earlier one's shows on hover, so a conversation of charts is not a + * column of buttons. + * + * Its room is kept while the turn is still going, unseen and out of reach, as the reply toolbar's + * is: what the Bot says after the drawing does not move down when the turn ends and this shows. + */ +const MakeArtifactAction = memo(function MakeArtifactAction({ + ask, + newest, + onMakeArtifact, + settled, +}: { + ask: string; + newest: boolean; + onMakeArtifact: (ask: string) => void; + /** The drawn answer's turn is over. */ + settled: boolean; +}) { + return ( +
+ onMakeArtifact(ask)} /> +
+ ); +}); + /** Whose answer this is, by the name the person knows the Bot by. */ function AnswererName({ botId }: { botId: string }) { const { data: bots } = useQuery(agentListQueryOptions()); @@ -2628,6 +2678,7 @@ export function ChatTranscript({ refusals = NO_REFUSALS, stoppedNotice, onCarryOn, + onMakeArtifact, stoppedDismissed = false, onDismissStopped, working, @@ -2682,6 +2733,14 @@ export function ChatTranscript({ ); // The latest reply's Copy stays shown; earlier ones show on hover (`TranscriptMessage`). const newestReply = [...replies.keys()].at(-1); + /* + * What "Make this an artifact" asks for each answer the Bot drew, by its row. The newest one's + * stays shown, as the newest reply's Copy does; earlier ones show on hover. + */ + const artifactAsks = onMakeArtifact + ? makeArtifactAsks(items) + : NO_ARTIFACT_ASKS; + const newestDrawn = [...artifactAsks.keys()].at(-1); /* * The folders this conversation's "Check your folders" steps named, for its other folder steps. * The same map while the names are the same: a new one on every render is a new context value, @@ -3187,6 +3246,13 @@ export function ChatTranscript({ if (taskWork.folds.inside.has(item.id)) return null; // A refused turn's notice, under the last row of the person's message it answered. const refusal = refusedUnder.get(item.id); + /* + * Under an answer the Bot drew: the way to keep it as an artifact, once its turn is over. Not on + * a read-only row, whose presses go nowhere. + */ + const ask = artifactAsks.get(item.id); + const offersArtifact = + ask !== undefined && onMakeArtifact !== undefined && !readOnly; return ( {rowContent(item, index)} + {/* + * Beside the drawn answer, never around it: wrapping the row once its turn ended would mount + * the interface again, and an interface drawn in a frame would load again. + */} + {offersArtifact ? ( + + ) : null} {/* * Inside the message's own row, not a row of its own: the scroller counts its rows by * position, and a row added beside a message would read as a new one arriving. The gap is diff --git a/app/src/components/channels/conversation-view.tsx b/app/src/components/channels/conversation-view.tsx index 5b909bd104..d4b653bb83 100644 --- a/app/src/components/channels/conversation-view.tsx +++ b/app/src/components/channels/conversation-view.tsx @@ -542,6 +542,44 @@ export function ConversationView({ .finally(() => setCarryOnSending(false)); }; + /** + * "MAKE THIS AN ARTIFACT" IS THE PERSON ASKING, SENT AS A MESSAGE TYPED HERE IS. + * + * The ask goes to the Bot as an ordinary message from the person, which any Bot answers by making + * the artifact with the `artifact_create` it already holds: a Bot connected over plain AG-UI gets + * exactly what a built-in one does. Like Carry on, it goes at once while the conversation is free + * and waits as queued while a turn is in flight. Pressed again while the same ask is waiting or + * still being sent, it does nothing, so two presses never become two artifacts. + */ + const [artifactAskSending, setArtifactAskSending] = useState( + null, + ); + const pressMakeArtifact = (ask: string) => { + if (artifactAskSending === ask) return; + if (queuedRef.current.some((message) => message.text === ask)) return; + if (stopIfNeedsCard()) return; + const started = submit( + { + agentId: null, + attachments: [], + commandIds: [], + isEmpty: false, + text: ask, + }, + inFlight, + ); + if (!started) return; + setArtifactAskSending(ask); + void started + .catch((error: unknown) => { + restoreFailedRun( + [{ attachments: [], commandIds: [], id: newId(), text: ask }], + error, + ); + }) + .finally(() => setArtifactAskSending(null)); + }; + /** * The turn ended. Whatever was waiting for it goes now, as one message. * @@ -653,6 +691,7 @@ export function ConversationView({ {...(stopped && pressCarryOn && !disabled ? { onCarryOn: pressCarryOn } : {})} + {...(disabled ? {} : { onMakeArtifact: pressMakeArtifact })} {...(stopped && stoppedDismissed ? { stoppedDismissed } : {})} {...(stopped && onDismissStopped ? { onDismissStopped } : {})} working={working} diff --git a/app/src/components/channels/drawn-answers.ts b/app/src/components/channels/drawn-answers.ts new file mode 100644 index 0000000000..b40eb763c8 --- /dev/null +++ b/app/src/components/channels/drawn-answers.ts @@ -0,0 +1,218 @@ +import type { ActivityMessage, ToolCall } from "@ag-ui/core"; +import { NOT_SHOWN } from "@openbot/shared/component-markers"; +import type { TranscriptItem } from "./tool-activity"; + +/** + * THE ANSWERS A BOT DREW IN THE CONVERSATION, AND WHAT "MAKE THIS AN ARTIFACT" SAYS FOR EACH. + * + * A drawn answer lives in the conversation only, as Claude's custom visuals do ("ephemeral by + * default": support.claude.com/en/articles/13979539). Claude offers "Save as artifact" on each + * visual; OpenBot offers "Make this an artifact" under each drawn answer. Pressing it sends the Bot + * an ordinary message from the person, which every Bot answers the same way, over plain AG-UI, with + * the `artifact_create` it already holds. Nothing here talks to the server. + * + * Drawn means one of: + * - an interface from the native catalog (`render_ui`), which arrives as a `generative-ui-surface` + * activity (`a2ui-surface` from older runtimes); + * - an HTML interface (`generateSandboxedUi`), an `open-generative-ui` activity; + * - a component call that put something on screen: a gallery chart or card, or a component published + * in the Playground. Each of those answers its call by saying it is on screen for the person when + * it drew, and with something else when it didn't (refused, wrong arguments, or a decision, whose + * answer is the person's choice). So that sentence is what says it drew, whichever drew it. + * + * Never a text answer and never an artifact's own card: an artifact is already kept. + */ + +/** The activities that are an interface a Bot drew. */ +const DRAWN_ACTIVITIES: ReadonlySet = new Set([ + "generative-ui-surface", + "a2ui-surface", + "open-generative-ui", +]); + +/** + * How every component that drew answers its call (`gallery-tools.tsx`, `sandboxed-tools.tsx`): its + * first sentence says it is on screen for the person ("It is now on screen for the person.", "The + * report is on screen for the person, filled with…"). A refusal, wrong arguments and a call made too + * early each open with what went wrong instead, and say nothing is on screen later, if at all. + */ +const SAYS_ON_SCREEN = + /^(?!Nothing\b)[^.]*\b(?:is|are) (?:now )?on screen for the person\b/; + +/** A tool result's words: frontend tools' strings sometimes arrive JSON-quoted. */ +function resultWords(result: string): string { + if (!result.startsWith('"')) return result; + try { + const parsed: unknown = JSON.parse(result); + return typeof parsed === "string" ? parsed : result; + } catch { + return result; + } +} + +/** Whether a component call put something on screen. */ +export function drewOnScreen(result: string | undefined): boolean { + if (result === undefined) return false; + const words = resultWords(result).trim(); + return !words.startsWith(NOT_SHOWN) && SAYS_ON_SCREEN.test(words); +} + +/** The longest title the message names; a longer one is cut at a word. */ +const TITLE_MAX = 60; + +function tidy(title: unknown): string | undefined { + if (typeof title !== "string") return undefined; + const words = title.replace(/\s+/g, " ").trim(); + if (words === "") return undefined; + if (words.length <= TITLE_MAX) return words; + const cut = words.slice(0, TITLE_MAX); + const space = cut.lastIndexOf(" "); + return `${(space > TITLE_MAX / 2 ? cut.slice(0, space) : cut).trimEnd()}…`; +} + +function parsedArgs(call: ToolCall): Record { + try { + const parsed: unknown = JSON.parse(call.function.arguments || "{}"); + return parsed && typeof parsed === "object" + ? (parsed as Record) + : {}; + } catch { + return {}; + } +} + +type SurfaceComponent = Record & { component?: unknown }; + +/** The components an A2UI surface was given, in the order the Bot wrote them. */ +function surfaceComponents(content: unknown): SurfaceComponent[] { + const operations = (content as { operations?: unknown } | null)?.operations; + if (!Array.isArray(operations)) return []; + return operations.flatMap((operation) => { + const update = ( + operation as { updateComponents?: { components?: unknown } } + )?.updateComponents; + return Array.isArray(update?.components) + ? (update.components as SurfaceComponent[]) + : []; + }); +} + +const HEADING_SIZES = new Set(["lg", "xl", "2xl", "3xl", "4xl"]); + +/** An A2UI surface's heading: a Card's title, or its first strong or large line of text. */ +function surfaceTitle(content: unknown): string | undefined { + const components = surfaceComponents(content); + for (const component of components) + if (component.component === "Card") { + const title = tidy(component.title); + if (title) return title; + } + for (const component of components) { + if (component.component !== "Text") continue; + const heading = + component.strong === true || + (typeof component.size === "string" && + HEADING_SIZES.has(component.size)) || + (typeof component.variant === "string" && + /^h[1-3]$/.test(component.variant)); + if (!heading) continue; + const title = tidy(component.text); + if (title) return title; + } + return undefined; +} + +/** An HTML interface's heading: its first `

` to `

`, as words. */ +function htmlTitle(content: unknown): string | undefined { + const html = (content as { html?: unknown } | null)?.html; + const source = Array.isArray(html) ? html.join("") : ""; + const match = /]*>([\s\S]*?)<\/h[1-3]>/i.exec(source); + return tidy(match?.[1]?.replace(/<[^>]*>/g, "")); +} + +/** A drawn answer, by its row, with the title it shows when one can be read. */ +export type DrawnAnswer = { id: string; title?: string }; + +function drawnActivity(message: ActivityMessage): DrawnAnswer | undefined { + if (!DRAWN_ACTIVITIES.has(message.activityType)) return undefined; + const content = message.content as Record | undefined; + // Not while it is still being drawn, nor once it failed to draw. + if (content?.generating === true) return undefined; + if (content?.status === "error" || content?.status === "failed") + return undefined; + const title = + message.activityType === "open-generative-ui" + ? htmlTitle(content) + : surfaceTitle(content); + return { id: message.id, ...(title ? { title } : {}) }; +} + +function drawnCall( + id: string, + call: ToolCall, + result: string | undefined, +): DrawnAnswer | undefined { + if (!drewOnScreen(result)) return undefined; + const args = parsedArgs(call); + const title = tidy(args.title) ?? tidy(args.heading); + return { id, ...(title ? { title } : {}) }; +} + +/** The drawn answers among a transcript's rows, top to bottom. */ +export function drawnAnswers(items: readonly TranscriptItem[]): DrawnAnswer[] { + return items.flatMap((item) => { + if (item.kind === "activity") return drawnActivity(item.message) ?? []; + if (item.kind === "tool") + return drawnCall(item.id, item.toolCall, item.result) ?? []; + // A lone call is drawn alone; a folded run of steps is not one drawn answer. + if (item.kind === "tools" && item.steps.length === 1) { + const [step] = item.steps; + return step ? (drawnCall(item.id, step.toolCall, step.result) ?? []) : []; + } + return []; + }); +} + +const ORDINALS = [ + "first", + "second", + "third", + "fourth", + "fifth", + "sixth", + "seventh", + "eighth", + "ninth", + "tenth", +]; + +/** + * What the person asks, for each drawn answer, by its row: short, in their voice, and naming which + * one when there are several. By its title where it has one no other drawn answer shares, else by + * where it is: the only one, the last one, or the second. + */ +export function makeArtifactAsks( + items: readonly TranscriptItem[], +): Map { + const drawn = drawnAnswers(items); + const titles = new Map(); + for (const answer of drawn) + if (answer.title) + titles.set(answer.title, (titles.get(answer.title) ?? 0) + 1); + return new Map( + drawn.map((answer, index) => { + const named = + answer.title !== undefined && titles.get(answer.title) === 1 + ? answer.title + : undefined; + const ask = named + ? `Make “${named}” an artifact.` + : drawn.length === 1 + ? "Make what you drew an artifact." + : index === drawn.length - 1 + ? "Make the last thing you drew an artifact." + : `Make the ${ORDINALS[index] ?? `number ${index + 1}`} thing you drew an artifact.`; + return [answer.id, ask]; + }), + ); +} diff --git a/app/src/components/channels/telemetry-assistant-message.tsx b/app/src/components/channels/telemetry-assistant-message.tsx index cc50b3a9f2..54a2aa1ff3 100644 --- a/app/src/components/channels/telemetry-assistant-message.tsx +++ b/app/src/components/channels/telemetry-assistant-message.tsx @@ -4,6 +4,7 @@ import { useCopilotChatConfiguration, } from "@copilotkit/react-core/v2"; import { type ComponentProps, createContext, useContext, useMemo } from "react"; +import { IconLayoutCollage } from "@/components/icons"; import { type ResultReference, recordResultAction, @@ -128,6 +129,29 @@ export function ReplyToolbar({ ); } +/** + * The toolbar under an answer a Bot drew: "Make this an artifact", as Claude offers "Save as + * artifact" on each of its visuals. The SDK's own toolbar and toolbar button, so it is drawn exactly + * as Copy is under a reply: an icon, its name in a tooltip and to a screen reader. + */ +export function MakeArtifactToolbar({ onPress }: { onPress: () => void }) { + return ( +
+ +
+ + + +
+
+
+ ); +} + /** Whether `text` reached the clipboard, as the SDK's own Copy reports it. */ async function copyText(text: string): Promise { try { diff --git a/app/tests/drawn-answers.test.ts b/app/tests/drawn-answers.test.ts new file mode 100644 index 0000000000..8612a2b290 --- /dev/null +++ b/app/tests/drawn-answers.test.ts @@ -0,0 +1,198 @@ +import { describe, expect, test } from "bun:test"; +import type { ActivityMessage, ToolCall } from "@ag-ui/core"; +import { NOT_SHOWN, NOT_SHOWN_TAIL } from "@openbot/shared/component-markers"; +import { NOT_DRAWN } from "@openbot/shared/tool-steps"; +import { + drewOnScreen, + makeArtifactAsks, +} from "@/components/channels/drawn-answers"; +import type { TranscriptItem } from "@/components/channels/tool-activity"; +import { GALLERY as ACTIVITY } from "@/components/gallery/activity"; +import { GALLERY as CARDS } from "@/components/gallery/cards"; +import { GALLERY as CHARTS } from "@/components/gallery/charts"; +import { GALLERY as DECISIONS } from "@/components/gallery/decisions"; +import { GALLERY as FORM } from "@/components/gallery/form"; +import { GALLERY as QUOTE } from "@/components/gallery/quote"; +import { GALLERY as TABLE } from "@/components/gallery/table"; +import { wrongArguments } from "@/lib/copilot/gallery-tools"; + +/** + * Which answers in a conversation a Bot drew, and what "Make this an artifact" asks for each. + * + * Against what the app really writes: every component this build ships answers its call in its own + * words once it is on screen (`gallery-tools.tsx`), a Playground component in the default ones + * (`sandboxed-tools.tsx`), a refused one with `NOT_SHOWN`, and a decision with the person's choice. + * Only the ones that drew are drawn answers. The interfaces are shaped as the runtime delivers them. + */ + +const SHIPPED = [ + ...ACTIVITY, + ...CARDS, + ...CHARTS, + ...DECISIONS, + ...FORM, + ...QUOTE, + ...TABLE, +]; +/** What `GrantedTool` and `SandboxedTool` answer when a component is on screen. */ +const ON_SCREEN = "It is now on screen for the person."; + +const call = (id: string, name: string, args: object = {}): ToolCall => ({ + id, + type: "function", + function: { name, arguments: JSON.stringify(args) }, +}); +const tool = ( + id: string, + name: string, + result: string | undefined, + args: object = {}, +): TranscriptItem => ({ + kind: "tool", + id, + toolCall: call(id, name, args), + ...(result === undefined ? {} : { result }), +}); +const activity = ( + id: string, + activityType: string, + content: Record, +): TranscriptItem => ({ + kind: "activity", + id, + message: { id, role: "activity", activityType, content } as ActivityMessage, +}); +const surface = (id: string, components: object[]) => + activity(id, "generative-ui-surface", { + surfaceId: id, + status: "ready", + operations: [ + { version: "1.0", createSurface: { surfaceId: id } }, + { version: "1.0", updateComponents: { surfaceId: id, components } }, + ], + }); + +describe("what counts as drawn", () => { + test("every shipped component that draws, once it is on screen, and nothing a decision answers", () => { + const draws = SHIPPED.filter((spec) => spec.kind !== "decision"); + expect(draws.length).toBeGreaterThan(5); + for (const spec of draws) { + const said = spec.confirmation ?? ON_SCREEN; + expect([spec.name, drewOnScreen(said)]).toEqual([spec.name, true]); + // A frontend tool's answer can arrive JSON-quoted. + expect(drewOnScreen(JSON.stringify(said))).toBe(true); + // Refused: the card says so, and there is nothing to keep. + expect( + drewOnScreen( + `${NOT_SHOWN}${spec.title}. That component was switched off for this Bot.${NOT_SHOWN_TAIL}`, + ), + ).toBe(false); + // Called with arguments it doesn't take: told so, and nothing drawn. + const wrong = wrongArguments(spec, { nonsense: [1, 2, 3] }); + if (wrong) expect(drewOnScreen(wrong)).toBe(false); + } + // Called in the same step as other tools: not drawn. + expect(drewOnScreen(NOT_DRAWN)).toBe(false); + // A call still on its way has drawn nothing yet. + expect(drewOnScreen(undefined)).toBe(false); + // A decision's answer is the person's choice. + expect(drewOnScreen(JSON.stringify({ choice: "Tuesday" }))).toBe(false); + expect(drewOnScreen("Tuesday")).toBe(false); + }); + + test("a text answer and an artifact's card are not drawn answers", () => { + const items: TranscriptItem[] = [ + { kind: "text", id: "a", role: "assistant", text: "Sintra is lovely." }, + tool( + "create", + "artifact_create", + JSON.stringify({ + ok: true, + artifact: { id: "x", title: "Plan", kind: "document", version: 1 }, + }), + { title: "Plan" }, + ), + tool("search", "web_search", "3 results"), + activity("call", "voice-chat", { startedAt: "2026-12-04T09:00:00Z" }), + ]; + expect(makeArtifactAsks(items).size).toBe(0); + }); + + test("an interface still being drawn, or one that failed, is not offered", () => { + expect( + makeArtifactAsks([ + activity("html", "open-generative-ui", { generating: true }), + activity("broken", "generative-ui-surface", { status: "error" }), + ]).size, + ).toBe(0); + }); +}); + +describe("what the person asks", () => { + test("the only drawn answer, with no title to name it by", () => { + const asks = makeArtifactAsks([ + surface("s", [{ id: "root", component: "Text", text: "Hello there." }]), + ]); + expect([...asks]).toEqual([["s", "Make what you drew an artifact."]]); + }); + + test("several, each named by its title where it has one of its own", () => { + const asks = makeArtifactAsks([ + { kind: "text", id: "q", role: "user", text: "Plan my trip." }, + surface("packing", [ + { id: "root", component: "Column", children: ["t"] }, + { id: "t", component: "Text", text: "Packing list", strong: true }, + ]), + surface("card", [ + { id: "root", component: "Card", title: "Saturday", child: "x" }, + ]), + tool( + "chart", + "showBarChart", + "The bar chart is now on screen for the person.", + { + title: "Spend by day", + }, + ), + activity("html", "open-generative-ui", { + generating: false, + html: ['

Train times

'], + }), + tool("plain", "custom_invoice_card", ON_SCREEN, {}), + tool( + "again", + "showBarChart", + "The bar chart is now on screen for the person.", + { + title: "Spend by day", + }, + ), + ]); + expect([...asks]).toEqual([ + ["packing", "Make “Packing list” an artifact."], + ["card", "Make “Saturday” an artifact."], + // Two share a title, so each is named by where it is. + ["chart", "Make the third thing you drew an artifact."], + ["html", "Make “Train times” an artifact."], + ["plain", "Make the fifth thing you drew an artifact."], + ["again", "Make the last thing you drew an artifact."], + ]); + }); + + test("a long title is cut at a word", () => { + const asks = makeArtifactAsks([ + tool( + "c", + "showLineChart", + "The line chart is now on screen for the person.", + { + title: + "Weekly active teams across every region since the launch of the new onboarding flow", + }, + ), + ]); + expect(asks.get("c")).toBe( + "Make “Weekly active teams across every region since the launch of…” an artifact.", + ); + }); +}); diff --git a/app/tests/make-artifact-browser.test.tsx b/app/tests/make-artifact-browser.test.tsx new file mode 100644 index 0000000000..150290fc53 --- /dev/null +++ b/app/tests/make-artifact-browser.test.tsx @@ -0,0 +1,736 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { Server } from "bun"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { getGetBotResponseMock } from "@/lib/api/generated/bots/bots.msw"; +import { OPENBOT_UI } from "@/lib/copilot/a2ui"; +import { personBody } from "./accounts-api"; +import { approvalInboxResponse } from "./approvals-api"; +import { createArtifactsServer, DANA } from "./artifacts-api"; +import { botGrantsBody } from "./bot-grants-api"; +import { still } from "./page-still"; +import { test } from "./renderer-crash"; + +/** + * "Make this an artifact" under an answer a Bot drew, in a real browser. + * + * OpenBot's version of Claude's "Save as artifact" on its custom visuals: a drawn answer lives in + * the conversation only, and the person keeps one with one press. The press is the person asking, + * as an ordinary message, and the Bot makes the artifact with its own `artifact_create`, so a Bot + * connected over plain AG-UI gets exactly what a built-in one does. The Bot here is that: a stock + * AG-UI agent at the runtime's address, which knows nothing about OpenBot. + * + * The real conversation in the app's frame (make-artifact.fixture.tsx), with the native catalog + * switched on, against a real HTTP server on this machine that answers at the API's and the + * runtime's addresses. The conversation already holds a text answer, an artifact the Bot made, and + * a packing list it drew; the person then asks for a trip budget, which the Bot draws. + * + * - Each drawn answer has the action; the text answer and the artifact's card have none. + * - Pressing it under the budget sends the person's ask, naming the budget by its title. + * - The Bot answers with `artifact_create`, and the budget's artifact card is drawn. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/make-artifact-browser.test.tsx + * + * Chromium by default. OPENBOT_APP_ENGINES=chromium,webkit adds WebKit. With OPENBOT_APP_SHOTS= + * each step is saved as make-artifact----.png, taken before the step is + * checked, so a run that fails still shows what the screen said. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const shots = process.env.OPENBOT_APP_SHOTS; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; + +const APP = join(import.meta.dir, ".."); +const ORGANIZATION = "/api/v2/organizations/default"; +const BOT_ID = "trip-planner"; +const CONVERSATION = "trip-conversation"; +const THREAD = "trip-thread"; +const BOT_PATH = `${ORGANIZATION}/bots/${BOT_ID}`; + +const ASKED = "Plan a weekend trip budget I can change."; +const DRAWN_SAID = + "Here's a budget you can change. Edit any cost to see the total."; +const ASK = "Make “Weekend trip budget” an artifact."; +const MADE_SAID = "It's an artifact now, so you can keep it and share it."; + +const BOT = { + ...getGetBotResponseMock().bot, + id: BOT_ID, + name: "Trip Planner", + mine: true, + canManage: true, + systemOwned: false, + visibility: "private" as const, +}; + +const PLAN_ID = "Sp4Lw8Kc2Vn6Qx1Rt9Mb3H"; +const BUDGET_ID = "Wb7Tq2Hx5Kd9Lm3Ns6Pv1Z"; + +/** The artifacts this person can open: the plan the Bot made before, and the budget it will make. */ +const artifacts = createArtifactsServer({ + me: DANA, + artifacts: [ + { + id: PLAN_ID, + title: "Sintra weekend plan", + kind: "document", + owner: DANA, + conversationId: CONVERSATION, + versions: [ + { + author: { kind: "bot", id: BOT_ID, name: "Trip Planner" }, + note: null, + createdAt: "2026-12-04T09:02:00.000Z", + content: { + markdown: + "# Sintra weekend plan\n\n## Saturday\n- Pena Palace in the morning\n- Lunch in the old town\n\n## Sunday\n- Quinta da Regaleira\n- Train back to Lisbon\n", + }, + }, + ], + }, + { + id: BUDGET_ID, + title: "Weekend trip budget", + kind: "page", + owner: DANA, + conversationId: CONVERSATION, + versions: [ + { + author: { kind: "bot", id: BOT_ID, name: "Trip Planner" }, + note: null, + createdAt: "2026-12-04T09:10:00.000Z", + content: { + files: { + "App.tsx": + "export default function App() {\n return

Weekend trip budget

;\n}\n", + }, + entry: "App.tsx", + }, + thumbnail: "making", + }, + ], + }, + ], +}); + +const ref = (id: string, title: string, kind: string) => ({ + id, + title, + kind, + version: 1, + url: `http://artifacts.openbot.test/${id}`, + visibility: "private", +}); + +type Component = Record & { id: string; component: string }; + +/** An interface the Bot drew from the native catalog, as the runtime delivers it. */ +function surfaceContent( + surfaceId: string, + dataModel: Record, + components: Component[], +) { + return { + surfaceId, + target: "chat", + catalogId: OPENBOT_UI.id, + status: "ready", + rejected: [], + operations: [ + { + version: "1.0", + createSurface: { surfaceId, catalogId: OPENBOT_UI.id, dataModel }, + }, + { version: "1.0", updateComponents: { surfaceId, components } }, + ], + }; +} + +const amount = (key: string, label: string): Component => ({ + id: key, + component: "TextField", + label, + variant: "number", + value: { "@path": `/${key}` }, +}); + +const PACKING = surfaceContent("packing", {}, [ + { id: "root", component: "Column", children: ["title", "items"] }, + { + id: "title", + component: "Text", + text: "Packing list", + size: "lg", + strong: true, + }, + { + id: "items", + component: "Text", + text: "Passport, charger, rain jacket and walking shoes.", + color: "secondary", + }, +]); + +const BUDGET = surfaceContent( + "budget", + { transport: 100, lodging: 250, food: 80 }, + [ + { + id: "root", + component: "Column", + children: ["title", "total", "transport", "lodging", "food"], + }, + { + id: "title", + component: "Text", + text: "Weekend trip budget", + size: "lg", + strong: true, + }, + { + id: "total", + component: "Text", + strong: true, + text: { + "@call": "calc", + args: { + expression: "'Total $' + (transport + lodging + food)", + transport: { "@path": "/transport" }, + lodging: { "@path": "/lodging" }, + food: { "@path": "/food" }, + }, + }, + }, + amount("transport", "Transport ($)"), + amount("lodging", "Lodging ($)"), + amount("food", "Food ($)"), + ], +); + +/** The conversation so far: a text answer, an artifact the Bot made, and a list it drew. */ +const HISTORY = [ + { + id: "ask-where", + role: "user", + content: "Where should I go for a weekend away from Lisbon?", + }, + { + id: "sintra-answer", + role: "assistant", + content: + "Sintra is an easy weekend: forty minutes by train, with palaces, gardens and good walks.", + }, + { id: "ask-plan", role: "user", content: "Write the plan up as a document." }, + { + id: "making-plan", + role: "assistant", + content: "", + toolCalls: [ + { + id: "create-plan", + type: "function", + function: { + name: "artifact_create", + arguments: JSON.stringify({ + kind: "document", + title: "Sintra weekend plan", + content: { markdown: "# Sintra weekend plan" }, + }), + }, + }, + ], + }, + { + id: "result-create-plan", + role: "tool", + toolCallId: "create-plan", + content: JSON.stringify({ + ok: true, + artifact: ref(PLAN_ID, "Sintra weekend plan", "document"), + }), + }, + { id: "ask-pack", role: "user", content: "What should I pack?" }, + { + id: "packing-surface", + role: "activity", + activityType: "generative-ui-surface", + content: PACKING, + }, +]; + +/** Everything the test's server holds now. */ +type Scene = { + /** Every run asked of the runtime. */ + runs: { messages: { role: string; content?: unknown }[] }[]; + /** The thread's history, as the platform's read returns it. */ + stored: unknown[]; +}; +let scene: Scene; + +const json = (body: unknown, status = 200) => + Response.json(body, { + status, + headers: { "cache-control": "private, no-store" }, + }); +const sse = (events: unknown[]) => + new Response( + events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), + { headers: { "content-type": "text/event-stream" } }, + ); +const said = (messageId: string, text: string) => [ + { type: "TEXT_MESSAGE_START", messageId, role: "assistant" }, + { type: "TEXT_MESSAGE_CONTENT", messageId, delta: text }, + { type: "TEXT_MESSAGE_END", messageId }, +]; + +/** A run the page asks for, answered as a stock AG-UI agent would. */ +function run(input: { + threadId: string; + runId: string; + messages: { id: string; role: string; content?: unknown }[]; +}): Response { + scene.runs.push(input); + const person = input.messages.filter((message) => message.role === "user"); + const last = person.at(-1)?.content; + const started = { + type: "RUN_STARTED", + threadId: input.threadId, + runId: input.runId, + }; + const finished = { + type: "RUN_FINISHED", + threadId: input.threadId, + runId: input.runId, + }; + if (last === ASKED) { + scene.stored = [ + ...scene.stored, + ...person.slice(-1), + { + id: "budget-surface", + role: "activity", + activityType: "generative-ui-surface", + content: BUDGET, + }, + { id: "budget-said", role: "assistant", content: DRAWN_SAID }, + ]; + return sse([ + started, + { + type: "ACTIVITY_SNAPSHOT", + messageId: "budget-surface", + activityType: "generative-ui-surface", + content: BUDGET, + }, + ...said("budget-said", DRAWN_SAID), + finished, + ]); + } + if (last === ASK) { + const args = JSON.stringify({ + kind: "page", + title: "Weekend trip budget", + content: { files: { "App.tsx": "…" }, entry: "App.tsx" }, + }); + const answer = JSON.stringify({ + ok: true, + artifact: ref(BUDGET_ID, "Weekend trip budget", "page"), + }); + scene.stored = [ + ...scene.stored, + ...person.slice(-1), + { + id: "making-budget", + role: "assistant", + content: "", + toolCalls: [ + { + id: "create-budget", + type: "function", + function: { name: "artifact_create", arguments: args }, + }, + ], + }, + { + id: "result-create-budget", + role: "tool", + toolCallId: "create-budget", + content: answer, + }, + { id: "budget-made", role: "assistant", content: MADE_SAID }, + ]; + return sse([ + started, + { + type: "TOOL_CALL_START", + toolCallId: "create-budget", + toolCallName: "artifact_create", + parentMessageId: "making-budget", + }, + { type: "TOOL_CALL_ARGS", toolCallId: "create-budget", delta: args }, + { type: "TOOL_CALL_END", toolCallId: "create-budget" }, + { + type: "TOOL_CALL_RESULT", + messageId: "result-create-budget", + toolCallId: "create-budget", + content: answer, + role: "tool", + }, + ...said("budget-made", MADE_SAID), + finished, + ]); + } + return sse([started, ...said(`reply-${input.runId}`, "Sure."), finished]); +} + +/** What the server answers at the API's and the runtime's addresses. */ +async function answer(request: Request): Promise { + const url = new URL(request.url); + const path = url.pathname; + const approvals = approvalInboxResponse(path, {}); + if (approvals) return approvals; + if (path.startsWith(`${ORGANIZATION}/artifacts`)) { + const given = await artifacts.answer( + request.method, + url, + Object.fromEntries(request.headers), + request.method === "GET" ? undefined : await request.json(), + ); + if (given) + return given.json !== undefined + ? Response.json(given.json, { + status: given.status, + headers: given.headers, + }) + : new Response(given.text ?? null, { + status: given.status, + headers: given.headers, + }); + } + if (path === "/api/copilotkit/info") + return json({ + version: "fixture", + agents: { [BOT_ID]: { description: "Fixture", capabilities: {} } }, + mode: "sse", + telemetryDisabled: true, + }); + if (path.endsWith("/connect")) + return sse([ + { type: "RUN_STARTED", threadId: THREAD, runId: "history" }, + { type: "MESSAGES_SNAPSHOT", messages: scene.stored }, + { type: "RUN_FINISHED", threadId: THREAD, runId: "history" }, + ]); + if (path.endsWith("/run")) return run(await request.json()); + if (path.startsWith(`${ORGANIZATION}/people/me/approval-modes/`)) + return json({ asksEveryStep: false }); + if (/\/agent\/[^/]+\/stop\//.test(path)) return json({ stopped: true }); + if (path === BOT_PATH) return json({ bot: BOT }); + if (path === `${ORGANIZATION}/bots`) + return json({ bots: [BOT], nextCursor: null }); + if (path === `${BOT_PATH}/grants`) return json(botGrantsBody()); + if (path === `${BOT_PATH}/components`) + return json({ components: [], nextCursor: null }); + if (path === `${ORGANIZATION}/people/me/capabilities`) + return json({ capabilities: {}, enforced: false }); + if (path === `${ORGANIZATION}/people/me`) + return json({ + person: personBody({ + id: DANA.id, + name: DANA.name ?? "Dana Whitfield", + email: DANA.email, + role: "member", + }), + openbotVersion: "v1.2.0", + }); + if (path === `${ORGANIZATION}/deployment`) + return json({ + generativeUi: true, + selfHostBanner: false, + localEvaluation: false, + edition: "team", + authProviders: [], + ssoConfigured: false, + ssoRequired: false, + }); + if (/\/conversations\/[^/]+\/(activity|signal-busy)$/.test(path)) + return new Response(null, { status: 204 }); + if (/\/conversations\/[^/]+\/voice-sessions$/.test(path)) + return json({ sessions: [], nextCursor: null }); + if (/\/conversations\/[^/]+\/refused-turns$/.test(path)) + return json({ refusedTurns: [], nextCursor: null }); + if (path === `${ORGANIZATION}/conversations/${CONVERSATION}/join-tokens`) + return json( + { + joinToken: "jt", + expiresAt: "2026-12-04T10:20:30.000Z", + threadId: THREAD, + runId: null, + realtime: { clientUrl: "ws://127.0.0.1/client", topic: "thread" }, + }, + 201, + ); + const ran = path.match( + new RegExp(`^${ORGANIZATION}/conversations/[^/]+/runs/([^/]+)$`), + ); + if (ran) + return json({ + run: { + id: decodeURIComponent(ran[1] ?? ""), + outcome: "succeeded", + endedAt: "2026-12-04T09:00:00.000Z", + }, + }); + if (/\/threads\/[^/]+\/messages$/.test(path)) + return json({ messages: scene.stored }); + return undefined; +} + +/** The fixture bundled for the browser. `@/lib/marks` is Vite's `import.meta.glob`, so no marks. */ +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "make-artifact.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + // The catalog's Map loads it on demand; OpenBot omits Map and does not ship it. + external: ["maplibre-gl"], + plugins: [ + { + name: "no-marks", + setup(build) { + build.onResolve({ filter: /^@\/lib\/marks$/ }, () => ({ + path: "marks", + namespace: "no-marks", + })); + build.onLoad({ filter: /.*/, namespace: "no-marks" }, () => ({ + contents: "export const markFor = () => null;", + loader: "js", + })); + }, + }, + ], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + const script = built.outputs.find((output) => output.kind === "entry-point"); + if (!script) throw new Error("bundle has no entry point"); + return script.text(); +} + +/** The directory of an installed package, from the app or the repository root. */ +function packageDir(name: string): string { + const dir = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */ +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const subpath = `.${id.slice(name.length)}`; + const entry = pkg.exports?.[subpath]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP)); + const entry = join(APP, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +const browsers = new Map(); +let server: Server | undefined; +let origin = ""; + +beforeAll(async () => { + if (!asked) return; + const script = await bundle(); + const figtree = join(packageDir("@fontsource-variable/figtree"), "files"); + server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + idleTimeout: 0, + async fetch(request) { + const path = new URL(request.url).pathname; + if (path === "/conversation.js") + return new Response(script, { + headers: { "content-type": "text/javascript" }, + }); + const font = join(figtree, path.split("/").pop() ?? ""); + if (path.startsWith("/files/") && existsSync(font)) + return new Response(Bun.file(font)); + if (path.startsWith("/api/")) + return (await answer(request)) ?? json({ detail: "Not found." }, 404); + const theme = new URL(request.url).searchParams.get("theme") ?? "light"; + return new Response( + `
`, + { headers: { "content-type": "text/html" } }, + ); + }, + }); + origin = `http://127.0.0.1:${server.port}`; + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + browsers.set( + engine, + // The CI job installs full Chromium without the headless shell. + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); + await server?.stop(true); +}); + +/** Styled for everything now on the page: CopilotKit's stylesheet, then the app's. */ +async function style(page: Page) { + const classes = await page.evaluate(() => + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ); + await page.addStyleTag({ + content: readFileSync( + packageStylesheet("@copilotkit/react-core/v2/styles.css"), + "utf8", + ), + }); + await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) }); +} + +async function shoot(page: Page, name: string) { + await style(page); + await still(page); + if (!shots) return; + mkdirSync(shots, { recursive: true }); + await page.screenshot({ path: join(shots, `${name}.png`) }); +} + +/** The action under one row, found by the row's message id. */ +const actionIn = (page: Page, rowId: string) => + page.locator(`[data-message-id="${rowId}"] [data-testid="make-artifact"]`); + +const windows = [ + { width: 1280, height: 900 }, + { width: 390, height: 844 }, +]; + +describe.skipIf(!asked)("Make this an artifact, under a drawn answer", () => { + for (const engine of engines) + for (const theme of ["light", "dark"] as const) + for (const window of windows) + test(`a drawn answer is kept as an artifact by asking the Bot, in ${engine}, ${theme}, ${window.width}px`, async () => { + scene = { runs: [], stored: [...HISTORY] }; + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: window, + colorScheme: theme, + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + const name = (step: string) => + `make-artifact-${step}-${engine}-${theme}-${window.width}`; + try { + await page.goto(`${origin}/channel/${CONVERSATION}?theme=${theme}`); + // The conversation so far: the packing list it drew, and the plan's card. + await page.getByText("Packing list").waitFor({ timeout: 15_000 }); + await page + .locator('[data-slot="artifact-card"]', { + hasText: "Sintra weekend plan", + }) + .waitFor({ timeout: 15_000 }); + + // The person asks for a budget, and the Bot draws one. + const box = page.getByRole("textbox", { name: "Message" }); + await box.click(); + await box.fill(ASKED); + await page.getByRole("button", { name: "Send message" }).click(); + await page.getByText(DRAWN_SAID).waitFor({ timeout: 15_000 }); + await page.getByText("Total $430").waitFor({ timeout: 15_000 }); + await page + .getByRole("button", { name: "Send message" }) + .waitFor({ timeout: 15_000 }); + await shoot(page, name("1-drawn")); + + // Each drawn answer has the action, the newest in sight; nothing else has one. + await actionIn(page, "budget-surface").waitFor({ timeout: 5_000 }); + expect(await actionIn(page, "budget-surface").count()).toBe(1); + expect(await actionIn(page, "packing-surface").count()).toBe(1); + expect(await actionIn(page, "sintra-answer").count()).toBe(0); + expect(await actionIn(page, "budget-said").count()).toBe(0); + expect( + await page + .locator('[data-message-id]:has([data-slot="artifact-card"])') + .locator('[data-testid="make-artifact"]') + .count(), + ).toBe(0); + expect( + await page.locator('[data-testid="make-artifact"]').count(), + ).toBe(2); + const action = actionIn(page, "budget-surface"); + expect(await action.getAttribute("aria-label")).toBe( + "Make this an artifact", + ); + expect(await action.isVisible()).toBe(true); + + // Pressed: the person's ask goes to the Bot, naming the budget by its title. + await action.click(); + await page + .locator('[data-slot="artifact-card"]', { + hasText: "Weekend trip budget", + }) + .waitFor({ timeout: 15_000 }); + await page.getByText(MADE_SAID).waitFor({ timeout: 15_000 }); + await page.getByText(ASK).waitFor({ timeout: 5_000 }); + await shoot(page, name("2-made")); + expect(scene.runs).toHaveLength(2); + expect(scene.runs[1]?.messages.at(-1)).toMatchObject({ + role: "user", + content: ASK, + }); + // The artifact's card is not a drawn answer: still only the two actions. + expect( + await page.locator('[data-testid="make-artifact"]').count(), + ).toBe(2); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth > innerWidth, + ), + ).toBe(false); + } finally { + await page.close(); + } + }, 90_000); +}); diff --git a/app/tests/make-artifact.fixture.tsx b/app/tests/make-artifact.fixture.tsx new file mode 100644 index 0000000000..8febff91ef --- /dev/null +++ b/app/tests/make-artifact.fixture.tsx @@ -0,0 +1,105 @@ +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { type InfiniteData, QueryClientProvider } from "@tanstack/react-query"; +import { + createBrowserHistory, + createRootRoute, + createRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { createRoot } from "react-dom/client"; +import { AppSidebar } from "@/components/app-sidebar/app-sidebar"; +import { ChannelChat } from "@/components/channels/channel-chat"; +import { SidebarShell } from "@/components/layout/sidebar-shell"; +import { SidebarInset } from "@/components/ui/sidebar"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { + type AgentChannel, + type ChannelPage, + channelKeys, +} from "@/lib/channels/queries"; +import { generativeUiProviderOptions } from "@/lib/copilot/a2ui"; +import { ActiveBotProvider } from "@/lib/copilot/active-bot"; +import { ArtifactTools } from "@/lib/copilot/artifact-tools"; +import { BotOffers } from "@/lib/copilot/bot-offer"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { queryClient } from "@/query-client"; + +/** + * A conversation with a Bot that draws, as a page of its own for make-artifact-browser.test.tsx to + * bundle and load in a browser: the real conversation in the app's real frame, with the native + * catalog switched on as a deployment that draws interfaces has it, and the artifact tools' cards + * registered as the app registers them. The Bot is the test's server, a stock AG-UI agent. + */ +setCurrentOrganization("default"); + +const CONVERSATION: AgentChannel = { + id: "trip-conversation", + name: "Trip Planner", + agentIds: ["trip-planner"], + threadId: "trip-thread", + active: true, + lastMessageAt: "2026-12-04T09:00:00.000Z", +}; + +queryClient.setQueryDefaults(channelKeys.list(), { staleTime: Infinity }); +queryClient.setQueryData>(channelKeys.list(), { + pages: [ + { + channels: [ + { + ...CONVERSATION, + summary: "Weekend trip", + lastMessage: null, + lastMessageAgentId: null, + createdAt: "2026-12-04T09:00:00.000Z", + pinned: false, + lastReadAt: "2026-12-04T09:00:00.000Z", + }, + ], + nextCursor: null, + }, + ], + pageParams: [""], +}); + +const rootRoute = createRootRoute({ + component: () => ( + + + + + + + + + + + ), +}); +const router = createRouter({ + history: createBrowserHistory(), + routeTree: rootRoute.addChildren([ + createRoute({ + getParentRoute: () => rootRoute, + path: "$", + component: () => null, + }), + ]), +}); + +const root = document.getElementById("root"); +if (root) + createRoot(root).render( + + + + + + + , + );