Public: anyone can read this; the crew can change it.
Talk opens on the conversation the person was in, at the place they left it #18322
Merged 11h 42m ago, live in production
scout/forge:scout/18317-talk-opens-on-the-conversation-the-perso → main 0 commits fork 1 thread · 1 unresolved
13 files
changed +242
−20
- docs/features/talk-place.md
- src/core/conversations.ts
- src/core/migration-pins/20261204222450-talk-place.pin
- src/core/migrations/20261204222450-talk-place.ts
- src/core/talk_place.ts
- src/http/lazy_lists.ts
- src/http/routes/talk.ts
- src/tui/screens/talk_chats.ts
- src/web/pages/talk.ts
- src/web/pages/talk_client.ts
- test/talk-links-click.test.ts
- test/talk-place.test.ts
- test/talk-preview-frame.test.ts
docs/features/talk-place.md added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | --- | |
| 2 | topic: Tell the crew | |
| 3 | row: Talk opens where you left it | |
| 4 | --- | |
| 5 | # Talk opens where you left it | |
| 6 | ||
| 7 | `/talk` opens on the conversation you were last in, at the place you left it: the turn at the top of the screen when you left (the end, when you were at the end). It is kept on the forge per person, so a new tab, another device or a sign-out and sign-in lands there. | |
| 8 | ||
| 9 | - Only `/talk` restores the scrolled place; `/talk/<id>`, named by its address, opens at its end. Opening a conversation writes the place, even though it is a GET. | |
| 10 | - Only opening a conversation moves the place; the scroll report of a page being left never does. | |
| 11 | - Opening a conversation on the page (`/talk/<id>`) or in the terminal (`ssh`, Talk, Enter on a chat) keeps it as the place. | |
| 12 | - A message sent without naming a conversation (`/talk`, the API's `conversation/say`, `talk` in the terminal) goes to that same conversation. | |
| 13 | - With no earlier conversation, or when it was archived or deleted, `/talk` opens the newest of your others, else a new empty one with the box focused. | |
| 14 | - Only your own conversations and their own turns are kept; anything else is refused (`POST /talk/place`, 404). |
src/core/conversations.ts +7 −2
| @@ -121,10 +121,15 @@ export function newConversation(db: Database, userId: string): Conversation { | ||
| 121 | 121 | } |
| 122 | 122 | |
| 123 | 123 | /** |
| 124 | * Where a message with no conversation named goes: the person's most recently | |
| 125 | * active conversation that is not archived, made on first use. | |
| 124 | * Where a message with no conversation named goes: the one the person was last in (#18317), else | |
| 125 | * their most recently active conversation that is not archived, made on first use. | |
| 126 | 126 | */ |
| 127 | 127 | export function openConversation(db: Database, userId: string): Conversation { |
| 128 | // The one they were last in (`talk_place`), while it is theirs and not put away. | |
| 129 | const kept = db | |
| 130 | .query("SELECT c.* FROM talk_place p JOIN conversation c ON c.id = p.conversation_id WHERE p.user_id = ?1 AND c.user_id = ?1 AND c.archived_at IS NULL") | |
| 131 | .get(userId) as ConversationRow | null; | |
| 132 | if (kept !== null) return conversationOf(kept); | |
| 128 | 133 | const row = db |
| 129 | 134 | .query("SELECT * FROM conversation WHERE user_id = ?1 AND archived_at IS NULL ORDER BY updated_at DESC, rowid DESC LIMIT 1") |
| 130 | 135 | .get(userId) as ConversationRow | null; |
src/core/migration-pins/20261204222450-talk-place.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | fc13b38975529aa374247dda2a278f49f2139dd04e7f2132fc423162ee5ae575 |
src/core/migrations/20261204222450-talk-place.ts added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | // Where each person was in Talk (#18317): the conversation last opened and the turn at the top of | |
| 2 | // the screen when they left it ('' when they were at the end). One row per person; it goes with the | |
| 3 | // person or the conversation. Additive. | |
| 4 | export default ` | |
| 5 | CREATE TABLE IF NOT EXISTS talk_place ( | |
| 6 | user_id TEXT PRIMARY KEY REFERENCES user(id) ON DELETE CASCADE, | |
| 7 | conversation_id TEXT NOT NULL REFERENCES conversation(id) ON DELETE CASCADE, | |
| 8 | turn_id TEXT NOT NULL DEFAULT '', | |
| 9 | updated_at TEXT NOT NULL | |
| 10 | ) WITHOUT ROWID; | |
| 11 | `; |
src/core/talk_place.ts added +39
| @@ -0,0 +1,39 @@ | ||
| 1 | /** | |
| 2 | * Where a person was in Talk (#18317): the conversation they last opened and the turn at the top of | |
| 3 | * the screen when they left, kept under the forge's data so a refresh, another tab or a new sign-in | |
| 4 | * opens there. Plain data in and out; every call names the person, and a conversation that is not | |
| 5 | * theirs is never kept. | |
| 6 | */ | |
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | ||
| 9 | /** | |
| 10 | * Keep the person's conversation and answer the turn kept with it: their scroll place holds only | |
| 11 | * while it is the same conversation. One statement; '' when there is none (or it is not theirs). | |
| 12 | */ | |
| 13 | export function keepOpen(db: Database, userId: string, conversationId: string): string { | |
| 14 | const row = db | |
| 15 | .query<{ t: string }, [string, string, string]>( | |
| 16 | `INSERT INTO talk_place (user_id, conversation_id, turn_id, updated_at) | |
| 17 | SELECT ?1, c.id, '', ?3 FROM conversation c WHERE c.id = ?2 AND c.user_id = ?1 | |
| 18 | ON CONFLICT(user_id) DO UPDATE SET | |
| 19 | turn_id = CASE WHEN talk_place.conversation_id = excluded.conversation_id THEN talk_place.turn_id ELSE '' END, | |
| 20 | conversation_id = excluded.conversation_id, updated_at = excluded.updated_at | |
| 21 | RETURNING turn_id AS t`, | |
| 22 | ) | |
| 23 | .get(userId, conversationId, new Date().toISOString()); | |
| 24 | return row?.t ?? ""; | |
| 25 | } | |
| 26 | ||
| 27 | /** | |
| 28 | * Keep the turn at the top of the screen in the conversation the person is in, or '' for the end. | |
| 29 | * Only opening a conversation (`keepOpen`) moves the place: a page being left reports after the | |
| 30 | * next one was opened, and must not move it back. False when the place is not that conversation, or | |
| 31 | * the turn is not in it. | |
| 32 | */ | |
| 33 | export function keepScroll(db: Database, userId: string, conversationId: string, turnId: string): boolean { | |
| 34 | if (turnId !== "" && db.query("SELECT 1 FROM conversation_turn WHERE id = ?1 AND conversation_id = ?2").get(turnId, conversationId) === null) return false; | |
| 35 | const done = db | |
| 36 | .query("UPDATE talk_place SET turn_id = ?3, updated_at = ?4 WHERE user_id = ?1 AND conversation_id = ?2") | |
| 37 | .run(userId, conversationId, turnId, new Date().toISOString()); | |
| 38 | return done.changes > 0; | |
| 39 | } |
src/http/lazy_lists.ts +1
src/http/routes/talk.ts +2 −1
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | * Talking to the crew: the conversations, their stream and what they do. |
| 3 | 3 | */ |
| 4 | 4 | |
| 5 | import { talkView, talkSend, talkWall, talkStream, talkAgainSend, talkQueueCancel, talkConfirm, talkUndo, talkAct, talkNew, talkDisplaySave, talkDownload, talkRename, talkArchive, talkPin } from "../../web/pages/talk.ts"; | |
| 5 | import { talkView, talkSend, talkWall, talkStream, talkAgainSend, talkQueueCancel, talkConfirm, talkUndo, talkAct, talkNew, talkDisplaySave, talkDownload, talkRename, talkArchive, talkPin, talkPlace } from "../../web/pages/talk.ts"; | |
| 6 | 6 | import { peekRoute } from "../../web/peek.ts"; |
| 7 | 7 | import { talkBuild, talkRestore, talkPublish } from "../../web/talk_build.ts"; |
| 8 | 8 | import { talkWorkCommit, talkWorkDiscard, talkWorkPull, talkWorkSave, talkWorkTest } from "../../web/talk_tree.ts"; |
| @@ -23,6 +23,7 @@ export function talkRoutes(router: Router<Handler>): void { | ||
| 23 | 23 | router.add("POST", "/talk/undo/:turn", talkUndo); |
| 24 | 24 | router.add("POST", "/talk/act", talkAct); |
| 25 | 25 | router.add("POST", "/talk/new", talkNew); |
| 26 | router.add("POST", "/talk/place", talkPlace); | |
| 26 | 27 | router.add("POST", "/talk/display", talkDisplaySave); |
| 27 | 28 | router.add("POST", "/talk/build", talkBuild); |
| 28 | 29 | router.add("POST", "/talk/dev", talkDev); |
src/tui/screens/talk_chats.ts +2
| @@ -29,6 +29,7 @@ import { | ||
| 29 | 29 | TITLE_MAX, |
| 30 | 30 | type Conversation, |
| 31 | 31 | } from "../../core/conversations.ts"; |
| 32 | import { keepOpen } from "../../core/talk_place.ts"; | |
| 32 | 33 | import { conversationMarkdown } from "../../core/conversation_markdown.ts"; |
| 33 | 34 | import { publicOrigin } from "../../core/public_origin.ts"; |
| 34 | 35 | import { filesOf, receiptIssues, repoOf, steerOf, stepOf } from "../../core/talk_steps.ts"; |
| @@ -164,6 +165,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr | ||
| 164 | 165 | let receipts: ReadonlyMap<string, LiveReceipt> = new Map(); |
| 165 | 166 | const load = (): void => { |
| 166 | 167 | if (f.user === undefined) return; |
| 168 | keepOpen(f.app.db, f.user.id, chat.id); | |
| 167 | 169 | const before = around === undefined ? undefined : pageAround(f.app.db, f.user.id, chat.id, around); |
| 168 | 170 | const listed = listTurns(f.app.db, f.user.id, chat.id, { limit: 50, ...(before === undefined ? {} : { before }) }); |
| 169 | 171 | turns = listed.ok ? listed.value : []; |
src/web/pages/talk.ts +24 −5
| @@ -42,6 +42,7 @@ import { | ||
| 42 | 42 | turnsAfter, |
| 43 | 43 | type Turn, |
| 44 | 44 | } from "../../core/conversations.ts"; |
| 45 | import { keepOpen, keepScroll } from "../../core/talk_place.ts"; | |
| 45 | 46 | import { conversationMarkdown } from "../../core/conversation_markdown.ts"; |
| 46 | 47 | import { contextOf, contextText, conversationTotal, spendWords, totalText, turnSpend, type Spend, type Context } from "../../core/conversation_cost.ts"; |
| 47 | 48 | import { aboutLine as aboutText } from "../../core/talk_about.ts"; |
| @@ -607,14 +608,14 @@ function hello(ctx: Ctx, user: User, here: string, buildMode: boolean, chosen: s | ||
| 607 | 608 | </li>`; |
| 608 | 609 | } |
| 609 | 610 | |
| 610 | async function talkPage(ctx: Ctx, conversation: Conversation, before0: string | undefined, latest: boolean, edit: boolean): Promise<Response> { | |
| 611 | async function talkPage(ctx: Ctx, conversation: Conversation, before0: string | undefined, latest: boolean, edit: boolean, left?: string): Promise<Response> { | |
| 611 | 612 | const user = ctx.auth.user!; |
| 612 | 613 | let before = before0; |
| 613 | 614 | const here = latest ? HERE : urlOf(conversation); |
| 614 | 615 | const showArchived = latest && ctx.url.searchParams.get("archived") === "1"; |
| 615 | 616 | const typed = (ctx.url.searchParams.get("find") ?? "").slice(0, FIND_CHARS); |
| 616 | 617 | // A search result names its turn: show the page that holds it, and let the fragment scroll there. |
| 617 | const focus = ctx.url.searchParams.get("turn"); | |
| 618 | const focus = ctx.url.searchParams.get("turn") ?? left ?? null; | |
| 618 | 619 | // Near the end pageAround has no `before`: that is the latest page, unpaged, and the fragment |
| 619 | 620 | // still lands. |
| 620 | 621 | if (before === undefined && focus !== null && focus !== "" && TURN_ID.test(focus)) before = pageAround(ctx.app.db, user.id, conversation.id, focus); |
| @@ -714,11 +715,11 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string | | ||
| 714 | 715 | // The model picker (`talk_model.ts`), only where a connection offers a model. |
| 715 | 716 | const picker = modelPicker(ctx, user, urlOf(conversation), conversation.id, { builds: buildMode, empty }); |
| 716 | 717 | // With a model to choose, the words have a row of their own over the tools; without, they share one. |
| 717 | const input = html`<textarea class="talk-input" name="${buildMode ? "prompt" : "text"}" rows="1" maxlength="${WORDS_MAX}" required placeholder="${buildMode ? (chosen === undefined ? "A tip calculator for friends" : `What to make from ${chosen}`) : "Message the forge"}" aria-label="${buildMode ? "What to build" : "Talk to the forge"}" aria-keyshortcuts="/ Enter Shift+Enter" title="Enter sends, Shift+Enter adds a line" aria-describedby="talk-error">${editing === undefined ? "" : editing.text}</textarea>`; | |
| 718 | const input = html`<textarea class="talk-input" ${empty && editing === undefined ? raw("autofocus ") : null}name="${buildMode ? "prompt" : "text"}" rows="1" maxlength="${WORDS_MAX}" required placeholder="${buildMode ? (chosen === undefined ? "A tip calculator for friends" : `What to make from ${chosen}`) : "Message the forge"}" aria-label="${buildMode ? "What to build" : "Talk to the forge"}" aria-keyshortcuts="/ Enter Shift+Enter" title="Enter sends, Shift+Enter adds a line" aria-describedby="talk-error">${editing === undefined ? "" : editing.text}</textarea>`; | |
| 718 | 719 | const tabs = split ? html`<nav class="seg talk-tabs" aria-label="Chat or preview"><a href="?pane=chat${paneQ === "" ? "" : `&${paneQ}`}"${shown === "chat" ? raw(' aria-current="page"') : null}>Chat</a><a href="?pane=preview${paneQ === "" ? "" : `&${paneQ}`}"${shown !== "chat" ? raw(' aria-current="page"') : null}>Preview</a></nav>` : null; |
| 719 | 720 | const body = html`<div class="talk-page" data-shell${!split ? null : html` data-frame-origins="${frames.join(" ")}"`} data-pane="${shown}"${listing ? raw(" data-view=\"list\"") : null}${split ? raw(" data-split") : null}><h1 class="sr-only">Talk</h1> |
| 720 | 721 | <div class="talk-side">${chats(ctx, conversation, showArchived, typed)}</div> |
| 721 | <div class="talk" data-talk data-density="${display.density}" data-motion="${display.motion}" data-enter="${display.enter}" data-fold="${display.steps}" data-user="${user.id}" data-c="${conversation.id}" data-here="${here}" data-paged="${paged ? "1" : "0"}" data-running="${running && !paged ? "1" : "0"}"> | |
| 722 | <div class="talk" data-talk data-density="${display.density}" data-motion="${display.motion}" data-enter="${display.enter}" data-fold="${display.steps}" data-user="${user.id}" data-c="${conversation.id}" data-here="${here}" data-paged="${paged ? "1" : "0"}"${left === undefined || !turns.some((t) => t.id === left) ? null : html` data-place="t-${left}"`} data-running="${running && !paged ? "1" : "0"}"> | |
| 722 | 723 | ${hereBar(ctx, conversation, context, display, tabs)} |
| 723 | 724 | ${pinnedPlan(conversation.id, conversationPlan(ctx.app.db, conversation.id))} |
| 724 | 725 | ${turns.length === DEFAULT_PAGE && turns[0] !== undefined |
| @@ -793,8 +794,13 @@ export function talkView(ctx: Ctx): Response | Promise<Response> { | ||
| 793 | 794 | const before = ctx.url.searchParams.get("before"); |
| 794 | 795 | const conversation = conversationOf(ctx, ctx.auth.user); |
| 795 | 796 | if (conversation === undefined) return notFoundPage(ctx); |
| 797 | // Opening a conversation keeps it as the place they left (#18317); the pane and build fragments | |
| 798 | // are not an opening. Coming back to /talk, the screen's top turn is where it opens; a | |
| 799 | // conversation named by its address opens at its end. | |
| 800 | const kept = ctx.url.searchParams.get("fragment") === null ? keepOpen(ctx.app.db, ctx.auth.user.id, conversation.id) : ""; | |
| 801 | const left = ctx.params["id"] === undefined && kept !== "" && TURN_ID.test(kept) && !ctx.url.searchParams.has("turn") && before === null && ctx.url.searchParams.get("edit") !== "1" ? kept : undefined; | |
| 796 | 802 | return timePhase(ctx.request, "render", () => |
| 797 | talkPage(ctx, conversation, before !== null && TURN_ID.test(before) && before !== "" ? before : undefined, ctx.params["id"] === undefined, ctx.url.searchParams.get("edit") === "1" && before === null), | |
| 803 | talkPage(ctx, conversation, before !== null && TURN_ID.test(before) && before !== "" ? before : undefined, ctx.params["id"] === undefined, ctx.url.searchParams.get("edit") === "1" && before === null, left), | |
| 798 | 804 | ); |
| 799 | 805 | } |
| 800 | 806 | |
| @@ -861,6 +867,19 @@ export async function talkNew(ctx: Ctx): Promise<Response> { | ||
| 861 | 867 | return redirect(urlOf(made.value)); |
| 862 | 868 | } |
| 863 | 869 | |
| 870 | // POST /talk/place — where the screen is: the conversation and its top turn ('' for the end). The | |
| 871 | // page sends it as it is left; a conversation or turn that is not theirs keeps nothing. | |
| 872 | export async function talkPlace(ctx: Ctx): Promise<Response> { | |
| 873 | const user = ctx.auth.user; | |
| 874 | if (user === undefined) return new Response(null, { status: 401 }); | |
| 875 | const form = await readForm(ctx, "rw"); | |
| 876 | if (form instanceof Response) return form; | |
| 877 | const c = form.get("c"); | |
| 878 | const t = form.get("turn") ?? ""; | |
| 879 | if (typeof c !== "string" || !CONVERSATION_ID.test(c) || typeof t !== "string" || (t !== "" && !TURN_ID.test(t))) return new Response(null, { status: 400 }); | |
| 880 | return new Response(null, { status: keepScroll(ctx.app.db, user.id, c, t) ? 204 : 404 }); | |
| 881 | } | |
| 882 | ||
| 864 | 883 | // POST /talk/:id/rename — the title from the form; an empty one clears it. |
| 865 | 884 | export async function talkRename(ctx: Ctx): Promise<Response> { |
| 866 | 885 | const user = ctx.auth.user; |
src/web/pages/talk_client.ts +14
| @@ -526,6 +526,20 @@ if (root) { | ||
| 526 | 526 | const toEnd = () => { const s = sc(); s.scrollTo({ top: s.scrollHeight, behavior: "instant" }); lastTop = s.scrollTop; lastH = grown = s.scrollHeight; }; |
| 527 | 527 | const resume = () => { stuck = true; fresh = false; toEnd(); draw(); }; |
| 528 | 528 | const detach = () => { if (stuck) { stuck = false; lastTop = sc().scrollTop; grown = sc().scrollHeight; draw(); } }; |
| 529 | // Where they left (#18317): the turn at the top of the screen goes to the server as the page is | |
| 530 | // left or after the scroll rests, and a page opened with data-place starts on that turn. | |
| 531 | const saveAt = () => { | |
| 532 | if (!navigator.sendBeacon || root.dataset.paged === "1" && !root.dataset.place) return; | |
| 533 | const top = sc() === root ? root.getBoundingClientRect().top : 0; | |
| 534 | let turn = ""; | |
| 535 | if (!atEnd()) for (const li of log.querySelectorAll('.talk-turn[id^="t-"]')) if (li.getBoundingClientRect().bottom > top + 1) { turn = li.id.slice(2); break; } | |
| 536 | navigator.sendBeacon("/talk/place", new URLSearchParams({ c: root.dataset.c, turn })); | |
| 537 | }; | |
| 538 | let rest = 0; | |
| 539 | document.addEventListener("scroll", () => { clearTimeout(rest); rest = setTimeout(saveAt, 600); }, { capture: true, passive: true }); | |
| 540 | addEventListener("pagehide", saveAt); | |
| 541 | const placed = root.dataset.place && document.getElementById(root.dataset.place); | |
| 542 | if (placed) { stuck = false; const go = () => placed.scrollIntoView({ block: "start", behavior: "instant" }); go(); addEventListener("load", go); } | |
| 529 | 543 | // Whatever moves the end is followed, not only the log: the composer wrapping its buttons, the |
| 530 | 544 | // status or error line, chips, a font arriving. The new-message dot is for the log alone. |
| 531 | 545 | const sizes = new window.ResizeObserver((seen) => { |
test/talk-links-click.test.ts +1 −1
| @@ -317,7 +317,7 @@ describe("the live stream", () => { | ||
| 317 | 317 | if (!asked.ok) throw new Error(asked.error); |
| 318 | 318 | appendTurn(app.db, bob.id, c.value.id, { role: "agent", text: "It is alice/lighthouse#1, at https://example.com/a." }); |
| 319 | 319 | const text = await ( |
| 320 | await fetch(`${servers.url}/talk/stream?after=${asked.value.id}`, { headers: { cookie: `forge_session=${createSession(app.db, bob.id).token}` } }) | |
| 320 | await fetch(`${servers.url}/talk/stream?c=${c.value.id}&after=${asked.value.id}`, { headers: { cookie: `forge_session=${createSession(app.db, bob.id).token}` } }) | |
| 321 | 321 | ).text(); |
| 322 | 322 | const turns = [...text.matchAll(/^event: turn\ndata: (.*)$/gm)].map((m) => (JSON.parse(m[1]!) as { html: string }).html); |
| 323 | 323 | expect(turns.join("")).toContain('<a href="/alice/lighthouse/issues/1">alice/lighthouse#1</a>'); |
test/talk-place.test.ts added +112
| @@ -0,0 +1,112 @@ | ||
| 1 | /** | |
| 2 | * Talk opens where the person left it (#18317): the conversation and the turn at the top of the | |
| 3 | * screen are kept per person on the server, so reloads and a new sign-in land there. | |
| 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 { createApp, type App } from "../src/app.ts"; | |
| 10 | import { appendTurn, archiveConversation, createConversation, dropConversation, openConversation } from "../src/core/conversations.ts"; | |
| 11 | import { createSession } from "../src/core/sessions.ts"; | |
| 12 | import { createUser, type User } from "../src/core/users.ts"; | |
| 13 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 14 | import { promote } from "./helpers/members.ts"; | |
| 15 | import { quietLogs } from "./helpers/globals.ts"; | |
| 16 | ||
| 17 | quietLogs(); | |
| 18 | ||
| 19 | let dir: string; | |
| 20 | let app: App; | |
| 21 | let servers: Servers; | |
| 22 | let alice: User; | |
| 23 | let bob: User; | |
| 24 | ||
| 25 | const cookieOf = (u: User) => `forge_session=${createSession(app.db, u.id).token}`; | |
| 26 | const get = (path: string, cookie: string) => fetch(`${servers.url}${path}`, { redirect: "manual", headers: { cookie } }); | |
| 27 | const place = (cookie: string, form: Record<string, string>) => | |
| 28 | fetch(`${servers.url}/talk/place`, { method: "POST", redirect: "manual", headers: { origin: servers.url, cookie }, body: new URLSearchParams(form) }); | |
| 29 | ||
| 30 | beforeAll(async () => { | |
| 31 | dir = await mkdtemp(join(tmpdir(), "forge-talk-place-")); | |
| 32 | app = createApp({ dataDir: dir, port: 0 }); | |
| 33 | servers = await serve(app); | |
| 34 | const mk = async (username: string, first: boolean) => { | |
| 35 | const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first }); | |
| 36 | if (!u.ok) throw new Error(u.error); | |
| 37 | promote(app.db, u.value); | |
| 38 | return u.value; | |
| 39 | }; | |
| 40 | alice = await mk("alice", true); | |
| 41 | bob = await mk("bob", false); | |
| 42 | }); | |
| 43 | afterAll(async () => { | |
| 44 | await servers.stop(); | |
| 45 | app.db.close(); | |
| 46 | await rm(dir, { recursive: true, force: true }); | |
| 47 | }); | |
| 48 | ||
| 49 | const marker = (id: string) => `data-c="${id}"`; | |
| 50 | ||
| 51 | test("a conversation opened is the one /talk opens: three reloads and a new sign-in", async () => { | |
| 52 | const first = createConversation(app.db, alice.id).value; | |
| 53 | const second = createConversation(app.db, alice.id).value; | |
| 54 | appendTurn(app.db, alice.id, first.id, { role: "person", text: "older words" }); | |
| 55 | appendTurn(app.db, alice.id, second.id, { role: "person", text: "newer words" }); | |
| 56 | const cookie = cookieOf(alice); | |
| 57 | // Without a place, /talk opens the most recently active one. | |
| 58 | expect(await (await get("/talk", cookie)).text()).toContain(marker(second.id)); | |
| 59 | // Opening the older one keeps it. | |
| 60 | expect((await get(`/talk/${first.id}`, cookie)).status).toBe(200); | |
| 61 | for (let i = 0; i < 3; i++) expect(await (await get("/talk", cookie)).text()).toContain(marker(first.id)); | |
| 62 | // A new sign-in is a new session: the place is the person's, not the browser's. | |
| 63 | expect(await (await get("/talk", cookieOf(alice))).text()).toContain(marker(first.id)); | |
| 64 | }); | |
| 65 | ||
| 66 | test("the scroll place is kept, validated, and opens on that turn", async () => { | |
| 67 | const c = createConversation(app.db, alice.id).value; | |
| 68 | const turns = [1, 2, 3].map((n) => appendTurn(app.db, alice.id, c.id, { role: "person", text: `line ${n}` })); | |
| 69 | const mid = (turns[1] as { value: { id: string } }).value.id; | |
| 70 | const cookie = cookieOf(alice); | |
| 71 | await get(`/talk/${c.id}`, cookie); | |
| 72 | expect((await place(cookie, { c: c.id, turn: mid })).status).toBe(204); | |
| 73 | const page = await (await get("/talk", cookie)).text(); | |
| 74 | expect(page).toContain(marker(c.id)); | |
| 75 | expect(page).toContain(`data-place="t-${mid}"`); | |
| 76 | // Bad input, another person's conversation and a turn that is not in it keep nothing. | |
| 77 | expect((await place(cookie, { c: "../x", turn: "" })).status).toBe(400); | |
| 78 | expect((await place(cookie, { c: c.id, turn: "NOPE!" })).status).toBe(400); | |
| 79 | expect((await place(cookie, { c: c.id, turn: "zzzzzz" })).status).toBe(404); | |
| 80 | const theirs = createConversation(app.db, bob.id).value; | |
| 81 | expect((await place(cookie, { c: theirs.id, turn: "" })).status).toBe(404); | |
| 82 | expect(await (await get("/talk", cookie)).text()).toContain(marker(c.id)); | |
| 83 | // Another site cannot move it. | |
| 84 | const cross = await fetch(`${servers.url}/talk/place`, { method: "POST", redirect: "manual", headers: { origin: "https://evil.example", cookie }, body: new URLSearchParams({ c: c.id, turn: "" }) }); | |
| 85 | expect(cross.status).toBe(403); | |
| 86 | }); | |
| 87 | ||
| 88 | test("an archived or deleted conversation falls back, and an empty one focuses the box", async () => { | |
| 89 | const c = createConversation(app.db, bob.id).value; | |
| 90 | const cookie = cookieOf(bob); | |
| 91 | await get(`/talk/${c.id}`, cookie); | |
| 92 | expect(openConversation(app.db, bob.id).id).toBe(c.id); | |
| 93 | archiveConversation(app.db, bob.id, c.id, true); | |
| 94 | expect(openConversation(app.db, bob.id).id).not.toBe(c.id); | |
| 95 | const d = createConversation(app.db, bob.id).value; | |
| 96 | await get(`/talk/${d.id}`, cookie); | |
| 97 | dropConversation(app.db, bob.id, d.id); | |
| 98 | const page = await (await get("/talk", cookie)).text(); | |
| 99 | expect(page).not.toContain(marker(d.id)); | |
| 100 | expect(page).toContain("autofocus"); | |
| 101 | }); | |
| 102 | ||
| 103 | test("the leave-beacon of the page just left does not move the place back", async () => { | |
| 104 | const a = createConversation(app.db, alice.id).value; | |
| 105 | const b = createConversation(app.db, alice.id).value; | |
| 106 | const turn = appendTurn(app.db, alice.id, a.id, { role: "person", text: "words" }) as { value: { id: string } }; | |
| 107 | const cookie = cookieOf(alice); | |
| 108 | await get(`/talk/${a.id}`, cookie); | |
| 109 | await get(`/talk/${b.id}`, cookie); | |
| 110 | expect((await place(cookie, { c: a.id, turn: turn.value.id })).status).toBe(404); | |
| 111 | expect(await (await get("/talk", cookie)).text()).toContain(marker(b.id)); | |
| 112 | }); |
test/talk-preview-frame.test.ts +14 −11
| @@ -50,13 +50,14 @@ let alice: User; | ||
| 50 | 50 | let bob: User; |
| 51 | 51 | const cookies: Record<string, string> = {}; |
| 52 | 52 | |
| 53 | const talkFor = (userId: string, repo: string): void => { | |
| 53 | const talkFor = (userId: string, repo: string): string => { | |
| 54 | 54 | const made = createConversation(app.db, userId); |
| 55 | 55 | const chat = made.value; |
| 56 | 56 | const [owner = "", name = ""] = repo.split("/"); |
| 57 | 57 | startChatBuild(app.db, chat.id, getRepo(app.db, owner, name)!.id); |
| 58 | 58 | appendTurn(app.db, userId, chat.id, { role: "person", text: "show me the app" }); |
| 59 | 59 | appendTurn(app.db, userId, chat.id, { role: "agent", text: "Here it is." }); |
| 60 | return chat.id; | |
| 60 | 61 | }; |
| 61 | 62 | |
| 62 | 63 | beforeAll(async () => { |
| @@ -100,14 +101,14 @@ afterAll(async () => { | ||
| 100 | 101 | // The check runs in a cell whose proxy (in the environment) is for the world: this browser only |
| 101 | 102 | // visits the forge's own listener, directly, as a look's browser does (`lookFlags`). |
| 102 | 103 | const FLAGS = ["--no-proxy-server", `--host-resolver-rules=MAP ${DOMAIN} 127.0.0.1, MAP *.${DOMAIN} 127.0.0.1`]; |
| 103 | const talk = async (as: "alice" | "bob") => { | |
| 104 | const talk = async (as: "alice" | "bob", id: string) => { | |
| 104 | 105 | // The pane frames an app only while its page, rendered by the forge, says so: ask for that page |
| 105 | 106 | // as the browser will, and wait for the frame to be in it (#18309: the look came back with no |
| 106 | 107 | // frame at all, once, under a loaded suite). Bob is never given one, so nothing is waited for. |
| 107 | 108 | if (as === "alice") { |
| 108 | 109 | let page = ""; |
| 109 | 110 | const drawn = async (): Promise<boolean> => { |
| 110 | const answer = await fetchAsHost(servers, `${DOMAIN}:${servers.port}`, "/talk", { headers: { cookie: `forge_session=${cookies[as]}`, accept: "text/html" } }); | |
| 111 | const answer = await fetchAsHost(servers, `${DOMAIN}:${servers.port}`, `/talk/${id}`, { headers: { cookie: `forge_session=${cookies[as]}`, accept: "text/html" } }); | |
| 111 | 112 | page = await answer.text(); |
| 112 | 113 | return page.includes("data-frame "); |
| 113 | 114 | }; |
| @@ -115,9 +116,11 @@ const talk = async (as: "alice" | "bob") => { | ||
| 115 | 116 | throw new Error(`${String(e)}; the stage said: ${/data-stage-note[^>]*>([^<]*)/.exec(page)?.[1] ?? "(no stage)"}`); |
| 116 | 117 | }); |
| 117 | 118 | } |
| 118 | return look(as); | |
| 119 | return look(as, id); | |
| 119 | 120 | }; |
| 120 | const look = (as: "alice" | "bob") => framesLoaded(chromium!, `${origin}/talk`, [{ name: "forge_session", value: cookies[as]!, url: origin }], FLAGS); | |
| 121 | // A conversation is named by its address: bare /talk opens the one the person last visited | |
| 122 | // (#18317). | |
| 123 | const look = (as: "alice" | "bob", id: string) => framesLoaded(chromium!, `${origin}/talk/${id}`, [{ name: "forge_session", value: cookies[as]!, url: origin }], FLAGS); | |
| 121 | 124 | |
| 122 | 125 | describe("an app's answer", () => { |
| 123 | 126 | test("is framed by the forge's own origin and no other", async () => { |
| @@ -210,23 +213,23 @@ describe("the grant in the frame's address", () => { | ||
| 210 | 213 | |
| 211 | 214 | describe("the pane's frame", () => { |
| 212 | 215 | test.skipIf(chromium === undefined)("draws a public app", async () => { |
| 213 | talkFor(alice.id, "alice/pub"); | |
| 214 | const frames = await talk("alice"); | |
| 216 | const id = talkFor(alice.id, "alice/pub"); | |
| 217 | const frames = await talk("alice", id); | |
| 215 | 218 | expect(frames).toHaveLength(1); |
| 216 | 219 | expect(frames[0]!.refused).toBe(false); |
| 217 | 220 | expect(frames[0]!.url).toContain(`pub.${DOMAIN}`); |
| 218 | 221 | }, 60_000); |
| 219 | 222 | |
| 220 | 223 | test.skipIf(chromium === undefined)("draws a private app for its owner", async () => { |
| 221 | talkFor(alice.id, "alice/priv"); | |
| 222 | const frames = await talk("alice"); | |
| 224 | const id = talkFor(alice.id, "alice/priv"); | |
| 225 | const frames = await talk("alice", id); | |
| 223 | 226 | expect(frames).toHaveLength(1); |
| 224 | 227 | expect(frames[0]!.refused).toBe(false); |
| 225 | 228 | expect(frames[0]!.url).toContain(`priv.${DOMAIN}`); |
| 226 | 229 | }, 60_000); |
| 227 | 230 | |
| 228 | 231 | test.skipIf(chromium === undefined)("draws nothing for a person who may not read the repository", async () => { |
| 229 | talkFor(bob.id, "alice/priv"); | |
| 230 | expect(await talk("bob")).toHaveLength(0); | |
| 232 | const id = talkFor(bob.id, "alice/priv"); | |
| 233 | expect(await talk("bob", id)).toHaveLength(0); | |
| 231 | 234 | }, 60_000); |
| 232 | 235 | }); |
new above
offline
High. keepScroll also sets conversation_id. The client sends its beacon on pagehide, which fires after the next page's response arrives. Click chat B in the list while in chat A: GET /talk/B runs keepOpen(B), then A's pagehide beacon posts c=A and moves the place back to A. Core flow broken, and no test covers it because no browser is involved. Fix: the scroll write must only update the turn while talk_place.conversation_id already equals c (UPDATE ... WHERE user_id=? AND conversation_id=?; no upsert, return 204 or 404 by the changed row count), so only opening a conversation moves the place. Add a test: keepOpen(A), keepOpen(B), then POST /talk/place for A must leave /talk on B.