Public: anyone can read this; the crew can change it.
/talk is a chat you'd expect: streaming, history, stop, retry, attachments and tool cards, clean and fast #8755
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/8752-talk-is-a-chat-you-d-expect-streaming-hi → main 3 commits fork 5 threads · 5 unresolved
docs/design/areas/talk.md +6
| @@ -12,3 +12,9 @@ | ||
| 12 | 12 | - `.talk-compose` — the composer, sticky to the bottom of the viewport (padded for the phone's safe area), so it stays reachable; its textarea is 16px so iOS does not zoom. |
| 13 | 13 | - `.talk-status` — one polite line (sending, answering, an error); it always takes its line, so nothing shifts. |
| 14 | 14 | - `.talk-more` — the "Earlier" link above the log. |
| 15 | - `.talk-body` — the text of one turn, above its meta line. | |
| 16 | - `.talk-plain` — a person's words, shown as typed (line breaks kept). | |
| 17 | - `.talk-meta` — who said it and when, with the copy button. | |
| 18 | - `.talk-copy` — a quiet text button that copies a message or a code block. | |
| 19 | - `.talk-suggest` — the starter questions on an empty chat; each fills the composer. | |
| 20 | - `.talk-jump` — "Latest" button, shown when you have scrolled up from the end. |
docs/features/talk.md +23
| @@ -17,3 +17,26 @@ Reached from the Talk icon in every page's top bar, "Talk to the forge" in the p | ||
| 17 | 17 | A reply streams in over `GET /talk/stream?after=<turn id>` (server-sent events, one `turn` frame per turn, each carrying the server-rendered markup). The stream ends with the turn (`done`), or after 40 seconds (`more`), well inside the edge's timeout; the page then reconnects from the last turn id it saw (`Last-Event-ID` works too). Without the script the composer is a plain form and a reload shows the answer. |
| 18 | 18 | |
| 19 | 19 | When the agent asks first (`needs_confirm`), the turn draws **Confirm** (the existing yes) and **Cancel** (a no: the confirm is spent, nothing runs, a turn says it was cancelled). A result shown once (an invite link) is drawn by Settings → Confirms instead, where Confirm leads. |
| 20 | ||
| 21 | ## Chat features: have, adding, not adding (#8752) | |
| 22 | ||
| 23 | Prior art read: Vercel AI Elements (Apache-2.0 React on shadcn; anatomy and behaviour ported, no code copied), AI SDK UI, ChatGPT and Claude.ai. No React: the page stays server-drawn with a small script. | |
| 24 | ||
| 25 | | Feature | Status | Why | | |
| 26 | | --- | --- | --- | | |
| 27 | | Server-drawn history, streaming over SSE, resume from turn id | have | the base of this page | | |
| 28 | | Confirm / Cancel in place for held writes | have | trust rule | | |
| 29 | | Enter sends, Shift+Enter breaks a line, autosizing box | this pull | what every chat does | | |
| 30 | | Draft kept on reload (localStorage, this device) | this pull | cheap, local | | |
| 31 | | Who and when under each message; copy a message; copy a code block | this pull | AI Elements `Message`, `CodeBlock` | | |
| 32 | | Tool calls as closed cards | this pull | AI Elements `Tool` | | |
| 33 | | Starter questions on an empty chat (links to `/talk?q=`, so they work without the script) | this pull | AI Elements `Suggestion` | | |
| 34 | | Stick to bottom, "Latest" jump button | this pull | AI Elements `Conversation` | | |
| 35 | | Many conversations: new, list, search, rename, archive, URL each | next pull | needs a migration: today one row per person | | |
| 36 | | Edit and resend, regenerate, Stop, queue | next pulls | need turn deletion and a cancel on `crew/conversation.ts` | | |
| 37 | | Attachments, cost and context left, tables, thinking, plan line | later | need storage / token data / markdown tables | | |
| 38 | | Syntax highlighting while streaming | not adding yet | re-tokenising a half-open fence makes text jump | | |
| 39 | ||
| 40 | **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. | |
| 41 | ||
| 42 | **The terminal** (`ssh <forge> talk <words>`, `forge talk`) sends one line and prints the answer; it has no log, so who/when, copy, tool cards, starters and the jump button do not apply to it. The conversation's whole history is read through `GET /api/v1/conversation/turns`, where every turn carries its role and time. |
src/web/pages/talk.ts +34 −12
| @@ -26,7 +26,7 @@ import { readForm } from "../form.ts"; | ||
| 26 | 26 | import { html, type Html } from "../html.ts"; |
| 27 | 27 | import { flashTo, page } from "../layout.ts"; |
| 28 | 28 | import { renderMarkdown } from "../markdown.ts"; |
| 29 | import { btn } from "../ui.ts"; | |
| 29 | import { btn, time } from "../ui.ts"; | |
| 30 | 30 | import { talkCss, talkJs } from "./talk_client.ts"; |
| 31 | 31 | |
| 32 | 32 | /** A stream lasts this long at most; the client reconnects from its last turn id. */ |
| @@ -65,11 +65,30 @@ function confirmButtons(id: string, tool: string): Html { | ||
| 65 | 65 | </div>`; |
| 66 | 66 | } |
| 67 | 67 | |
| 68 | /** Who said it and when, with the copy button: the line under a message. */ | |
| 69 | const meta = (who: string, at: string): Html => | |
| 70 | html`<p class="talk-meta small muted">${who} · ${time(at)}</p>`; | |
| 71 | ||
| 72 | /** A tool call or its outcome as a quiet card: closed, the name alone; open, the whole line. */ | |
| 73 | const toolCard = (id: string, says: string, name: string, at: string): Html => | |
| 74 | html`<li class="talk-turn talk-tool" id="${id}"><details><summary>${name.slice(0, 60)} <span class="talk-when">${time(at)}</span></summary><p>${says}</p></details></li>`; | |
| 75 | ||
| 76 | /** What an empty chat offers to start with; each is a link that fills the composer (`?q=`), so it works without the script. */ | |
| 77 | const SUGGESTIONS = ["What needs my attention?", "What did the crew do today?", "Show me my apps"] as const; | |
| 78 | ||
| 68 | 79 | /** One turn as the page and the stream both draw it; `waiting` is the confirms still open. */ |
| 69 | 80 | export function turnHtml(turn: Turn, waiting: ReadonlySet<string>): Html { |
| 70 | 81 | const id = `t-${turn.id}`; |
| 71 | if (turn.role === "person") return html`<li class="talk-turn talk-person" id="${id}">${turn.text}</li>`; | |
| 72 | if (turn.role === "agent") return html`<li class="talk-turn talk-agent" id="${id}">${renderMarkdown(turn.text)}</li>`; | |
| 82 | if (turn.role === "person") | |
| 83 | return html`<li class="talk-turn talk-person" id="${id}"> | |
| 84 | <div class="talk-body talk-plain">${turn.text}</div> | |
| 85 | ${meta("You", turn.createdAt)} | |
| 86 | </li>`; | |
| 87 | if (turn.role === "agent") | |
| 88 | return html`<li class="talk-turn talk-agent" id="${id}"> | |
| 89 | <div class="talk-body">${renderMarkdown(turn.text)}</div> | |
| 90 | ${meta("Forge", turn.createdAt)} | |
| 91 | </li>`; | |
| 73 | 92 | const data = parse(turn.text); |
Server-rendered suggestion buttons are dead without JS. Build them in the client or make each a link to /talk?q=... that prefills the form. |
||
| 74 | 93 | if (turn.role === "confirm") { |
| 75 | 94 | const confirm = String(data?.["confirm"] ?? ""); |
| @@ -83,12 +102,13 @@ export function turnHtml(turn: Turn, waiting: ReadonlySet<string>): Html { | ||
| 83 | 102 | if (data !== undefined && "confirm" in data) { |
| 84 | 103 | const tool = String(data["tool"] ?? ""); |
| 85 | 104 | const says = data["cancelled"] === true ? `Cancelled: ${tool}.` : data["done"] === true ? `Done: ${tool}.${typeof data["undo"] === "string" ? ` To undo: ${data["undo"]}.` : ""}` : `${tool} did not go through: ${String(data["message"] ?? data["error"] ?? "")}`; |
| 86 | return html`<li class="talk-turn talk-tool" id="${id}">${says}</li>`; | |
| 105 | return toolCard(id, says, tool, turn.createdAt); | |
| 87 | 106 | } |
| 88 | return html`<li class="talk-turn talk-tool" id="${id}">${turn.text.slice(0, 300)}</li>`; | |
| 107 | const call = turn.text.slice(0, 300); | |
| 108 | return toolCard(id, call, call.split(/[\s(:{]/, 1)[0] ?? "tool", turn.createdAt); | |
| 89 | 109 | } |
| 90 | 110 | |
| 91 | function talkPage(ctx: Ctx, before: string | undefined): Response { | |
| 111 | function talkPage(ctx: Ctx, before: string | undefined, prefill: string): Response { | |
| 92 | 112 | const user = ctx.auth.user!; |
| 93 | 113 | const conversation = openConversation(ctx.app.db, user.id); |
| 94 | 114 | const listed = listTurns(ctx.app.db, user.id, conversation.id, { |
| @@ -101,24 +121,25 @@ function talkPage(ctx: Ctx, before: string | undefined): Response { | ||
| 101 | 121 | // Paging back, the log ends before the newest turn: it does not follow. |
| 102 | 122 | const last = turns.at(-1)?.id ?? ""; |
| 103 | 123 | const body = html`<div class="page-head"><h1>Talk</h1></div> |
| 104 | <div class="talk" data-talk data-paged="${before === undefined ? "0" : "1"}" data-running="${running && before === undefined ? "1" : "0"}"> | |
| 124 | <div class="talk" data-talk data-user="${user.id}" data-paged="${before === undefined ? "0" : "1"}" data-running="${running && before === undefined ? "1" : "0"}"> | |
| 105 | 125 | <div> |
| 106 | 126 | ${turns.length === DEFAULT_PAGE && turns[0] !== undefined |
| 107 | 127 | ? html`<p class="talk-more small"><a href="${HERE}?before=${turns[0].id}">Earlier</a></p>` |
| 108 | 128 | : null} |
| 109 | 129 | ${before === undefined ? null : html`<p class="talk-more small"><a href="${HERE}">Latest</a></p>`} |
| 110 | <ol class="talk-log" data-last="${last}" aria-label="Conversation with the forge"> | |
| 130 | <ol class="talk-log" role="log" data-last="${last}" aria-label="Conversation with the forge"> | |
| 111 | 131 | ${turns.length === 0 |
| 112 | ? html`<li class="muted talk-turn">Ask the forge anything, or tell it what to change. It acts as you, with your permissions, and asks before anything hard to undo.</li>` | |
| 132 | ? html`<li class="muted talk-turn">Ask the forge anything, or tell it what to change. It acts as you, with your permissions, and asks before anything hard to undo. | |
| 133 | <span class="talk-suggest">${SUGGESTIONS.map((q) => html`<a class="btn" href="${HERE}?q=${encodeURIComponent(q)}" data-suggest="${q}">${q}</a>`)}</span></li>` | |
| 113 | 134 | : turns.map((t) => turnHtml(t, waiting))} |
| 114 | 135 | </ol> |
| 115 | 136 | <div id="end"></div> |
| 116 | 137 | </div> |
| 117 | 138 | <form class="talk-compose" method="post" action="${HERE}"> |
| 118 | 139 | <p class="talk-status small muted" role="status" aria-live="polite">${running ? "The forge is answering…" : ""}</p> |
| 119 | <textarea class="input" name="text" rows="2" maxlength="${WORDS_MAX}" required placeholder="Talk to the forge" aria-label="Talk to the forge"></textarea> | |
| 140 | <textarea class="input" name="text" rows="1" maxlength="${WORDS_MAX}" required placeholder="Talk to the forge" aria-label="Talk to the forge">${prefill}</textarea> | |
| 120 | 141 | <div class="bar"> |
| 121 | <span class="muted small">Ctrl+Enter sends</span> | |
| 142 | <span class="muted small" data-hint></span> | |
| 122 | 143 | <span class="spacer"></span> |
outdated
This hint is wrong with JS off, where Enter adds a line. Set it from the script. |
||
| 123 | 144 | ${btn("Send", { variant: "primary" })} |
| 124 | 145 | </div> |
| @@ -132,7 +153,8 @@ export function talkView(ctx: Ctx): Response { | ||
| 132 | 153 | if (ctx.auth.user === undefined) return signInFirst(ctx); |
| 133 | 154 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 134 | 155 | const before = ctx.url.searchParams.get("before"); |
| 135 | return timePhase(ctx.request, "render", () => talkPage(ctx, before !== null && TURN_ID.test(before) && before !== "" ? before : undefined)); | |
| 156 | const q = ctx.url.searchParams.get("q"); | |
| 157 | return timePhase(ctx.request, "render", () => talkPage(ctx, before !== null && TURN_ID.test(before) && before !== "" ? before : undefined, q !== null && SUGGESTIONS.some((s) => s === q) ? q : "")); | |
| 136 | 158 | } |
| 137 | 159 | |
| 138 | 160 | // POST /talk — the plain form, for a browser without the script. |
src/web/pages/talk_client.ts +68 −5
| @@ -18,10 +18,23 @@ export const talkCss = /* css */ ` | ||
| 18 | 18 | .talk-confirm .bar { margin-top: 8px; gap: 8px; } |
| 19 | 19 | .talk-confirm .btn { min-height: 2.75rem; flex: 1 1 8rem; } |
| 20 | 20 | .talk-compose { position: sticky; bottom: 0; background: var(--bg); padding: 0.5rem 0 max(0.5rem, env(safe-area-inset-bottom)); border-top: 1px solid var(--border); z-index: 8; } |
| 21 | .talk-compose textarea { width: 100%; min-height: 56px; max-height: 40dvh; font-size: 16px; resize: vertical; box-sizing: border-box; } | |
| 21 | .talk-compose textarea { width: 100%; min-height: 44px; max-height: 40dvh; font-size: 16px; resize: none; overflow-y: auto; box-sizing: border-box; } | |
| 22 | 22 | .talk-compose .bar { margin-top: 6px; gap: 8px; align-items: center; } |
| 23 | 23 | .talk-compose .btn { min-height: 2.75rem; } |
| 24 | 24 | .talk-status { min-height: 1.5em; margin: 0; } |
| 25 | .talk-meta { margin: 4px 0 0; display: flex; gap: 6px; align-items: center; } | |
| 26 | .talk-copy { margin-left: auto; background: none; border: 0; color: inherit; font: inherit; cursor: pointer; padding: 6px 8px; min-height: 2rem; opacity: 0.7; } | |
| 27 | .talk-copy:hover { opacity: 1; text-decoration: underline; } | |
| 28 | .talk-plain { white-space: pre-wrap; } | |
| 29 | .talk-tool details { border: 1px solid var(--border); border-radius: var(--radius-lg); padding: 2px 10px; } | |
| 30 | .talk-tool summary { cursor: pointer; padding: 6px 0; min-height: 1.5rem; } | |
| 31 | .talk-tool details p { margin: 0 0 8px; white-space: pre-wrap; } | |
| 32 | .talk-suggest { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; } | |
| 33 | .talk-suggest .btn { min-height: 2.75rem; } | |
| 34 | .talk-jump { position: absolute; bottom: calc(100% + 8px); left: 50%; transform: translateX(-50%); z-index: 9; min-height: 2.75rem; } | |
| 35 | .talk-jump[hidden] { display: none; } | |
| 36 | .talk-body pre { position: relative; } | |
| 37 | .talk-body pre .talk-copy { position: absolute; top: 2px; right: 2px; } | |
| 25 | 38 | .talk-more { text-align: center; } |
| 26 | 39 | `; |
| 27 | 40 | |
| @@ -38,7 +51,54 @@ if (root) { | ||
| 38 | 51 | let retry = 0; |
| 39 | 52 | const paged = root.dataset.paged === "1"; |
| 40 | 53 | const say = (words) => { status.textContent = words; }; |
| 41 | const toEnd = () => { const end = document.getElementById("end"); if (end) end.scrollIntoView({ block: "end" }); }; | |
| 54 | const hint = root.querySelector("[data-hint]"); | |
| 55 | if (hint) hint.textContent = "Enter sends, Shift+Enter adds a line"; | |
| 56 | const jump = Object.assign(document.createElement("button"), { type: "button", className: "btn talk-jump", textContent: "Latest ↓", hidden: true }); | |
| 57 | jump.setAttribute("aria-label", "Jump to the latest message"); | |
| 58 | form.appendChild(jump); | |
outdated
A shared draft key leaks drafts across accounts on one device. Scope it to the user. Also, a new turn arriving while scrolled up only unhides the button silently: announce it in the status line. |
||
| 59 | const nearEnd = () => window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 120; | |
| 60 | let stuck = true; | |
| 61 | const toEnd = (force) => { | |
| 62 | if (!force && !stuck) { jump.hidden = false; say("New message"); return; } | |
| 63 | const end = document.getElementById("end"); | |
| 64 | if (end) end.scrollIntoView({ block: "end" }); | |
| 65 | jump.hidden = true; | |
| 66 | }; | |
| 67 | window.addEventListener("scroll", () => { stuck = nearEnd(); if (stuck) jump.hidden = true; }, { passive: true }); | |
| 68 | jump.addEventListener("click", () => { stuck = true; toEnd(true); box.focus(); }); | |
| 69 | const draftKey = "talk-draft:" + (root.dataset.user || ""); | |
| 70 | try { if (!box.value) box.value = localStorage.getItem(draftKey) || ""; } catch (_) {} | |
| 71 | const grow = () => { box.style.height = "auto"; box.style.height = Math.min(box.scrollHeight, window.innerHeight * 0.4) + "px"; }; | |
| 72 | box.addEventListener("input", () => { grow(); try { localStorage.setItem(draftKey, box.value); } catch (_) {} }); | |
| 73 | grow(); | |
| 74 | const copyButton = (label) => { | |
| 75 | const b = Object.assign(document.createElement("button"), { type: "button", className: "talk-copy", textContent: "Copy" }); | |
| 76 | b.setAttribute("data-copy", ""); | |
| 77 | b.setAttribute("aria-label", label); | |
| 78 | return b; | |
| 79 | }; | |
| 80 | root.addEventListener("click", async (e) => { | |
| 81 | const s = e.target.closest("[data-suggest]"); | |
| 82 | if (s) { e.preventDefault(); box.value = s.dataset.suggest; grow(); box.focus(); return; } | |
| 83 | const c = e.target.closest("[data-copy]"); | |
| 84 | if (!c) return; | |
| 85 | const pre = c.closest("pre"); | |
| 86 | const src = pre ? pre.querySelector("code") : c.closest(".talk-turn").querySelector(".talk-body"); | |
| 87 | try { await navigator.clipboard.writeText(src.textContent); c.textContent = "Copied"; say("Copied."); } catch (_) { say("Copy is not allowed here."); } | |
| 88 | setTimeout(() => { c.textContent = "Copy"; }, 1500); | |
| 89 | }); | |
| 90 | // Copy buttons are drawn here, not by the server: without the script they would do nothing. | |
| 91 | const decorate = (scope) => { | |
| 92 | scope.querySelectorAll(".talk-body pre:not([data-c])").forEach((pre) => { | |
| 93 | pre.dataset.c = "1"; | |
| 94 | pre.insertBefore(copyButton("Copy this code"), pre.firstChild); | |
| 95 | }); | |
| 96 | scope.querySelectorAll(".talk-turn:not([data-m]) > .talk-meta").forEach((m) => { | |
| 97 | m.parentNode.dataset.m = "1"; | |
| 98 | m.appendChild(copyButton("Copy this message")); | |
| 99 | }); | |
| 100 | }; | |
| 101 | decorate(log); | |
| 42 | 102 | const follow = () => { |
| 43 | 103 | if (paged) return; |
| 44 | 104 | if (source) source.close(); |
| @@ -46,7 +106,7 @@ if (root) { | ||
| 46 | 106 | source.addEventListener("turn", (e) => { |
| 47 | 107 | const turn = JSON.parse(e.data); |
| 48 | 108 | last = turn.id; |
| 49 | if (!document.getElementById("t-" + turn.id)) log.insertAdjacentHTML("beforeend", turn.html); | |
| 109 | if (!document.getElementById("t-" + turn.id)) { log.insertAdjacentHTML("beforeend", turn.html); decorate(log); } | |
| 50 | 110 | retry = 0; |
| 51 | 111 | toEnd(); |
| 52 | 112 | }); |
| @@ -78,6 +138,9 @@ if (root) { | ||
| 78 | 138 | return; |
| 79 | 139 | } |
| 80 | 140 | box.value = ""; |
| 141 | grow(); | |
| 142 | try { localStorage.removeItem(draftKey); } catch (_) {} | |
| 143 | stuck = true; | |
| 81 | 144 | if (paged) { location.href = "/talk"; return; } |
| 82 | 145 | follow(); |
| 83 | 146 | } catch (_) { |
| @@ -86,7 +149,7 @@ if (root) { | ||
| 86 | 149 | }; |
| 87 | 150 | form.addEventListener("submit", send); |
| 88 | 151 | box.addEventListener("keydown", (e) => { |
| 89 | if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) form.requestSubmit(); | |
| 152 | if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); form.requestSubmit(); } | |
| 90 | 153 | }); |
| 91 | 154 | log.addEventListener("submit", async (e) => { |
| 92 | 155 | const f = e.target.closest("form[data-confirm]"); |
| @@ -105,7 +168,7 @@ if (root) { | ||
| 105 | 168 | say("That was not sent: no connection."); |
| 106 | 169 | } |
| 107 | 170 | }); |
| 108 | toEnd(); | |
| 171 | toEnd(true); | |
| 109 | 172 | if (root.dataset.running === "1" && !paged) follow(); |
| 110 | 173 | } |
| 111 | 174 | `; |
test/talk-page.test.ts +118
| @@ -116,6 +116,124 @@ describe("the page", () => { | ||
| 116 | 116 | expect((await post("/talk", bob, { text: " " })).status).toBe(303); |
| 117 | 117 | }); |
| 118 | 118 | |
| 119 | test("a message shows who and when, with a copy button; a tool call is a closed card; an empty chat offers starters", async () => { | |
| 120 | const carol = await createUser(app.db, { origin: "seed", trusted: true, username: "dana", email: "[email protected]", password: "a-good-passphrase" }); | |
| 121 | if (!carol.ok) throw new Error(carol.error); | |
| 122 | promote(app.db, carol.value); | |
| 123 | const empty = await (await get("/talk", carol.value)).text(); | |
| 124 | expect(empty).toContain('href="/talk?q=What%20needs%20my%20attention%3F"'); | |
| 125 | expect(empty).not.toMatch(/<button[^>]*(data-suggest|data-copy|data-jump)/); | |
| 126 | say(carol.value, "person", "hi"); | |
| 127 | say(carol.value, "agent", "hello"); | |
| 128 | say(carol.value, "tool", "list_issues {\"repo\":\"x\"}"); | |
| 129 | const page = await (await get("/talk", carol.value)).text(); | |
| 130 | expect(page).not.toContain("data-suggest="); | |
| 131 | expect(page).toContain("You · <time"); | |
| 132 | expect(page).toContain("Forge · <time"); | |
| 133 | expect(page).not.toContain("data-copy"); | |
| 134 | expect(page).toContain('role="log"'); | |
| 135 | expect(page).toMatch(/<details><summary>list_issues /); | |
outdated
These are substring checks on the script source and would pass with broken behaviour. Drive the script against a DOM and assert on the outcomes. |
||
| 136 | expect(page).not.toMatch(/<details open/); | |
| 137 | }); | |
| 138 | ||
| 139 | test("a suggestion link prefills the composer without the script, and only with a known suggestion", async () => { | |
| 140 | const q = "What needs my attention?"; | |
| 141 | const page = await (await get(`/talk?q=${encodeURIComponent(q)}`, alice)).text(); | |
| 142 | expect(page).toMatch(/<textarea[^>]*>What needs my attention\?<\/textarea>/); | |
| 143 | const other = await (await get(`/talk?q=${encodeURIComponent("<script>x</script>")}`, alice)).text(); | |
| 144 | expect(other).not.toContain("<script>x</script>"); | |
| 145 | expect(other).not.toMatch(/<textarea[^>]*>[^<]/); | |
| 146 | }); | |
| 147 | ||
| 148 | describe("the script, driven against a DOM", () => { | |
| 149 | const boot = async (user = "u1", store: Record<string, string> = {}) => { | |
| 150 | const sources: Array<{ on: Record<string, (e: { data: string }) => void> }> = []; | |
| 151 | const { Window } = await import("happy-dom"); | |
| 152 | const { talkJs } = await import("../src/web/pages/talk_client.ts"); | |
| 153 | const window = new Window({ url: "http://localhost/talk" }); | |
| 154 | const doc = window.document as any; | |
| 155 | doc.body.innerHTML = `<div class="talk" data-talk data-user="${user}" data-paged="0" data-running="1"><div> | |
| 156 | <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> | |
| 157 | <form class="talk-compose"><p class="talk-status" role="status"></p><textarea name="text"></textarea><span data-hint></span></form></div>`; | |
| 158 | const sent: string[] = []; | |
| 159 | const copied: string[] = []; | |
| 160 | const fetchStub = async (_u: string, init: { body: string }) => { sent.push(JSON.parse(init.body).text); return { ok: true, json: async () => ({}) }; }; | |
| 161 | const local = { getItem: (k: string) => store[k] ?? null, setItem: (k: string, v: string) => { store[k] = v; }, removeItem: (k: string) => { delete store[k]; } }; | |
| 162 | const nav = { clipboard: { writeText: async (t: string) => { copied.push(t); } } }; | |
| 163 | class ES { on: Record<string, (e: { data: string }) => void> = {}; constructor() { sources.push(this); } addEventListener(n: string, f: (e: { data: string }) => void) { this.on[n] = f; } close() {} } | |
| 164 | doc.getElementById("end").scrollIntoView = () => {}; | |
| 165 | new Function("document", "window", "EventSource", "fetch", "localStorage", "navigator", talkJs)(doc, window, ES, fetchStub, local, nav); | |
| 166 | const box = doc.querySelector("textarea"); | |
| 167 | const key = (init: object) => box.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...init })); | |
| 168 | const emit = (id: string, html: string) => sources.at(-1)!.on["turn"]!({ data: JSON.stringify({ id, html }) }); | |
| 169 | return { emit, window, doc, box, sent, copied, store, key, status: doc.querySelector(".talk-status") }; | |
| 170 | }; | |
| 171 | const tick = () => new Promise((r) => setTimeout(r, 5)); | |
| 172 | ||
| 173 | test("Enter submits; Shift+Enter and an IME composition do not", async () => { | |
| 174 | const t = await boot(); | |
| 175 | t.box.value = "hello"; | |
| 176 | expect(t.key({ shiftKey: true })).toBe(true); | |
| 177 | expect(t.key({ isComposing: true })).toBe(true); | |
| 178 | await tick(); | |
| 179 | expect(t.sent).toEqual([]); | |
| 180 | expect(t.key({})).toBe(false); | |
| 181 | await tick(); | |
| 182 | expect(t.sent).toEqual(["hello"]); | |
| 183 | expect(t.doc.querySelector("[data-hint]").textContent).toContain("Enter sends"); | |
| 184 | await t.window.happyDOM.close(); | |
| 185 | }); | |
| 186 | ||
| 187 | test("the draft is stored per person on input, restored on load, and cleared on send", async () => { | |
| 188 | const t = await boot("u1"); | |
| 189 | t.box.value = "half"; | |
| 190 | t.box.dispatchEvent(new t.window.Event("input", { bubbles: true })); | |
| 191 | expect(t.store["talk-draft:u1"]).toBe("half"); | |
| 192 | const again = await boot("u1", t.store); | |
| 193 | expect(again.box.value).toBe("half"); | |
| 194 | const other = await boot("u2", t.store); | |
| 195 | expect(other.box.value).toBe(""); | |
| 196 | again.key({}); | |
| 197 | await tick(); | |
| 198 | expect(again.store["talk-draft:u1"]).toBeUndefined(); | |
| 199 | }); | |
| 200 | ||
| 201 | test("copy buttons are drawn by the script, code first in tab order, and copy the text", async () => { | |
| 202 | const t = await boot(); | |
| 203 | const pre = t.doc.querySelector("pre"); | |
| 204 | expect(pre.firstElementChild.getAttribute("data-copy")).toBe(""); | |
| 205 | expect(t.doc.querySelector(".talk-meta [data-copy]")).not.toBeNull(); | |
| 206 | pre.firstElementChild.dispatchEvent(new t.window.MouseEvent("click", { bubbles: true })); | |
| 207 | await tick(); | |
| 208 | expect(t.copied).toEqual(["let a = 1;"]); | |
| 209 | }); | |
| 210 | ||
| 211 | test("a code block in a streamed turn gets its Copy button too", async () => { | |
| 212 | const t = await boot(); | |
| 213 | t.emit("2", '<li class="talk-turn" id="t-2"><div class="talk-body"><pre><code>x</code></pre></div><p class="talk-meta">Forge</p></li>'); | |
| 214 | expect(t.doc.querySelectorAll("#t-2 pre [data-copy]").length).toBe(1); | |
| 215 | expect(t.doc.querySelectorAll("#t-2 .talk-meta [data-copy]").length).toBe(1); | |
| 216 | }); | |
| 217 | ||
| 218 | test("the jump button shows only when scrolled up, and a new message is announced", async () => { | |
| 219 | const t = await boot(); | |
| 220 | const jump = t.doc.querySelector(".talk-jump"); | |
| 221 | t.emit("2", '<li class="talk-turn" id="t-2">a</li>'); | |
| 222 | expect(jump.hidden).toBe(true); | |
| 223 | expect(t.status.textContent).not.toContain("New message"); | |
| 224 | Object.defineProperty(t.window, "innerHeight", { value: 800, configurable: true }); | |
| 225 | Object.defineProperty(t.window, "scrollY", { value: 0, configurable: true }); | |
| 226 | Object.defineProperty(t.doc.documentElement, "scrollHeight", { value: 5000, configurable: true }); | |
| 227 | t.window.dispatchEvent(new t.window.Event("scroll")); | |
| 228 | t.emit("3", '<li class="talk-turn" id="t-3">b</li>'); | |
| 229 | expect(jump.hidden).toBe(false); | |
| 230 | expect(t.status.textContent).toBe("New message"); | |
| 231 | Object.defineProperty(t.window, "scrollY", { value: 4400, configurable: true }); | |
| 232 | t.window.dispatchEvent(new t.window.Event("scroll")); | |
| 233 | expect(jump.hidden).toBe(true); | |
| 234 | }); | |
| 235 | }); | |
| 236 | ||
| 119 | 237 | test("Talk is one tap away: the chrome, the palette and home", async () => { |
| 120 | 238 | const home = await (await get("/explore", alice)).text(); |
| 121 | 239 | expect(home).toContain('href="/talk"'); |
The Copy button is rendered for every message but only works with JS. Inject it from the client, as is done for code blocks.