Public: anyone can read this; the crew can change it.
Talk's composer is red only when a message was not sent, and one control pauses, resumes or jumps to the latest #16199
Check · Review · Land · Live done — Landed and live in production.
talk/fix-composer-follow → main 0 commits
8 files
changed +408
−131
docs/design/areas/talk.md +3 −1
| @@ -19,7 +19,9 @@ | ||
| 19 | 19 | - `.talk-suggest` — the starter questions on an empty chat; each fills the composer. |
| 20 | 20 | - `.talk-crew` — the one line of the crew's live work (or "The crew is idle."), above the composer; a fixed one-line height that clips with an ellipsis, so it never shifts the page. |
| 21 | 21 | - `.talk-about` — the one line naming the subject (`?about=`), above the composer; no rule of its own: it is plain `small muted` text that wraps like any paragraph. |
| 22 | - `.talk-jump` — "Latest" button, shown when you have scrolled up from the end. | |
| 22 | - `.talk-jump` — the one follow control, a round pill centred above the composer: Pause while a reply is written and followed, Resume once let go, Latest when above the end with nothing running; hidden otherwise. | |
| 23 | - `.talk-dot` — the accent dot on that control when something new arrived below. | |
| 24 | - `.talk-error` — the line under the composer saying why a message was not sent; shown only then, with the box marked invalid. | |
| 23 | 25 | - `.talk-chats` — the conversations list above the chat (#8814): New, the person's conversations newest first, and the Archived filter link. |
| 24 | 26 | - `.talk-here` — the line naming the open conversation, with its Rename and Archive forms. |
| 25 | 27 | - `.talk-steps` — the quiet steps line under a reply ("read 3 files, opened #12"). |
docs/design/size-budget.json +2 −2
| @@ -68,8 +68,8 @@ | ||
| 68 | 68 | "css": 48384 |
| 69 | 69 | }, |
| 70 | 70 | "/talk": { |
| 71 | "js": 28160, | |
| 72 | "css": 50432 | |
| 71 | "js": 28928, | |
| 72 | "css": 50688 | |
| 73 | 73 | }, |
| 74 | 74 | "/:owner/:name/pulls/:number": { |
| 75 | 75 | "js": 32000, |
docs/features/talk.md +14 −4
| @@ -31,7 +31,7 @@ When the agent asks first (`needs_confirm`), the turn draws **Do it** (the exist | ||
| 31 | 31 | The reply is drawn as it is written. The runner reports each piece of the block it is writing (`onDelta` in `src/crew/agent_runner.ts`; the Claude adapter asks for partial output with `--include-partial-messages` only for a Talk turn, so a crew run is unchanged). `src/crew/conversation_live.ts` holds the block in process memory, per conversation: the text so far (at most 20,000 characters, as a stored turn), whether the agent is thinking, and the tool call it is waiting on. It is cleared when the block is stored and when the turn ends, however it ends. |
| 32 | 32 | |
| 33 | 33 | - **Frames:** the stream sends `live` `{html, thinking, tool}` at once when something changes, at most one every 125 ms, always the latest. `html` is the text so far drawn by the same Markdown renderer as a stored reply (an unfinished fence is closed for drawing); `tool` is the step in plain words while it runs ("Reading src/a.ts…", `runningStep` in `src/core/talk_steps.ts`, or "Working: <tool words>…" for a tool with no words of its own), never its arguments as JSON; `thinking` is true or false, and the thoughts themselves arrive only in the stored, folded turn. A stream that connects mid-block gets the whole block in its first `live` frame. When the block is stored its `turn` frame is followed, in the same look, by an empty `live` frame, which removes the element: the server alone takes it away, so a turn from another door lands above the block and leaves it in place. A fresh attempt after a lost session starts from an empty block. |
| 34 | - **The page:** one element, `<li id="live">`, last in the log before any queued message, `aria-hidden` so a screen reader hears the stored reply once. When you were at the end, the page goes to its true end with each frame (the talk column where it scrolls on its own, from 56.25rem, judged from the column's own position; else the window), below the composer; scrolled up, nothing moves. A lost stream removes it; the stream that comes back draws it again. | |
| 34 | - **The page:** one element, `<li id="live">`, last in the log before any queued message, `aria-hidden` so a screen reader hears the stored reply once. It never scrolls the page itself; the page's one follow rule does (see "Following" below). A lost stream removes it; the stream that comes back draws it again. | |
| 35 | 35 | - **Who sees it:** only the conversation's owner: the stream finds the conversation by its owner, and another person naming it gets 404. |
| 36 | 36 | - **Secrets:** what leaves the block is redacted as the stored turn is (`redactHeld`: held values and credential shapes, which the stored turn now masks too), and the end of the text that could be the start of a held value is held back until the rest arrives, so a value cut across two pieces never shows in part; a word at the end that is, or could still become, a short held value waits for the letter that settles it, so nothing shows masked and then clear; the run of token characters being written (a credential shape is masked only once it is long enough) waits for the character after it, so the text grows a word at a time. |
| 37 | 37 | - **Other turns:** every turn is stored through `appendTurn` (`src/core/conversations.ts`), which wakes the open streams of its conversation, so a confirm, a receipt, an undo, a routine's post or a slash answer arrives at once too. A look once a second stays as the net. |
| @@ -104,7 +104,7 @@ Prior art read: Vercel AI Elements (Apache-2.0 React on shadcn; anatomy and beha | ||
| 104 | 104 | | Who and when under each message; copy a message; copy a code block | this pull | AI Elements `Message`, `CodeBlock` | |
| 105 | 105 | | Tool calls as closed cards | this pull | AI Elements `Tool` | |
| 106 | 106 | | Starter questions on an empty chat (links to `/talk?q=`, so they work without the script) | this pull | AI Elements `Suggestion` | |
| 107 | | Stick to bottom, "Latest" jump button | this pull | AI Elements `Conversation` | | |
| 107 | | Stick to bottom, with Pause, Resume and Latest in one control | have (#15734) | AI Elements `Conversation` | | |
| 108 | 108 | | Thinking as one closed line; a steps line under a reply ("read 3 files, opened #12"); links to each issue, pull, file or app the turn opened or changed | this pull | AI Elements `Reasoning`, `ChainOfThought` | |
| 109 | 109 | | Many conversations: new, list, rename, archive, URL each | have (#8814) | search (#8823, #13259) | |
| 110 | 110 | | Edit and resend, regenerate, Retry (see below) | have (#8817) | replaced turns are kept and marked, not deleted | |
| @@ -114,7 +114,7 @@ Prior art read: Vercel AI Elements (Apache-2.0 React on shadcn; anatomy and beha | ||
| 114 | 114 | | The reply drawn as it is written | have | see "Live" | |
| 115 | 115 | | Code highlighting and tables in replies | this pull (#8816) | a reply is stored whole and drawn whole, so no half-open fence is ever tokenised | |
| 116 | 116 | |
| 117 | **Without the script** the page is a plain form: Enter adds a line, starters are links that prefill the box, and Copy and Latest are not drawn (the script draws them, along with the "Enter sends" hint). The log is `role="log"`; with the script, a new message while you are scrolled up is announced in the status line. | |
| 117 | **Without the script** the page is a plain form: Enter adds a line, starters are links that prefill the box, and Copy and the follow control are not shown (the script draws or shows them, along with the "Enter sends" hint). The log is `role="log"`; with the script, a new message while you are scrolled up is announced in the status line. | |
| 118 | 118 | |
| 119 | 119 | **Cost and context.** Above the log, "Spent $0.52 in this conversation" totals the finished runs' `cost_usd` (`conversationTotal`); it, and a turn's cost, show nothing when no run reported one, never `$0`. `GET /api/v1/conversation/turns` (the read the MCP `say` tool points to) carries `totalUsd` and each agent turn's `costUsd`, `null` when unknown. Under a finished reply a quiet line gives the turn's dollars (`$0.12 this turn`); above the log, "Context 85% full (170k of 200k tokens)". Both are read from the run's record (`conversation_run`: `cost_usd`, and `context_tokens`/`context_window` from the last message's usage and the result's `modelUsage`), shown by `core/conversation_cost.ts`. When a run names no window, 200k is assumed and the line says so by showing it. From 80 % the line adds that a new conversation answers faster and costs less (information only: New starts another, see "Many conversations"). A reply that streams in gets both when the stream ends; the terminal (`forge talk`) prints the last turn's cost, the total ("Spent $0.52 in this conversation") and the share after its confirmation line. The MCP read of all this is the turns route above. |
| 120 | 120 | |
| @@ -130,7 +130,17 @@ A reply is drawn by the README renderer and then, for Talk alone, by `linkTalk` | ||
| 130 | 130 | |
| 131 | 131 | An agent reply is Markdown, drawn on the server by the same renderer as a README: fenced code is highlighted, tables and links render, and everything else is escaped (a `<script>` in a reply shows as text). A table wider than the column scrolls inside it; the page does not. The reply sits in the column like a person's turn, with none of the README's padding or line measure. |
| 132 | 132 | |
| 133 | A reply grows in one live element while it is written (see "Live") and is then stored as one finished turn; the page only appends a turn whose id it has not drawn (a repeat is ignored). Turns already on the page are not touched, so nothing above a new reply moves, and the page follows the end only if you were already there (otherwise "Latest" appears). An unfinished fence in a stored reply is closed for drawing. The page's own bytes are held by a test (`test/talk-page.test.ts`): the stylesheet under 6,300 B, the script under 20,700 B, and a page with a code reply under 40,000 B. | |
| 133 | A reply grows in one live element while it is written (see "Live") and is then stored as one finished turn; the page only appends a turn whose id it has not drawn (a repeat is ignored). Turns already on the page are not touched, so nothing above a new reply moves, and the page follows the end only if you were already there (otherwise "Latest" appears). An unfinished fence in a stored reply is closed for drawing. The page's own bytes are held by a test (`test/talk-page.test.ts`): the stylesheet under 6,700 B, the script under 23,600 B, and a page with a code reply under 40,000 B. | |
| 134 | ||
| 135 | ## Following | |
| 136 | ||
| 137 | The thread follows a growing reply while you are at the true end of the element that scrolls (the window on a phone, the talk column where it scrolls on its own), within 70 px of its end with the composer counted. One rule does it, a `ResizeObserver` on everything in the scroller that can move its end: the log, the composer (an error or status line, buttons that wrap where fonts are wider) and the talk column itself (`followJs` in `src/web/pages/talk_client.ts`); the live block and a stored turn never scroll by themselves. | |
| 138 | ||
| 139 | - **Letting go:** any move up lets go: a scroll up, the wheel, a finger dragging the thread down, PageUp, Home or Up outside the box, or selecting text in the thread while a reply is written. Then nothing moves. | |
| 140 | - **The one control,** centred above the composer: while a reply is written and followed it reads **Pause** (it keeps your place so you can read); once let go it reads **Resume** while a reply is written, else **Latest** when you are above the end, with a dot when something new arrived. Hidden when there is nothing to do. **End** outside the box and **Send** come back to the end too. A press is said once in the status line. | |
| 141 | - **The composer** is never painted as an error after a send: the script takes over the empty check, so the box is not `required` once it runs (it still is without the script). It is marked invalid only when a message could not be sent, with the reason in a line under it, and typing clears it. | |
| 142 | - **Terminal:** `ssh <forge> talk --follow` prints as written; a terminal has no scroller or composer to paint, so nothing here applies there. | |
| 143 | - Proof: `test/talk-follow.test.ts` drives it in a real Chromium at 390 px (the page scrolls) and 1280 px (the column scrolls). | |
| 134 | 144 | |
| 135 | 145 | **Copy:** each code block and each message has a Copy button, which copies the text, not the markup. The buttons are drawn by the script: with JavaScript off there are none, and the code is still there to select. |
| 136 | 146 |
src/web/icons.ts +2
| @@ -81,6 +81,8 @@ const PATHS = { | ||
| 81 | 81 | shield: `<path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/>`, |
| 82 | 82 | code: `<path d="m16 18 6-6-6-6"/><path d="m8 6-6 6 6 6"/>`, |
| 83 | 83 | up: `<path d="M14 9 9 4 4 9"/><path d="M20 20h-7a4 4 0 0 1-4-4V4"/>`, |
| 84 | arrowDown: `<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>`, | |
| 85 | pause: `<rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>`, | |
| 84 | 86 | history: `<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>`, |
| 85 | 87 | activity: `<path d="M22 12h-4l-3 9L9 3l-3 9H2"/>`, |
| 86 | 88 | sync: `<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M3 21v-5h5"/>`, |
src/web/pages/talk.ts +4 −2
| @@ -66,7 +66,7 @@ import { liveCrewRows } from "../../actions/crew_now.ts"; | ||
| 66 | 66 | import { crewLineHtml } from "../crew_now.ts"; |
| 67 | 67 | import { renderMarkdown } from "../markdown.ts"; |
| 68 | 68 | import { agentHtml, voiceCss, voiceOf, type Voice } from "../talk_parts.ts"; |
| 69 | import { badge, btn, row, time } from "../ui.ts"; | |
| 69 | import { badge, btn, icon, row, time } from "../ui.ts"; | |
| 70 | 70 | import { buildBox, buildCss, chosenTemplate, panelFor } from "../talk_build.ts"; |
| 71 | 71 | import { chatBuildOf } from "../../core/chat_build.ts"; |
| 72 | 72 | import { runningStep, stepOf, repoOf, type Step } from "../../core/talk_steps.ts"; |
| @@ -483,7 +483,9 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string | | ||
| 483 | 483 | <p class="talk-status small muted" role="status">${running ? "The forge is answering…" : ""}</p> |
| 484 | 484 | <div class="talk-chips" data-chips role="group" aria-label="Attached files"></div> |
| 485 | 485 | ${editing === undefined && aboutText(ctx.app.db, ctx.url.searchParams.get("about"), ctx.auth.user) !== null ? html`<input type="hidden" name="about" value="${ctx.url.searchParams.get("about")}" />` : null} |
| 486 | <textarea class="input" name="text" rows="1" maxlength="${WORDS_MAX}" required placeholder="Talk to the forge" aria-label="Talk to the forge" aria-keyshortcuts="/">${editing === undefined ? "" : editing.text}</textarea> | |
| 486 | <textarea class="input" name="text" rows="1" maxlength="${WORDS_MAX}" required placeholder="Talk to the forge" aria-label="Talk to the forge" aria-keyshortcuts="/" aria-describedby="talk-error">${editing === undefined ? "" : editing.text}</textarea> | |
| 487 | <p class="talk-error small" id="talk-error" data-error hidden></p> | |
| 488 | <button type="button" class="btn talk-jump" data-jump hidden>${icon("pause")}${icon("arrowDown")}<span data-word></span><i class="talk-dot"></i></button> | |
| 487 | 489 | <div class="bar"> |
| 488 | 490 | <span class="muted small" data-compose-hint></span> |
| 489 | 491 | <button type="button" class="btn talk-dictate" data-dictate aria-pressed="false" hidden>Dictate</button> |
src/web/pages/talk_client.ts +91 −43
| @@ -4,6 +4,16 @@ | ||
| 4 | 4 | * user text; every turn it draws arrives as markup the server escaped. |
| 5 | 5 | * |
| 6 | 6 | * Why the script is shaped as it is (kept here, out of the bytes it ships): |
| 7 | * - The script checks the words itself, so it takes `required` off the box: a required box it | |
| 8 | * empties after a send would paint as an error. The box is red only when a message could not be | |
| 9 | * sent, with the reason in the line under it. | |
| 10 | * - Following is one rule on the element that scrolls (the talk column where it scrolls on its | |
| 11 | * own, else the page): while stuck, any growth of the log keeps the end in view; any move up (a | |
| 12 | * scroll, the wheel, a drag, PageUp, a selection while a reply is written) lets go, and then | |
| 13 | * nothing moves. A scroll is the reader's own only within a second of their wheel, touch, key or | |
| 14 | * scrollbar, so the layout moving under them (a turn stored, the box shrinking) never lets go or | |
| 15 | * takes hold. The one control above the composer pauses a reply being followed, and resumes or | |
| 16 | * jumps to the latest once let go; End and Send do the same. | |
| 7 | 17 | * - Copy buttons are drawn by the script, not the server: without the script |
| 8 | 18 | * they would do nothing. |
| 9 | 19 | * - While a reply streams the composer stays open: Send queues the message, |
| @@ -83,7 +93,11 @@ export const talkCss = /* css */ ` | ||
| 83 | 93 | .talk-steps { margin: 4px 0 0; } |
| 84 | 94 | .talk-links { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 2px 0 0; } |
| 85 | 95 | .talk-suggest { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; } |
| 86 | .talk-jump { position: absolute; bottom: calc(100% + 8px); left: 50%; transform: translateX(-50%); z-index: 9; min-height: 2.75rem; } | |
| 96 | .talk-jump { position: absolute; bottom: calc(100% + 8px); left: 50%; transform: translateX(-50%); z-index: 9; min-height: 2.75rem; border-radius: 999px; box-shadow: var(--shadow-2); gap: 6px; } | |
| 97 | .talk-jump[data-follow="pause"] .ico + .ico, .talk-jump:not([data-follow="pause"]) .ico:first-child, .talk-jump:not([data-new]) .talk-dot { display: none; } | |
| 98 | .talk-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); } | |
| 99 | .talk-error { margin: 4px 0 0; color: var(--danger); } | |
| 100 | .talk-error[hidden] { display: none; } | |
| 87 | 101 | .talk-jump[hidden], .talk-dictate[hidden] { display: none; } |
| 88 | 102 | .talk-dictate[aria-pressed="true"] { background: var(--accent); color: var(--bg); } |
| 89 | 103 | .talk-body pre { position: relative; } |
| @@ -158,12 +172,12 @@ export const dictateJs = ` | ||
| 158 | 172 | `; |
| 159 | 173 | |
| 160 | 174 | /** |
| 161 | * The follow rule: while a reply streams the view follows only when the reader is within 120 px | |
| 162 | * of the end; scrolled further up it stays put and "jump to latest" shows. Defines | |
| 163 | * `follows(viewHeight, scrollY, pageHeight)`. | |
| 175 | * The follow rule (#15734): the thread keeps its end in view while the reader is at the true end | |
| 176 | * of the element that scrolls, within 70 px of its `scrollHeight` (the composer sits inside the | |
| 177 | * scroller, so it is counted). Defines `follows(scrollHeight, scrollTop, clientHeight)`. | |
| 164 | 178 | */ |
| 165 | 179 | export const followJs = ` |
| 166 | const follows = (viewHeight, scrollY, pageHeight) => viewHeight + scrollY >= pageHeight - 120; | |
| 180 | const follows = (height, top, view) => height - top - view <= 70; | |
| 167 | 181 | `; |
| 168 | 182 | |
| 169 | 183 | /** |
| @@ -199,31 +213,17 @@ export const draftJs = ` | ||
| 199 | 213 | * stream that comes back draws it again). It is hidden from screen readers: the stored turn is |
| 200 | 214 | * what is announced, once. |
| 201 | 215 | * |
| 202 | * Following: when the reader was at the end before a frame, the page goes to the true end after | |
| 203 | * it (the composer sits below the log's end, so the log's own end is not enough); the scroller is | |
| 204 | * the talk column where it scrolls on its own (from 56.25rem), else the window. Where the column | |
| 205 | * scrolls, "at the end" is the page's own follow rule (`follows`) read on the column itself, since | |
| 206 | * the page's `stuck` follows the window's scroll only, and measured to the log's end (`#end`, where | |
| 207 | * the page's own `toEnd` puts the reader after Send), not past the composer below it. A reader who | |
| 208 | * scrolled up is left where they are. | |
| 216 | * It never scrolls the page itself: the page's one follow rule (the log's ResizeObserver, see | |
| 217 | * `followJs`) keeps the end in view while the reader follows, and leaves a reader who scrolled up | |
| 218 | * where they are. | |
| 209 | 219 | * |
| 210 | * Defines `liveOn(source)`, called once for each stream; needs `root`, `log`, `stuck` and `follows` | |
| 211 | * in scope. | |
| 220 | * Defines `liveOn(source)`, called once for each stream; needs `log`, `status` and `say` in scope. | |
| 212 | 221 | */ |
| 213 | 222 | export const liveJs = ` |
| 214 | 223 | const liveDrop = () => { const l = document.getElementById("live"); if (l) l.remove(); }; |
| 215 | const liveOwn = () => /auto|scroll/.test(window.getComputedStyle(root).overflowY) && root.scrollHeight > root.clientHeight; | |
| 216 | const liveAtEnd = () => { | |
| 217 | const e = document.getElementById("end"); | |
| 218 | return !liveOwn() ? stuck : !!e && follows(root.clientHeight, root.scrollTop, e.getBoundingClientRect().top - root.getBoundingClientRect().top + root.scrollTop); | |
| 219 | }; | |
| 220 | const liveEnd = () => { | |
| 221 | if (liveOwn()) root.scrollTop = root.scrollHeight; | |
| 222 | else { window.scrollTo(0, document.documentElement.scrollHeight); stuck = true; } | |
| 223 | }; | |
| 224 | 224 | const liveOn = (src) => { |
| 225 | 225 | src.addEventListener("live", (e) => { |
| 226 | const f = JSON.parse(e.data), was = liveAtEnd(); | |
| 226 | const f = JSON.parse(e.data); | |
| 227 | 227 | if (!f.html && !f.tool && !f.thinking) return liveDrop(); |
| 228 | 228 | let l = document.getElementById("live"); |
| 229 | 229 | if (!l) { |
| @@ -234,7 +234,6 @@ export const liveJs = ` | ||
| 234 | 234 | l.innerHTML = f.html; |
| 235 | 235 | if (f.tool || !f.html) l.append(Object.assign(document.createElement("p"), { className: "talk-steps small muted", textContent: f.tool || "Thinking…" })); |
| 236 | 236 | if (f.tool && status.textContent !== f.tool) say(f.tool); |
| 237 | if (was) liveEnd(); | |
| 238 | 237 | }); |
| 239 | 238 | src.addEventListener("turn", () => queueMicrotask(() => { const l = document.getElementById("live"); if (l) log.insertBefore(l, log.querySelector("[data-queued]")); })); |
| 240 | 239 | src.addEventListener("done", liveDrop); |
| @@ -261,9 +260,10 @@ if (root) { | ||
| 261 | 260 | const say = (words) => { status.textContent = words; }; |
| 262 | 261 | const hint = root.querySelector("[data-compose-hint]"); |
| 263 | 262 | if (hint) hint.textContent = "Enter sends, Shift+Enter adds a line"; |
| 264 | const jump = Object.assign(document.createElement("button"), { type: "button", className: "btn talk-jump", textContent: "Latest ↓", hidden: true }); | |
| 265 | jump.setAttribute("aria-label", "Jump to the latest message"); | |
| 266 | form.appendChild(jump); | |
| 263 | const jump = form.querySelector("[data-jump]"); | |
| 264 | const err = form.querySelector("[data-error]"); | |
| 265 | box.required = false; | |
| 266 | const fail = (words) => { say(""); err.textContent = words; err.hidden = false; box.setAttribute("aria-invalid", "true"); }; | |
| 267 | 267 | // The keyboard covers the layout viewport on phones: lift the composer by what it hides. |
| 268 | 268 | const vv = window.visualViewport; |
| 269 | 269 | if (vv) { |
| @@ -278,9 +278,11 @@ if (root) { | ||
| 278 | 278 | const keys = () => root.querySelector("[data-keys]"); |
| 279 | 279 | const typing = () => /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName) || document.activeElement.isContentEditable; |
| 280 | 280 | document.addEventListener("keydown", (e) => { |
| 281 | if (/^(Page|Arrow|Home|End| )/.test(e.key) && !e.altKey && !typing()) touched(); | |
| 282 | if (/^(PageUp|Home|ArrowUp)$/.test(e.key) && !e.altKey && !typing()) detach(); | |
| 281 | 283 | if (e.key === "?" && !e.metaKey && !e.ctrlKey && !e.altKey && !typing() && keys()) { e.preventDefault(); keys().hidden = !keys().hidden; return; } |
| 282 | 284 | if (e.key === "Escape" && keys() && !keys().hidden) { e.preventDefault(); e.stopImmediatePropagation(); keys().hidden = true; return; } |
| 283 | if (e.key === "End" && !e.metaKey && !e.altKey && !e.shiftKey && !typing()) { e.preventDefault(); stuck = true; toEnd(true); return; } | |
| 285 | if (e.key === "End" && !e.metaKey && !e.altKey && !e.shiftKey && !typing()) { e.preventDefault(); resume(); return; } | |
| 284 | 286 | if ((e.key === "ArrowUp" || e.key === "ArrowDown") && e.altKey && !e.metaKey && !e.ctrlKey && !e.shiftKey) { |
| 285 | 287 | const rows = [...document.querySelectorAll(".talk-chats ul.list:not([aria-label]) > li:not([data-pinned-heading])")].filter((li) => li.querySelector("a")); |
| 286 | 288 | const at = rows.findIndex((li) => li.hasAttribute("aria-current")); |
| @@ -297,16 +299,57 @@ if (root) { | ||
| 297 | 299 | if (l) { e.preventDefault(); l.click(); } |
| 298 | 300 | }); |
| 299 | 301 | ${followJs} |
| 300 | const nearEnd = () => follows(window.innerHeight, window.scrollY, document.documentElement.scrollHeight); | |
| 301 | let stuck = true; | |
| 302 | const toEnd = (force) => { | |
| 303 | if (!force && !stuck) { jump.hidden = false; say("New message"); return; } | |
| 304 | const end = document.getElementById("end"); | |
| 305 | if (end) end.scrollIntoView({ block: "end" }); | |
| 306 | jump.hidden = true; | |
| 302 | const page = document.scrollingElement || document.documentElement; | |
| 303 | const sc = () => /auto|scroll/.test(window.getComputedStyle(root).overflowY) && root.scrollHeight > root.clientHeight ? root : page; | |
| 304 | const atEnd = () => { const s = sc(); return follows(s.scrollHeight, s.scrollTop, s.clientHeight); }; | |
| 305 | let stuck = true, fresh = false, lastTop = 0, lastH = 0, grown = 0, hand = -1e9; | |
| 306 | const touched = () => { hand = performance.now(); }; | |
| 307 | const followWords = { pause: ["Pause", "Pause scrolling and keep this place"], resume: ["Resume", "Resume following the reply"], latest: ["Latest", "Jump to the latest message"] }; | |
| 308 | const draw = () => { | |
| 309 | const how = stuck ? (answering ? "pause" : "") : answering ? "resume" : atEnd() ? "" : "latest"; | |
| 310 | jump.hidden = !how; | |
| 311 | if (!how) return; | |
| 312 | jump.dataset.follow = how; | |
| 313 | jump.toggleAttribute("data-new", fresh && how !== "pause"); | |
| 314 | jump.querySelector("[data-word]").textContent = followWords[how][0]; | |
| 315 | jump.setAttribute("aria-label", followWords[how][1]); | |
| 307 | 316 | }; |
| 308 | window.addEventListener("scroll", () => { stuck = nearEnd(); if (stuck) jump.hidden = true; }, { passive: true }); | |
| 309 | jump.addEventListener("click", () => { stuck = true; toEnd(true); box.focus(); }); | |
| 317 | const toEnd = () => { const s = sc(); s.scrollTo({ top: s.scrollHeight, behavior: "instant" }); lastTop = s.scrollTop; lastH = grown = s.scrollHeight; }; | |
| 318 | const resume = () => { stuck = true; fresh = false; toEnd(); draw(); }; | |
| 319 | const detach = () => { if (stuck) { stuck = false; lastTop = sc().scrollTop; grown = sc().scrollHeight; draw(); } }; | |
| 320 | // Whatever moves the end is followed, not only the log: the composer wrapping its buttons, the | |
| 321 | // status or error line, chips, a font arriving. The new-message dot is for the log alone. | |
| 322 | const sizes = new window.ResizeObserver((seen) => { | |
| 323 | const h = sc().scrollHeight; | |
| 324 | if (stuck) toEnd(); else if (h > grown + 1 && seen.some((e) => e.target === log)) fresh = true; | |
| 325 | grown = h; | |
| 326 | draw(); | |
| 327 | }); | |
| 328 | for (const el of [root, log, form, ...root.children]) sizes.observe(el); | |
| 329 | document.addEventListener("scroll", (e) => { | |
| 330 | const s = sc(); | |
| 331 | if (e.target !== s && !(e.target === document && s === page)) return; | |
| 332 | const t = s.scrollTop, h = s.scrollHeight; | |
| 333 | const by = performance.now() - hand < 1000; | |
| 334 | if (by && t < lastTop - 2 && h >= lastH) stuck = false; | |
| 335 | else if (by && t > lastTop && atEnd()) { stuck = true; fresh = false; } | |
| 336 | lastTop = t; lastH = h; | |
| 337 | draw(); | |
| 338 | }, { capture: true, passive: true }); | |
| 339 | const mine = (e) => sc() !== root || root.contains(e.target); | |
| 340 | document.addEventListener("wheel", (e) => { touched(); if (e.deltaY < 0 && mine(e)) detach(); }, { passive: true }); | |
| 341 | document.addEventListener("pointerdown", (e) => { if (e.target === sc() || e.target === document.documentElement) touched(); }, true); | |
| 342 | document.addEventListener("pointermove", (e) => { if (e.buttons && performance.now() - hand < 1000) touched(); }, { passive: true }); | |
| 343 | let touchY = 0; | |
| 344 | document.addEventListener("touchstart", (e) => { touched(); touchY = e.touches[0].clientY; }, { passive: true }); | |
| 345 | document.addEventListener("touchmove", (e) => { touched(); if (e.touches[0].clientY > touchY + 4 && mine(e)) detach(); }, { passive: true }); | |
| 346 | document.addEventListener("touchend", touched, { passive: true }); | |
| 347 | document.addEventListener("selectionchange", () => { const s = window.getSelection(); if (answering && s && !s.isCollapsed && log.contains(s.anchorNode)) detach(); }); | |
| 348 | jump.addEventListener("click", () => { | |
| 349 | if (jump.dataset.follow === "pause") { detach(); say("Scrolling paused."); return; } | |
| 350 | resume(); | |
| 351 | if (jump.hidden) box.focus(); else say("Following the reply."); | |
| 352 | }); | |
| 310 | 353 | const draftKey = "talk-draft:" + (root.dataset.user || "") + ":" + (cid || ""); |
| 311 | 354 | let draftTimer = 0; |
| 312 | 355 | ${draftJs} |
| @@ -316,6 +359,7 @@ if (root) { | ||
| 316 | 359 | const grow = () => { box.style.height = "auto"; box.style.height = Math.min(box.scrollHeight, window.innerHeight * 0.4) + "px"; }; |
| 317 | 360 | box.addEventListener("input", () => { |
| 318 | 361 | grow(); |
| 362 | if (!err.hidden) { err.hidden = true; box.removeAttribute("aria-invalid"); } | |
| 319 | 363 | clearTimeout(draftTimer); |
| 320 | 364 | draftTimer = setTimeout(saveDraft, 300); |
| 321 | 365 | }); |
| @@ -386,6 +430,10 @@ if (root) { | ||
| 386 | 430 | answering = on; |
| 387 | 431 | action.textContent = on ? "Queue" : "Send"; |
| 388 | 432 | stopBtn.hidden = steerBtn.hidden = !on; |
| 433 | // The composer just changed (Steer and Stop, a row that wraps): a follower stays at the end | |
| 434 | // now, in this task, rather than for a frame until the size observer catches up. | |
| 435 | if (stuck) toEnd(); | |
| 436 | draw(); | |
| 389 | 437 | }; |
| 390 | 438 | const stop = async () => { |
| 391 | 439 | say("Stopping…"); |
| @@ -428,9 +476,9 @@ if (root) { | ||
| 428 | 476 | const q = log.querySelector("[data-queued]"); |
| 429 | 477 | if (q) q.insertAdjacentHTML("beforebegin", turn.html); else log.insertAdjacentHTML("beforeend", turn.html); |
| 430 | 478 | decorate(log); |
| 479 | if (!stuck) say("New message"); | |
| 431 | 480 | } |
| 432 | 481 | retry = 0; |
| 433 | toEnd(); | |
| 434 | 482 | }); |
| 435 | 483 | source.addEventListener("queued", (e) => { |
| 436 | 484 | log.querySelectorAll("[data-queued]").forEach((q) => q.remove()); |
| @@ -523,7 +571,7 @@ ${dictateJs} | ||
| 523 | 571 | }); |
| 524 | 572 | if (!res.ok) { |
| 525 | 573 | const body = await res.json().catch(() => ({})); |
| 526 | say(body.message || "That was not sent."); | |
| 574 | fail(body.message || "That was not sent."); | |
| 527 | 575 | return; |
| 528 | 576 | } |
| 529 | 577 | box.value = ""; |
| @@ -532,14 +580,14 @@ ${dictateJs} | ||
| 532 | 580 | grow(); |
| 533 | 581 | clearTimeout(draftTimer); |
| 534 | 582 | draft.save(""); |
| 535 | stuck = true; | |
| 583 | resume(); | |
| 536 | 584 | const out = await res.json().catch(() => ({})); |
| 537 | 585 | if (out.how === "queued") { say("Queued: it sends after this answer."); if (!source) follow(); return; } |
| 538 | 586 | if (out.how === "interrupted") { say("Stopping, then sending…"); return; } |
| 539 | 587 | if (paged) { location.href = here; return; } |
| 540 | 588 | follow(); |
| 541 | 589 | } catch (_) { |
| 542 | say("That was not sent: no connection."); | |
| 590 | fail("That was not sent: no connection."); | |
| 543 | 591 | } |
| 544 | 592 | }; |
| 545 | 593 | form.addEventListener("submit", send); |
| @@ -572,7 +620,7 @@ ${dictateJs} | ||
| 572 | 620 | say("That was not sent: no connection."); |
| 573 | 621 | } |
| 574 | 622 | }); |
| 575 | toEnd(true); | |
| 623 | resume(); | |
| 576 | 624 | if (root.dataset.running === "1" && !paged) { log.setAttribute("aria-busy", "true"); follow(); } |
| 577 | 625 | document.addEventListener("click", async (e) => { |
| 578 | 626 | const a = e.target.closest("[data-shell] :is(.talk-tabs, .talk-pane nav) a:not(.talk-back)"), shell = a && a.closest("[data-shell]"); |
test/talk-follow.test.ts added +179
| @@ -0,0 +1,179 @@ | ||
| 1 | /** | |
| 2 | * Following a reply on /talk (#15734), in a real Chromium at a phone width (the page scrolls) and a | |
| 3 | * laptop width (the talk column scrolls): the thread keeps its end in view while the reader is at | |
| 4 | * the true end of whichever element scrolls; a wheel up, PageUp or the Pause control lets go and | |
| 5 | * then nothing moves; Resume, End and Send come back to the end. And the composer never paints as | |
| 6 | * an error after a send: it is invalid only when a message could not be sent, with the reason | |
| 7 | * under it. Skipped, and says so, where no Chromium starts. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 10 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { appendTurn, openConversation } from "../src/core/conversations.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import { createUser } from "../src/core/users.ts"; | |
| 17 | import { findChromium } from "../src/looks/capture.ts"; | |
| 18 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 19 | import { clock } from "../src/web/pages/talk.ts"; | |
| 20 | import { chromiumRuns, evaluateLoaded } from "./helpers/chrome.ts"; | |
| 21 | import { quietLogs } from "./helpers/globals.ts"; | |
| 22 | import { promote } from "./helpers/members.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | ||
| 26 | const found = findChromium(); | |
| 27 | const chromium = found !== undefined && chromiumRuns(found) ? found : undefined; | |
| 28 | if (chromium === undefined) | |
| 29 | console.log( | |
| 30 | "SKIPPING: no chromium that starts on this machine, so following a reply is not driven", | |
| 31 | ); | |
| 32 | ||
| 33 | let dir: string; | |
| 34 | let app: App; | |
| 35 | let servers: Servers; | |
| 36 | let token: string; | |
| 37 | const was = { running: clock.running, streamMs: clock.streamMs }; | |
| 38 | ||
| 39 | beforeAll(async () => { | |
| 40 | dir = await mkdtemp(join(tmpdir(), "forge-talk-follow-")); | |
| 41 | app = createApp({ dataDir: dir, port: 0 }); | |
| 42 | servers = await serve(app); | |
| 43 | const made = await createUser(app.db, { | |
| 44 | origin: "seed", | |
| 45 | trusted: true, | |
| 46 | username: "alice", | |
| 47 | email: "[email protected]", | |
| 48 | password: "a-good-passphrase", | |
| 49 | adminIfFirst: true, | |
| 50 | }); | |
| 51 | if (!made.ok) throw new Error(made.error); | |
| 52 | promote(app.db, made.value); | |
| 53 | const chat = openConversation(app.db, made.value.id); | |
| 54 | for (let i = 0; i < 12; i++) { | |
| 55 | appendTurn(app.db, made.value.id, chat.id, { | |
| 56 | role: "person", | |
| 57 | text: `Question ${i}`, | |
| 58 | }); | |
| 59 | appendTurn(app.db, made.value.id, chat.id, { | |
| 60 | role: "agent", | |
| 61 | text: `Answer ${i}.\n\n${"A line of the answer. ".repeat(30)}`, | |
| 62 | }); | |
| 63 | } | |
| 64 | token = createSession(app.db, made.value.id).token; | |
| 65 | // A turn is running for the whole test, so the page follows as it does while a reply is written. | |
| 66 | clock.running = () => true; | |
| 67 | clock.streamMs = 60_000; | |
| 68 | }, 30_000); | |
| 69 | afterAll(async () => { | |
| 70 | clock.running = was.running; | |
| 71 | clock.streamMs = was.streamMs; | |
| 72 | servers.stop(); | |
| 73 | app.close(); | |
| 74 | await rm(dir, { recursive: true, force: true }); | |
| 75 | }); | |
| 76 | ||
| 77 | /** Drives the page and returns what it saw at each step. Waits are frames, never a clock. */ | |
| 78 | const DRIVE = `(async () => { | |
| 79 | const frames = async (n) => { for (let i = 0; i < n; i++) await new Promise(requestAnimationFrame); }; | |
| 80 | const root = document.querySelector("[data-talk]"), log = root.querySelector(".talk-log"), jump = document.querySelector("[data-jump]"); | |
| 81 | const box = document.querySelector("form.talk-compose textarea"), err = document.querySelector("[data-error]"); | |
| 82 | const sc = () => getComputedStyle(root).overflowY === "auto" && root.scrollHeight > root.clientHeight ? root : document.scrollingElement; | |
| 83 | const dist = () => Math.round(sc().scrollHeight - sc().scrollTop - sc().clientHeight); | |
| 84 | const state = () => (jump.hidden ? "hidden" : jump.dataset.follow) + (jump.hasAttribute("data-new") ? "+new" : ""); | |
| 85 | const grow = async () => { const li = document.createElement("li"); li.style.height = "1500px"; log.append(li); await frames(3); }; | |
| 86 | // The stream's running frame shows the control: wait for that signal, not a clock. | |
| 87 | await new Promise((done) => { const check = () => state() === "pause" && done(); new MutationObserver(check).observe(jump, { attributes: true }); check(); }); | |
| 88 | const seen = { scroller: sc() === root ? "column" : "page", start: [state(), dist()] }; | |
| 89 | await grow(); | |
| 90 | seen.followed = [state(), dist()]; | |
| 91 | // What sits below the log changes height too (the error and status lines, buttons that wrap | |
| 92 | // where fonts are wider): the end it moves is followed all the same. The line stays until the | |
| 93 | // next input clears it, as on the page. | |
| 94 | err.hidden = false; | |
| 95 | err.textContent = "A line long enough to wrap on any phone. ".repeat(4); | |
| 96 | await frames(3); | |
| 97 | seen.composerGrew = [state(), dist()]; | |
| 98 | jump.click(); | |
| 99 | const top = sc().scrollTop; | |
| 100 | await grow(); | |
| 101 | seen.paused = [state(), sc().scrollTop - top]; | |
| 102 | document.dispatchEvent(new KeyboardEvent("keydown", { key: "End", bubbles: true })); | |
| 103 | await frames(2); | |
| 104 | seen.end = [state(), dist()]; | |
| 105 | log.dispatchEvent(new WheelEvent("wheel", { deltaY: -120, bubbles: true })); | |
| 106 | const top2 = sc().scrollTop; | |
| 107 | await grow(); | |
| 108 | seen.wheel = [state(), sc().scrollTop - top2]; | |
| 109 | jump.click(); | |
| 110 | await frames(2); | |
| 111 | seen.resumed = [state(), dist()]; | |
| 112 | document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "PageUp", bubbles: true })); | |
| 113 | await frames(1); | |
| 114 | seen.pageUp = state(); | |
| 115 | jump.click(); | |
| 116 | seen.required = box.required; | |
| 117 | const real = window.fetch; | |
| 118 | const answer = (status, body) => { window.fetch = async () => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); }; | |
| 119 | answer(429, { message: "Slow down: 12 messages a minute." }); | |
| 120 | box.value = "hello"; | |
| 121 | box.form.requestSubmit(); | |
| 122 | await frames(3); | |
| 123 | seen.refused = { invalid: box.getAttribute("aria-invalid"), says: err.hidden ? "" : err.textContent, kept: box.value }; | |
| 124 | box.dispatchEvent(new Event("input")); | |
| 125 | seen.typed = box.getAttribute("aria-invalid"); | |
| 126 | answer(202, { how: "queued" }); | |
| 127 | box.form.requestSubmit(); | |
| 128 | await frames(3); | |
| 129 | seen.sent = { invalid: box.getAttribute("aria-invalid"), painted: box.matches(":user-invalid, :invalid"), value: box.value, error: err.hidden }; | |
| 130 | window.fetch = real; | |
| 131 | return JSON.stringify(seen); | |
| 132 | })()`; | |
| 133 | ||
| 134 | const drive = async (width: number, height: number) => | |
| 135 | JSON.parse( | |
| 136 | await evaluateLoaded( | |
| 137 | chromium!, | |
| 138 | `${servers.url}/talk`, | |
| 139 | { width, height }, | |
| 140 | [{ name: "forge_session", value: token }], | |
| 141 | DRIVE, | |
| 142 | ), | |
| 143 | ); | |
| 144 | ||
| 145 | for (const [width, height, scroller] of [ | |
| 146 | [390, 844, "page"], | |
| 147 | [1280, 800, "column"], | |
| 148 | ] as const) { | |
| 149 | test.skipIf(chromium === undefined)( | |
| 150 | `at ${width} px the ${scroller} follows, pauses, lets go and comes back; a send never paints an error`, | |
| 151 | async () => { | |
| 152 | const seen = await drive(width, height); | |
| 153 | // One comparison of everything seen, so a failure anywhere prints the whole drive. A | |
| 154 | // distance is "end" within 2 px of the true end, else its pixels. | |
| 155 | const at = ([how, px]: [string, number]) => [how, px <= 2 ? "end" : px]; | |
| 156 | expect({ ...seen, start: at(seen.start), followed: at(seen.followed), composerGrew: at(seen.composerGrew), end: at(seen.end), resumed: at(seen.resumed) }).toEqual({ | |
| 157 | scroller, | |
| 158 | // At the true end while a reply runs: the control offers to pause, and stays there as | |
| 159 | // the log grows and as the composer below it changes height. | |
| 160 | start: ["pause", "end"], | |
| 161 | followed: ["pause", "end"], | |
| 162 | composerGrew: ["pause", "end"], | |
| 163 | // Paused: the page holds still while the log grows, and says there is more. | |
| 164 | paused: ["resume+new", 0], | |
| 165 | end: ["pause", "end"], | |
| 166 | // A wheel up lets go the same way; Resume comes back; PageUp lets go. | |
| 167 | wheel: ["resume+new", 0], | |
| 168 | resumed: ["pause", "end"], | |
| 169 | pageUp: "resume", | |
| 170 | // The box is never required once the script runs, so emptying it paints nothing. | |
| 171 | required: false, | |
| 172 | refused: { invalid: "true", says: "Slow down: 12 messages a minute.", kept: "hello" }, | |
| 173 | typed: null, | |
| 174 | sent: { invalid: null, painted: false, value: "", error: true }, | |
| 175 | }); | |
| 176 | }, | |
| 177 | 60_000, | |
| 178 | ); | |
| 179 | } |
test/talk-page.test.ts +113 −79
| @@ -201,7 +201,9 @@ describe("the page", () => { | ||
| 201 | 201 | promote(app.db, carol.value); |
| 202 | 202 | const empty = await (await get("/talk", carol.value)).text(); |
| 203 | 203 | expect(empty).toContain('name="text" value="What is waiting for me?"'); |
| 204 | expect(empty).not.toMatch(/<button[^>]*(data-copy|data-jump)/); | |
| 204 | // Copy is the script's; the follow control is drawn hidden and only the script shows it. | |
| 205 | expect(empty).not.toMatch(/<button[^>]*data-copy/); | |
| 206 | expect(empty).toMatch(/<button type="button" class="btn talk-jump" data-jump hidden>/); | |
| 205 | 207 | say(carol.value, "person", "hi"); |
| 206 | 208 | say(carol.value, "agent", "hello"); |
| 207 | 209 | say(carol.value, "tool", "list_issues {\"repo\":\"x\"}"); |
| @@ -256,12 +258,13 @@ describe("the page", () => { | ||
| 256 | 258 | expect(talkJs).toContain("pre.tabIndex = 0"); |
| 257 | 259 | }); |
| 258 | 260 | |
| 259 | test("the view follows a streaming reply only when the reader is at the bottom", async () => { | |
| 261 | test("the view follows a streaming reply only when the reader is at the true end of what scrolls", async () => { | |
| 260 | 262 | const { followJs } = await import("../src/web/pages/talk_client.ts"); |
| 261 | const follows = new Function(`${followJs}; return follows;`)() as (v: number, y: number, h: number) => boolean; | |
| 262 | expect(follows(800, 1200, 2000)).toBe(true); | |
| 263 | expect(follows(800, 1100, 2000)).toBe(true); | |
| 264 | expect(follows(800, 400, 2000)).toBe(false); | |
| 263 | const follows = new Function(`${followJs}; return follows;`)() as (height: number, top: number, view: number) => boolean; | |
| 264 | expect(follows(2000, 1200, 800)).toBe(true); | |
| 265 | expect(follows(2000, 1130, 800)).toBe(true); | |
| 266 | expect(follows(2000, 1100, 800)).toBe(false); | |
| 267 | expect(follows(2000, 400, 800)).toBe(false); | |
| 265 | 268 | }); |
| 266 | 269 | |
| 267 | 270 | test("an unfinished code block closes itself and leaves what is above it as it was", async () => { |
| @@ -368,8 +371,8 @@ describe("the page", () => { | ||
| 368 | 371 | |
| 369 | 372 | test("the page's own bytes are held: stylesheet and script stay small", async () => { |
| 370 | 373 | const { talkCss, talkJs } = await import("../src/web/pages/talk_client.ts"); |
| 371 | expect(Buffer.byteLength(talkCss)).toBeLessThan(6_300); | |
| 372 | expect(Buffer.byteLength(talkJs)).toBeLessThan(20_700); | |
| 374 | expect(Buffer.byteLength(talkCss)).toBeLessThan(6_700); | |
| 375 | expect(Buffer.byteLength(talkJs)).toBeLessThan(23_600); | |
| 373 | 376 | say(alice, "agent", "```ts\nlet x = 1;\n```"); |
| 374 | 377 | const page = await get("/talk", alice); |
| 375 | 378 | const size = (await page.arrayBuffer()).byteLength; |
| @@ -444,7 +447,7 @@ describe("the page", () => { | ||
| 444 | 447 | const doc = window.document as any; |
| 445 | 448 | doc.body.innerHTML = `<div class="talk" data-talk data-user="${user}" data-c="${conv}" data-paged="0" data-running="1"><div> |
| 446 | 449 | <ol class="talk-log" role="log" data-last=""><li class="talk-turn talk-agent" id="t-1"><div class="talk-body"><pre><code>let a = 1;</code></pre></div><p class="talk-meta">Forge · now</p></li></ol><div id="end"></div></div> |
| 447 | <form class="talk-compose"><p class="talk-status" role="status"></p><ul data-chips></ul><textarea name="text"></textarea><div class="bar"><span data-compose-hint></span><label data-attach hidden><input type="file" data-pick /></label><button class="btn" type="button" data-stop hidden>Stop</button><button class="btn" type="button" data-steer hidden>Steer</button><button class="btn" type="submit">Send</button></div></form></div>`; | |
| 450 | <form class="talk-compose"><p class="talk-status" role="status"></p><ul data-chips></ul><textarea name="text" required></textarea><p data-error hidden></p><button type="button" class="btn talk-jump" data-jump hidden><span data-word></span></button><div class="bar"><span data-compose-hint></span><label data-attach hidden><input type="file" data-pick /></label><button class="btn" type="button" data-stop hidden>Stop</button><button class="btn" type="button" data-steer hidden>Steer</button><button class="btn" type="submit">Send</button></div></form></div>`; | |
| 448 | 451 | const how = { value: "started" }; |
| 449 | 452 | const cancel = { status: 200 }; |
| 450 | 453 | const page = { html: "" }; |
| @@ -466,12 +469,25 @@ describe("the page", () => { | ||
| 466 | 469 | const local = { get length() { return Object.keys(store).length; }, key: (i: number) => Object.keys(store)[i] ?? null, getItem: (k: string) => store[k] ?? null, setItem: (k: string, v: string) => { store[k] = v; }, removeItem: (k: string) => { delete store[k]; } }; |
| 467 | 470 | const nav = { clipboard: { writeText: async (t: string) => { copied.push(t); } } }; |
| 468 | 471 | class ES { on: Record<string, (e: { data: string }) => void> = {}; constructor() { sources.push(this); } addEventListener(n: string, f: (e: { data: string }) => void) { const was = this.on[n]; this.on[n] = was ? (e) => { was(e); f(e); } : f; } close() {} } |
| 469 | doc.getElementById("end").scrollIntoView = () => {}; | |
| 472 | // The page scrolls (a phone): 5,000 px of it in an 800 px view. Growth is reported by hand. | |
| 473 | const grows: Array<() => void> = []; | |
| 474 | (window as any).ResizeObserver = class { els: unknown[] = []; constructor(f: (seen: { target: unknown }[]) => void) { grows.push(() => f(this.els.map((target) => ({ target })))); } observe(el: unknown) { this.els.push(el); } }; | |
| 475 | const view = scrollable(doc.scrollingElement ?? doc.documentElement, 5000, 800); | |
| 470 | 476 | new Function("document", "window", "EventSource", "fetch", "localStorage", "navigator", talkJs)(doc, window, ES, fetchStub, local, nav); |
| 471 | 477 | const box = doc.querySelector("textarea"); |
| 472 | 478 | const key = (init: object) => box.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...init })); |
| 473 | 479 | const emit = (id: string, html: string) => sources.at(-1)!.on["turn"]!({ data: JSON.stringify({ id, html }) }); |
| 474 | return { how, cancel, page, emit, bodies, sources, urls, window, doc, box, sent, copied, store, key, status: doc.querySelector(".talk-status") }; | |
| 480 | const grow = () => { for (const f of grows) f(); }; | |
| 481 | return { how, cancel, page, emit, bodies, sources, urls, window, doc, box, sent, copied, store, key, view, grow, hand: () => doc.documentElement.dispatchEvent(new window.PointerEvent("pointerdown", { bubbles: true })), jump: doc.querySelector("[data-jump]"), status: doc.querySelector(".talk-status") }; | |
| 482 | }; | |
| 483 | /** An element that scrolls `height` px in a `client` px view; each programmatic move is kept. */ | |
| 484 | const scrollable = (el: any, height: number, client: number) => { | |
| 485 | const v = { top: 0, height, client, moves: [] as number[] }; | |
| 486 | Object.defineProperty(el, "scrollHeight", { get: () => v.height, configurable: true }); | |
| 487 | Object.defineProperty(el, "clientHeight", { get: () => v.client, configurable: true }); | |
| 488 | Object.defineProperty(el, "scrollTop", { get: () => v.top, set: (y: number) => { v.top = y; }, configurable: true }); | |
| 489 | el.scrollTo = (o: { top: number }) => { v.top = Math.max(0, Math.min(o.top, v.height - v.client)); v.moves.push(v.top); }; | |
| 490 | return v; | |
| 475 | 491 | }; |
| 476 | 492 | const tick = () => new Promise((r) => setTimeout(r, 5)); |
| 477 | 493 | |
| @@ -594,10 +610,9 @@ describe("the page", () => { | ||
| 594 | 610 | return e; |
| 595 | 611 | }; |
| 596 | 612 | t.sources.at(-1)!.on["running"]!({ data: "{}" }); |
| 597 | let scrolled = 0; | |
| 598 | t.doc.getElementById("end").scrollIntoView = () => { scrolled++; }; | |
| 613 | const moved = t.view.moves.length; | |
| 599 | 614 | expect(press({ key: "End" }).defaultPrevented).toBe(true); |
| 600 | expect(scrolled).toBe(1); | |
| 615 | expect(t.view.moves.length).toBe(moved + 1); | |
| 601 | 616 | press({ key: "?" }); |
| 602 | 617 | expect(keys.hidden).toBe(false); |
| 603 | 618 | press({ key: "Escape" }); |
| @@ -613,15 +628,14 @@ describe("the page", () => { | ||
| 613 | 628 | |
| 614 | 629 | test("End inside the box leaves the caret alone and does not scroll", async () => { |
| 615 | 630 | const t = await boot(); |
| 616 | let scrolled = 0; | |
| 617 | t.doc.getElementById("end").scrollIntoView = () => { scrolled++; }; | |
| 631 | const moved = t.view.moves.length; | |
| 618 | 632 | t.box.value = "hello"; |
| 619 | 633 | t.box.focus(); |
| 620 | 634 | t.box.setSelectionRange(2, 2); |
| 621 | 635 | const e = new t.window.KeyboardEvent("keydown", { key: "End", bubbles: true, cancelable: true }); |
| 622 | 636 | t.box.dispatchEvent(e); |
| 623 | 637 | expect(e.defaultPrevented).toBe(false); |
| 624 | expect(scrolled).toBe(0); | |
| 638 | expect(t.view.moves.length).toBe(moved); | |
| 625 | 639 | expect(t.box.selectionStart).toBe(2); |
| 626 | 640 | await t.window.happyDOM.close(); |
| 627 | 641 | }); |
| @@ -794,59 +808,75 @@ describe("the page", () => { | ||
| 794 | 808 | expect(t.status.textContent).toBe("The forge replied."); |
| 795 | 809 | }); |
| 796 | 810 | |
| 797 | test("the page follows the block to the true end only when the reader was there; scrolled up, nothing moves", async () => { | |
| 811 | test("a reply starting changes the composer, and a follower is at the end in that same moment, before any size is observed", async () => { | |
| 798 | 812 | const t = await boot(); |
| 799 | const on = () => t.sources.at(-1)!.on; | |
| 800 | const frame = (words: string) => on()["live"]!({ data: JSON.stringify({ html: `<div class="talk-body prose"><p>${words}</p></div>`, tool: "", thinking: false }) }); | |
| 801 | const went: number[] = []; | |
| 802 | let into = 0; | |
| 803 | t.doc.getElementById("end").scrollIntoView = () => { into++; }; | |
| 804 | Object.defineProperty(t.window, "innerHeight", { value: 800, configurable: true }); | |
| 805 | Object.defineProperty(t.doc.documentElement, "scrollHeight", { value: 5000, configurable: true }); | |
| 806 | // The composer sits below the log's end: only the document's own end is the end. | |
| 807 | t.window.scrollTo = (_x: number, y: number) => { | |
| 808 | went.push(y); | |
| 809 | Object.defineProperty(t.window, "scrollY", { value: y - 800, configurable: true }); | |
| 810 | t.window.dispatchEvent(new t.window.Event("scroll")); | |
| 811 | }; | |
| 812 | on()["running"]!({ data: "{}" }); | |
| 813 | for (const w of ["one", "one two", "one two three", "one two three four", "one two three four five"]) frame(w); | |
| 814 | expect(went).toEqual([5000, 5000, 5000, 5000, 5000]); | |
| 815 | // Scrolled up: five more frames move nothing. | |
| 816 | Object.defineProperty(t.window, "scrollY", { value: 0, configurable: true }); | |
| 817 | t.window.dispatchEvent(new t.window.Event("scroll")); | |
| 818 | for (const w of ["six", "seven", "eight", "nine", "ten"]) frame(w); | |
| 819 | expect(went).toHaveLength(5); | |
| 820 | expect(into).toBe(0); | |
| 821 | expect(t.doc.getElementById("live").textContent).toBe("ten"); | |
| 813 | expect(t.view.top).toBe(4200); | |
| 814 | // Steer and Stop appear and the composer's row wraps (wider fonts): 52 px more page. | |
| 815 | t.view.height = 5052; | |
| 816 | t.sources.at(-1)!.on["running"]!({ data: "{}" }); | |
| 817 | expect(t.view.top).toBe(4252); | |
| 822 | 818 | }); |
| 823 | 819 | |
| 824 | test("on a wide screen, where the talk column scrolls on its own, the column follows the block only from its end", async () => { | |
| 820 | test("following, the page's true end stays in view as the log grows; scrolled up, nothing moves and the control says there is more", async () => { | |
| 821 | const t = await boot(); | |
| 822 | t.sources.at(-1)!.on["running"]!({ data: "{}" }); | |
| 823 | // Loaded at the true end of what scrolls, the composer counted: the control offers to pause. | |
| 824 | expect(t.view.top).toBe(4200); | |
| 825 | expect([t.jump.hidden, t.jump.dataset.follow, t.jump.getAttribute("aria-label")]).toEqual([false, "pause", "Pause scrolling and keep this place"]); | |
| 826 | for (const h of [5600, 6100, 7000]) { | |
| 827 | t.view.height = h; | |
| 828 | t.grow(); | |
| 829 | expect(t.view.top).toBe(h - 800); | |
| 830 | } | |
| 831 | // The layout moving the page (a turn stored, the box shrinking) is not the reader: still following. | |
| 832 | t.view.top = 3000; | |
| 833 | t.doc.dispatchEvent(new t.window.Event("scroll")); | |
| 834 | expect(t.jump.dataset.follow).toBe("pause"); | |
| 835 | // The reader scrolling up (the scrollbar here) lets go: growth moves nothing, and the control resumes, marked new. | |
| 836 | const moved = t.view.moves.length; | |
| 837 | t.view.top = 1000; | |
| 838 | t.hand(); | |
| 839 | t.doc.dispatchEvent(new t.window.Event("scroll")); | |
| 840 | t.view.height = 9000; | |
| 841 | t.grow(); | |
| 842 | expect(t.view.moves.length).toBe(moved); | |
| 843 | expect(t.view.top).toBe(1000); | |
| 844 | expect([t.jump.dataset.follow, t.jump.hasAttribute("data-new")]).toEqual(["resume", true]); | |
| 845 | t.jump.click(); | |
| 846 | expect(t.view.top).toBe(8200); | |
| 847 | expect([t.jump.dataset.follow, t.jump.hasAttribute("data-new")]).toEqual(["pause", false]); | |
| 848 | // Pause holds the place where it is, with no scroll at all. | |
| 849 | t.jump.click(); | |
| 850 | t.view.height = 9500; | |
| 851 | t.grow(); | |
| 852 | expect(t.view.top).toBe(8200); | |
| 853 | expect(t.jump.dataset.follow).toBe("resume"); | |
| 854 | // A wheel up inside the thread lets go too, once followed again. | |
| 855 | t.jump.click(); | |
| 856 | t.doc.querySelector(".talk-log").dispatchEvent(new t.window.WheelEvent("wheel", { deltaY: -40, bubbles: true })); | |
| 857 | expect(t.jump.dataset.follow).toBe("resume"); | |
| 858 | }); | |
| 859 | ||
| 860 | test("on a wide screen, where the talk column scrolls on its own, the column follows and the window never moves", async () => { | |
| 825 | 861 | const t = await boot(); |
| 826 | const on = () => t.sources.at(-1)!.on; | |
| 827 | 862 | const root = t.doc.querySelector("[data-talk]"); |
| 828 | let top = 2300; | |
| 829 | 863 | root.style.overflowY = "auto"; |
| 830 | Object.defineProperty(root, "scrollHeight", { value: 3000, configurable: true }); | |
| 831 | Object.defineProperty(root, "clientHeight", { value: 700, configurable: true }); | |
| 832 | Object.defineProperty(root, "scrollTop", { get: () => top, set: (v: number) => { top = v; }, configurable: true }); | |
| 833 | // The log's end sits at 2,900 px in the column, the composer below it: after Send the page's | |
| 834 | // toEnd leaves the reader with #end in view, 300 px short of the column's own end. | |
| 835 | root.getBoundingClientRect = () => ({ top: 0 }); | |
| 836 | t.doc.getElementById("end").getBoundingClientRect = () => ({ top: 2900 - top }); | |
| 837 | top = 2200; | |
| 838 | let windowMoved = false; | |
| 839 | t.window.scrollTo = () => { windowMoved = true; }; | |
| 840 | on()["live"]!({ data: JSON.stringify({ html: "<p>a</p>", tool: "", thinking: false }) }); | |
| 841 | expect(top).toBe(3000); | |
| 842 | on()["live"]!({ data: JSON.stringify({ html: "<p>a b</p>", tool: "", thinking: false }) }); | |
| 843 | expect(top).toBe(3000); | |
| 844 | expect(windowMoved).toBe(false); | |
| 845 | // Scrolled up in the column: the next frame moves nothing. | |
| 846 | top = 0; | |
| 847 | on()["live"]!({ data: JSON.stringify({ html: "<p>ab</p>", tool: "", thinking: false }) }); | |
| 848 | expect(top).toBe(0); | |
| 849 | expect(windowMoved).toBe(false); | |
| 864 | const col = scrollable(root, 3000, 700); | |
| 865 | t.sources.at(-1)!.on["running"]!({ data: "{}" }); | |
| 866 | const pageMoves = t.view.moves.length; | |
| 867 | t.grow(); | |
| 868 | expect(col.top).toBe(2300); | |
| 869 | col.height = 3400; | |
| 870 | t.grow(); | |
| 871 | expect(col.top).toBe(2700); | |
| 872 | expect(t.view.moves.length).toBe(pageMoves); | |
| 873 | // Scrolled up in the column: the next growth moves nothing. | |
| 874 | col.top = 0; | |
| 875 | root.dispatchEvent(new t.window.PointerEvent("pointerdown", { bubbles: true })); | |
| 876 | root.dispatchEvent(new t.window.Event("scroll")); | |
| 877 | col.height = 3800; | |
| 878 | t.grow(); | |
| 879 | expect(col.top).toBe(0); | |
| 850 | 880 | }); |
| 851 | 881 | |
| 852 | 882 | test("a turn that arrives again is not drawn twice or replaced, so what is above it keeps its place", async () => { |
| @@ -863,16 +893,18 @@ describe("the page", () => { | ||
| 863 | 893 | expect(t.doc.querySelectorAll("#t-2 pre [data-copy]").length).toBe(1); |
| 864 | 894 | }); |
| 865 | 895 | |
| 866 | test("a turn arriving while scrolled up does not scroll the page", async () => { | |
| 896 | test("a turn arriving while scrolled up does not scroll the page, and is announced once", async () => { | |
| 867 | 897 | const t = await boot(); |
| 868 | let scrolled = 0; | |
| 869 | t.doc.getElementById("end").scrollIntoView = () => { scrolled++; }; | |
| 870 | Object.defineProperty(t.window, "innerHeight", { value: 800, configurable: true }); | |
| 871 | Object.defineProperty(t.window, "scrollY", { value: 0, configurable: true }); | |
| 872 | Object.defineProperty(t.doc.documentElement, "scrollHeight", { value: 5000, configurable: true }); | |
| 873 | t.window.dispatchEvent(new t.window.Event("scroll")); | |
| 898 | t.view.top = 0; | |
| 899 | t.hand(); | |
| 900 | t.doc.dispatchEvent(new t.window.Event("scroll")); | |
| 901 | const moved = t.view.moves.length; | |
| 874 | 902 | t.emit("2", '<li class="talk-turn" id="t-2"><div class="talk-body"><pre><code>x</code></pre></div></li>'); |
| 875 | expect(scrolled).toBe(0); | |
| 903 | t.view.height = 5600; | |
| 904 | t.grow(); | |
| 905 | expect(t.view.moves.length).toBe(moved); | |
| 906 | expect(t.status.textContent).toBe("New message"); | |
| 907 | expect([t.jump.hidden, t.jump.dataset.follow, t.jump.hasAttribute("data-new")]).toEqual([false, "latest", true]); | |
| 876 | 908 | }); |
| 877 | 909 | |
| 878 | 910 | test("a streaming reply is held busy and announced once finished; the jump button is a real button with a name", async () => { |
| @@ -891,7 +923,8 @@ describe("the page", () => { | ||
| 891 | 923 | const jump = t.doc.querySelector(".talk-jump"); |
| 892 | 924 | expect(jump.tagName).toBe("BUTTON"); |
| 893 | 925 | expect(jump.getAttribute("type")).toBe("button"); |
| 894 | expect(jump.getAttribute("aria-label")).toBe("Jump to the latest message"); | |
| 926 | // At the end and nothing running: there is nothing to jump to. | |
| 927 | expect(jump.hidden).toBe(true); | |
| 895 | 928 | }); |
| 896 | 929 | |
| 897 | 930 | test("a lost connection, a drain and a hand-over each clear aria-busy; the last failed retry says so", async () => { |
| @@ -920,15 +953,16 @@ describe("the page", () => { | ||
| 920 | 953 | t.emit("2", '<li class="talk-turn" id="t-2">a</li>'); |
| 921 | 954 | expect(jump.hidden).toBe(true); |
| 922 | 955 | expect(t.status.textContent).not.toContain("New message"); |
| 923 | Object.defineProperty(t.window, "innerHeight", { value: 800, configurable: true }); | |
| 924 | Object.defineProperty(t.window, "scrollY", { value: 0, configurable: true }); | |
| 925 | Object.defineProperty(t.doc.documentElement, "scrollHeight", { value: 5000, configurable: true }); | |
| 926 | t.window.dispatchEvent(new t.window.Event("scroll")); | |
| 956 | t.view.top = 0; | |
| 957 | t.hand(); | |
| 958 | t.doc.dispatchEvent(new t.window.Event("scroll")); | |
| 927 | 959 | t.emit("3", '<li class="talk-turn" id="t-3">b</li>'); |
| 928 | 960 | expect(jump.hidden).toBe(false); |
| 929 | 961 | expect(t.status.textContent).toBe("New message"); |
| 930 | Object.defineProperty(t.window, "scrollY", { value: 4400, configurable: true }); | |
| 931 | t.window.dispatchEvent(new t.window.Event("scroll")); | |
| 962 | // Back at the end by hand: following again, and nothing to jump to. | |
| 963 | t.view.top = 4200; | |
| 964 | t.hand(); | |
| 965 | t.doc.dispatchEvent(new t.window.Event("scroll")); | |
| 932 | 966 | expect(jump.hidden).toBe(true); |
| 933 | 967 | }); |
| 934 | 968 | }); |
new above
offline