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

/talk keeps an unsent message per conversation, so leaving the page does not lose it #14510

Merged opened this

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

Merged

torque/forge:torque/14488-talk-keeps-an-unsent-message-per-convers → main 5 commits fork

  • Merged. torque/14488-talk-keeps-an-unsent-message-per-convers was merged into main as aa430e4.

Review

Sign in to review this change.
3 files changed +89 −10
src/web/pages/talk_client.ts +29 −4
@@ -115,6 +115,29 @@ export const dictateJs = `
115115 }
116116 `;
117117
118 /**
119 * The unsent draft (#14488): one localStorage entry per conversation, `{t, v}` (time, text). `load`
120 * drops every talk draft older than seven days, then returns this key's text; `save` of an empty
121 * string removes it. Defines `draftStore(store, key, now)`; storage errors are swallowed.
122 */
123 export const draftJs = `
124 const draftStore = (store, key, now = Date.now) => {
125 const run = (f) => { try { return f(); } catch (_) { return ""; } };
126 return {
127 load: () => run(() => {
128 for (let i = store.length; i--;) {
129 const k = store.key(i);
130 let d = 0;
131 try { d = JSON.parse(store.getItem(k)); } catch (_) {}
132 if (k.startsWith("talk-draft:") && !(d && now() - d.t < 6048e5)) store.removeItem(k);
133 }
134 return (JSON.parse(store.getItem(key)) || {}).v || "";
135 }),
136 save: (v) => run(() => v ? store.setItem(key, JSON.stringify({ t: now(), v })) : store.removeItem(key)),
137 };
138 };
139 `;
140
118141 /**
119142 * Runs after DOMContentLoaded (`pageScriptAsset`). Reads the page's own `data-talk-*`; sends with
120143 * fetch, follows with EventSource.
@@ -164,8 +187,10 @@ if (root) {
164187 jump.addEventListener("click", () => { stuck = true; toEnd(true); box.focus(); });
165188 const draftKey = "talk-draft:" + (root.dataset.user || "") + ":" + (cid || "");
166189 let draftTimer = 0;
167 const saveDraft = () => { clearTimeout(draftTimer); try { if (box.value) sessionStorage.setItem(draftKey, box.value); else sessionStorage.removeItem(draftKey); } catch (_) {} };
168 try { if (!box.value) box.value = sessionStorage.getItem(draftKey) || ""; } catch (_) {}
190 ${draftJs}
191 const draft = draftStore(localStorage, draftKey);
192 const saveDraft = () => { clearTimeout(draftTimer); draft.save(box.value); };
193 { const old = draft.load(); if (!box.value) box.value = old; }
169194 const grow = () => { box.style.height = "auto"; box.style.height = Math.min(box.scrollHeight, window.innerHeight * 0.4) + "px"; };
170195 box.addEventListener("input", () => {
171196 grow();
@@ -360,7 +385,7 @@ ${dictateJs}
360385 const text = box.value.trim();
361386 if (!text) { if (attached.length) say("Add a few words about what you attached."); return; }
362387 if (editing) {
363 if (await again("edit", new URLSearchParams({ text }))) { clearTimeout(draftTimer); try { sessionStorage.removeItem(draftKey); } catch (_) {} }
388 if (await again("edit", new URLSearchParams({ text }))) { clearTimeout(draftTimer); draft.save(""); }
364389 return;
365390 }
366391 const steer = e.submitter === steerBtn;
@@ -381,7 +406,7 @@ ${dictateJs}
381406 chips.replaceChildren();
382407 grow();
383408 clearTimeout(draftTimer);
384 try { sessionStorage.removeItem(draftKey); } catch (_) {}
409 draft.save("");
385410 stuck = true;
386411 const out = await res.json().catch(() => ({}));
387412 if (out.how === "queued") { say("Queued: it sends after this answer."); if (!source) follow(); return; }
test/talk-draft.test.ts added +54
@@ -0,0 +1,54 @@
1 /**
2 * The /talk unsent draft (#14488): saved per conversation, restored, cleared, expired after 7 days.
3 */
4 import { expect, test } from "bun:test";
5 import { draftJs } from "../src/web/pages/talk_client.ts";
6
7 class Fake {
8 m = new Map<string, string>();
9 get length() { return this.m.size; }
10 key(i: number) { return [...this.m.keys()][i] ?? null; }
11 getItem(k: string) { return this.m.get(k) ?? null; }
12 setItem(k: string, v: string) { this.m.set(k, v); }
13 removeItem(k: string) { this.m.delete(k); }
14 }
15 const make = (store: Fake, key: string, now: () => number) =>
16 new Function(`${draftJs}; return draftStore;`)()(store, key, now) as { load(): string; save(t: string): void };
17 const DAY = 864e5;
18
19 test("save then restore, per conversation", () => {
20 const s = new Fake();
21 make(s, "talk-draft:u:a", () => 1000).save("half a thought");
22 expect(make(s, "talk-draft:u:a", () => 2000).load()).toBe("half a thought");
23 expect(make(s, "talk-draft:u:b", () => 2000).load()).toBe("");
24 });
25
26 test("saving an empty box (sent or cleared) removes the draft", () => {
27 const s = new Fake();
28 const d = make(s, "talk-draft:u:a", () => 1000);
29 d.save("x");
30 d.save("");
31 expect(s.length).toBe(0);
32 expect(d.load()).toBe("");
33 });
34
35 test("drafts older than 7 days are dropped on load, others kept", () => {
36 const s = new Fake();
37 const t0 = 10 * DAY;
38 make(s, "talk-draft:u:old", () => t0).save("old");
39 make(s, "talk-draft:u:new", () => t0 + 5 * DAY).save("new");
40 s.setItem("other", "keep");
41 s.setItem("talk-draft:u:junk", "not json");
42 expect(make(s, "talk-draft:u:old", () => t0 + 8 * DAY).load()).toBe("");
43 expect(s.getItem("talk-draft:u:old")).toBeNull();
44 expect(s.getItem("talk-draft:u:junk")).toBeNull();
45 expect(s.getItem("other")).toBe("keep");
46 expect(make(s, "talk-draft:u:new", () => t0 + 8 * DAY).load()).toBe("new");
47 });
48
49 test("a throwing storage never breaks the page", () => {
50 const bad = { length: 0, key: () => null, getItem: () => { throw new Error("x"); }, setItem: () => { throw new Error("x"); }, removeItem: () => { throw new Error("x"); } };
51 const d = make(bad as unknown as Fake, "talk-draft:u:a", Date.now);
52 expect(d.load()).toBe("");
53 expect(() => d.save("x")).not.toThrow();
54 });
test/talk-page.test.ts +6 −6
@@ -294,7 +294,7 @@ describe("the page", () => {
294294 test("the page's own bytes are held: stylesheet and script stay small", async () => {
295295 const { talkCss, talkJs } = await import("../src/web/pages/talk_client.ts");
296296 expect(Buffer.byteLength(talkCss)).toBeLessThan(4_500);
297 expect(Buffer.byteLength(talkJs)).toBeLessThan(17_100);
297 expect(Buffer.byteLength(talkJs)).toBeLessThan(17_600);
298298 say(alice, "agent", "```ts\nlet x = 1;\n```");
299299 const page = await get("/talk", alice);
300300 const size = (await page.arrayBuffer()).byteLength;
@@ -388,11 +388,11 @@ describe("the page", () => {
388388 bodies.push(body);
389389 return { ok: true, json: async () => ({ how: how.value, queued: "q1" }) };
390390 };
391 const local = { getItem: (k: string) => store[k] ?? null, setItem: (k: string, v: string) => { store[k] = v; }, removeItem: (k: string) => { delete store[k]; } };
391 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]; } };
392392 const nav = { clipboard: { writeText: async (t: string) => { copied.push(t); } } };
393393 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() {} }
394394 doc.getElementById("end").scrollIntoView = () => {};
395 new Function("document", "window", "EventSource", "fetch", "sessionStorage", "navigator", talkJs)(doc, window, ES, fetchStub, local, nav);
395 new Function("document", "window", "EventSource", "fetch", "localStorage", "navigator", talkJs)(doc, window, ES, fetchStub, local, nav);
396396 const box = doc.querySelector("textarea");
397397 const key = (init: object) => box.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...init }));
398398 const emit = (id: string, html: string) => sources.at(-1)!.on["turn"]!({ data: JSON.stringify({ id, html }) });
@@ -515,7 +515,7 @@ describe("the page", () => {
515515 t.box.dispatchEvent(new t.window.Event("input", { bubbles: true }));
516516 expect(t.store["talk-draft:u1:c1"]).toBeUndefined();
517517 await new Promise((r) => setTimeout(r, 380)); // real-timer: the script debounces with the page's own setTimeout, 300 ms
518 expect(t.store["talk-draft:u1:c1"]).toBe("half");
518 expect(JSON.parse(t.store["talk-draft:u1:c1"]!).v).toBe("half");
519519 const again = await boot("u1", t.store);
520520 expect(again.box.value).toBe("half");
521521 expect((await boot("u2", t.store)).box.value).toBe("");
@@ -539,7 +539,7 @@ describe("the page", () => {
539539 t.box.value = "just typed";
540540 t.box.dispatchEvent(new t.window.Event("input", { bubbles: true }));
541541 t.window.dispatchEvent(new t.window.Event("pagehide"));
542 expect(t.store["talk-draft:u1:c1"]).toBe("just typed");
542 expect(JSON.parse(t.store["talk-draft:u1:c1"]!).v).toBe("just typed");
543543 t.box.value = "";
544544 t.window.dispatchEvent(new t.window.Event("pagehide"));
545545 expect(t.store["talk-draft:u1:c1"]).toBeUndefined();
@@ -547,7 +547,7 @@ describe("the page", () => {
547547 t.box.dispatchEvent(new t.window.Event("input", { bubbles: true }));
548548 Object.defineProperty(t.doc, "visibilityState", { value: "hidden", configurable: true });
549549 t.doc.dispatchEvent(new t.window.Event("visibilitychange"));
550 expect(t.store["talk-draft:u1:c1"]).toBe("again");
550 expect(JSON.parse(t.store["talk-draft:u1:c1"]!).v).toBe("again");
551551 });
552552
553553 test("the served page escapes a hostile conversation id in data-c, and the served script keys the draft", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs