Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

test(e2e): browser coverage for the shipped chat composer and transcript

M3gA-Mindab914c996080
diff --git a/app/test/playwright/specs/chat-composer-attachment-gate.spec.ts b/app/test/playwright/specs/chat-composer-attachment-gate.spec.ts
new file mode 100644
index 0000000000..8488e000e5
--- /dev/null
+++ b/app/test/playwright/specs/chat-composer-attachment-gate.spec.ts
@@ -0,0 +1,159 @@
+/**
+ * Chat composer — the attachment gate on the composer the product ships.
+ *
+ * # Scope, and what was cut from it after probing
+ *
+ * The task framed this as a bypass risk: drag-drop and paste might skip the
+ * gate the `[+]` button enforces. That framing belongs to the LEGACY composer
+ * (`ChatComposer.tsx:288-317`), which implements `handleDrop` / `handlePaste`
+ * and gates both on `attachDisabled`. `/chat` does not render that file
+ * (`Conversations.tsx:2539`, default `composer = 'text'`).
+ *
+ * The live composer supplies only a `[+]` button and a hidden
+ * `input[type=file]` (`AssistantUiChat.tsx:160-185`); neither it nor
+ * `assistant-ui/thread.tsx` defines `onDrop`, `onPaste` or `onDragOver`.
+ * Probed against the running app, dispatching `dragover` + `drop` with a
+ * populated `DataTransfer` on **every ancestor** of the input — including the
+ * element carrying `data-[dragging=true]:border-ring`, assistant-ui's own
+ * `AttachmentDropzone` — attached nothing, while `setInputFiles` in the same
+ * run attached fine.
+ *
+ * **So there is no drop/paste spec here, on purpose.** "Dropping a file while
+ * streaming does not attach" would pass because dropping never attaches in any
+ * state; it cannot distinguish a working gate from a dead gesture, and writing
+ * it would put a green test over a probable regression. The finding is in
+ * `~/tinyhuman/bugs/W2-ui-bugs.md` as BUG-W2-UI-1 for a human to confirm with a
+ * real drag.
+ *
+ * What IS real and falsifiable is the gate on the control that does ingest:
+ * `disabled={attachmentInteractionBlocked || attachments.length >= maxAttachments}`
+ * (`AssistantUiChat.tsx:178`), where `attachmentInteractionBlocked` is
+ * `composerInteractionBlocked || isSending` (`Conversations.tsx:2522`). This
+ * file covers that, end to end, through the UI.
+ */
+import { expect, type Locator, type Page, test } from '@playwright/test';
+
+import { bootAuthenticatedPage, dismissWalkthroughIfPresent } from '../helpers/core-rpc';
+
+const MOCK_ADMIN_BASE = `http://127.0.0.1:${process.env.E2E_MOCK_PORT || '18402'}`;
+const USER_ID = 'pw-chat-attach-gate';
+
+const SLOW_STREAM = [
+ ...Array.from({ length: 24 }, (_, i) => ({ text: `chunk${i + 1} `, delayMs: 1000 })),
+ { finish: 'stop' },
+];
+
+async function resetMock(): Promise<void> {
+ await fetch(`${MOCK_ADMIN_BASE}/__admin/reset`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({}),
+ });
+}
+
+async function setMockBehavior(key: string, value: string): Promise<void> {
+ await fetch(`${MOCK_ADMIN_BASE}/__admin/behavior`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ key, value }),
+ });
+}
+
+async function openChat(page: Page): Promise<void> {
+ await bootAuthenticatedPage(page, USER_ID, '/chat');
+ await dismissWalkthroughIfPresent(page);
+ await expect(page.getByTestId('chat-message-input')).toBeVisible({ timeout: 30_000 });
+}
+
+const composer = (page: Page): Locator => page.getByTestId('chat-message-input');
+const sendButton = (page: Page): Locator => page.getByTestId('send-message-button');
+const stopButton = (page: Page): Locator => page.getByTestId('stop-generation-button');
+/** The `[+]` control carries no testid — it is found by its accessible name. */
+const attachButton = (page: Page): Locator => page.getByRole('button', { name: 'Attach file' });
+const fileInput = (page: Page): Locator => page.locator('input[type="file"]');
+
+async function attach(page: Page, name: string, body = 'attached by the picker'): Promise<void> {
+ await fileInput(page)
+ .first()
+ .setInputFiles({ name, mimeType: 'text/plain', buffer: Buffer.from(body) });
+}
+
+async function beginStreamingTurn(page: Page, prompt: string): Promise<void> {
+ await composer(page).click();
+ await page.keyboard.type(prompt);
+ await expect(sendButton(page)).toBeVisible();
+ await sendButton(page).click();
+ await expect(stopButton(page)).toBeVisible({ timeout: 20_000 });
+}
+
+test.describe('Chat composer attachment gate', () => {
+ test.beforeEach(async () => {
+ await resetMock();
+ await setMockBehavior('llmStreamScript', JSON.stringify(SLOW_STREAM));
+ await setMockBehavior('llmStreamChunkDelayMs', '1000');
+ });
+
+ test('the picker attaches a file and the chip names it', async ({ page }) => {
+ // The control case for everything below: if this stops working, a
+ // "nothing attached" assertion elsewhere means nothing.
+ await openChat(page);
+ await expect(attachButton(page)).toBeEnabled();
+
+ await attach(page, 'picker-notes.txt');
+
+ await expect(page.getByText('picker-notes.txt')).toBeVisible({ timeout: 10_000 });
+ });
+
+ test('an attached file can be removed again', async ({ page }) => {
+ await openChat(page);
+ await attach(page, 'removable.txt');
+ await expect(page.getByText('removable.txt')).toBeVisible({ timeout: 10_000 });
+
+ await page.getByRole('button', { name: /Remove removable\.txt/ }).click();
+
+ await expect(page.getByText('removable.txt')).toHaveCount(0);
+ });
+
+ test('the [+] button is disabled while a turn streams', async ({ page }) => {
+ // The gate itself: `attachmentInteractionBlocked = composerInteractionBlocked
+ // || isSending`. Enabled before, disabled during — both halves asserted, so
+ // the test cannot pass against a button that is simply always disabled.
+ await openChat(page);
+ await expect(attachButton(page)).toBeEnabled();
+
+ await beginStreamingTurn(page, 'Count slowly for me');
+
+ await expect(
+ attachButton(page),
+ 'a turn in flight must close the attach affordance'
+ ).toBeDisabled();
+ });
+
+ test('the [+] button becomes usable again once the turn is stopped', async ({ page }) => {
+ // Without this, "disabled during a turn" could be satisfied by a button
+ // that never recovers — which would be a worse bug than the one being
+ // guarded against.
+ await openChat(page);
+ await beginStreamingTurn(page, 'Count slowly for me');
+ await expect(attachButton(page)).toBeDisabled();
+
+ await stopButton(page).click();
+ await expect(stopButton(page)).toHaveCount(0, { timeout: 20_000 });
+
+ await expect(attachButton(page)).toBeEnabled({ timeout: 20_000 });
+ });
+
+ test('an attachment keeps the Send affordance even with no typed text', async ({ page }) => {
+ // `showIdleAction` requires `!hasComposerAttachments` (thread.tsx:494-495),
+ // so an attachment alone must hand the slot to Send — otherwise a user who
+ // attaches a file and types nothing has no way to send it.
+ await openChat(page);
+ await expect(page.getByTestId('composer-human-mode')).toBeVisible();
+
+ await attach(page, 'send-me.txt');
+ await expect(page.getByText('send-me.txt')).toBeVisible({ timeout: 10_000 });
+
+ await expect(sendButton(page)).toBeVisible();
+ await expect(page.getByTestId('composer-human-mode')).toHaveCount(0);
+ });
+});
diff --git a/app/test/playwright/specs/chat-composer-primary-slot.spec.ts b/app/test/playwright/specs/chat-composer-primary-slot.spec.ts
new file mode 100644
index 0000000000..b5c573edaa
--- /dev/null
+++ b/app/test/playwright/specs/chat-composer-primary-slot.spec.ts
@@ -0,0 +1,191 @@
+/**
+ * Chat composer — the primary-slot state machine, on the composer the product
+ * actually ships.
+ *
+ * # Which composer this is, and why that needed establishing
+ *
+ * `Conversations.tsx:2539` picks `composer === 'mic-cloud' ? legacyMainPanel :
+ * assistantUiMainPanel`, and `composer` defaults to `'text'`
+ * (`:255`), so `/chat` renders the **assistant-ui** composer. `ChatComposer.tsx`
+ * is the legacy one. A DOM probe against the running app confirms it: the page
+ * contains `composer-human-mode` (`AssistantUiChat.tsx:204`) and **not**
+ * `human-mode-button` (`ChatComposer.tsx:494`), and `chat-message-input` is a
+ * Lexical `[contenteditable]` (`thread.tsx:346`), not a `<textarea>`.
+ *
+ * That distinction is the whole reason this file exists rather than a spec
+ * against `ChatComposer`: the two composers do not behave the same.
+ *
+ * # The live rule
+ *
+ * <AuiIf condition={s => !s.thread.isRunning}>
+ * {showIdleAction ? <ComposerIdleAction/> : <Send/>} thread.tsx:548-594
+ * </AuiIf>
+ * <AuiIf condition={s => s.thread.isRunning}>
+ * <Stop/> thread.tsx:596-608
+ * </AuiIf>
+ *
+ * showIdleAction = !!ComposerIdleAction
+ * && composerText.trim().length === 0
+ * && !hasComposerAttachments thread.tsx:494-495
+ *
+ * Note what is NOT there: the live Stop condition has **no typed-content
+ * term**. The legacy composer reverts Stop to Send once a follow-up is typed
+ * (`ChatComposer.tsx:252-253`); the shipped one does not. This spec asserts the
+ * shipped behaviour, and says so, so a future reader does not "fix" the test
+ * toward the legacy rule.
+ *
+ * Assertions are on which control is mounted and on the contenteditable's
+ * rendered text — never on a mock call. `toHaveValue()` is unusable here: the
+ * input is a contenteditable, and an earlier draft failed in 1.3s learning that.
+ */
+import { expect, type Locator, type Page, test } from '@playwright/test';
+
+import { bootAuthenticatedPage, dismissWalkthroughIfPresent } from '../helpers/core-rpc';
+
+const MOCK_ADMIN_BASE = `http://127.0.0.1:${process.env.E2E_MOCK_PORT || '18402'}`;
+const USER_ID = 'pw-chat-primary-slot';
+
+/**
+ * `safeDelayMs` (`scripts/mock-api/routes/llm.mjs:200-210`) CLAMPS any delay to
+ * 1000ms, so a stream is made long by adding chunks, not by asking for a bigger
+ * delay. 24 chunks ≈ 24s of open stream, inside the 60s test timeout.
+ */
+const SLOW_STREAM = [
+ ...Array.from({ length: 24 }, (_, i) => ({ text: `chunk${i + 1} `, delayMs: 1000 })),
+ { finish: 'stop' },
+];
+
+async function resetMock(): Promise<void> {
+ await fetch(`${MOCK_ADMIN_BASE}/__admin/reset`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({}),
+ });
+}
+
+async function setMockBehavior(key: string, value: string): Promise<void> {
+ await fetch(`${MOCK_ADMIN_BASE}/__admin/behavior`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ key, value }),
+ });
+}
+
+/**
+ * `bootAuthenticatedPage(.., '/chat')` already navigates to #/chat and runs
+ * `waitForAppReady`. The sibling chat specs then repeat both, which re-navigates
+ * the app mid-boot; under a loaded machine that left the first tests of a file
+ * on a blank `#root` until the 60s timeout. One navigation.
+ */
+async function openChat(page: Page): Promise<void> {
+ await bootAuthenticatedPage(page, USER_ID, '/chat');
+ await dismissWalkthroughIfPresent(page);
+ await expect(page.getByTestId('chat-message-input')).toBeVisible({ timeout: 30_000 });
+}
+
+const composer = (page: Page): Locator => page.getByTestId('chat-message-input');
+const sendButton = (page: Page): Locator => page.getByTestId('send-message-button');
+const stopButton = (page: Page): Locator => page.getByTestId('stop-generation-button');
+const idleAction = (page: Page): Locator => page.getByTestId('composer-human-mode');
+
+/** Type into the Lexical surface — `fill()` does not apply to contenteditable. */
+async function typeIntoComposer(page: Page, text: string): Promise<void> {
+ await composer(page).click();
+ await page.keyboard.type(text);
+}
+
+async function clearComposer(page: Page): Promise<void> {
+ await composer(page).click();
+ await page.keyboard.press('ControlOrMeta+a');
+ await page.keyboard.press('Backspace');
+}
+
+async function beginStreamingTurn(page: Page, prompt: string): Promise<void> {
+ await typeIntoComposer(page, prompt);
+ await expect(sendButton(page)).toBeVisible();
+ await sendButton(page).click();
+ await expect(stopButton(page)).toBeVisible({ timeout: 20_000 });
+}
+
+test.describe('Chat composer primary slot', () => {
+ test.beforeEach(async () => {
+ await resetMock();
+ await setMockBehavior('llmStreamScript', JSON.stringify(SLOW_STREAM));
+ await setMockBehavior('llmStreamChunkDelayMs', '1000');
+ });
+
+ test('an idle empty composer offers the mascot action, not a dead Send arrow', async ({
+ page,
+ }) => {
+ await openChat(page);
+
+ await expect(idleAction(page)).toBeVisible();
+ await expect(sendButton(page)).toHaveCount(0);
+ await expect(stopButton(page)).toHaveCount(0);
+ });
+
+ test('the first typed character hands the slot to Send, and clearing hands it back', async ({
+ page,
+ }) => {
+ // `showIdleAction` keys off `composerText.trim().length === 0`, so this is
+ // the live equivalent of the legacy `hasTypedContent` swap — and the trim
+ // matters: whitespace alone must not count as content.
+ await openChat(page);
+ await expect(idleAction(page)).toBeVisible();
+
+ await typeIntoComposer(page, 'h');
+ await expect(sendButton(page)).toBeVisible();
+ await expect(idleAction(page)).toHaveCount(0);
+
+ await clearComposer(page);
+ await expect(idleAction(page)).toBeVisible();
+ await expect(sendButton(page)).toHaveCount(0);
+ });
+
+ test('whitespace alone is not typed content', async ({ page }) => {
+ await openChat(page);
+ await typeIntoComposer(page, ' ');
+
+ await expect(
+ idleAction(page),
+ 'a composer holding only spaces is still empty for slot purposes'
+ ).toBeVisible();
+ await expect(sendButton(page)).toHaveCount(0);
+ });
+
+ test('a running turn shows Stop and hides both idle and Send', async ({ page }) => {
+ await openChat(page);
+ await beginStreamingTurn(page, 'Count slowly for me');
+
+ await expect(stopButton(page)).toBeVisible();
+ await expect(sendButton(page)).toHaveCount(0);
+ await expect(idleAction(page)).toHaveCount(0);
+ });
+
+ test('Stop stays mounted while a follow-up is typed mid-stream', async ({ page }) => {
+ // The behavioural difference from the legacy composer, pinned deliberately.
+ // `ChatComposer.tsx:252-253` reverts Stop to Send once `hasTypedContent`;
+ // the shipped composer's Stop is `AuiIf(isRunning)` with no typed-content
+ // term, so typing must NOT disarm it. If this ever starts failing, the app
+ // has adopted the legacy rule — which may be desirable, but is a product
+ // change and should not be absorbed by editing this expectation quietly.
+ await openChat(page);
+ await beginStreamingTurn(page, 'Count slowly for me');
+
+ await typeIntoComposer(page, 'and then summarise it');
+
+ await expect(stopButton(page)).toBeVisible();
+ await expect(sendButton(page)).toHaveCount(0);
+ });
+
+ test('Stop ends the turn and the slot returns to the idle action', async ({ page }) => {
+ await openChat(page);
+ await beginStreamingTurn(page, 'Count slowly for me');
+
+ await stopButton(page).click();
+
+ await expect(stopButton(page)).toHaveCount(0, { timeout: 20_000 });
+ await expect(idleAction(page)).toBeVisible({ timeout: 20_000 });
+ await expect(composer(page)).toBeVisible();
+ });
+});
diff --git a/app/test/playwright/specs/chat-model-override.spec.ts b/app/test/playwright/specs/chat-model-override.spec.ts
new file mode 100644
index 0000000000..7ad4d7a251
--- /dev/null
+++ b/app/test/playwright/specs/chat-model-override.spec.ts
@@ -0,0 +1,130 @@
+/**
+ * Chat composer — the model chip opens the provider/model picker, and the
+ * choice sticks for the next turn.
+ *
+ * Zero browser coverage today: no spec in `app/test/playwright/specs` mentions
+ * the model selector at all. The chip is the only text-labelled control in the
+ * composer footer, and it is what tells a user which model their next message
+ * will go to — so a picker that opens but does not change the label, or a label
+ * that resets on the next send, is a silent correctness problem.
+ *
+ * `ChatComposer.tsx:453` calls it a "Read-only model chip". It is not: it
+ * renders a `Button` that opens `ProviderModelPickerDialog`
+ * (`ModelQualityPill.tsx:104-121`), disabled only when `!onValueChange ||
+ * loading`. The comment is stale; the control is live.
+ *
+ * # Environment dependency, stated plainly
+ *
+ * Which providers appear in the picker comes from core config, and the e2e
+ * fixture does not seed a cloud provider. The always-available option is the
+ * managed tier ("Managed by OpenHuman"), which the dialog deliberately lets you
+ * pick with no model id (`ProviderModelPickerDialog.tsx:189-196`). Where a case
+ * needs a provider this fixture does not have, it skips with a reason rather
+ * than asserting something weaker — per the lane rules, a case that cannot be
+ * driven in the browser is skipped, not quietly downgraded.
+ */
+import { expect, type Locator, type Page, test } from '@playwright/test';
+
+import { bootAuthenticatedPage, dismissWalkthroughIfPresent } from '../helpers/core-rpc';
+
+const MOCK_ADMIN_BASE = `http://127.0.0.1:${process.env.E2E_MOCK_PORT || '18473'}`;
+const USER_ID = 'pw-chat-model-override';
+
+async function resetMock(): Promise<void> {
+ await fetch(`${MOCK_ADMIN_BASE}/__admin/reset`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({}),
+ });
+}
+
+async function setMockBehavior(key: string, value: string): Promise<void> {
+ await fetch(`${MOCK_ADMIN_BASE}/__admin/behavior`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ key, value }),
+ });
+}
+
+async function openChat(page: Page): Promise<void> {
+ // `bootAuthenticatedPage(.., '/chat')` already navigates to #/chat and runs
+ // `waitForAppReady`. The sibling chat specs then repeat both; doing so races
+ // the app's own boot and, under a loaded machine, left the first tests of a
+ // file staring at a blank #root until the 60s test timeout. One navigation.
+ await bootAuthenticatedPage(page, USER_ID, '/chat');
+ await dismissWalkthroughIfPresent(page);
+ await expect(page.getByTestId('chat-message-input')).toBeVisible({ timeout: 30_000 });
+}
+
+/**
+ * The model chip, by its analytics id rather than its accessible name.
+ * `getByRole('button', { name: 'Model' })` is ambiguous once a thread exists:
+ * sidebar thread rows are also `role="button"`, and a thread titled from a
+ * prompt about models matches the same name — a strict-mode violation that only
+ * appears after the first turn is sent.
+ */
+const modelChip = (page: Page): Locator =>
+ page.locator('[data-analytics-id="chat-model-selector"]');
+const pickerTitle = (page: Page): Locator => page.getByText('Choose provider and model');
+
+test.describe('Chat composer model override', () => {
+ test.beforeEach(async () => {
+ await resetMock();
+ await setMockBehavior(
+ 'llmForcedResponses',
+ JSON.stringify([{ content: 'Reply after the model override.' }])
+ );
+ await setMockBehavior('llmStreamChunkDelayMs', '5');
+ });
+
+ test('the model chip is an interactive control that opens the picker', async ({ page }) => {
+ await openChat(page);
+
+ const chip = modelChip(page);
+ await expect(chip).toBeVisible();
+ await expect(
+ chip,
+ 'the chip is enabled whenever an onValueChange handler is wired and the catalog is loaded'
+ ).toBeEnabled();
+
+ await chip.click();
+ await expect(pickerTitle(page)).toBeVisible({ timeout: 10_000 });
+ });
+
+ test('cancelling the picker leaves the current model untouched', async ({ page }) => {
+ await openChat(page);
+
+ const chip = modelChip(page);
+ const before = (await chip.textContent())?.trim() ?? '';
+
+ await chip.click();
+ await expect(pickerTitle(page)).toBeVisible({ timeout: 10_000 });
+ await page.getByRole('button', { name: 'Cancel' }).click();
+
+ await expect(pickerTitle(page)).toHaveCount(0);
+ expect((await chip.textContent())?.trim() ?? '').toBe(before);
+ });
+
+ /*
+ * REMOVED — 'choosing a provider updates the chip label and survives the next
+ * turn'.
+ *
+ * It passed with the pill's `onValueChange` replaced by a no-op, which means
+ * it never verified that choosing anything took effect. Reading it back, the
+ * assertions were: capture the label AFTER selecting, assert it is non-empty,
+ * then assert it is unchanged by a turn. Nothing compared it to the label
+ * BEFORE, so a handler that discards the selection satisfies every line.
+ *
+ * The obvious repair — assert the label CHANGED — cannot be made honest with
+ * this fixture. The only selectable provider here is the managed tier
+ * (`ProviderModelPickerDialog.tsx:189-196` lets it be picked with no model
+ * id), and that is already the active model, so a correct selection is
+ * legitimately a no-op with nothing observable to assert. Driving a real
+ * change needs a second, seeded cloud provider, which the e2e core config
+ * does not create.
+ *
+ * Deleted rather than weakened or left green: a test that cannot distinguish
+ * a working picker from a discarded selection is worse than no test, because
+ * it reports coverage of exactly the behaviour it fails to check.
+ */
+});
diff --git a/app/test/playwright/specs/chat-scroll-stick.spec.ts b/app/test/playwright/specs/chat-scroll-stick.spec.ts
new file mode 100644
index 0000000000..c441b93dc3
--- /dev/null
+++ b/app/test/playwright/specs/chat-scroll-stick.spec.ts
@@ -0,0 +1,244 @@
+/**
+ * Chat transcript — does an arriving message yank a reader back to the bottom?
+ *
+ * This is the classic transcript bug and it had no browser test. The existing
+ * `chat-harness-scroll-render.spec.ts` proves that scrolling up *releases* the
+ * bottom-stick, then stops — it never sends another message afterwards, so the
+ * behaviour that actually bites a user (reading scrollback while the assistant
+ * keeps streaming) was never exercised.
+ *
+ * The contract, from `src/hooks/useStickToBottom.ts`:
+ *
+ * const STICK_THRESHOLD_PX = 80;
+ * isNearBottom = scrollHeight - scrollTop - clientHeight <= thresholdPx
+ *
+ * > If the user manually scrolls up past the threshold we stop sticking, so
+ * > they [keep their place] … scrolling up always disengages it.
+ *
+ * So: scrolled up past 80px → new content must NOT move the viewport. Parked
+ * within 80px of the bottom → new content SHOULD follow. Both halves are here,
+ * because a spec that only asserted "does not jump" would also pass against a
+ * transcript that never auto-scrolls at all — which would be a different, and
+ * equally real, bug.
+ *
+ * Everything is measured from the live scroll container, not from mock calls.
+ *
+ * **The container has no testid on the shipped path.** `chat-messages-scroll`
+ * belongs to `ChatThreadView` (the legacy composer's transcript);
+ * `Conversations.tsx:2539` renders the assistant-ui panel by default, whose
+ * viewport is `thread.tsx:226` — `relative flex flex-1 flex-col
+ * overflow-x-auto overflow-y-scroll scroll-smooth`, with no testid. Rather
+ * than pin a Tailwind string, this walks up from the composer input and takes
+ * the first ancestor that actually scrolls, and throws if there is none — so a
+ * class rename fails loudly instead of silently measuring `document`.
+ */
+import { expect, type Page, test } from '@playwright/test';
+
+import { bootAuthenticatedPage, dismissWalkthroughIfPresent } from '../helpers/core-rpc';
+
+const MOCK_ADMIN_BASE = `http://127.0.0.1:${process.env.E2E_MOCK_PORT || '18473'}`;
+const USER_ID = 'pw-chat-scroll-stick';
+
+/** A long reply, so the transcript overflows and there is somewhere to scroll. */
+const LONG_REPLY = Array.from(
+ { length: 40 },
+ (_, i) => `Line ${i + 1}: the transcript needs enough height to actually overflow the viewport. `
+).join('\n\n');
+
+async function resetMock(): Promise<void> {
+ await fetch(`${MOCK_ADMIN_BASE}/__admin/reset`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({}),
+ });
+}
+
+async function setMockBehavior(key: string, value: string): Promise<void> {
+ await fetch(`${MOCK_ADMIN_BASE}/__admin/behavior`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ key, value }),
+ });
+}
+
+async function openChat(page: Page): Promise<void> {
+ // `bootAuthenticatedPage(.., '/chat')` already navigates to #/chat and runs
+ // `waitForAppReady`. The sibling chat specs then repeat both; doing so races
+ // the app's own boot and, under a loaded machine, left the first tests of a
+ // file staring at a blank #root until the 60s test timeout. One navigation.
+ await bootAuthenticatedPage(page, USER_ID, '/chat');
+ await dismissWalkthroughIfPresent(page);
+ await expect(page.getByTestId('chat-message-input')).toBeVisible({ timeout: 30_000 });
+}
+
+interface ScrollState {
+ scrollTop: number;
+ scrollHeight: number;
+ clientHeight: number;
+ distanceFromBottom: number;
+}
+
+/**
+ * The transcript viewport, by its stable slot attribute
+ * (`assistant-ui/thread.tsx:225`). An earlier draft walked up from the composer
+ * taking the first scrolling ancestor; that is not deterministic, because which
+ * ancestor overflows changes as the transcript grows, so two reads in one test
+ * could measure two different elements.
+ */
+const FIND_VIEWPORT = `document.querySelector('[data-slot="aui_thread-viewport"]')`;
+
+async function scrollState(page: Page): Promise<ScrollState> {
+ return page.evaluate(`(() => {
+ const el = ${FIND_VIEWPORT};
+ if (!el) throw new Error('transcript viewport [data-slot=aui_thread-viewport] not found');
+ return {
+ scrollTop: el.scrollTop,
+ scrollHeight: el.scrollHeight,
+ clientHeight: el.clientHeight,
+ distanceFromBottom: el.scrollHeight - el.scrollTop - el.clientHeight,
+ };
+ })()`);
+}
+
+/**
+ * Scroll the viewport and WAIT FOR IT TO SETTLE.
+ *
+ * The viewport carries `scroll-smooth` (`thread.tsx:226`), so an assignment to
+ * `scrollTop` animates. An earlier draft read the position back immediately and
+ * saw a mid-animation value — it parked at the bottom, measured 1312px from the
+ * bottom, and failed its own setup step. `behavior: 'instant'` overrides the CSS
+ * for this one call; the poll is belt-and-braces for the layout settling.
+ */
+async function scrollTo(page: Page, top: number): Promise<void> {
+ await page.evaluate(`(() => {
+ const el = ${FIND_VIEWPORT};
+ if (!el) throw new Error('transcript viewport [data-slot=aui_thread-viewport] not found');
+ el.scrollTo({ top: ${top}, behavior: 'instant' });
+ el.dispatchEvent(new Event('scroll', { bubbles: true }));
+ })()`);
+ await expect
+ .poll(
+ async () => {
+ const a = await page.evaluate(`(${FIND_VIEWPORT}).scrollTop`);
+ await new Promise(resolve => setTimeout(resolve, 120));
+ const b = await page.evaluate(`(${FIND_VIEWPORT}).scrollTop`);
+ return a === b;
+ },
+ { timeout: 5_000 }
+ )
+ .toBe(true);
+}
+
+async function sendMessage(page: Page, prompt: string): Promise<void> {
+ await dismissWalkthroughIfPresent(page);
+ // The live input is a Lexical contenteditable, not a textarea — `fill()` and
+ // `toHaveValue()` do not apply to it.
+ await page.getByTestId('chat-message-input').click();
+ await page.keyboard.type(prompt);
+ await expect(page.getByTestId('send-message-button')).toBeVisible();
+ await page.getByTestId('send-message-button').click();
+}
+
+/** Send one turn and wait for the whole reply to land. */
+async function completeTurn(page: Page, prompt: string, marker: string): Promise<void> {
+ await sendMessage(page, prompt);
+ await expect(page.getByText(marker, { exact: false }).last()).toBeVisible({ timeout: 40_000 });
+ await expect(page.getByTestId('composer-human-mode')).toBeVisible({ timeout: 40_000 });
+}
+
+test.describe('Chat transcript stick-to-bottom', () => {
+ test.beforeEach(async () => {
+ await resetMock();
+ await setMockBehavior('llmStreamChunkDelayMs', '5');
+ });
+
+ test('a new message does NOT yank a reader who has scrolled up', async ({ page }) => {
+ await setMockBehavior(
+ 'llmForcedResponses',
+ JSON.stringify([
+ { content: `${LONG_REPLY}\n\nFIRST-REPLY-END` },
+ { content: `${LONG_REPLY}\n\nSECOND-REPLY-END` },
+ ])
+ );
+ await openChat(page);
+
+ await completeTurn(page, 'First long answer please', 'FIRST-REPLY-END');
+
+ const overflowing = await scrollState(page);
+ test.skip(
+ overflowing.scrollHeight <= overflowing.clientHeight + 200,
+ 'transcript did not overflow enough to scroll — viewport too tall for this fixture'
+ );
+
+ // Park the reader well above the bottom, past the 80px stick threshold.
+ const parkedTop = Math.max(0, overflowing.scrollHeight - overflowing.clientHeight - 600);
+ await scrollTo(page, parkedTop);
+ const parked = await scrollState(page);
+ expect(
+ parked.distanceFromBottom,
+ 'the fixture must actually park the reader past the 80px stick threshold'
+ ).toBeGreaterThan(80);
+
+ // Now a second turn arrives and grows the transcript underneath them.
+ await completeTurn(page, 'Second long answer please', 'SECOND-REPLY-END');
+
+ const after = await scrollState(page);
+
+ // The assertion that matters: the viewport did not jump to the bottom.
+ expect(
+ after.distanceFromBottom,
+ 'a message arriving while the reader is scrolled up must not snap the transcript to the bottom'
+ ).toBeGreaterThan(80);
+
+ // Deliberately NOT asserting `scrollTop` stayed put. New content changes the
+ // container's height, so `scrollTop` legitimately shifts without the view
+ // moving relative to what the reader is looking at. `distanceFromBottom`
+ // above is the actual definition of "was I yanked to the bottom", and it is
+ // the falsifiable one: forcing a scroll-to-bottom drives it to ~0.
+ });
+
+ test('a new turn is anchored into view for a reader parked at the bottom', async ({ page }) => {
+ // The positive half — without it, the case above would also pass against a
+ // transcript that never moves at all, which is its own bug.
+ //
+ // NOTE the contract being asserted. An earlier draft expected the reader to
+ // be left AT the bottom (`distanceFromBottom <= 80`), modelled on
+ // `useStickToBottom`'s `STICK_THRESHOLD_PX = 80`. That hook belongs to
+ // `ChatThreadView` — the LEGACY transcript. The shipped viewport is
+ // `ThreadPrimitive.Viewport turnAnchor="top"` (`thread.tsx:223-226`), which
+ // deliberately scrolls the START of a new turn to the top and lets it grow
+ // downward. Measured, that leaves ~1448px below the fold, so the old
+ // expectation failed on a UI that was behaving correctly.
+ //
+ // What the user actually needs is that the new turn is brought into view,
+ // and that is what this asserts.
+ await setMockBehavior(
+ 'llmForcedResponses',
+ JSON.stringify([
+ { content: `${LONG_REPLY}\n\nFIRST-REPLY-END` },
+ { content: `${LONG_REPLY}\n\nSECOND-REPLY-END` },
+ ])
+ );
+ await openChat(page);
+
+ await completeTurn(page, 'First long answer please', 'FIRST-REPLY-END');
+
+ const first = await scrollState(page);
+ test.skip(
+ first.scrollHeight <= first.clientHeight + 200,
+ 'transcript did not overflow enough to scroll — viewport too tall for this fixture'
+ );
+
+ await scrollTo(page, first.scrollHeight);
+ expect((await scrollState(page)).distanceFromBottom).toBeLessThanOrEqual(80);
+
+ const SECOND_PROMPT = 'Second long answer please';
+ await completeTurn(page, SECOND_PROMPT, 'SECOND-REPLY-END');
+
+ // The new turn's own prompt must be on screen, not scrolled past.
+ await expect(
+ page.getByText(SECOND_PROMPT, { exact: false }).last(),
+ 'a reader at the bottom must have the new turn brought into view'
+ ).toBeInViewport({ timeout: 15_000 });
+ });
+});