Public: anyone can read this; the crew can change it.

The Talk page keeps an unsent draft in the browser and restores it after a reload #13492

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13464-the-talk-page-keeps-an-unsent-draft-in-t → main 4 commits fork 2 threads · 2 unresolved

  • Merged. scout/13464-the-talk-page-keeps-an-unsent-draft-in-t was merged into main as 8cfeb4f.

Review

Sign in to review this change.
3 files changed +77 −12
docs/features/talk.md +1 −1
@@ -77,7 +77,7 @@ Prior art read: Vercel AI Elements (Apache-2.0 React on shadcn; anatomy and beha
7777 | Server-drawn history, streaming over SSE, resume from turn id | have | the base of this page |
7878 | Confirm / Cancel in place for held writes | have | trust rule |
7979 | Enter sends, Shift+Enter breaks a line, autosizing box | this pull | what every chat does |
80 | Draft kept on reload (localStorage, this device) | this pull | cheap, local |
80 | Draft kept on reload (localStorage, this device): per person and conversation, saved after a 300 ms pause and when the page is hidden or closed | this pull | cheap, local |
8181 | Who and when under each message; copy a message; copy a code block | this pull | AI Elements `Message`, `CodeBlock` |
8282 | Tool calls as closed cards | this pull | AI Elements `Tool` |
8383 | Starter questions on an empty chat (links to `/talk?q=`, so they work without the script) | this pull | AI Elements `Suggestion` |
src/web/pages/talk_client.ts +13 −3
@@ -127,10 +127,19 @@ if (root) {
127127 };
128128 window.addEventListener("scroll", () => { stuck = nearEnd(); if (stuck) jump.hidden = true; }, { passive: true });
129129 jump.addEventListener("click", () => { stuck = true; toEnd(true); box.focus(); });
130 const draftKey = "talk-draft:" + (root.dataset.user || "");
130 const draftKey = "talk-draft:" + (root.dataset.user || "") + ":" + (cid || "");
131 let draftTimer = 0;
132 const saveDraft = () => { clearTimeout(draftTimer); try { if (box.value) localStorage.setItem(draftKey, box.value); else localStorage.removeItem(draftKey); } catch (_) {} };
131133 try { if (!box.value) box.value = localStorage.getItem(draftKey) || ""; } catch (_) {}
outdated

Typing then reloading or closing the tab within 300 ms drops the draft. Flush on pagehide and visibilitychange: addEventListener('pagehide', save), using the same save function the timer calls. Add a test that dispatches pagehide right after input and finds the draft stored.

132134 const grow = () => { box.style.height = "auto"; box.style.height = Math.min(box.scrollHeight, window.innerHeight * 0.4) + "px"; };
133 box.addEventListener("input", () => { grow(); try { localStorage.setItem(draftKey, box.value); } catch (_) {} });
135 box.addEventListener("input", () => {
136 grow();
137 clearTimeout(draftTimer);
138 draftTimer = setTimeout(saveDraft, 300);
139 });
140 // A reload or a closed tab inside the pause still keeps what was typed.
141 window.addEventListener("pagehide", saveDraft);
142 document.addEventListener("visibilitychange", () => { if (document.visibilityState === "hidden") saveDraft(); });
134143 grow();
135144 const copyButton = (label) => {
136145 const b = Object.assign(document.createElement("button"), { type: "button", className: "talk-copy", textContent: "Copy" });
@@ -316,7 +325,7 @@ if (root) {
316325 const text = box.value.trim();
317326 if (!text) { if (attached.length) say("Add a few words about what you attached."); return; }
318327 if (editing) {
319 if (await again("edit", new URLSearchParams({ text }))) { try { localStorage.removeItem(draftKey); } catch (_) {} }
328 if (await again("edit", new URLSearchParams({ text }))) { clearTimeout(draftTimer); try { localStorage.removeItem(draftKey); } catch (_) {} }
320329 return;
321330 }
322331 const steer = e.submitter === steerBtn;
@@ -336,6 +345,7 @@ if (root) {
336345 attached.length = 0;
337346 chips.replaceChildren();
338347 grow();
348 clearTimeout(draftTimer);
339349 try { localStorage.removeItem(draftKey); } catch (_) {}
340350 stuck = true;
341351 const out = await res.json().catch(() => ({}));
test/talk-page.test.ts +63 −8
@@ -303,7 +303,7 @@ describe("the page", () => {
303303 test("the page's own bytes are held: stylesheet and script stay small", async () => {
304304 const { talkCss, talkJs } = await import("../src/web/pages/talk_client.ts");
305305 expect(Buffer.byteLength(talkCss)).toBeLessThan(4_300);
306 expect(Buffer.byteLength(talkJs)).toBeLessThan(15_200);
306 expect(Buffer.byteLength(talkJs)).toBeLessThan(15_900);
307307 say(alice, "agent", "```ts\nlet x = 1;\n```");
308308 const page = await get("/talk", alice);
309309 const size = (await page.arrayBuffer()).byteLength;
@@ -370,13 +370,13 @@ describe("the page", () => {
370370 expect(t.bodies.at(-1)).toMatchObject({ text: "do this instead", during: "steer" });
371371 });
372372
373 const boot = async (user = "u1", store: Record<string, string> = {}) => {
373 const boot = async (user = "u1", store: Record<string, string> = {}, conv = "c1") => {
374374 const sources: Array<{ on: Record<string, (e: { data: string }) => void> }> = [];
375375 const { Window } = await import("happy-dom");
376376 const { talkJs } = await import("../src/web/pages/talk_client.ts");
377377 const window = new Window({ url: "http://localhost/talk" });
378378 const doc = window.document as any;
379 doc.body.innerHTML = `<div class="talk" data-talk data-user="${user}" data-paged="0" data-running="1"><div>
379 doc.body.innerHTML = `<div class="talk" data-talk data-user="${user}" data-c="${conv}" data-paged="0" data-running="1"><div>
380380 <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>
381381 <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>`;
382382 const how = { value: "started" };
@@ -506,18 +506,73 @@ describe("the page", () => {
506506 await t.window.happyDOM.close();
507507 });
508508
509 test("the draft is stored per person on input, restored on load, and cleared on send", async () => {
509 test("the draft is stored per person and conversation after a 300 ms pause, restored on load, cleared on send", async () => {
510510 const t = await boot("u1");
511511 t.box.value = "half";
512512 t.box.dispatchEvent(new t.window.Event("input", { bubbles: true }));
513 expect(t.store["talk-draft:u1"]).toBe("half");
513 expect(t.store["talk-draft:u1:c1"]).toBeUndefined();
514 await new Promise((r) => setTimeout(r, 380)); // real-timer: the script debounces with the page's own setTimeout, 300 ms
515 expect(t.store["talk-draft:u1:c1"]).toBe("half");
514516 const again = await boot("u1", t.store);
515517 expect(again.box.value).toBe("half");
516 const other = await boot("u2", t.store);
517 expect(other.box.value).toBe("");
518 expect((await boot("u2", t.store)).box.value).toBe("");
519 expect((await boot("u1", t.store, "c2")).box.value).toBe("");
518520 again.key({});
519521 await tick();
520 expect(again.store["talk-draft:u1"]).toBeUndefined();
522 expect(again.store["talk-draft:u1:c1"]).toBeUndefined();
523 });
524
525 test("a send before the pause ends leaves no draft behind", async () => {
526 const t = await boot("u1");
527 t.box.value = "quick";
528 t.box.dispatchEvent(new t.window.Event("input", { bubbles: true }));
529 t.key({});
530 await new Promise((r) => setTimeout(r, 380)); // real-timer: the script debounces with the page's own setTimeout, 300 ms
531 expect(Object.keys(t.store)).toEqual([]);
532 });
533
534 test("leaving the page inside the pause still stores the draft, and an emptied box stores nothing", async () => {
535 const t = await boot("u1");
536 t.box.value = "just typed";
537 t.box.dispatchEvent(new t.window.Event("input", { bubbles: true }));
538 t.window.dispatchEvent(new t.window.Event("pagehide"));
539 expect(t.store["talk-draft:u1:c1"]).toBe("just typed");
outdated

This imports talkJs rather than fetching the served script, and nothing exercises escaping with a hostile id. A substring check on '}, 300)' is brittle and would pass on dead code. Assert on served output with a quote-bearing id, and cover the pagehide flush.

540 t.box.value = "";
541 t.window.dispatchEvent(new t.window.Event("pagehide"));
542 expect(t.store["talk-draft:u1:c1"]).toBeUndefined();
543 t.box.value = "again";
544 t.box.dispatchEvent(new t.window.Event("input", { bubbles: true }));
545 Object.defineProperty(t.doc, "visibilityState", { value: "hidden", configurable: true });
546 t.doc.dispatchEvent(new t.window.Event("visibilitychange"));
547 expect(t.store["talk-draft:u1:c1"]).toBe("again");
548 });
549
550 test("the served page escapes a hostile conversation id in data-c, and the served script keys the draft", async () => {
551 const hostile = `x"><b id=pwn>&'`;
552 const made = createConversation(app.db, alice.id);
553 if (!made.ok) throw new Error(made.error);
554 const c = made.value;
555 app.db.run("PRAGMA foreign_keys = OFF");
556 app.db.query("UPDATE conversation SET id = ?1 WHERE id = ?2").run(hostile, c.id);
557 app.db.query("UPDATE conversation SET updated_at = ?2 WHERE id = ?1").run(hostile, "9999-01-01T00:00:00.000Z");
558 try {
559 // /talk opens the newest conversation straight from the store, so the id never passes the
560 // route's own check.
561 const page = await (await get("/talk", alice)).text();
562 expect(page).toContain("data-c=");
563 expect(page).not.toContain("<b id=pwn>");
564 expect(page).not.toContain(`data-c="${hostile}"`);
565 expect(page).toMatch(/data-c="x&(quot|#34|#x22);&(gt|#62|#x3e);&lt;b id=pwn&gt;/i);
566 expect(page).toContain(`data-user="${alice.id}"`);
567 const src = page.match(/<script[^>]*\ssrc="([^"]+)"/g)?.map((m) => m.match(/src="([^"]+)"/)![1]!) ?? [];
568 const bodies = await Promise.all(src.map(async (u) => await (await get(u, alice)).text()));
569 const mine = bodies.find((b) => b.includes("talk-draft:"));
570 expect(mine).toBeDefined();
571 expect(mine).toContain("pagehide");
572 } finally {
573 app.db.query("UPDATE conversation SET id = ?2 WHERE id = ?1").run(hostile, c.id);
574 app.db.run("PRAGMA foreign_keys = ON");
575 }
521576 });
522577
523578 test("copy buttons are drawn by the script, code first in tab order, and copy the text", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs