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

opened this

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

  • Merged. scout/18317-talk-opens-on-the-conversation-the-perso was merged into main as 3eab8eb.

Review

Sign in to review this change.
13 files changed +242 −20
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 {
121121 }
122122
123123 /**
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.
126126 */
127127 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);
128133 const row = db
129134 .query("SELECT * FROM conversation WHERE user_id = ?1 AND archived_at IS NULL ORDER BY updated_at DESC, rowid DESC LIMIT 1")
130135 .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;
outdated

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.

39 }
src/http/lazy_lists.ts +1
@@ -1185,6 +1185,7 @@ export const TALK_ROUTES = [
11851185 ["POST", "/talk/undo/:turn"],
11861186 ["POST", "/talk/act"],
11871187 ["POST", "/talk/new"],
1188 ["POST", "/talk/place"],
11881189 ["POST", "/talk/display"],
11891190 ["POST", "/talk/build"],
11901191 ["POST", "/talk/dev"],
src/http/routes/talk.ts +2 −1
@@ -2,7 +2,7 @@
22 * Talking to the crew: the conversations, their stream and what they do.
33 */
44
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";
66 import { peekRoute } from "../../web/peek.ts";
77 import { talkBuild, talkRestore, talkPublish } from "../../web/talk_build.ts";
88 import { talkWorkCommit, talkWorkDiscard, talkWorkPull, talkWorkSave, talkWorkTest } from "../../web/talk_tree.ts";
@@ -23,6 +23,7 @@ export function talkRoutes(router: Router<Handler>): void {
2323 router.add("POST", "/talk/undo/:turn", talkUndo);
2424 router.add("POST", "/talk/act", talkAct);
2525 router.add("POST", "/talk/new", talkNew);
26 router.add("POST", "/talk/place", talkPlace);
2627 router.add("POST", "/talk/display", talkDisplaySave);
2728 router.add("POST", "/talk/build", talkBuild);
2829 router.add("POST", "/talk/dev", talkDev);
src/tui/screens/talk_chats.ts +2
@@ -29,6 +29,7 @@ import {
2929 TITLE_MAX,
3030 type Conversation,
3131 } from "../../core/conversations.ts";
32 import { keepOpen } from "../../core/talk_place.ts";
3233 import { conversationMarkdown } from "../../core/conversation_markdown.ts";
3334 import { publicOrigin } from "../../core/public_origin.ts";
3435 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
164165 let receipts: ReadonlyMap<string, LiveReceipt> = new Map();
165166 const load = (): void => {
166167 if (f.user === undefined) return;
168 keepOpen(f.app.db, f.user.id, chat.id);
167169 const before = around === undefined ? undefined : pageAround(f.app.db, f.user.id, chat.id, around);
168170 const listed = listTurns(f.app.db, f.user.id, chat.id, { limit: 50, ...(before === undefined ? {} : { before }) });
169171 turns = listed.ok ? listed.value : [];
src/web/pages/talk.ts +24 −5
@@ -42,6 +42,7 @@ import {
4242 turnsAfter,
4343 type Turn,
4444 } from "../../core/conversations.ts";
45 import { keepOpen, keepScroll } from "../../core/talk_place.ts";
4546 import { conversationMarkdown } from "../../core/conversation_markdown.ts";
4647 import { contextOf, contextText, conversationTotal, spendWords, totalText, turnSpend, type Spend, type Context } from "../../core/conversation_cost.ts";
4748 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
607608 </li>`;
608609 }
609610
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> {
611612 const user = ctx.auth.user!;
612613 let before = before0;
613614 const here = latest ? HERE : urlOf(conversation);
614615 const showArchived = latest && ctx.url.searchParams.get("archived") === "1";
615616 const typed = (ctx.url.searchParams.get("find") ?? "").slice(0, FIND_CHARS);
616617 // 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;
618619 // Near the end pageAround has no `before`: that is the latest page, unpaged, and the fragment
619620 // still lands.
620621 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 |
714715 // The model picker (`talk_model.ts`), only where a connection offers a model.
715716 const picker = modelPicker(ctx, user, urlOf(conversation), conversation.id, { builds: buildMode, empty });
716717 // 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>`;
718719 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;
719720 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>
720721 <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"}">
722723 ${hereBar(ctx, conversation, context, display, tabs)}
723724 ${pinnedPlan(conversation.id, conversationPlan(ctx.app.db, conversation.id))}
724725 ${turns.length === DEFAULT_PAGE && turns[0] !== undefined
@@ -793,8 +794,13 @@ export function talkView(ctx: Ctx): Response | Promise<Response> {
793794 const before = ctx.url.searchParams.get("before");
794795 const conversation = conversationOf(ctx, ctx.auth.user);
795796 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;
796802 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),
798804 );
799805 }
800806
@@ -861,6 +867,19 @@ export async function talkNew(ctx: Ctx): Promise<Response> {
861867 return redirect(urlOf(made.value));
862868 }
863869
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
864883 // POST /talk/:id/rename — the title from the form; an empty one clears it.
865884 export async function talkRename(ctx: Ctx): Promise<Response> {
866885 const user = ctx.auth.user;
src/web/pages/talk_client.ts +14
@@ -526,6 +526,20 @@ if (root) {
526526 const toEnd = () => { const s = sc(); s.scrollTo({ top: s.scrollHeight, behavior: "instant" }); lastTop = s.scrollTop; lastH = grown = s.scrollHeight; };
527527 const resume = () => { stuck = true; fresh = false; toEnd(); draw(); };
528528 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); }
529543 // Whatever moves the end is followed, not only the log: the composer wrapping its buttons, the
530544 // status or error line, chips, a font arriving. The new-message dot is for the log alone.
531545 const sizes = new window.ResizeObserver((seen) => {
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;
5050 let bob: User;
5151 const cookies: Record<string, string> = {};
5252
53 const talkFor = (userId: string, repo: string): void => {
53 const talkFor = (userId: string, repo: string): string => {
5454 const made = createConversation(app.db, userId);
5555 const chat = made.value;
5656 const [owner = "", name = ""] = repo.split("/");
5757 startChatBuild(app.db, chat.id, getRepo(app.db, owner, name)!.id);
5858 appendTurn(app.db, userId, chat.id, { role: "person", text: "show me the app" });
5959 appendTurn(app.db, userId, chat.id, { role: "agent", text: "Here it is." });
60 return chat.id;
6061 };
6162
6263 beforeAll(async () => {
@@ -100,14 +101,14 @@ afterAll(async () => {
100101 // The check runs in a cell whose proxy (in the environment) is for the world: this browser only
101102 // visits the forge's own listener, directly, as a look's browser does (`lookFlags`).
102103 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) => {
104105 // The pane frames an app only while its page, rendered by the forge, says so: ask for that page
105106 // as the browser will, and wait for the frame to be in it (#18309: the look came back with no
106107 // frame at all, once, under a loaded suite). Bob is never given one, so nothing is waited for.
107108 if (as === "alice") {
108109 let page = "";
109110 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" } });
111112 page = await answer.text();
112113 return page.includes("data-frame ");
113114 };
@@ -115,9 +116,11 @@ const talk = async (as: "alice" | "bob") => {
115116 throw new Error(`${String(e)}; the stage said: ${/data-stage-note[^>]*>([^<]*)/.exec(page)?.[1] ?? "(no stage)"}`);
116117 });
117118 }
118 return look(as);
119 return look(as, id);
119120 };
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);
121124
122125 describe("an app's answer", () => {
123126 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", () => {
210213
211214 describe("the pane's frame", () => {
212215 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);
215218 expect(frames).toHaveLength(1);
216219 expect(frames[0]!.refused).toBe(false);
217220 expect(frames[0]!.url).toContain(`pub.${DOMAIN}`);
218221 }, 60_000);
219222
220223 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);
223226 expect(frames).toHaveLength(1);
224227 expect(frames[0]!.refused).toBe(false);
225228 expect(frames[0]!.url).toContain(`priv.${DOMAIN}`);
226229 }, 60_000);
227230
228231 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);
231234 }, 60_000);
232235 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs