diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3452be1743..b879036197 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -620,7 +620,9 @@ jobs: # Bots panels saying Working for as long as its Bot works, through a read of every query and # while a task it handed out works on. And Return in the message box starting a new line on a # phone's touch keyboard while a computer's Enter still sends, never on the Enter that confirms - # a composed character. And a Bot's instructions at 5000 characters, held whole by its Setup + # a composed character. And every key typed in the message box landing where it was typed while a + # Bot's answer streams in, as it starts and ends, typed into the middle of the words, and in Home's + # box locked to a Bot, the box never drawn again under the keys. And a Bot's instructions at 5000 characters, held whole by its Setup # page and the New Bot sheet, and a 5001st refused in view. And push notifications in this # browser, turned on and off in Settings and saved through the API, a push shown by the service # worker and a click on it opening its conversation, and on an iPhone in Safari the Home Screen @@ -808,6 +810,7 @@ jobs: app/tests/composer-keeps-draft-browser.test.tsx app/tests/composer-send-while-dictating.test.tsx app/tests/composer-touch-return.test.tsx + app/tests/composer-typing-while-streaming.test.tsx app/tests/computer-panel-phone-layout.test.tsx app/tests/computer-starting-browser.test.tsx app/tests/connected-bot-mistakes-layout.test.tsx diff --git a/app/src/components/channels/composer/composer.tsx b/app/src/components/channels/composer/composer.tsx index 827606598b..713941ffe9 100644 --- a/app/src/components/channels/composer/composer.tsx +++ b/app/src/components/channels/composer/composer.tsx @@ -98,6 +98,8 @@ import { useDictation } from "./use-dictation"; /** One shared empty list, so a box with no commands does not rebuild its triggers per render. */ const NO_COMMANDS: readonly CommandOption[] = []; +/** The same for a box with no Bots to mention. */ +const NO_AGENTS: readonly AgentOption[] = []; /** Send was pressed while live dictation listened, it heard nothing, and the box had nothing else. */ const NOTHING_HEARD = "No words were heard, so nothing was sent. Try again."; @@ -461,8 +463,8 @@ export function Composer({ compact = false, voiceCall, modelPicker, - agents = [], - lockedAgent, + agents: givenAgents = NO_AGENTS, + lockedAgent: givenLockedAgent, commands = NO_COMMANDS, onSubmit, onQueue, @@ -482,6 +484,27 @@ export function Composer({ queuedAttachmentCount = 0, draftKey, }: ComposerProps) { + /* + * THE BOTS, AND THE BOT THE BOX IS LOCKED TO, KEPT THE SAME OBJECTS WHILE THEY SAY THE SAME THING. + * + * The screens build them afresh on every render (`toAgentOptions(...)` in `channel-chat.tsx` and + * on Home), and a conversation renders again for every word of an answer as it streams in. Each + * new list was a new `triggers` for prompt-area, and a new locked Bot a new `value`, and either + * makes prompt-area draw the box again from `value`, after the render that brought them. A key + * pressed in that moment is not in that `value` yet: the box was drawn without the letter just + * typed, then with it, and the caret was left where the shorter words ended. So the next letters + * went in front of the last one ("teh"), and in an empty box the caret went to the start, with + * everything typed after it landing ahead of the first letter. Kept the same, they change only + * when a Bot does, so an answer streaming in never draws the box again under somebody typing. + */ + const agents = useKeptWhileSame( + givenAgents, + JSON.stringify(givenAgents.map(agentKey)), + ); + const lockedAgent = useKeptWhileSame( + givenLockedAgent, + givenLockedAgent ? JSON.stringify(agentKey(givenLockedAgent)) : "", + ); /* * Where this composer keeps its unsent message, and what it had kept, read once as it mounts. * Words handed in by the caller (`initialValue`, `initialFiles`) are a message being put back on @@ -2511,6 +2534,21 @@ export function Composer({ ); } +/** What a Bot shows in the box: its chip and its line in the `@` menu. */ +function agentKey(agent: AgentOption) { + return [agent.id, agent.name, agent.description ?? null, agent.avatarSeed]; +} + +/** + * `value`, or the one kept before it while `key` is the same: a new object only once it says + * something new. Kept as `chat-transcript.tsx` keeps the names its steps found. + */ +function useKeptWhileSame(value: T, key: string): T { + const kept = useRef({ key, value }); + if (kept.current.key !== key) kept.current = { key, value }; + return kept.current.value; +} + /** The locked Bot's chip, as `@` would have made it. */ function lockedChip(agent: AgentOption): Segment { return { diff --git a/app/tests/composer-typing-while-streaming.fixture.tsx b/app/tests/composer-typing-while-streaming.fixture.tsx new file mode 100644 index 0000000000..370e4eb973 --- /dev/null +++ b/app/tests/composer-typing-while-streaming.fixture.tsx @@ -0,0 +1,139 @@ +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { useEffect, useState } from "react"; +import { createRoot } from "react-dom/client"; +import { Composer } from "@/components/channels/composer/composer"; +import { toAgentOptions } from "@/components/channels/composer/triggers"; +import { authKeys } from "@/lib/auth/queries"; +import { deploymentKeys } from "@/lib/deployment/queries"; +import { queryClient } from "@/query-client"; + +/** + * The message box under a Bot's answer as it streams in, for composer-typing-while-streaming.test.tsx + * to bundle and load in a browser. + * + * The answer grows by a word every `TOKEN_MS`, from a timer, as a socket's messages arrive: each word + * renders the page again at the default priority, as `useAgent`'s update does in `channel-chat.tsx`. + * Drawing it takes `RENDER_MS`, standing in for the transcript laying out a long answer again. And + * every render hands the box its Bots as new objects, built by `toAgentOptions`, as the screens do. + * + * `?layout=thread` (the default) is a conversation's compact box, with the props + * `conversation-view.tsx` gives it: a turn in flight while the answer streams, and a queue to park + * a message in. `?layout=home` is Home's box locked to a Bot, as `index.tsx` draws it when a Bot is + * pressed in the Bots panel, with the page rendering again as a Bot works elsewhere. + * + * `window.stream(true)` starts the answer and `window.stream(false)` ends it. `?token=` streams + * slower than a word every 16 ms, for watching it. + */ +declare global { + interface Window { + stream: (on: boolean) => void; + } +} + +const params = new URLSearchParams(location.search); +const RENDER_MS = 8; +const TOKEN_MS = Number(params.get("token") ?? 16); + +queryClient.setQueryData(deploymentKeys.capabilities(), { + generativeUi: true, + transcription: false, +}); +queryClient.setQueryData(authKeys.currentUser(), { + id: "u-1", + name: "Dana Reyes", + email: "dana@example.com", +}); + +const PROFILES = [{ id: "design-bot", name: "Design Bot", title: "Design" }]; + +/** What the Bot writes, a word at a time, from the start again once it runs out. */ +const ANSWER = ( + "Here is a first pass at the landing page. The opening section leads with the promise in one " + + "line and a single button, so the page says what it is before it asks for anything. The second " + + "section walks through the three things a team does in its first week, each with a short " + + "example drawn from a real conversation, and a picture of the screen it happens on. The third " + + "section answers the questions people ask on a first call: where their data lives, what a Bot " + + "may touch, and how a person stays in charge of every change. The page closes on the same " + + "button it opened with, and a line about pricing for anyone still deciding. For the visuals, " + + "the screens are the product's own, cropped close enough to read, with nothing drawn on top of " + + "them. Each example names the team it came from and what they were trying to get done, in their " + + "words rather than ours. The tone stays plain: short sentences, no claims a reader cannot check, " + + "and every number on the page linked to where it came from. I kept the copy for the second " + + "section longest, because that is where a reader decides whether this is for them, but it can " + + "come down by a third without losing an example if you would rather the page scrolled less. " + + "Next I can draft the three examples in full, or mock up the opening section at a phone's width." +).split(" "); + +/** The Bot's answer so far, laid out for as long as a long answer takes. */ +function Answer({ words }: { words: number }) { + const until = performance.now() + RENDER_MS; + while (performance.now() < until) { + // Standing in for the transcript's markdown, parsed and laid out again for every token. + } + return ( +

+ {Array.from({ length: words }, (_, i) => ANSWER[i % ANSWER.length]).join( + " ", + )} +

+ ); +} + +function Page() { + const [streaming, setStreaming] = useState(false); + const [words, setWords] = useState(0); + useEffect(() => { + window.stream = setStreaming; + }, []); + useEffect(() => { + if (!streaming) return; + const id = setInterval(() => setWords((count) => count + 1), TOKEN_MS); + return () => clearInterval(id); + }, [streaming]); + + if (params.get("layout") === "home") { + return ( +
+ undefined} + /> +
+ +
+
+ ); + } + return ( +
+
+ +
+
+ undefined} + onSubmit={() => undefined} + pending={streaming} + /> +
+
+ ); +} + +const root = document.getElementById("root"); +if (root) { + createRoot(root).render( + + + + + , + ); +} diff --git a/app/tests/composer-typing-while-streaming.test.tsx b/app/tests/composer-typing-while-streaming.test.tsx new file mode 100644 index 0000000000..efb276ed0b --- /dev/null +++ b/app/tests/composer-typing-while-streaming.test.tsx @@ -0,0 +1,293 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { test } from "./renderer-crash"; + +/** + * Typing in the message box while a Bot's answer streams in: every key lands where it was typed. + * + * Reported on the web app: "sometimes (maybe esp while content is being generated) it jumps to the + * beginning and the text you write gets garbled. Sometimes it appears to jump twice, a visual + * glitch, but the text is fine." Typed while the answer streamed, a letter landed in front of the + * one before it ("teh"), and the caret was put back short of where the person had left it. + * + * The box is the real composer, bundled from the fixture beside this file with the app's + * stylesheet, under an answer that grows a word every 16 ms the way a streamed one does: each word + * renders the conversation again, at the default priority, taking a few milliseconds to draw. The + * person types with the keyboard, at the pace of a quick typist. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/composer-typing-while-streaming.test.tsx + * + * Chromium by default. OPENBOT_APP_ENGINES=chromium,webkit adds WebKit. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +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 ORIGIN = "http://openbot.test"; +const SENTENCE = + "Actually, make the second section shorter and keep the tone warm but direct"; + +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [ + join(import.meta.dir, "composer-typing-while-streaming.fixture.tsx"), + ], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + }); + 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(); +} + +/** 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 = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package for ${id}`); + 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 script: string; + +beforeAll(async () => { + if (!asked) return; + script = await bundle(); + 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(); +}); + +async function open( + engine: "chromium" | "webkit", + layout: "thread" | "home", +): Promise { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: { width: 1280, height: 800 }, + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + await page.route(`${ORIGIN}/**`, (route) => { + const path = new URL(route.request().url()).pathname; + if (path === "/composer.js") + return route.fulfill({ contentType: "text/javascript", body: script }); + if (path === "/") + return route.fulfill({ + contentType: "text/html", + body: '
', + }); + return route.fulfill({ status: 404 }); + }); + await page.goto(`${ORIGIN}/?layout=${layout}`); + await editor(page).waitFor(); + const classes = await page.evaluate(() => [ + ...new Set( + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ), + ]); + await page.addStyleTag({ content: await stylesheet(classes) }); + return page; +} + +const editor = (page: Page) => page.getByRole("textbox", { name: "Message" }); + +/** + * Watch the box from here on: every time its words were drawn again from scratch (its children + * replaced) rather than typed into, with the words it was drawn with. + */ +async function watchRedraws(page: Page) { + await editor(page).evaluate((box) => { + const redraws: string[] = []; + new MutationObserver((records) => { + if ( + records.some( + (record) => record.target === box && record.removedNodes.length > 0, + ) + ) + redraws.push(box.textContent ?? ""); + }).observe(box, { childList: true, subtree: true, characterData: true }); + (window as unknown as { redraws: string[] }).redraws = redraws; + }); +} + +/** The box's words, where the caret is in them, and every redraw since `watchRedraws`. */ +function read(page: Page) { + return editor(page).evaluate((box) => { + const selection = getSelection(); + let caret: number | null = null; + if ( + selection?.rangeCount && + box.contains(selection.getRangeAt(0).startContainer) + ) { + const before = document.createRange(); + before.selectNodeContents(box); + const range = selection.getRangeAt(0); + before.setEnd(range.startContainer, range.startOffset); + caret = before.toString().length; + } + return { + text: box.textContent ?? "", + caret, + redraws: (window as unknown as { redraws: string[] }).redraws, + }; + }); +} + +/** Start or end the answer above the box. */ +const stream = (page: Page, on: boolean) => + page.evaluate((streaming) => window.stream(streaming), on); + +/** Typed at the pace of a quick typist: a key every 30 ms. */ +const type = (page: Page, words: string) => + page.keyboard.type(words, { delay: 30 }); + +describe.skipIf(!asked)( + "Typing in the message box while an answer streams", + () => { + for (const engine of engines) { + test(`every key lands where it was typed, in ${engine}`, async () => { + const page = await open(engine, "thread"); + try { + await editor(page).click(); + await stream(page, true); + await watchRedraws(page); + await type(page, SENTENCE); + const box = await read(page); + await stream(page, false); + + expect(box.text).toBe(SENTENCE); + expect(box.caret).toBe(SENTENCE.length); + // Never drawn again under the keys: a redraw puts the caret back at its offset in the words + // it draws, and drawn with the words from a key ago, that is short of where it was. + expect(box.redraws).toEqual([]); + } finally { + await page.close(); + } + }, 60_000); + + test(`every key lands where it was typed as an answer starts and ends, in ${engine}`, async () => { + const page = await open(engine, "thread"); + try { + await editor(page).click(); + await watchRedraws(page); + // The box goes from idle to a turn in flight and back, mid-sentence. + await type(page, "Actually, make the "); + await stream(page, true); + await type(page, "second section shorter and keep "); + await stream(page, false); + await type(page, "the tone warm but direct"); + const box = await read(page); + + expect(box.text).toBe(SENTENCE); + expect(box.caret).toBe(SENTENCE.length); + expect(box.redraws).toEqual([]); + } finally { + await page.close(); + } + }, 60_000); + + test(`words typed into the middle of the box are never drawn twice, in ${engine}`, async () => { + const page = await open(engine, "thread"); + try { + const after = "keep the tone warm but direct"; + await editor(page).click(); + await type(page, `Actually, ${after}`); + // Back in front of "keep", and the words that were missing typed there while the answer + // streams. + for (let i = 0; i < after.length; i++) + await page.keyboard.press("ArrowLeft"); + await stream(page, true); + await watchRedraws(page); + await type(page, "make the second section shorter and "); + const box = await read(page); + await stream(page, false); + + expect(box.text).toBe(SENTENCE); + expect(box.caret).toBe(SENTENCE.length - after.length); + // Drawn again with the words from a key ago, the caret lands back where it was in the + // middle of the words, so they come out right: but the box is drawn twice for that key, and + // seen to jump. + expect(box.redraws).toEqual([]); + } finally { + await page.close(); + } + }, 60_000); + + test(`every key lands where it was typed in Home's box locked to a Bot, in ${engine}`, async () => { + const page = await open(engine, "home"); + try { + // Opened for the Bot, the box has the caret after its chip, as Home's does. + await page.waitForFunction(() => + document.activeElement?.matches('[role="textbox"]'), + ); + await stream(page, true); + await watchRedraws(page); + await type(page, SENTENCE); + const box = await read(page); + await stream(page, false); + + expect(box.text).toBe(`@Design Bot ${SENTENCE}`); + expect(box.caret).toBe(box.text.length); + expect(box.redraws).toEqual([]); + } finally { + await page.close(); + } + }, 60_000); + } + }, +);