|
| 1 | +import { GlobalRegistrator } from "@happy-dom/global-registrator"; |
| 2 | +import { QueryClientProvider } from "@tanstack/react-query"; |
| 3 | +import { cleanup, render, waitFor } from "@testing-library/react"; |
| 4 | +import userEvent from "@testing-library/user-event"; |
| 5 | +import { expect } from "bun:test"; |
| 6 | +import { ChannelChat } from "@/components/channels/channel-chat"; |
| 7 | +import { GALLERY as ACTIVITY } from "@/components/gallery/activity"; |
| 8 | +import { GALLERY as CARDS } from "@/components/gallery/cards"; |
| 9 | +import { GALLERY as CHARTS } from "@/components/gallery/charts"; |
| 10 | +import { GALLERY as DECISIONS } from "@/components/gallery/decisions"; |
| 11 | +import { GALLERY as FORMS } from "@/components/gallery/form"; |
| 12 | +import { GALLERY as QUOTES } from "@/components/gallery/quote"; |
| 13 | +import { GALLERY as TABLES } from "@/components/gallery/table"; |
| 14 | +import type { AgentChannel } from "@/lib/channels/queries"; |
| 15 | +import { GALLERY_COMPONENTS } from "@/lib/copilot/gallery-registry"; |
| 16 | +import { CopilotProvider } from "@/lib/copilot/provider"; |
| 17 | +import { deploymentKeys } from "@/lib/deployment/queries"; |
| 18 | +import { queryClient } from "@/query-client"; |
| 19 | +import { MY_CAPABILITIES_PATH } from "./admin-settings-api"; |
| 20 | +import { botGrantsPath, botGrantsResponse } from "./bot-grants-api"; |
| 21 | +import { answerBotsList, botPath } from "./bots-api"; |
| 22 | +import { |
| 23 | + ANNOUNCE_COMPONENTS_PATH, |
| 24 | + announcedResponse, |
| 25 | + botComponentsPath, |
| 26 | + botComponentsResponse, |
| 27 | +} from "./components-api"; |
| 28 | +import { settleReactWork } from "./settle-react-work"; |
| 29 | + |
| 30 | +/** |
| 31 | + * The signed-in app, as a person's conversation with one Bot sends its runs: the app's own |
| 32 | + * CopilotKit provider with every tool it registers, and every component of the gallery, as Vite |
| 33 | + * registers them (`import.meta.glob` is Vite's, so `bun test` finds none by itself). |
| 34 | + * |
| 35 | + * The Bot is the one with the most to offer: every component, its computer and both authoring |
| 36 | + * skills, with generative UI on. So its runs are production-sized: about 145 KB each, sent whole. |
| 37 | + * |
| 38 | + * Every run the app sends is kept as it left (`runs`), and answered by `answerRun`, which is the |
| 39 | + * server: by default a short reply. |
| 40 | + */ |
| 41 | + |
| 42 | +export const BOT = "run-parts-bot"; |
| 43 | +const channel: AgentChannel = { |
| 44 | + id: "run-parts-channel", |
| 45 | + name: "Run parts", |
| 46 | + agentIds: [BOT], |
| 47 | + threadId: "run-parts-thread", |
| 48 | + active: true, |
| 49 | + lastMessageAt: null, |
| 50 | +}; |
| 51 | +const NativeResponse = globalThis.Response; |
| 52 | +const EVERY_COMPONENT = [ |
| 53 | + ...ACTIVITY, |
| 54 | + ...CARDS, |
| 55 | + ...CHARTS, |
| 56 | + ...DECISIONS, |
| 57 | + ...FORMS, |
| 58 | + ...QUOTES, |
| 59 | + ...TABLES, |
| 60 | +]; |
| 61 | + |
| 62 | +/** A run as it left the browser: its body, exactly. */ |
| 63 | +export type SentRun = { raw: string; body: Record<string, unknown> }; |
| 64 | + |
| 65 | +export function sse(events: unknown[]): Response { |
| 66 | + return new NativeResponse( |
| 67 | + events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), |
| 68 | + { headers: { "content-type": "text/event-stream" } }, |
| 69 | + ); |
| 70 | +} |
| 71 | + |
| 72 | +/** A run answered in a word, as a Bot does. */ |
| 73 | +export function reply(body: Record<string, unknown>): Response { |
| 74 | + const id = `reply-${String(body.runId)}`; |
| 75 | + return sse([ |
| 76 | + { type: "RUN_STARTED", threadId: body.threadId, runId: body.runId }, |
| 77 | + { type: "TEXT_MESSAGE_START", messageId: id, role: "assistant" }, |
| 78 | + { type: "TEXT_MESSAGE_CONTENT", messageId: id, delta: "Done." }, |
| 79 | + { type: "TEXT_MESSAGE_END", messageId: id }, |
| 80 | + { type: "RUN_FINISHED", threadId: body.threadId, runId: body.runId }, |
| 81 | + ]); |
| 82 | +} |
| 83 | + |
| 84 | +class QuietSocket { |
| 85 | + static readonly OPEN = 1; |
| 86 | + readyState = 0; |
| 87 | + onopen: (() => void) | null = null; |
| 88 | + onclose: (() => void) | null = null; |
| 89 | + onerror: (() => void) | null = null; |
| 90 | + onmessage: ((event: { data: unknown }) => void) | null = null; |
| 91 | + send() {} |
| 92 | + close() {} |
| 93 | +} |
| 94 | + |
| 95 | +export const runs: SentRun[] = []; |
| 96 | +/** The server's answer to each run. */ |
| 97 | +export let answerRun: (run: SentRun) => Response | Promise<Response> = (run) => |
| 98 | + reply(run.body); |
| 99 | +export function answerRunsWith( |
| 100 | + answer: (run: SentRun) => Response | Promise<Response>, |
| 101 | +) { |
| 102 | + answerRun = answer; |
| 103 | +} |
| 104 | + |
| 105 | +let originalFetch: typeof fetch; |
| 106 | +let originalSocket: typeof WebSocket; |
| 107 | +let added: typeof EVERY_COMPONENT = []; |
| 108 | + |
| 109 | +export function setUpApp() { |
| 110 | + if (GALLERY_COMPONENTS.length === 0) { |
| 111 | + added = [...EVERY_COMPONENT].sort((a, b) => a.name.localeCompare(b.name)); |
| 112 | + GALLERY_COMPONENTS.push(...added); |
| 113 | + } |
| 114 | + GlobalRegistrator.register(); |
| 115 | + originalFetch = globalThis.fetch; |
| 116 | + originalSocket = globalThis.WebSocket; |
| 117 | + globalThis.WebSocket = QuietSocket as unknown as typeof WebSocket; |
| 118 | + globalThis.fetch = Object.assign( |
| 119 | + async (input: Parameters<typeof fetch>[0], init?: RequestInit) => { |
| 120 | + const url = new URL( |
| 121 | + typeof input === "string" |
| 122 | + ? input |
| 123 | + : input instanceof URL |
| 124 | + ? input.href |
| 125 | + : input.url, |
| 126 | + "http://localhost", |
| 127 | + ); |
| 128 | + const request = input instanceof Request ? input : new Request(url, init); |
| 129 | + if (url.pathname === ANNOUNCE_COMPONENTS_PATH) return announcedResponse(); |
| 130 | + if (url.pathname === botComponentsPath(BOT)) |
| 131 | + return botComponentsResponse( |
| 132 | + EVERY_COMPONENT.map((spec) => ({ |
| 133 | + name: spec.name, |
| 134 | + description: spec.description, |
| 135 | + })), |
| 136 | + ); |
| 137 | + if (url.pathname === botPath(BOT)) |
| 138 | + return NativeResponse.json({ |
| 139 | + bot: { |
| 140 | + id: BOT, |
| 141 | + name: "Run parts", |
| 142 | + visibility: "public", |
| 143 | + canManage: true, |
| 144 | + }, |
| 145 | + }); |
| 146 | + if (url.pathname === botGrantsPath(BOT)) |
| 147 | + return botGrantsResponse({ |
| 148 | + skills: [ |
| 149 | + { |
| 150 | + slug: "bot-creator", |
| 151 | + title: "Make a coworker", |
| 152 | + summary: "", |
| 153 | + instructions: "", |
| 154 | + }, |
| 155 | + { |
| 156 | + slug: "skill-creator", |
| 157 | + title: "Make a skill", |
| 158 | + summary: "", |
| 159 | + instructions: "", |
| 160 | + }, |
| 161 | + ], |
| 162 | + tools: [], |
| 163 | + }); |
| 164 | + if (url.pathname === MY_CAPABILITIES_PATH) |
| 165 | + return NativeResponse.json({ capabilities: {}, enforced: false }); |
| 166 | + if (url.pathname.endsWith("/info")) |
| 167 | + return NativeResponse.json({ |
| 168 | + version: "fixture", |
| 169 | + agents: { [BOT]: { description: "Fixture", capabilities: {} } }, |
| 170 | + mode: "sse", |
| 171 | + telemetryDisabled: true, |
| 172 | + }); |
| 173 | + if (url.pathname.endsWith("/connect")) { |
| 174 | + const { threadId } = (await request.json()) as { threadId: string }; |
| 175 | + return sse([ |
| 176 | + { type: "RUN_STARTED", threadId, runId: "join" }, |
| 177 | + { type: "MESSAGES_SNAPSHOT", messages: [] }, |
| 178 | + { type: "RUN_FINISHED", threadId, runId: "join" }, |
| 179 | + ]); |
| 180 | + } |
| 181 | + if (url.pathname.endsWith("/run")) { |
| 182 | + const raw = await request.text(); |
| 183 | + const run = { raw, body: JSON.parse(raw) as Record<string, unknown> }; |
| 184 | + runs.push(run); |
| 185 | + return answerRun(run); |
| 186 | + } |
| 187 | + if (url.pathname.match(/\/threads\/[^/]+\/messages$/)) |
| 188 | + return NativeResponse.json({ messages: [] }); |
| 189 | + const bots = answerBotsList(url, init, { visible: [] }); |
| 190 | + if (bots) return bots; |
| 191 | + if (/^\/api\/plugins\/for\/[^/]+$/.test(url.pathname)) |
| 192 | + return NativeResponse.json({ skills: [], tools: [] }); |
| 193 | + if (/voice-sessions$/.test(url.pathname)) |
| 194 | + return NativeResponse.json({ sessions: [], nextCursor: null }); |
| 195 | + if (/\/(activity|signal-busy|mark-read)$/.test(url.pathname)) |
| 196 | + return new NativeResponse(null, { status: 204 }); |
| 197 | + if (/approval-modes\/[^/]+$/.test(url.pathname)) |
| 198 | + return NativeResponse.json({ asksEveryStep: false }); |
| 199 | + return NativeResponse.json({ error: "Not found" }, { status: 404 }); |
| 200 | + }, |
| 201 | + { preconnect: () => undefined }, |
| 202 | + ); |
| 203 | +} |
| 204 | + |
| 205 | +export async function tearDownApp() { |
| 206 | + cleanup(); |
| 207 | + await settleReactWork(); |
| 208 | + for (const spec of added) |
| 209 | + GALLERY_COMPONENTS.splice(GALLERY_COMPONENTS.indexOf(spec), 1); |
| 210 | + added = []; |
| 211 | + globalThis.fetch = originalFetch; |
| 212 | + globalThis.WebSocket = originalSocket; |
| 213 | + GlobalRegistrator.unregister(); |
| 214 | +} |
| 215 | + |
| 216 | +/** |
| 217 | + * The app open on the Bot's conversation, on a server that does or doesn't take a run's parts by |
| 218 | + * reference, with `send` to type a message and press Enter. |
| 219 | + */ |
| 220 | +export async function openConversation(options: { |
| 221 | + runPartsByReference: boolean | undefined; |
| 222 | +}) { |
| 223 | + cleanup(); |
| 224 | + queryClient.clear(); |
| 225 | + runs.length = 0; |
| 226 | + queryClient.setQueryData(deploymentKeys.capabilities(), { |
| 227 | + generativeUi: true, |
| 228 | + selfHostBanner: false, |
| 229 | + localEvaluation: false, |
| 230 | + ...(options.runPartsByReference === undefined |
| 231 | + ? {} |
| 232 | + : { runPartsByReference: options.runPartsByReference }), |
| 233 | + } as never); |
| 234 | + const view = render( |
| 235 | + <QueryClientProvider client={queryClient}> |
| 236 | + <CopilotProvider> |
| 237 | + <ChannelChat channel={channel} runtimeAgentId={BOT} /> |
| 238 | + </CopilotProvider> |
| 239 | + </QueryClientProvider>, |
| 240 | + ); |
| 241 | + const user = userEvent.setup({ document: view.container.ownerDocument }); |
| 242 | + const editor = await view.findByRole("textbox", { name: "Message" }); |
| 243 | + await waitFor(() => |
| 244 | + expect(editor.getAttribute("aria-disabled")).not.toBe("true"), |
| 245 | + ); |
| 246 | + const send = async (text: string) => { |
| 247 | + const before = runs.length; |
| 248 | + await user.click(editor); |
| 249 | + await user.keyboard(text); |
| 250 | + await user.keyboard("{Enter}"); |
| 251 | + await waitFor(() => expect(runs.length).toBeGreaterThan(before), { |
| 252 | + timeout: 10_000, |
| 253 | + }); |
| 254 | + return runs[runs.length - 1] as SentRun; |
| 255 | + }; |
| 256 | + return { view, send }; |
| 257 | +} |
0 commit comments