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

Talk's Send: shown at once, never doubled, a queued message is plain and editable (#16579) #16582

opened this

Check · Review · Land · Live — Its check is red. Next: builder, its check is red.

Ready to land

fix/talk-send-once → main 1 commit

Review

Sign in to review this change.
6 files changed +384 −36
docs/design/size-budget.json +1 −1
@@ -68,7 +68,7 @@
6868 "css": 49920
6969 },
7070 "/talk": {
71 "js": 40960,
71 "js": 41984,
7272 "css": 56064
7373 },
7474 "/:owner/:name/pulls/:number": {
docs/features/talk.md +2 −1
@@ -93,7 +93,8 @@ It checks identity, same origin and token scope. Viewers of `/talk` see the `Sto
9393
9494 The composer stays open while the agent works. `say()` in `src/crew/conversation.ts` takes `during`: `inject` (the old behaviour, still the default for the API without `during`, MCP and plain `ssh talk`), `queue` (kept in memory for after the turn; up to 5; each runs as its own turn, in order) or `interrupt` (stops the turn, keeps its words and the `Stopped.` line, and sends the message first). Stop clears the queue; a forge restart drops it. A file attached to a queued message is held: it cannot be removed (409) or sent with another message (`file_taken`), and one gone by the time it runs is left out.
9595
96 - **Web:** while an answer runs Send reads Queue and Steer and Stop appear. A queued message shows dimmed, "Queued", with Cancel (a post form to `POST /talk/queue/:id/cancel`, so it works without the script); every open tab sees it over the stream (`queued` frame). Cancel puts the text back in the box.
96 - **Web:** while an answer runs Send reads Queue and Steer and Stop appear. A queued message shows dimmed, "Queued: sends when this answer ends.", with Edit (the script's: it comes out of the queue and back into the box) and Drop (a post form to `POST /talk/queue/:id/cancel`, so it works without the script); every open tab sees it over the stream (`queued` frame).
97 - **Sent once:** Send shows the message in the thread at once, marked "Sending…", and empties the box; until the server answers, Send is disabled and a second press, a double tap or Enter sends nothing. Each send carries an `Idempotency-Key` (the same words sent again after a failure keep their key), so two requests for one press keep one message; without the script the form carries a key made with the page (`key`), and a resubmit of it is one message too. A send that fails puts the words back in the box. Proof: `test/talk-send-once.test.ts`, which drives it in Chromium at 390 px with touch.
9798 - **API:** `POST /api/v1/conversation/messages` with `during: "queue" | "steer"` (anything else is 422 `invalid_during`; a sixth queued message is 429 `queue_full`); `DELETE /api/v1/conversation/queue/:id` (404 for an id that is not yours or already went); `GET /api/v1/conversation/turns` lists `queued`.
9899 - **Terminal:** `ssh <forge> talk /queue <words>`, `talk /steer <words>`, `talk /queued` (ids and words), `talk /unqueue <id>`; they work with `--attach` too.
99100
src/web/pages/talk.ts +13 −1
@@ -15,6 +15,7 @@
1515 */
1616
1717 import { ownTokenJs } from "../own_token.ts";
18 import { lookupIdempotent, MAX_KEY_LENGTH, requestFingerprint, storeIdempotent } from "../../core/idempotency.ts";
1819 import { blockedFlash } from "../blocked.ts";
1920 import { noTalkAccountBlocked } from "../../actions/blocked_words.ts";
2021 import type { Database } from "bun:sqlite";
@@ -63,6 +64,7 @@ import { signInFirst, forbiddenPage, notFoundPage } from "../chrome.ts";
6364 import { field, readForm } from "../form.ts";
6465 import { html, raw, type Html } from "../html.ts";
6566 import { flashTo, fragment, page, redirect } from "../layout.ts";
67 import { QUEUED_WORDS } from "./talk_client.ts";
6668 import { canRead, getRepo, getRepoById } from "../../core/repos.ts";
6769 import { getPull } from "../../core/pulls.ts";
6870 import { answerWall } from "../../actions/pulls.ts";
@@ -335,7 +337,7 @@ export function exchangeActs(db: Database, userId: string, conversationId: strin
335337 /** A message waiting for the running turn; Cancel is a form that works without the script. */
336338 export const queuedHtml = (q: { id: string; text: string }): Html =>
337339 html`<li class="talk-turn talk-person talk-queued" data-queued="${q.id}"><div class="talk-body talk-plain">${q.text}</div>
338 <form class="talk-meta small muted" method="post" action="${HERE}/queue/${q.id}/cancel" data-unqueue>Queued, sends after this answer ${btn("Cancel", { label: "Cancel this queued message" })}</form></li>`;
340 <form class="talk-meta small muted" method="post" action="${HERE}/queue/${q.id}/cancel" data-unqueue>${QUEUED_WORDS} ${btn("Edit", { type: "button", label: "Edit this queued message", extra: "js-only" })} ${btn("Drop", { label: "Drop this queued message" })}</form></li>`;
339341
340342 /**
341343 * How full the context is, one quiet line above the log; always drawn so a finished run can fill
@@ -662,6 +664,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
662664 ${conversation.archivedAt === null ? null : html`<p class="small muted" data-archived-note>Archived: sending here keeps it archived; Restore puts it back in the list.</p>`}
663665 ${about}
664666 ${editing === undefined && about !== null ? html`<input type="hidden" name="about" value="${ctx.url.searchParams.get("about")}" />` : null}
667 ${editing === undefined && !buildMode ? html`<input type="hidden" name="key" value="${last === "" ? "start" : last}" />` : null}
665668 ${chosen === undefined ? null : html`<input type="hidden" name="template" value="${chosen}" />`}
666669 ${confirmsDock(pendingConfirms)}
667670 <p class="sr-only" role="status" data-confirms-said></p>
@@ -685,6 +688,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
685688 </form>
686689 ${picker === null ? null : modelForm(urlOf(conversation))}
687690 <template id="talk-ico">${icon("copy")}${icon("check")}</template>
691 <template id="talk-queued">${queuedHtml({ id: "", text: "" })}</template>
688692 </div>
689693 ${split ? html`<div class="talk-work">${panel}${pane.html}</div>` : null}
690694 </div>`;
@@ -728,8 +732,16 @@ export async function talkSend(ctx: Ctx): Promise<Response> {
728732 const text = form.get("text");
729733 if (typeof text !== "string" || text.trim() === "" || text.length > WORDS_MAX)
730734 return flashTo(ctx, `${here}#end`, { tone: "danger", message: `Say something, up to ${WORDS_MAX} characters.` });
735 // The form's key, the turn its page was drawn after: the same words posted twice from one page
736 // send once (`core/idempotency.ts`, scoped to the person as the API's keys are); other words are
737 // their own message. The look, the send and the record run with no await between.
738 const key = form.get("key");
739 const fingerprint = requestFingerprint("POST", here, text);
740 const sentKey = typeof key === "string" && key !== "" && key.length <= MAX_KEY_LENGTH ? `talk-form:${conversation.id}:${key}:${fingerprint}` : undefined;
741 if (sentKey !== undefined && lookupIdempotent(ctx.app.db, `user:${user.id}`, sentKey) !== undefined) return redirect(`${here}#end`);
731742 const about = form.get("about");
732743 const said = talk(ctx.app, user, text, [], "queue", conversation.id, typeof about === "string" ? about : null);
744 if (sentKey !== undefined && said.ok) storeIdempotent(ctx.app.db, { tokenId: `user:${user.id}`, key: sentKey, fingerprint, response: { status: 303, body: "", contentType: "text/plain", headers: [["location", `${here}#end`]] } });
733745 // Kept: the line under the message says why it could not start and when to Retry; with no
734746 // account, the ask for one beside it.
735747 if (said.ok && said.value.kept?.why === "no_account") return flashTo(ctx, `${here}#end`, blockedFlash(noTalkAccountBlocked(ctx.app, user), "attn"));
src/web/pages/talk_client.ts +86 −19
@@ -268,6 +268,7 @@ body:has(.talk-page) .topbar { background: var(--bg); backdrop-filter: none; -we
268268 .talk-keys dt { font-weight: 600; }
269269 .talk-keys dd { margin: 0; }
270270 .talk-queued { opacity: .7; }
271 [data-pending] { opacity: .7; }
271272 .talk-queued .btn { min-height: 2.75rem; }
272273 `;
273274 /**
@@ -405,12 +406,16 @@ export const liveJs = `
405406 * Runs after DOMContentLoaded (`pageScriptAsset`). Reads the page's own `data-talk-*`; sends with
406407 * fetch, follows with EventSource.
407408 */
409 /** What a queued message says under it: it is not sent yet, and when it will be. */
410 export const QUEUED_WORDS = "Queued: sends when this answer ends.";
411
408412 const talkSource = `
409413 const root = document.querySelector("[data-talk]");
410414 if (root) {
411415 const log = root.querySelector(".talk-log");
412416 const form = root.querySelector("form.talk-compose");
413417 const box = form.querySelector("textarea");
418 const sendBtn = form.querySelector(".talk-send");
414419 const status = root.querySelector(".talk-status");
415420 let last = log.dataset.last || "";
416421 let source = null;
@@ -706,20 +711,28 @@ if (root) {
706711 stopBtn.addEventListener("click", stop);
707712 steerBtn.addEventListener("click", () => form.requestSubmit(steerBtn));
708713 document.addEventListener("keydown", (e) => { if (e.key === "Escape" && answering) { e.preventDefault(); stop(); } });
709 log.addEventListener("submit", async (e) => {
710 const f = e.target.closest("form[data-unqueue]");
711 if (!f) return;
712 e.preventDefault();
714 const unqueue = async (f, edit) => {
713715 const li = f.closest("[data-queued]");
714716 try {
715717 const res = await fetch(f.action, { method: "POST", headers: { accept: "application/json" }, body: new URLSearchParams() });
716 if (!res.ok && res.status !== 404) { say("That was not cancelled."); return; }
717 if (res.ok) { const t = li.querySelector(".talk-body").textContent; box.value = box.value ? box.value + "\\n" + t : t; grow(); say("Cancelled. The message is back in the box."); }
718 if (!res.ok && res.status !== 404) { say(edit ? "That was not taken back to edit." : "That was not dropped."); return; }
719 if (res.ok && edit) { const t = li.querySelector(".talk-body").textContent; const had = box.value !== ""; box.value = had ? box.value + "\\n" + t : t; grow(); box.focus(); say(had ? "Back in the box, after what you had typed; it sends when you press Send." : "Back in the box to edit; it sends when you press Send."); }
720 else if (res.ok) say("Dropped: it will not be sent.");
718721 else say("It had already gone.");
719722 li.remove();
720723 } catch (_) {
721 say("That was not cancelled: no connection.");
724 say("That was not changed: no connection.");
722725 }
726 };
727 log.addEventListener("submit", (e) => {
728 const f = e.target.closest("form[data-unqueue]");
729 if (!f) return;
730 e.preventDefault();
731 unqueue(f, false);
732 });
733 log.addEventListener("click", (e) => {
734 const b = e.target.closest && e.target.closest("[data-unqueue] button[type=button]");
735 if (b) unqueue(b.form, true);
723736 });
724737 ${liveJs}
725738 const follow = () => {
@@ -732,6 +745,15 @@ if (root) {
732745 const turn = JSON.parse(e.data);
733746 last = turn.id;
734747 if (turn.held) addConfirm(turn.held);
748 // Its own turn replaces the line shown sending, matched by its words: another tab's message,
749 // or a queued one that starts, leaves it where it is.
750 if (turn.role === "person") {
751 const t = document.createElement("template");
752 t.innerHTML = turn.html;
753 const said = (t.content.querySelector(".talk-body")?.textContent || "").trim();
754 const mine = [...log.querySelectorAll("[data-pending]")].find((p) => p.firstChild.textContent.trim() === said);
755 if (mine) mine.remove();
756 }
735757 if (!document.getElementById("t-" + turn.id)) {
736758 place(turn.html);
737759 decorate(log);
@@ -931,6 +953,8 @@ ${dictateJs}
931953 });
932954 document.addEventListener("forge:swapped", crewFold);
933955 crewFold();
956 let sending = false, sendKey = "", keyText = null;
957 const QUEUED = ${JSON.stringify(QUEUED_WORDS)};
934958 const send = async (e) => {
935959 const by = e.submitter;
936960 if (by && by.hasAttribute("formaction")) { if (by.hasAttribute("data-answer")) { e.preventDefault(); answerConfirm(by); } return; }
@@ -948,32 +972,75 @@ ${dictateJs}
948972 return;
949973 }
950974 const steer = e.submitter === steerBtn;
975 // One send at a time: a second press, a double tap or Enter again while this one is out is
976 // nothing, and the button says so until the server answers.
977 if (sending) return;
978 sending = true;
979 sendBtn.disabled = true;
980 // The same words sent again after a failure carry the same key, so a request that landed but
981 // whose answer was lost is kept once (core/idempotency.ts).
982 if (text !== keyText) { sendKey = typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : "k" + Math.random().toString(36).slice(2) + Date.now().toString(36); keyText = text; }
983 // The files go with the words, and come back with them if the send fails.
984 const kept = attached.splice(0);
985 const files = kept.map((f) => f.id);
986 // Shown at once, marked sending (and said, for a screen reader), and the box is free.
951987 say("Sending…");
988 const pending = document.createElement("li");
989 pending.className = "talk-turn talk-person";
990 pending.setAttribute("data-pending", "");
991 pending.innerHTML = '<div class="talk-body talk-plain"></div><p class="talk-meta small muted">Sending…</p>';
992 pending.firstChild.textContent = text;
993 log.append(pending);
994 box.value = "";
995 chips.replaceChildren();
996 grow();
997 clearTimeout(draftTimer);
998 draft.save("");
999 resume();
1000 // A failed send puts it all back: the words (unless something new was typed) and every file.
1001 const back = (words) => {
1002 pending.remove();
1003 if (!box.value.trim()) { box.value = text; grow(); draft.save(text); }
1004 for (const f of kept) { attached.push(f); drawChip(f); }
1005 fail(words);
1006 };
9521007 try {
9531008 const res = await fetch("/api/v1/conversation/messages", {
9541009 method: "POST",
955 headers: { "content-type": "application/json" },
956 body: JSON.stringify({ text, conversation: cid, files: attached.map((f) => f.id), during: steer && answering ? "steer" : "queue", about: form.about?.value || undefined }),
1010 headers: { "content-type": "application/json", "idempotency-key": sendKey },
1011 body: JSON.stringify({ text, conversation: cid, files, during: steer && answering ? "steer" : "queue", about: form.about?.value || undefined }),
9571012 });
9581013 if (!res.ok) {
9591014 const body = await res.json().catch(() => ({}));
960 fail(body.message || "That was not sent.");
1015 // A refusal retrying cannot change spends its key; a lost or busy server keeps it.
1016 if (res.status < 500 && res.status !== 429 && res.status !== 408) keyText = null;
1017 back(body.message || "That was not sent.");
9611018 return;
9621019 }
963 box.value = "";
964 attached.length = 0;
965 chips.replaceChildren();
966 grow();
967 clearTimeout(draftTimer);
968 draft.save("");
969 resume();
1020 keyText = null;
9701021 const out = await res.json().catch(() => ({}));
971 if (out.how === "queued") { say("Queued: it sends after this answer."); if (!source) follow(); return; }
1022 if (out.how === "queued") {
1023 // Plainly queued, under the answer it waits for, with Edit and Drop until it goes.
1024 // The row the server draws (one template, the queued frame's own markup), filled in.
1025 const row = document.getElementById("talk-queued").content.firstElementChild.cloneNode(true);
1026 row.setAttribute("data-queued", out.queued);
1027 row.querySelector(".talk-body").textContent = text;
1028 row.querySelector("form").setAttribute("action", "/talk/queue/" + encodeURIComponent(out.queued) + "/cancel");
1029 pending.replaceWith(row);
1030 say(QUEUED);
1031 if (!source) follow();
1032 return;
1033 }
9721034 if (out.how === "interrupted") { say("Stopping, then sending…"); return; }
1035 // Kept, not started (#16471): the line under it says why; the stream draws both.
1036 if (out.how === "kept") say(out.message || "Your message is kept; Retry when you are ready.");
9731037 if (paged) { location.href = here; return; }
9741038 follow();
9751039 } catch (_) {
976 fail("That was not sent: no connection.");
1040 back("That was not sent: no connection. Send again; it is kept once.");
1041 } finally {
1042 sending = false;
1043 sendBtn.disabled = false;
9771044 }
9781045 };
9791046 form.addEventListener("submit", send);
test/talk-page.test.ts +74 −14
@@ -16,7 +16,7 @@ import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1616 import { sayNo, sayYes } from "../src/actions/conversation_confirms.ts";
1717 import { openIssue } from "../src/actions/issues.ts";
1818 import { openPull } from "../src/actions/pulls.ts";
19 import { clock, STREAMS_MAX } from "../src/web/pages/talk.ts";
19 import { clock, queuedHtml, STREAMS_MAX } from "../src/web/pages/talk.ts";
2020 import { addSubscription, setGrants } from "../src/core/subscriptions.ts";
2121 import { serveTalk } from "../src/tui/ssh-talk.ts";
2222 import { aboutContext, aboutLine, parseAbout } from "../src/core/talk_about.ts";
@@ -457,7 +457,9 @@ describe("the page", () => {
457457 // 18,100 to 18,500 for the phone (#16442): one head row with the picker and tabs, a table that
458458 // scrolls in its bubble, an opaque top bar over the head: 18,294 measured.
459459 expect(Buffer.byteLength(talkCss)).toBeLessThan(18_500);
460 expect(Buffer.byteLength(talkJs)).toBeLessThan(54_800);
460 // The script to 56,000 for sending once (#16579, #16582): the line shown while a message sends,
461 // a failed send's words and files put back, one send at a time with its key: 55,722 measured.
462 expect(Buffer.byteLength(talkJs)).toBeLessThan(56_000);
461463 // A page of its own, so what other tests said to alice never counts: one question and a code reply.
462464 const sizer = await createUser(app.db, { origin: "seed", trusted: true, username: "sizer", email: "[email protected]", password: "a-good-passphrase" });
463465 if (!sizer.ok) throw new Error(sizer.error);
@@ -468,12 +470,13 @@ describe("the page", () => {
468470 // WITHOUT its palette index; whoever raises it should measure the same way.
469471 const page = (await (await get("/talk", sizer.value)).text()).replace(/<script type="application\/json" id="palette-index">[\s\S]*?<\/script>/, "");
470472 const size = Buffer.byteLength(page);
471 // Raised from 47,000 by the widgets' rules and no more (widgetCss, 2,495 B raw): they ride every
472 // Talk page, because a chart can arrive in a live reply, and a page drawn without them would
473 // show it unstyled until a reload. 48,328 measured. Then to 50,000 by the reply's one last line
474 // and the pane's first-version words: 49,466 measured. Then to 54,600 by the same phone rules
475 // (#16442), which ride inline: 54,393 measured.
476 expect(size).toBeLessThan(54_600);
473 // Raised from 47,000 by the widgets' rules and no more (widgetCss, 2,495 B raw): they ride
474 // every Talk page, because a chart can arrive in a live reply, and a page drawn without them
475 // would show it unstyled until a reload. 48,328 measured. Then to 50,000 by the reply's one
476 // last line and the pane's first-version words: 49,466 measured. Then to 54,600 by the same
477 // phone rules (#16442), which ride inline: 54,393 measured. Then to 55,400 by sending once
478 // (#16582): the queued row's one template, which the script fills: 55,122 measured.
479 expect(size).toBeLessThan(55_400);
477480 });
478481
479482 describe("the script, driven against a DOM", () => {
@@ -503,9 +506,9 @@ describe("the page", () => {
503506 expect(t.urls).toHaveLength(2);
504507 });
505508
506 const queuedFrame = (id: string, text: string) => ({ id, html: `<li class="talk-turn talk-queued" data-queued="${id}"><div class="talk-body">${text}</div><form data-unqueue method="post" action="/talk/queue/${id}/cancel"><button>Cancel</button></form></li>` });
509 const queuedFrame = (id: string, text: string) => ({ id, html: `<li class="talk-turn talk-queued" data-queued="${id}"><div class="talk-body">${text}</div><form data-unqueue method="post" action="/talk/queue/${id}/cancel"><button type="button">Edit</button><button type="submit">Drop</button></form></li>` });
507510
508 test("a message sent mid-answer is queued; the stream's queued frame draws it; Cancel puts it back without overwriting what is typed (#8819)", async () => {
511 test("a message sent mid-answer is queued; the stream's queued frame draws it; Edit puts it back without overwriting what is typed (#8819, #16579)", async () => {
509512 const t = await boot();
510513 t.how.value = "queued";
511514 t.sources.at(-1)!.on["running"]!({ data: "{}" });
@@ -518,11 +521,18 @@ describe("the page", () => {
518521 t.sources.at(-1)!.on["queued"]!({ data: JSON.stringify({ items: [queuedFrame("q1", "and then this")] }) });
519522 expect(t.doc.querySelectorAll("[data-queued]")).toHaveLength(1);
520523 t.box.value = "something new";
521 t.doc.querySelector("form[data-unqueue]").dispatchEvent(new t.window.Event("submit", { bubbles: true, cancelable: true }));
524 t.doc.querySelector("form[data-unqueue] button[type=button]").dispatchEvent(new t.window.MouseEvent("click", { bubbles: true, cancelable: true }));
522525 await tick();
523526 expect(t.urls.at(-1)).toEndWith("/talk/queue/q1/cancel");
524527 expect(t.doc.querySelector("[data-queued]")).toBeNull();
525528 expect(t.box.value).toBe("something new\nand then this");
529 // Drop lets a queued message go and leaves the box as it is.
530 t.sources.at(-1)!.on["queued"]!({ data: JSON.stringify({ items: [queuedFrame("q2", "not this")] }) });
531 t.doc.querySelector("form[data-unqueue]").dispatchEvent(new t.window.Event("submit", { bubbles: true, cancelable: true }));
532 await tick();
533 expect(t.urls.at(-1)).toEndWith("/talk/queue/q2/cancel");
534 expect(t.doc.querySelector("[data-queued]")).toBeNull();
535 expect(t.box.value).toBe("something new\nand then this");
526536 });
527537
528538 test("Cancel keeps the message when the server fails and drops it only on a 404; Steer sends a steer", async () => {
@@ -567,7 +577,7 @@ describe("the page", () => {
567577 const doc = window.document as any;
568578 doc.body.innerHTML = `<div class="talk" data-talk data-user="${user}" data-c="${conv}" data-paged="0" data-running="1"><header class="talk-head"><details><summary>More</summary></details></header><div>
569579 <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>
570 <form class="talk-compose"><div data-confirms hidden><p data-confirms-count></p><div class="talk-confirm-list"></div></div><p data-confirms-said></p><div class="talk-box"><div data-chips></div><p data-to-line hidden><span></span><button type="button" data-to-off>x</button></p><textarea name="text" required></textarea><div class="talk-tools"><button type="button" data-attach hidden aria-label="Attach files"></button><input type="file" multiple hidden data-files /><span data-compose-hint></span><button class="btn" type="button" data-steer hidden>Steer</button><button class="btn" type="button" data-stop hidden aria-label="Stop the answer">Stop</button><button class="btn talk-send" type="submit" aria-label="Send">Send</button></div></div><p data-error hidden></p><p class="talk-status" role="status"></p><button type="button" class="btn talk-jump" data-jump hidden><span data-word></span></button></form></div>`;
580 <template id="talk-queued">${queuedHtml({ id: "", text: "" }).text}</template><form class="talk-compose"><div data-confirms hidden><p data-confirms-count></p><div class="talk-confirm-list"></div></div><p data-confirms-said></p><div class="talk-box"><div data-chips></div><p data-to-line hidden><span></span><button type="button" data-to-off>x</button></p><textarea name="text" required></textarea><div class="talk-tools"><button type="button" data-attach hidden aria-label="Attach files"></button><input type="file" multiple hidden data-files /><span data-compose-hint></span><button class="btn" type="button" data-steer hidden>Steer</button><button class="btn" type="button" data-stop hidden aria-label="Stop the answer">Stop</button><button class="btn talk-send" type="submit" aria-label="Send">Send</button></div></div><p data-error hidden></p><p class="talk-status" role="status"></p><button type="button" class="btn talk-jump" data-jump hidden><span data-word></span></button></form></div>`;
571581 const how = { value: "started" };
572582 const cancel = { status: 200 };
573583 const answer = { status: 200, message: "this confirm was already answered; it does nothing twice" };
@@ -590,7 +600,8 @@ describe("the page", () => {
590600 const body = JSON.parse(init.body);
591601 sent.push(body.text);
592602 bodies.push(body);
593 return { ok: true, json: async () => ({ how: how.value, queued: "q1" }) };
603 if (how.value === "offline") throw new TypeError("Failed to fetch");
604 return { ok: true, json: async () => ({ how: how.value, queued: "q1", ...(how.value === "kept" ? { why: "busy", message: "The forge is answering as many people as it can at once. Your message is kept; Retry in a minute.", turn: "t-k" } : {}) }) };
594605 };
595606 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]; } };
596607 const nav = { clipboard: { writeText: async (t: string) => { copied.push(t); } } };
@@ -603,7 +614,7 @@ describe("the page", () => {
603614 const box = doc.querySelector("textarea");
604615 const key = (init: object) => box.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...init }));
605616 const emitConfirm = (id: string, held: string) => sources.at(-1)!.on["turn"]!({ data: JSON.stringify({ id, html: "", held }) });
606 const emit = (id: string, html: string) => sources.at(-1)!.on["turn"]!({ data: JSON.stringify({ id, html }) });
617 const emit = (id: string, html: string, role?: string) => sources.at(-1)!.on["turn"]!({ data: JSON.stringify({ id, html, ...(role === undefined ? {} : { role }) }) });
607618 const grow = () => { for (const f of grows) f(); };
608619 return { how, cancel, answer, emitConfirm, redirects, 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") };
609620 };
@@ -819,6 +830,55 @@ describe("the page", () => {
819830 expect(t.bodies.at(-1)!.files).toEqual([]);
820831 });
821832
833 test("a send that fails puts back the words and every attached file, and says so (#16582)", async () => {
834 const t = await boot();
835 const paste = new t.window.Event("paste", { bubbles: true, cancelable: true }) as any;
836 paste.clipboardData = { files: [{ name: "shot.png" }] };
837 t.box.dispatchEvent(paste);
838 await tick();
839 const chips = t.doc.querySelector("[data-chips]");
840 t.how.value = "offline";
841 t.box.value = "see this";
842 t.doc.querySelector("form").requestSubmit();
843 // At once: shown sending, and said for a screen reader.
844 expect(t.doc.querySelector("[data-pending]")).not.toBeNull();
845 expect(t.status.textContent).toBe("Sending…");
846 await tick();
847 expect(t.doc.querySelector("[data-pending]")).toBeNull();
848 expect(t.box.value).toBe("see this");
849 expect(chips.textContent).toContain("shot.png");
850 expect(t.doc.querySelector("[data-error]").textContent).toContain("no connection");
851 // Sent again, the file goes with it.
852 t.how.value = "started";
853 t.doc.querySelector("form").requestSubmit();
854 await tick();
855 expect(t.bodies.at(-1)).toMatchObject({ text: "see this", files: ["f1"] });
856 });
857
858 test("a kept send says its line, not Sending…, and the stream's turn replaces the line shown sending (#16471, #16582)", async () => {
859 const t = await boot();
860 t.how.value = "kept";
861 t.box.value = "while it is full";
862 t.doc.querySelector("form").requestSubmit();
863 await tick();
864 expect(t.status.textContent).toBe("The forge is answering as many people as it can at once. Your message is kept; Retry in a minute.");
865 t.emit("t-k", `<li class="talk-turn talk-person" id="t-k"><div class="talk-body">while it is full</div></li>`, "person");
866 expect(t.doc.querySelector("[data-pending]")).toBeNull();
867 });
868
869 test("the line shown sending leaves for its own turn only, never for another person turn on the stream (#16582)", async () => {
870 const t = await boot();
871 t.box.value = "mine";
872 t.doc.querySelector("form").requestSubmit();
873 await tick();
874 expect(t.doc.querySelector("[data-pending]")).not.toBeNull();
875 t.emit("t-8", `<li class="talk-turn talk-person" id="t-8"><div class="talk-body">from the other tab</div></li>`, "person");
876 expect(t.doc.querySelector("[data-pending]")).not.toBeNull();
877 t.emit("t-9", `<li class="talk-turn talk-person" id="t-9"><div class="talk-body">mine</div></li>`, "person");
878 expect(t.doc.querySelector("[data-pending]")).toBeNull();
879 expect(t.doc.querySelectorAll("#t-9")).toHaveLength(1);
880 });
881
822882 test("tapping a starter sends its prompt through the composer and follows the answer, with no page load", async () => {
823883 const t = await boot();
824884 t.doc.querySelector(".talk-log").insertAdjacentHTML("beforeend", '<li><div class="talk-suggest"><form method="post" action="/talk" data-starter><input type="hidden" name="text" value="What shipped this week?" /><button class="btn" type="submit">What shipped this week?</button></form></div></li>');
test/talk-send-once.test.ts added +208
@@ -0,0 +1,208 @@
1 /**
2 * Talk's send, once (the owner, 11-27: "if i hit send twice it will send then queue one"): a press
3 * shows the message at once and frees the box; a second press, a double tap or Enter while it is
4 * out sends nothing more; every send carries a key, so two requests for one press keep one message
5 * (the API's Idempotency-Key, the plain form's own key); a message sent while the forge answers is
6 * shown plainly as queued, with Edit and Drop, never as a silent second turn.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { chmodSync, writeFileSync } from "node:fs";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { listTurns, openConversation } from "../src/core/conversations.ts";
16 import { createSession } from "../src/core/sessions.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { configureConversation, queuedOf } from "../src/crew/conversation.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { findChromium } from "../src/looks/capture.ts";
21 import { queuedHtml } from "../src/web/pages/talk.ts";
22 import { QUEUED_WORDS } from "../src/web/pages/talk_client.ts";
23 import { chromiumRuns, evaluateLoaded } from "./helpers/chrome.ts";
24 import { quietLogs } from "./helpers/globals.ts";
25
26 quietLogs();
27
28 let dir: string;
29 let app: App;
30 let servers: Servers;
31 let ada: User;
32 let cookie: string;
33
34 /** An agent that answers once `gate` exists, so a turn can be held running. */
35 const gated = (name: string): string => {
36 const bin = join(dir, name);
37 writeFileSync(
38 bin,
39 `#!/bin/sh
40 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
41 IFS= read -r first
42 echo '{"type":"system","subtype":"init","session_id":"s-${name}","model":"fake"}'
43 while [ ! -f "${dir}/${name}.gate" ]; do sleep 0.05; done
44 echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","total_cost_usd":0.01,"num_turns":1,"session_id":"s-${name}","terminal_reason":"completed","usage":{"input_tokens":1,"output_tokens":1}}'
45 `,
46 );
47 chmodSync(bin, 0o755);
48 return bin;
49 };
50
51 /** How many times `text` is the person's: as a turn, or waiting in the queue behind one. */
52 const persons = (u: User, text: string): number => {
53 const r = listTurns(app.db, u.id, openConversation(app.db, u.id).id, { limit: 200 });
54 const turns = r.ok ? r.value.filter((t) => t.role === "person" && t.text === text).length : 0;
55 return turns + queuedOf(app, u.id).filter((q) => q.text === text).length;
56 };
57
58 beforeAll(async () => {
59 dir = await mkdtemp(join(tmpdir(), "forge-send-once-"));
60 app = createApp({ dataDir: dir, port: 0 });
61 servers = await serve(app);
62 const made = await createUser(app.db, {
63 origin: "seed",
64 trusted: true,
65 username: "ada",
66 email: "[email protected]",
67 password: "a-good-passphrase",
68 adminIfFirst: true,
69 });
70 if (!made.ok) throw new Error(made.error);
71 ada = made.value;
72 cookie = `forge_session=${createSession(app.db, ada.id).token}`;
73 writeFileSync(join(dir, "answers.gate"), "");
74 configureConversation(app, {
75 binary: gated("answers"),
76 localUrl: servers.url,
77 budgetUsd: 1,
78 timeoutMs: 30_000,
79 signal: new AbortController().signal,
80 });
81 });
82 afterAll(async () => {
83 await servers.stop();
84 app.close();
85 await rm(dir, { recursive: true, force: true });
86 });
87
88 const api = (text: string, key: string) =>
89 fetch(`${servers.url}/api/v1/conversation/messages`, {
90 method: "POST",
91 headers: { cookie, origin: servers.url, "content-type": "application/json", "idempotency-key": key },
92 body: JSON.stringify({ text }),
93 });
94
95 test("the same key twice, even at once, keeps one message, and the second answer is the first's", async () => {
96 const [a, b] = await Promise.all([api("one press", "press-1"), api("one press", "press-1")]);
97 expect([a.status, b.status]).toEqual([202, 202]);
98 expect([a.headers.get("idempotent-replay"), b.headers.get("idempotent-replay")].filter((h) => h === "true")).toHaveLength(1);
99 const again = await api("one press", "press-1");
100 expect(again.headers.get("idempotent-replay")).toBe("true");
101 expect(persons(ada, "one press")).toBe(1);
102 });
103
104 test("with no script, the form's key keeps a resubmit to one message", async () => {
105 const page = await (await fetch(`${servers.url}/talk`, { headers: { cookie } })).text();
106 const key = /<input type="hidden" name="key" value="([^"]+)"/.exec(page)?.[1];
107 expect(key).toBeDefined();
108 const post = () =>
109 fetch(`${servers.url}/talk`, {
110 method: "POST",
111 redirect: "manual",
112 headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" },
113 body: new URLSearchParams({ text: "pressed twice, no script", key: key! }),
114 });
115 expect((await post()).status).toBe(303);
116 const second = await post();
117 expect(second.status).toBe(303);
118 expect(second.headers.get("location")).toBe("/talk#end");
119 expect(persons(ada, "pressed twice, no script")).toBe(1);
120 // Other words from the same stale page are their own message, never dropped.
121 const other = await fetch(`${servers.url}/talk`, { method: "POST", redirect: "manual", headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ text: "something else", key: key! }) });
122 expect(other.status).toBe(303);
123 expect(persons(ada, "something else")).toBe(1);
124 });
125
126 test("a queued message says so plainly, with Edit and Drop", () => {
127 const row = queuedHtml({ id: "q1", text: "after this" }).text;
128 expect(QUEUED_WORDS).toBe("Queued: sends when this answer ends.");
129 expect(row).toContain(QUEUED_WORDS);
130 expect(row).toMatch(/<button\s+type="button"[^>]*class="btn js-only"[^>]*aria-label="Edit this queued message"/);
131 expect(row).toMatch(/<button\s+type="submit"[^>]*aria-label="Drop this queued message"/);
132 expect(row).toContain('action="/talk/queue/q1/cancel"');
133 });
134
135 const found = findChromium();
136 const chromium = found !== undefined && chromiumRuns(found) ? found : undefined;
137 const sandboxed = process.env["FORGE_TEST_SOCKET"] !== undefined;
138 if (chromium === undefined) {
139 if (sandboxed) console.log("SKIPPING: no chromium that starts in this sandbox, so Talk's send is not driven at 390");
140 else
141 test("a chromium starts, so Talk's send is driven at 390", () => {
142 throw new Error("no chromium starts here: Talk's send cannot be driven at 390 px");
143 });
144 }
145
146 describe.skipIf(chromium === undefined)("at 390 px with a finger", () => {
147 test("a double tap is one message, shown at once; a send while it answers is one queued line, and Edit takes it back", async () => {
148 // The answer is held, so the forge is answering when the second message is sent.
149 configureConversation(app, {
150 binary: gated("held"),
151 localUrl: servers.url,
152 budgetUsd: 1,
153 timeoutMs: 30_000,
154 signal: new AbortController().signal,
155 });
156 const drive = `(async () => {
157 // Waits on the page's own signal: every change it makes to the document (the pending line, Send's
158 // disabled state, the queued row, the box) is a mutation, and the condition is read at each.
159 const wait = (ok) => new Promise((done) => { if (ok()) return done(true); const seen = new MutationObserver(() => { if (ok()) { seen.disconnect(); done(true); } }); seen.observe(document, { subtree: true, childList: true, attributes: true, characterData: true }); });
160 const form = document.querySelector("form.talk-compose"), box = form.querySelector("textarea"), send = form.querySelector(".talk-send");
161 box.value = "double tapped"; box.dispatchEvent(new Event("input", { bubbles: true }));
162 send.click();
163 const now = { pending: document.querySelector("[data-pending] .talk-body")?.textContent ?? null, sending: document.querySelector("[data-pending] .talk-meta")?.textContent ?? null, box: box.value, disabled: send.disabled };
164 send.click();
165 box.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
166 form.requestSubmit();
167 await wait(() => !send.disabled && !document.querySelector("[data-pending]"));
168 await wait(() => document.querySelector(".talk-log").getAttribute("aria-busy") === "true");
169 box.value = "while it answers"; box.dispatchEvent(new Event("input", { bubbles: true }));
170 send.click();
171 await wait(() => document.querySelectorAll("[data-queued]").length === 1 && !send.disabled);
172 const q = document.querySelector("[data-queued]");
173 const queued = { count: document.querySelectorAll("[data-queued]").length, text: q?.querySelector(".talk-body")?.textContent ?? null, says: q?.querySelector(".talk-meta")?.textContent ?? "", edit: !!q?.querySelector("button[type=button]"), drop: !!q?.querySelector("button[type=submit]") };
174 q?.querySelector("button[type=button]")?.click();
175 await wait(() => document.querySelectorAll("[data-queued]").length === 0 && box.value !== "");
176 return JSON.stringify({ now, queued, edited: box.value, left: document.querySelectorAll("[data-queued]").length });
177 })()`;
178 const cookies = [{ name: "forge_session", value: createSession(app.db, ada.id).token }];
179 let seen: {
180 now: { pending: string | null; sending: string | null; box: string; disabled: boolean };
181 queued: { count: number; text: string | null; says: string; edit: boolean; drop: boolean };
182 edited: string;
183 left: number;
184 };
185 try {
186 seen = JSON.parse(await evaluateLoaded(chromium!, `${servers.url}/talk`, { width: 390, height: 844 }, cookies, drive, "light", true));
187 } finally {
188 writeFileSync(join(dir, "held.gate"), "");
189 }
190 // At once: the words in the thread, marked sending; the box empty; Send not pressable again.
191 expect(seen.now).toEqual({ pending: "double tapped", sending: "Sending…", box: "", disabled: true });
192 // The second tap, Enter and another submit sent nothing more.
193 expect(persons(ada, "double tapped")).toBe(1);
194 // Sent while it answered: one queued line, plain, with Edit and Drop.
195 expect(seen.queued).toEqual({
196 count: 1,
197 text: "while it answers",
198 says: expect.stringContaining(QUEUED_WORDS),
199 edit: true,
200 drop: true,
201 });
202 // Edit took it back into the box and out of the queue: it never became a turn.
203 expect(seen.edited).toBe("while it answers");
204 expect(seen.left).toBe(0);
205 expect(queuedOf(app, ada.id)).toHaveLength(0);
206 expect(persons(ada, "while it answers")).toBe(0);
207 }, 60_000);
208 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs