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

A half-written tell survives a reload and a lost connection #13199

Merged opened this

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

Merged

scout/forge:scout/13129-a-half-written-tell-survives-a-reload-an → main 7 commits fork 5 threads · 5 unresolved

  • Merged. scout/13129-a-half-written-tell-survives-a-reload-an was merged into main as 8aa04ed.

Review

Sign in to review this change.
6 files changed +200 −3
docs/features/README.md +1
@@ -256,6 +256,7 @@ Read with the guide page [Your apps](../guide-your-apps.md).
256256 - [GeoJSON (.geojson) as an outline and a properties table](geojson.md)
257257 - [GPS tracks (.gpx) as a route outline](gpx.md)
258258 - [HTML preview](html-preview.md)
259 - [A half-written tell is kept](kept-tell.md)
259260 - [Jupyter notebooks](notebook.md)
260261 - [Markdown relative images and links](markdown-relative.md)
261262 - [Notebooks, JSON Lines and logs in the terminal](terminal-workspace-kinds.md)
docs/features/kept-tell.md added +22
@@ -0,0 +1,22 @@
1 # A half-written tell is kept
2
3 This page is for anyone who writes a tell. The words you type in "Tell the crew" on a repo's toolbar page, or on the page you reach by sharing to the forge from your phone, are kept in your browser tab. Reload, lose the connection or get a refusal, and the words are back.
4
5 ## How to use it
6
7 1. Open a repo's toolbar page and type in "Tell the crew". Do not send.
8 2. Reload. The words are back, with a muted line above the box: "Draft restored".
9 3. Send. If the next page shows the success note, the draft is dropped. If the connection was lost or the tell was refused, the draft is still there on the next load.
10
11 ## What it does and does not do
12
13 - The draft is kept per page, in the tab's own session storage. It never leaves your browser and goes when the tab closes.
14 - Sending alone does not drop it; only a page that shows success does.
15 - A box that already has words (a shared text) is not overwritten.
16 - A draft that looks like a token or key (`sk-…`, `ghp_…`, or a long mixed run of letters and digits) is not stored. If you had a saved draft, it stays as it was. URLs and file paths are kept.
17 - Without JavaScript the box works as it always did, and nothing is kept.
18 - The feed composer has its own draft; this does not touch it.
19
20 ## The terminal
21
22 The terminal is unchanged: this is a browser behaviour of the two pages above, and the terminal keeps no draft of its own. Its input is a command line, so the shell's history is what remembers what you typed there.
src/web/keep.ts added +29
@@ -0,0 +1,29 @@
1 /**
2 * The kept tell: a half-written tell in a `<textarea data-keep>` survives a
3 * reload and a lost connection, per page, in sessionStorage (so it goes with
4 * the tab). Sending does not clear it: submit only marks it sent, and the
5 * next page load drops it when that page shows a success toast; a refusal or
6 * a dead connection puts the words back, with a muted "Draft restored" line.
7 * A draft that looks like a token is not stored (the earlier saved draft is
outdated

The generic 32+ char rule catches URLs and paths. Narrow it.

8 * left as it was). Without the script the box works as before. Static text;
9 * nothing is interpolated.
10 */
11 export const SECRET_LOOK = String.raw`(^|[^A-Za-z0-9])((sk|pk|ghp|gho|ghs|glpat|xox[a-z]|forge|fgt)[-_](?=[A-Za-z0-9_-]*[0-9])[A-Za-z0-9_-]{8,}|(?=[A-Za-z0-9_+=-]*[a-z])(?=[A-Za-z0-9_+=-]*[A-Z])(?=[A-Za-z0-9_+=-]*[0-9])[A-Za-z0-9_+=-]{32,})($|[^A-Za-z0-9])`;
12
13 export const keepJs = /* js */ `
14 (function (store) {

The script runs 16 lines (14 to 29), over the 15-line cap in issue box 2. Merge the sent-marker read/remove with the toast check, or put the cue creation on one line shared with the restore. Then tighten the test cap from 25 to 15.

15 var secret = new RegExp(${JSON.stringify(SECRET_LOOK)});
16 document.querySelectorAll('textarea[data-keep]').forEach(function (box) {
outdated

On a token-looking draft this removes the earlier saved draft; leave it instead.

17 var key = 'keep.' + location.pathname + '.' + box.name, sent = key + '.sent', put = false;
18 try {
outdated

Clears on submit, before the server answers: a lost connection or refused tell loses the draft. Clear only after a confirmed send.

19 if (store.getItem(sent) && document.querySelector('.toast[data-tone="success"]')) store.removeItem(key);
20 store.removeItem(sent); if (!box.value && store.getItem(key)) { box.value = store.getItem(key); put = true; }
21 } catch (e) {}
22 if (put) { var note = document.createElement('p'); note.className = 'muted small'; note.setAttribute('role', 'status'); note.textContent = 'Draft restored'; box.parentNode.insertBefore(note, box); }
23 box.addEventListener('input', function () {
24 try { if (!box.value) store.removeItem(key); else if (!secret.test(box.value)) store.setItem(key, box.value); } catch (e) {}
25 });
26 if (box.form) box.form.addEventListener('submit', function () { try { store.setItem(sent, '1'); } catch (e) {} });
27 });
28 })(window.sessionStorage);
29 `;
src/web/studio/share_tell.ts +3 −1
@@ -5,6 +5,7 @@
55 * chosen, and Send posts `POST /tell` (same-origin checked there). A share
66 * that cannot be a tell is answered with a sentence and a way back.
77 */
8 import { keepJs } from "../keep.ts";
89 import { appsFirst } from "../../actions/first_ask.ts";
910 import type { Ctx } from "../../http/context.ts";
1011 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
@@ -57,12 +58,13 @@ export function shareTellPage(ctx: Ctx): Response {
5758 return done(page({
5859 ctx,
5960 title: "Tell the crew",
61 scriptJs: keepJs,
6062 body: html`<h1>Tell the crew</h1>
6163 <p class="muted small">Shared from your phone. Nothing is sent until you tap Send.</p>
6264 <form class="stack" method="post" action="/tell">
6365 <input type="hidden" name="${COMPOSER_FIELDS.back}" value="/feed" />
6466 <input type="hidden" name="${COMPOSER_FIELDS.once}" value="${shareToken(user.id, draft)}" />
65 <textarea class="input" name="${COMPOSER_FIELDS.text}" rows="6" maxlength="${String(TELL_MAX)}" required aria-label="Tell the crew">${draft}</textarea>
67 <textarea class="input" name="${COMPOSER_FIELDS.text}" rows="6" maxlength="${String(TELL_MAX)}" required aria-label="Tell the crew" data-keep>${draft}</textarea>
6668 <div class="bar">${target}<span class="spacer"></span>${btn("Send", { variant: "primary" })}</div>
6769 </form>`,
6870 }));
src/web/studio/toolbar.ts +3 −2
@@ -15,6 +15,7 @@
1515 * links to #606's page. Signed out, the page is where you are and home.
1616 */
1717
18 import { keepJs } from "../keep.ts";
1819 import { HELP_BUILD } from "../../core/contribute.ts";
1920 import { lacks } from "../../core/roles.ts";
2021 import { addCommentThrough, openIssueThrough } from "../../actions/issues.ts";
@@ -258,7 +259,7 @@ export async function toolbarPage(ctx: Ctx): Promise<Response> {
258259 : html`<input type="hidden" name="page" value="${address}" />
259260 ${when(pull !== undefined, () => html`<input type="hidden" name="pull" value="${pull!.number}" />`)}`}
260261 <label>Tell the crew
261 <textarea name="text" rows="3" maxlength="${MAX_BODY}" required></textarea>
262 <textarea name="text" rows="3" maxlength="${MAX_BODY}" required data-keep></textarea>
262263 </label>
263264 <div class="form-actions">${btn("Tell", { variant: "primary" })}</div>
264265 </form>`,
@@ -272,7 +273,7 @@ export async function toolbarPage(ctx: Ctx): Promise<Response> {
272273 ${other}${home}
273274 </div>
274275 </div>`;
275 const response = page({ ctx, title: `${repo.name} · forge`, body });
276 const response = page({ ctx, title: `${repo.name} · forge`, body, scriptJs: keepJs });
276277 notePhase(request, "render", performance.now() - renderStart);
277278 return response;
278279 }
test/tell-keep.test.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * A half-written tell survives a reload and a lost connection (#13129): kept per page in
3 * sessionStorage, dropped only when the next page shows a success, never a token.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { newApp } from "../src/actions/apps.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { keepJs } from "../src/web/keep.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17
18 type Node = { tag: string; className: string; textContent: string; attrs: Record<string, string>; setAttribute(k: string, v: string): void };
19
20 function run(path: string, stored: Record<string, string>, opts: { initial?: string; toast?: boolean } = {}) {
21 const store = new Map(Object.entries(stored));
22 const storage = { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => void store.set(k, v), removeItem: (k: string) => void store.delete(k) };
23 const on: Record<string, () => void> = {};
24 const inserted: Node[] = [];
25 const form = { addEventListener: (e: string, f: () => void) => (on["form" + e] = f) };
26 const box = {
27 name: "text", value: opts.initial ?? "", form,
28 parentNode: { insertBefore: (n: Node) => void inserted.push(n) },
29 addEventListener: (e: string, f: () => void) => (on[e] = f),
30 };
31 const doc = {
32 querySelectorAll: () => [box],
33 querySelector: (s: string) => (opts.toast && s.includes("success") ? {} : null),
34 createElement: (tag: string): Node => ({ tag, className: "", textContent: "", attrs: {}, setAttribute(k, v) { this.attrs[k] = v; } }),
35 };
36 new Function("document", "location", "window", keepJs)(doc, { pathname: path }, { sessionStorage: storage });
37 return { store, box, on, inserted };
38 }
39
40 test("typing is kept per page and put back on reload, with a cue", () => {
41 const a = run("/x/toolbar", {});
42 a.box.value = "make the header blue";
43 a.on.input!();
44 expect([...a.store.values()]).toEqual(["make the header blue"]);
45 const b = run("/x/toolbar", Object.fromEntries(a.store));
46 expect(b.box.value).toBe("make the header blue");
47 expect(b.inserted.map((n) => n.textContent)).toEqual(["Draft restored"]);
48 expect(b.inserted[0]!.attrs.role).toBe("status");
49 const c = run("/other", Object.fromEntries(a.store));
50 expect(c.box.value).toBe("");
outdated

Greps source strings; render the pages and assert behaviour instead.

51 expect(c.inserted).toEqual([]);
52 });
53
54 test("a box already filled is not overwritten", () => {
55 const a = run("/p", { "keep./p.text": "old" }, { initial: "shared words" });
56 expect(a.box.value).toBe("shared words");
57 expect(a.inserted).toEqual([]);
58 });
59
60 test("submit alone does not lose the words: a lost connection or a refusal restores them", () => {
61 const a = run("/p", { "keep./p.text": "half" });
62 a.on.formsubmit!();
63 expect(a.store.get("keep./p.text")).toBe("half");
64 // The next load has no success toast (connection lost) or a danger one: the words come back.
65 const lost = run("/p", Object.fromEntries(a.store));
66 expect(lost.box.value).toBe("half");
67 expect(lost.store.has("keep./p.text.sent")).toBe(false);
68 });
69
70 test("a send that the next page confirms drops the draft", () => {
71 const a = run("/p", { "keep./p.text": "half" });
72 a.on.formsubmit!();
73 const next = run("/p", Object.fromEntries(a.store), { toast: true });
74 expect(next.box.value).toBe("");
75 expect(next.store.size).toBe(0);
76 expect(next.inserted).toEqual([]);
77 });
78
79 test("a draft that looks like a token is never stored, and the earlier draft stays", () => {
80 for (const secret of ["sk-ant-oat01-abcdefghijklmnop", "use ghp_abcdefghijklmnopqrstuvwxyz0123 please", "Abcdefgh1jklmnopQRSTUVWXYZ0123456789abcd"]) {
81 const a = run("/p", { "keep./p.text": "earlier" }, { initial: "x" });
82 a.box.value = secret;
83 a.on.input!();
84 expect(a.store.get("keep./p.text")).toBe("earlier");
85 }
86 });
87
88 test("a URL or a file path is kept", () => {
89 for (const words of ["see //example.com/some/long/path/that/goes/on", "https://example.com/docs/a-very-long-page-name-here", "edit src/web/studio/some_long_module_name_here.ts now", "forge-the-header-should-be-bluer"]) {
90 const a = run("/p", { "keep./p.text": "earlier" }, { initial: "x" });
91 a.box.value = words;
92 a.on.input!();
93 expect(a.store.get("keep./p.text")).toBe(words);
94 }
95 });
96
97 test("the script stays small", () => {
98 expect(keepJs.trim().split("\n").length).toBeLessThanOrEqual(15);
99 });
100
101 let dataDir: string;
102 let app: App;
103 let servers: Servers;
104 let cookie = "";
105
106 beforeAll(async () => {
107 dataDir = await mkdtemp(join(tmpdir(), "forge-tell-keep-"));
108 app = createApp({ dataDir, port: 0, host: "forge.test" });
109 servers = await serve(app);
110 const made = await createUser(app.db, {
111 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
112 password: "a-good-passphrase", adminIfFirst: true,
113 });
114 if (!made.ok) throw new Error(made.error);
115 const r = await newApp(app, made.value, { name: "open", description: "x", visibility: "public" });
116 if (!r.ok) throw new Error(String(r.error));
117 const res = await fetch(`${servers.url}/signin`, {
118 method: "POST",
119 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
120 redirect: "manual",
121 });
122 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
123 }, 120_000);
124
125 afterAll(async () => {
126 servers.stop();
127 app.close();
128 await rm(dataDir, { recursive: true, force: true });
129 });
130
131 test("the toolbar and share pages mark the tell box and load the script", async () => {
132 for (const path of ["/alice/open/toolbar?env=production", "/tell?text=hello"]) {
133 const res = await fetch(`${servers.url}${path}`, { headers: { cookie } });
134 expect(res.status).toBe(200);
135 const body = await res.text();
136 expect(/<textarea[^>]*\bdata-keep\b[^>]*name="(text|body)"|<textarea[^>]*name="text"[^>]*\bdata-keep\b/.test(body)).toBe(true);
137 const srcs = [...body.matchAll(/<script[^>]*src="([^"]+)"/g)].map((m) => m[1]!);
138 const texts = await Promise.all(srcs.map(async (u) => (await fetch(`${servers.url}${u}`)).text()));
139 expect(texts.some((t) => t.includes("textarea[data-keep]"))).toBe(true);
140 expect(res.headers.get("content-security-policy")).toContain("script-src");
141 }
142 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs