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

Speed up four slow test files: route-marks, api-hints, here-pages, talk-phone #17364

opened this

Merged 41h ago, live in production

scout/forge:scout/17361-speed-up-four-slow-test-files-route-mark → main 0 commits fork

  • Merged. scout/17361-speed-up-four-slow-test-files-route-mark was merged into main as 90d6ee2.

Review

Sign in to review this change.
8 files changed +561 −491
test/api-hints.test.ts +26 −19
@@ -48,26 +48,33 @@ describe("refusals carry a hint", () => {
4848 await rm(dataDir, { recursive: true, force: true });
4949 });
5050
51 test("every OpenAPI route, called badly, answers a hint on 401/403/404/409/422", async () => {
52 const seen = new Set<number>();
53 for (const r of ROUTES) {
54 const path = r.path.replace(/\{[^}]+\}/g, "nope");
55 for (const auth of [null, token]) {
56 const res = await fetch(`${servers.url}${path}`, {
57 method: r.method.toUpperCase(),
58 headers: { accept: "application/json", "content-type": "application/json", ...(auth ? { authorization: `Bearer ${auth}` } : {}) },
59 ...(r.method === "get" ? {} : { body: "{}" }),
60 });
61 if (!HINTED.has(res.status)) continue;
62 const text = await res.text();
63 let body: { hint?: unknown } | null = null;
64 try { body = JSON.parse(text); } catch { continue; } // a page, not an API answer
65 if (body === null || typeof (body as { error?: unknown }).error !== "string") continue;
66 seen.add(res.status);
67 expect(typeof body.hint, `${r.method} ${r.path} -> ${res.status}`).toBe("string");
68 expect((body.hint as string).trim().length, `${r.method} ${r.path}`).toBeGreaterThan(0);
51 // The walk is split in eight tests, each an eighth of the routes, so none nears the 2 s budget
52 // (#17361).
53 const CHUNKS = 8;
54 for (let k = 0; k < CHUNKS; k++) {
55 test(`every OpenAPI route, called badly, answers a hint on 401/403/404/409/422 (${k + 1} of ${CHUNKS})`, async () => {
56 for (const r of ROUTES.filter((_, i) => i % CHUNKS === k)) {
57 const path = r.path.replace(/\{[^}]+\}/g, "nope");
58 for (const auth of [null, token]) {
59 const res = await fetch(`${servers.url}${path}`, {
60 method: r.method.toUpperCase(),
61 headers: { accept: "application/json", "content-type": "application/json", ...(auth ? { authorization: `Bearer ${auth}` } : {}) },
62 ...(r.method === "get" ? {} : { body: "{}" }),
63 });
64 if (!HINTED.has(res.status)) continue;
65 const text = await res.text();
66 let body: { hint?: unknown } | null = null;
67 try { body = JSON.parse(text); } catch { continue; } // a page, not an API answer
68 if (body === null || typeof (body as { error?: unknown }).error !== "string") continue;
69 expect(typeof body.hint, `${r.method} ${r.path} -> ${res.status}`).toBe("string");
70 expect((body.hint as string).trim().length, `${r.method} ${r.path}`).toBeGreaterThan(0);
71 }
6972 }
70 }
73 }, 120_000);
74 }
75
76 test("calls built to provoke each of 401/403/404/409/422 each answer a hint", async () => {
77 const seen = new Set<number>();
7178 // Calls built to provoke each status, so the walk cannot pass by seeing only two.
7279 const provoked: Record<string, Response> = {
7380 "401 no token": await call("POST", "/api/v1/repos", null, { name: "x" }),
test/helpers/talk-phone.ts added +456
@@ -0,0 +1,456 @@
1 /**
2 * The fixture of the Talk-on-a-phone tests, shared by test/talk-phone.test.ts and one file a width
3 * (test/talk-phone-360.test.ts, -375, -390): the file was 21 s of CPU against its 20 s budget
4 * (#17361).
5 *
6 * Talk on a phone (#16442, #16560), measured in a real Chromium at 360, 375 and 390 px with a
7 * finger:
8 * the head is one row (the list, the title, the model picker, the tabs, the menu and New) and
9 * nothing in it wraps; the composer does not move as the status line or the tool-call count change;
10 * the chat list opens at its top on the newest chat; the "answering" line ends with the answer; a
11 * long chat reads oldest to newest and opens on the newest; Earlier puts the older turns above in
12 * order and keeps the turn being read where it was, even while a reply arrives; a wide table
13 * scrolls inside its bubble, never the page; the top bar is opaque with the head clear below it,
14 * and the composer stays on screen at the newest end and halfway up.
15 *
16 * Skipped, and says so, where no Chromium starts, except in the forge's own check (`FORGE_CHECK`):
17 * there a missing Chromium fails every browser test, so a green check means they ran (#16560).
18 */
19 import { afterAll, beforeAll, expect, test } from "bun:test";
20 import { mkdtemp, rm } from "node:fs/promises";
21 import { tmpdir } from "node:os";
22 import { join } from "node:path";
23 import { createApp, type App } from "../../src/app.ts";
24 import { saveConnection } from "../../src/core/connections.ts";
25 import {
26 appendTurn,
27 openConversation,
28 createConversation,
29 renameConversation,
30 } from "../../src/core/conversations.ts";
31 import { createSession } from "../../src/core/sessions.ts";
32 import { createUser } from "../../src/core/users.ts";
33 import { findChromium } from "../../src/looks/capture.ts";
34 import { serve, type Servers } from "../../src/http/server.ts";
35 import { chromiumRuns, sharedBrowser, type SharedBrowser } from "./chrome.ts";
36 import { quietLogs } from "./globals.ts";
37 import { promote } from "./members.ts";
38
39 quietLogs();
40 const found = findChromium();
41 const chromium = found !== undefined && chromiumRuns(found) ? found : undefined;
42 /** The forge's own check names its run: there a browser test runs or fails, it never skips. */
43 const inCheck = (process.env["FORGE_CHECK"] ?? "") !== "";
44 export const skip = chromium === undefined && !inCheck;
45 if (skip)
46 console.log(
47 "SKIPPING: no chromium that starts on this machine, so Talk on a phone is not measured",
48 );
49
50 export const WIDTHS = [360, 375, 390] as const;
51 let dir: string;
52 export let app: App;
53 export let servers: Servers;
54 export let token: string;
55 export let aliceId: string;
56 export let shortId: string;
57 export let manyId: string;
58 export let longId: string;
59 export let listToken: string;
60 /**
61 * One Chromium for the file, a fresh browser context per page: the 29 pages each started their own
62 * and the file took 24 to 42 s against its 20 s budget in the check.
63 */
64 let browser: SharedBrowser | undefined;
65
66 const toolTurns = (userId: string, id: string, n: number): void => {
67 appendTurn(app.db, userId, id, { role: "person", text: "change the title" });
68 for (let i = 0; i < n; i++)
69 appendTurn(app.db, userId, id, { role: "tool", text: `step ${i}` });
70 appendTurn(app.db, userId, id, { role: "agent", text: "Done." });
71 };
72 const TABLE =
73 "| Pull | What it does |\n|---|---|\n| #16552 | `a-very-long-identifier-that-never-wraps-anywhere-on-a-phone` and more words |\n| #16561 | Earlier keeps the place |";
74
75 beforeAll(async () => {
76 dir = await mkdtemp(join(tmpdir(), "forge-talk-phone-"));
77 app = createApp({ dataDir: dir, port: 0 });
78 servers = await serve(app);
79 const made = await createUser(app.db, {
80 origin: "seed",
81 trusted: true,
82 username: "alice",
83 email: "[email protected]",
84 password: "a-good-passphrase",
85 adminIfFirst: true,
86 });
87 if (!made.ok) throw new Error(made.error);
88 promote(app.db, made.value);
89 aliceId = made.value.id;
90 token = createSession(app.db, aliceId).token;
91 // A connection that offers models, so the head carries the picker as it does for the owner.
92 const spark = saveConnection(app.db, app.config.dataDir, {
93 name: "Spark",
94 protocol: "openai",
95 base: "http://127.0.0.1:9/v1",
96 key: "sk-spark",
97 scope: "forge",
98 userId: aliceId,
99 models: [{ id: "canned/small" }, { id: "canned/large-model" }],
100 said: "2 models listed",
101 });
102 if (!spark.ok) throw new Error(spark.error);
103 const a = openConversation(app.db, aliceId);
104 shortId = a.id;
105 renameConversation(
106 app.db,
107 aliceId,
108 shortId,
109 "A short chat whose title is longer than a phone",
110 );
111 toolTurns(aliceId, a.id, 1);
112 const b = createConversation(app.db, aliceId);
113 if (!b.ok) throw new Error(b.error);
114 manyId = b.value.id;
115 toolTurns(aliceId, manyId, 9);
116 // A long chat: 120 turns, one of them a table wider than any phone.
117 const c = createConversation(app.db, aliceId);
118 if (!c.ok) throw new Error(c.error);
119 longId = c.value.id;
120 for (let i = 0; i < 120; i++)
121 appendTurn(app.db, aliceId, longId, {
122 role: i % 2 === 0 ? "person" : "agent",
123 text: i === 101 ? TABLE : `message ${i}`,
124 });
125 // A second person with twenty chats, to see where the list opens.
126 const bob = await createUser(app.db, {
127 origin: "seed",
128 trusted: true,
129 username: "bob",
130 email: "[email protected]",
131 password: "a-good-passphrase",
132 });
133 if (!bob.ok) throw new Error(bob.error);
134 promote(app.db, bob.value);
135 for (let i = 0; i < 20; i++) {
136 const c = createConversation(app.db, bob.value.id);
137 if (!c.ok) throw new Error(c.error);
138 renameConversation(app.db, bob.value.id, c.value.id, `Chat number ${i}`);
139 appendTurn(app.db, bob.value.id, c.value.id, {
140 role: "person",
141 text: "hello",
142 });
143 }
144 listToken = createSession(app.db, bob.value.id).token;
145 }, 30_000);
146 afterAll(async () => {
147 await browser?.close();
148 servers.stop();
149 app.close();
150 await rm(dir, { recursive: true, force: true });
151 });
152
153 export const phone = (
154 width: number,
155 path: string,
156 as: string,
157 expression: string,
158 ): Promise<any> => {
159 if (chromium === undefined)
160 throw new Error(
161 "no Chromium starts in this check, so Talk on a phone is not measured: the check's image must carry one (FORGE_CHROMIUM)",
162 );
163 const started = chromium;
164 return (browser === undefined ? sharedBrowser(started).then((b) => (browser = b)) : Promise.resolve(browser))
165 .then((b) => b.evaluate(`${servers.url}${path}`, { width, height: 740 }, [{ name: "forge_session", value: as }], expression, "light", true))
166 .then((v) => JSON.parse(v));
167 };
168 /** In the page: wait for `f` to hold, checking every 25 ms, at most `ms`. */
169 export const WAIT =
170 "const wait = (f, ms = 6000) => new Promise((ok) => { const t0 = performance.now(); const t = setInterval(() => { if (f() || performance.now() - t0 > ms) { clearInterval(t); ok(); } }, 25); });";
171 /** In the page: the log's turns, in the order a person reads them. */
172 export const IDS =
173 "const ids = () => [...document.querySelectorAll('.talk-log li[id^=\"t-\"]')].map((l) => l.id);";
174
175 /** The browser tests of one width. */
176 export function widthTests(width: (typeof WIDTHS)[number]): void {
177 test.skipIf(skip)(
178 `${width} px: the message box does not ride when the status line speaks, nor with the tool-call count`,
179 async () => {
180 const at = `(async () => {
181 const box = () => document.querySelector(".talk-box").getBoundingClientRect().bottom;
182 const st = document.querySelector(".talk-status"), form = document.querySelector("form.talk-compose");
183 const quiet = box();
184 st.textContent = "The forge replied.";
185 const spoke = box();
186 form.setAttribute("data-answering", "");
187 st.textContent = "The forge is answering…";
188 const busy = box();
189 return JSON.stringify({ quiet, spoke, busy, sw: document.documentElement.scrollWidth, vh: innerHeight });
190 })()`;
191 const few = await phone(width, `/talk/${shortId}`, token, at);
192 const many = await phone(width, `/talk/${manyId}`, token, at);
193 for (const s of [few, many]) {
194 expect(Math.abs(s.spoke - s.quiet)).toBeLessThanOrEqual(1);
195 expect(Math.abs(s.busy - s.quiet)).toBeLessThanOrEqual(1);
196 expect(s.sw).toBeLessThanOrEqual(width);
197 // A short chat's box sits at the foot of the screen, not under the last turn.
198 expect(s.vh - s.quiet).toBeLessThanOrEqual(48);
199 }
200 expect(Math.abs(few.quiet - many.quiet)).toBeLessThanOrEqual(1);
201 },
202 30_000,
203 );
204
205 test.skipIf(skip)(
206 `${width} px: the controls are one 44 px row in the lower half beside the composer, and the head is the title alone`,
207 async () => {
208 const s = await phone(
209 width,
210 `/talk/${shortId}`,
211 token,
212 `(async () => {
213 const frame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
214 const head = document.querySelector(".talk-head"), dock = document.querySelector(".talk-dock");
215 // A chat beside a live preview: the page splits and the dock carries Chat and Preview.
216 document.querySelector(".talk-page").setAttribute("data-split", "");
217 dock.querySelector("form").insertAdjacentHTML("afterend", '<nav class="seg talk-tabs" aria-label="Chat or preview"><a href="?pane=chat" aria-current="page">Chat</a><a href="?pane=preview">Preview</a></nav>');
218 await frame();
219 const box = (e) => { const r = e.getBoundingClientRect(); return { top: r.top, bottom: r.bottom, left: r.left, right: r.right, w: r.width, h: r.height, cls: String(e.className || e.tagName), text: (e.getAttribute("aria-label") || e.textContent || "").trim().slice(0, 20) }; };
220 const shown = (e) => e.getBoundingClientRect().width > 0;
221 const d = dock.getBoundingClientRect();
222 const kids = [...dock.querySelectorAll(":scope > *")].filter(shown).map(box);
223 const targets = [...dock.querySelectorAll(":scope > a, :scope > form button, :scope > .talk-tabs a, :scope > .menu > summary")].filter(shown).map(box);
224 const headKids = [...head.querySelectorAll(":scope > *")].filter(shown).map((e) => String(e.className || e.tagName));
225 // The model picker is one tap into the menu, and fits above the dock.
226 dock.querySelector(".menu > summary").click();
227 await frame();
228 const sel = dock.querySelector(".talk-model select"), panel = dock.querySelector(".menu-panel");
229 const model = { sel: box(sel), panel: box(panel), tracked: shown(sel) };
230 const ids = [...document.querySelectorAll("[id]")].map((e) => e.id), dup = ids.filter((x, i) => ids.indexOf(x) !== i);
231 return JSON.stringify({ dock: { top: d.top, bottom: d.bottom, h: d.height }, kids, targets, headKids, model, dup, vh: innerHeight, sw: document.documentElement.scrollWidth });
232 })()`,
233 );
234 const seen = JSON.stringify(s);
235 expect(s.dock.h, seen).toBeLessThanOrEqual(52);
236 expect(s.sw, seen).toBeLessThanOrEqual(width);
237 // Every control is reachable in the lower half, a 44 px target, nothing wrapped or past the
238 // edge.
239 expect(s.dock.top, seen).toBeGreaterThan(s.vh / 2);
240 expect(s.dock.bottom, seen).toBeLessThanOrEqual(s.vh);
241 const top = Math.min(...s.kids.map((k: { top: number }) => k.top));
242 for (const k of s.kids) {
243 expect(k.right, seen).toBeLessThanOrEqual(width);
244 expect(k.left, seen).toBeGreaterThanOrEqual(0);
245 expect(k.bottom, seen).toBeLessThanOrEqual(top + 52);
246 }
247 const names = s.targets.map((k: { text: string }) => k.text).join("|");
248 for (const word of ["Chats", "New conversation", "Chat", "Preview", "Conversation menu"]) expect(names, seen).toContain(word);
249 for (const k of s.targets) {
250 expect(Math.min(k.w, k.h), seen).toBeGreaterThanOrEqual(44);
251 expect(k.top, seen).toBeGreaterThan(s.vh / 2);
252 }
253 // The head keeps the title and nothing else.
254 expect(s.headKids, seen).toEqual(["talk-title"]);
255 // The model: in the menu, in the lower half, 44 px tall, on screen, above the bar.
256 expect(s.model.tracked, seen).toBe(true);
257 expect(s.model.sel.h, seen).toBeGreaterThanOrEqual(44);
258 expect(s.model.sel.right, seen).toBeLessThanOrEqual(width);
259 expect(s.model.panel.bottom, seen).toBeLessThanOrEqual(s.dock.top + 8);
260 expect(s.dup, seen).toEqual([]);
261 },
262 30_000,
263 );
264
265 test.skipIf(skip)(
266 `${width} px: with the keyboard open the dock rides with the composer above it and nothing rides under the keyboard`,
267 async () => {
268 const s = await phone(
269 width,
270 `/talk/${longId}`,
271 token,
272 `(async () => {
273 const frame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
274 await frame();
275 const dock = document.querySelector(".talk-dock"), foot = document.querySelector(".talk-base"), box = document.querySelector(".talk-box"), input = document.querySelector(".talk-input");
276 const at = (where) => ({ where, dockTop: dock.getBoundingClientRect().top, dockBottom: dock.getBoundingClientRect().bottom, boxTop: box.getBoundingClientRect().top, boxBottom: box.getBoundingClientRect().bottom, footTop: foot.getBoundingClientRect().top, last: [...document.querySelectorAll(".talk-log li[id^='t-']")].at(-1).getBoundingClientRect().bottom, kb: getComputedStyle(document.documentElement).getPropertyValue("--kb").trim(), vh: innerHeight });
277 const before = at("closed");
278 // A stand-in keyboard: the visual viewport 300 px shorter while the box is focused.
279 Object.defineProperty(visualViewport, "height", { configurable: true, get: () => innerHeight - 300 });
280 input.focus();
281 visualViewport.dispatchEvent(new Event("resize"));
282 await frame();
283 const open = at("open");
284 return JSON.stringify({ before, open });
285 })()`,
286 );
287 const seen = JSON.stringify(s);
288 expect(s.before.dockBottom, seen).toBeLessThanOrEqual(s.before.boxTop + 1);
289 expect(s.before.boxBottom, seen).toBeLessThanOrEqual(s.before.vh);
290 expect(s.open.kb, seen).toBe("300px");
291 // Both stay above the keyboard and the dock stays above the box.
292 expect(s.open.boxBottom, seen).toBeLessThanOrEqual(s.open.vh - 300 + 1);
293 expect(s.open.dockBottom, seen).toBeLessThanOrEqual(s.open.boxTop + 1);
294 },
295 30_000,
296 );
297
298 test.skipIf(skip)(
299 `${width} px: Chats is a labelled 44 px control in the dock, and it opens the list at its top on the newest chat`,
300 async () => {
301 // Bob's Talk opens on his newest chat; the way to the others is in the dock.
302 const at = await phone(
303 width,
304 `/talk`,
305 listToken,
306 `(() => {
307 const dock = document.querySelector(".talk-dock"), a = [...dock.querySelectorAll("a")].find((x) => x.textContent.trim() === "Chats");
308 if (!a) return JSON.stringify({ found: false, dock: dock.innerText });
309 const r = a.getBoundingClientRect(), h = dock.getBoundingClientRect();
310 return JSON.stringify({ found: true, href: a.getAttribute("href"), w: r.width, h: r.height, left: r.left, right: r.right, top: r.top, bottom: r.bottom, vh: innerHeight, dockTop: h.top, dockBottom: h.bottom, shown: getComputedStyle(a).visibility === "visible" && r.width > 0 });
311 })()`,
312 );
313 const seen = JSON.stringify(at);
314 expect(at.found, seen).toBe(true);
315 expect(at.shown, seen).toBe(true);
316 expect(Math.min(at.w, at.h), seen).toBeGreaterThanOrEqual(44);
317 expect(at.left, seen).toBeGreaterThanOrEqual(0);
318 expect(at.right, seen).toBeLessThanOrEqual(width);
319 expect(at.top, seen).toBeGreaterThan(at.vh / 2);
320 expect(at.bottom, seen).toBeLessThanOrEqual(at.dockBottom);
321 expect(at.href, seen).toEndWith("?chats=1");
322 const list = await phone(width, at.href, listToken, `(async () => { await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); const first = document.querySelector(".talk-list .row"); const r = first.getBoundingClientRect(); return JSON.stringify({ y: scrollY, top: r.top, bottom: r.bottom, vh: innerHeight, text: first.textContent }); })()`);
323 const said = JSON.stringify(list);
324 expect(list.y, said).toBe(0);
325 expect(list.top, said).toBeGreaterThanOrEqual(0);
326 expect(list.bottom, said).toBeLessThanOrEqual(list.vh);
327 expect(list.text, said).toContain("Chat number 19");
328 },
329 30_000,
330 );
331
332 test.skipIf(skip)(
333 `${width} px: the chat list opens at its top, the newest chat in view`,
334 async () => {
335 const s = await phone(
336 width,
337 `/talk?chats=1`,
338 listToken,
339 `(async () => { await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); const first = document.querySelector(".talk-list .row"); const r = first.getBoundingClientRect(); return JSON.stringify({ y: window.scrollY, tall: document.documentElement.scrollHeight > innerHeight, top: r.top, text: first.textContent }); })()`,
340 );
341 const seen = JSON.stringify(s);
342 expect(s.y, seen).toBe(0);
343 expect(s.top, seen).toBeGreaterThanOrEqual(0);
344 expect(s.text, seen).toContain("Chat number 19");
345 expect(s.tall, seen).toBe(true);
346 },
347 30_000,
348 );
349
350 test.skipIf(skip)(
351 `${width} px: a long chat reads oldest to newest, opens on the newest, and a wide table scrolls in its bubble`,
352 async () => {
353 const s = await phone(
354 width,
355 `/talk/${longId}`,
356 token,
357 `(async () => {
358 ${IDS}
359 await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
360 const all = [...document.querySelectorAll(".talk-log li[id^='t-']")], last = all.at(-1).getBoundingClientRect();
361 const texts = all.map((l) => (l.querySelector(".talk-body")?.textContent ?? "").trim());
362 return JSON.stringify({ ids: ids(), texts, y: scrollY, max: document.scrollingElement.scrollHeight - innerHeight, lastBottom: last.bottom, vh: innerHeight, vw: innerWidth, sw: document.documentElement.scrollWidth, table: !!document.querySelector(".talk-body table") });
363 })()`,
364 );
365 const seen = JSON.stringify({
366 ...s,
367 ids: s.ids.length,
368 texts: s.texts.slice(0, 3),
369 });
370 expect(s.ids, seen).toEqual([...s.ids].sort());
371 expect(s.texts[0], seen).toBe("message 70");
372 expect(s.texts.at(-1), seen).toBe("message 119");
373 expect(s.table, seen).toBe(true);
374 // The page is the phone's width: a wide table does not zoom the whole page out.
375 expect(s.vw, seen).toBe(width);
376 expect(s.sw, seen).toBeLessThanOrEqual(width);
377 expect(s.max - s.y, seen).toBeLessThanOrEqual(2);
378 expect(s.lastBottom, seen).toBeLessThanOrEqual(s.vh);
379 },
380 30_000,
381 );
382
383 test.skipIf(skip)(
384 `${width} px: the top bar is opaque with the head clear below it, and the composer stays on screen wherever the thread is`,
385 async () => {
386 const s = await phone(
387 width,
388 `/talk/${longId}`,
389 token,
390 `(async () => {
391 const frame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
392 await frame();
393 const bar = document.querySelector(".topbar"), head = document.querySelector(".talk-head"), box = document.querySelector(".talk-box");
394 const cs = getComputedStyle(bar);
395 // A chat beside a live preview: the head carries Chat and Preview, the tallest thing in it.
396 head.querySelector(".talk-model")?.insertAdjacentHTML("afterend", '<nav class="seg talk-tabs" aria-label="Chat or preview"><a href="?pane=chat" aria-current="page">Chat</a><a href="?pane=preview">Preview</a></nav>');
397 const kids = () => Math.min(...[...head.children].filter((e) => e.getBoundingClientRect().width > 0).map((e) => e.getBoundingClientRect().top));
398 const at = (where) => ({ where, barBottom: bar.getBoundingClientRect().bottom, headTop: head.getBoundingClientRect().top, kidsTop: kids(), boxTop: box.getBoundingClientRect().top, boxBottom: box.getBoundingClientRect().bottom, vh: innerHeight });
399 const end = at("end");
400 scrollTo({ top: document.scrollingElement.scrollHeight / 2, behavior: "instant" });
401 await frame();
402 const middle = at("middle");
403 // The visual viewport changing with nothing typed into (a pinch, a toolbar) is not a keyboard.
404 visualViewport.dispatchEvent(new Event("resize"));
405 await frame();
406 return JSON.stringify({ bg: cs.backgroundColor, blur: cs.backdropFilter, kb: getComputedStyle(document.documentElement).getPropertyValue("--kb").trim(), end, middle });
407 })()`,
408 );
409 const seen = JSON.stringify(s);
410 // Opaque: no alpha in the colour, nothing blurred through it.
411 expect(s.bg, seen).not.toMatch(/\/ 0\.|rgba\(.*, 0\.\d+\)/);
412 expect(s.blur, seen).toBe("none");
413 expect(["", "0px"], seen).toContain(s.kb);
414 for (const p of [s.end, s.middle]) {
415 expect(p.headTop, seen).toBeGreaterThanOrEqual(p.barBottom - 0.5);
416 expect(p.kidsTop, seen).toBeGreaterThanOrEqual(p.barBottom + 1);
417 expect(p.boxBottom, seen).toBeLessThanOrEqual(p.vh);
418 expect(p.boxTop, seen).toBeGreaterThan(p.vh - 140);
419 }
420 },
421 30_000,
422 );
423
424 test.skipIf(skip)(
425 `${width} px: Earlier puts the older turns above in order and the turn being read stays put`,
426 async () => {
427 const s = await phone(
428 width,
429 `/talk/${longId}`,
430 token,
431 `(async () => {
432 ${WAIT} ${IDS}
433 scrollTo({ top: 0, behavior: "instant" });
434 await new Promise((r) => requestAnimationFrame(r));
435 const first = document.querySelector(".talk-log li[id^='t-']"), topBefore = first.getBoundingClientRect().top, url = location.href;
436 document.querySelector("a[data-earlier]").click();
437 await wait(() => ids().length >= 100);
438 // How far the turn being read moved, in pixels: a place, not a time.
439 const shift = Math.abs(first.getBoundingClientRect().top - topBefore);
440 document.querySelector("a[data-earlier]").click();
441 await wait(() => ids().length >= 120);
442 return JSON.stringify({ ids: ids(), shift, same: location.href === url, more: !!document.querySelector("a[data-earlier]"), latest: document.querySelector("[data-jump]").hidden === false });
443 })()`,
444 );
445 const seen = JSON.stringify({ ...s, ids: s.ids.length });
446 expect(s.same, seen).toBe(true);
447 expect(s.ids.length, seen).toBe(120);
448 expect(s.ids, seen).toEqual([...s.ids].sort());
449 expect(new Set(s.ids).size, seen).toBe(120);
450 expect(s.shift, seen).toBeLessThanOrEqual(2);
451 expect(s.more, seen).toBe(false);
452 expect(s.latest, seen).toBe(true);
453 },
454 30_000,
455 );
456 }
test/here-pages.test.ts +31 −20
@@ -14,6 +14,9 @@ beforeAll(async () => {
1414 dir = await mkdtemp(join(tmpdir(), "here-pages-"));
1515 app = createApp({ dataDir: dir, port: 0 });
1616 servers = await serve(app);
17 // The first page and the first picture each load their code once: that cost is the file's, not a
18 // test's.
19 for (const p of ["/", "/og/site.png", "/sitemap.xml"]) await (await fetch(`${servers.url}${p}`)).arrayBuffer();
1720 });
1821 afterAll(async () => {
1922 await servers.stop();
@@ -26,26 +29,34 @@ const here = (p: string) => get(`/api/v1/here?path=${encodeURIComponent(p)}`);
2629 const alternateOf = (res: Response) => /<([^>]+)>; rel="alternate"/.exec(res.headers.get("link") ?? "")?.[1];
2730
2831 describe("the alternate link", () => {
29 test("every literal public page advertises an alternate that answers 200 as exactly its own kind", async () => {
30 const paths = buildRouter()
31 .routes()
32 .filter((r) => r.method === "GET" && !r.pattern.includes(":") && !r.pattern.includes("*") && isPublicPage(r.pattern))
33 .map((r) => r.pattern);
34 expect(paths.length).toBeGreaterThan(10);
35 let followed = 0;
36 const kinds: Record<string, string> = {};
37 for (const p of paths) {
38 const res = await get(p);
39 await res.body?.cancel();
40 const link = alternateOf(res);
41 if (link === undefined) continue; // a file or a redirect, not a page that advertises
42 followed++;
43 const twin = await get(link);
44 expect(`${p} ${twin.status}`).toBe(`${p} 200`);
45 const body = (await twin.json()) as { here: { kind: string; path: string } };
46 kinds[p] = body.here.kind;
47 if (body.here.kind === "page") expect(body.here.path).toBe(p);
48 }
32 const paths = buildRouter()
33 .routes()
34 .filter((r) => r.method === "GET" && !r.pattern.includes(":") && !r.pattern.includes("*") && isPublicPage(r.pattern))
35 .map((r) => r.pattern);
36 // The walk is split in eight tests, each an eighth of the pages, so none nears the 2 s budget
37 // (#17361); the test after them judges what they gathered.
38 const CHUNKS = 8;
39 let followed = 0;
40 const kinds: Record<string, string> = {};
41 for (let k = 0; k < CHUNKS; k++) {
42 test(`every literal public page advertises an alternate that answers 200 as exactly its own kind (${k + 1} of ${CHUNKS})`, async () => {
43 expect(paths.length).toBeGreaterThan(10);
44 for (const p of paths.filter((_, i) => i % CHUNKS === k)) {
45 const res = await get(p);
46 await res.body?.cancel();
47 const link = alternateOf(res);
48 if (link === undefined) continue; // a file or a redirect, not a page that advertises
49 followed++;
50 const twin = await get(link);
51 expect(`${p} ${twin.status}`).toBe(`${p} 200`);
52 const body = (await twin.json()) as { here: { kind: string; path: string } };
53 kinds[p] = body.here.kind;
54 if (body.here.kind === "page") expect(body.here.path).toBe(p);
55 }
56 }, 30_000);
57 }
58
59 test("the pages followed named every kind the forge knows", () => {
4960 expect(followed).toBeGreaterThan(5);
5061 // Exactly the kind the forge already named for a path it knew; a page it did not is `page`.
5162 expect(kinds["/privacy"]).toBe("forge");
test/route-marks.test.ts +21 −15
@@ -165,21 +165,27 @@ describe("every admin-only action refuses the everyday account", () => {
165165 r.status === 403 &&
166166 (api ? JSON.parse(r.text).message === SIGN_IN_AS_ADMIN : r.text.includes(SIGN_IN_AS_ADMIN.replace("'", "&#39;")));
167167
168 test("each admin route refuses the everyday account with the sentence, and lets the admin through", async () => {
169 const admin = routes().filter((r) => markOf(r.pattern) === "admin");
170 expect(admin.length).toBeGreaterThan(150);
171 const wrong: string[] = [];
172 for (const r of admin) {
173 const everyday = await send(carol, r.method, r.pattern, r.api);
174 if (!refusedKindly(everyday, r.api)) wrong.push(`${r.method} ${r.pattern}: everyday got ${everyday.status}`);
175 const own = await send(alice, r.method, r.pattern, r.api);
176 if (refusedKindly(own, r.api) || own.status >= 500) wrong.push(`${r.method} ${r.pattern}: admin got ${own.status}`);
177 // A page with nothing to fill in answers the admin outright.
178 if (r.method === "GET" && !r.pattern.includes(":") && own.status >= 400 && !(`GET ${r.pattern}` in ADMIN_GET_WANTS))
179 wrong.push(`${r.method} ${r.pattern}: admin got ${own.status}`);
180 }
181 expect(wrong).toEqual([]);
182 }, 120_000);
168 // The walk is split in eight tests, each an eighth of the routes, so none nears the 2 s budget
169 // (#17361).
170 const CHUNKS = 8;
171 for (let k = 0; k < CHUNKS; k++) {
172 test(`each admin route refuses the everyday account with the sentence, and lets the admin through (${k + 1} of ${CHUNKS})`, async () => {
173 const every = routes().filter((r) => markOf(r.pattern) === "admin");
174 expect(every.length).toBeGreaterThan(150);
175 const admin = every.filter((_, i) => i % CHUNKS === k);
176 const wrong: string[] = [];
177 for (const r of admin) {
178 const everyday = await send(carol, r.method, r.pattern, r.api);
179 if (!refusedKindly(everyday, r.api)) wrong.push(`${r.method} ${r.pattern}: everyday got ${everyday.status}`);
180 const own = await send(alice, r.method, r.pattern, r.api);
181 if (refusedKindly(own, r.api) || own.status >= 500) wrong.push(`${r.method} ${r.pattern}: admin got ${own.status}`);
182 // A page with nothing to fill in answers the admin outright.
183 if (r.method === "GET" && !r.pattern.includes(":") && own.status >= 400 && !(`GET ${r.pattern}` in ADMIN_GET_WANTS))
184 wrong.push(`${r.method} ${r.pattern}: admin got ${own.status}`);
185 }
186 expect(wrong).toEqual([]);
187 }, 120_000);
188 }
183189
184190 const mcp = async (u: User, method: string, params: Record<string, unknown>, token?: string) => {
185191 const res = await http.handle(
test/talk-phone-360.test.ts added +7
@@ -0,0 +1,7 @@
1 /**
2 * Talk on a phone at 360 px, in a real Chromium: the width's half of test/talk-phone.test.ts
3 * (#17361).
4 */
5 import { widthTests } from "./helpers/talk-phone.ts";
6
7 widthTests(360);
test/talk-phone-375.test.ts added +7
@@ -0,0 +1,7 @@
1 /**
2 * Talk on a phone at 375 px, in a real Chromium: the width's half of test/talk-phone.test.ts
3 * (#17361).
4 */
5 import { widthTests } from "./helpers/talk-phone.ts";
6
7 widthTests(375);
test/talk-phone-390.test.ts added +7
@@ -0,0 +1,7 @@
1 /**
2 * Talk on a phone at 390 px, in a real Chromium: the width's half of test/talk-phone.test.ts
3 * (#17361).
4 */
5 import { widthTests } from "./helpers/talk-phone.ts";
6
7 widthTests(390);
test/talk-phone.test.ts +6 −437
@@ -11,164 +11,14 @@
1111 *
1212 * Skipped, and says so, where no Chromium starts, except in the forge's own check (`FORGE_CHECK`):
1313 * there a missing Chromium fails every browser test, so a green check means they ran (#16560).
14 *
15 * The width-by-width tests are in test/talk-phone-<width>.test.ts, on the fixture in
16 * test/helpers/talk-phone.ts.
1417 */
15 import { afterAll, beforeAll, expect, test } from "bun:test";
16 import { mkdtemp, rm } from "node:fs/promises";
17 import { tmpdir } from "node:os";
18 import { join } from "node:path";
19 import { createApp, type App } from "../src/app.ts";
20 import { saveConnection } from "../src/core/connections.ts";
21 import {
22 appendTurn,
23 openConversation,
24 createConversation,
25 listTurns,
26 renameConversation,
27 } from "../src/core/conversations.ts";
28 import { createSession } from "../src/core/sessions.ts";
29 import { createUser } from "../src/core/users.ts";
30 import { findChromium } from "../src/looks/capture.ts";
31 import { serve, type Servers } from "../src/http/server.ts";
18 import { expect, test } from "bun:test";
19 import { appendTurn, listTurns } from "../src/core/conversations.ts";
3220 import { clock } from "../src/web/pages/talk.ts";
33 import { chromiumRuns, sharedBrowser, type SharedBrowser } from "./helpers/chrome.ts";
34 import { quietLogs } from "./helpers/globals.ts";
35 import { promote } from "./helpers/members.ts";
36
37 quietLogs();
38 const found = findChromium();
39 const chromium = found !== undefined && chromiumRuns(found) ? found : undefined;
40 /** The forge's own check names its run: there a browser test runs or fails, it never skips. */
41 const inCheck = (process.env["FORGE_CHECK"] ?? "") !== "";
42 const skip = chromium === undefined && !inCheck;
43 if (skip)
44 console.log(
45 "SKIPPING: no chromium that starts on this machine, so Talk on a phone is not measured",
46 );
47
48 const WIDTHS = [360, 375, 390] as const;
49 let dir: string;
50 let app: App;
51 let servers: Servers;
52 let token: string;
53 let aliceId: string;
54 let shortId: string;
55 let manyId: string;
56 let longId: string;
57 let listToken: string;
58 /**
59 * One Chromium for the file, a fresh browser context per page: the 29 pages each started their own
60 * and the file took 24 to 42 s against its 20 s budget in the check.
61 */
62 let browser: SharedBrowser | undefined;
63
64 const toolTurns = (userId: string, id: string, n: number): void => {
65 appendTurn(app.db, userId, id, { role: "person", text: "change the title" });
66 for (let i = 0; i < n; i++)
67 appendTurn(app.db, userId, id, { role: "tool", text: `step ${i}` });
68 appendTurn(app.db, userId, id, { role: "agent", text: "Done." });
69 };
70 const TABLE =
71 "| Pull | What it does |\n|---|---|\n| #16552 | `a-very-long-identifier-that-never-wraps-anywhere-on-a-phone` and more words |\n| #16561 | Earlier keeps the place |";
72
73 beforeAll(async () => {
74 dir = await mkdtemp(join(tmpdir(), "forge-talk-phone-"));
75 app = createApp({ dataDir: dir, port: 0 });
76 servers = await serve(app);
77 const made = await createUser(app.db, {
78 origin: "seed",
79 trusted: true,
80 username: "alice",
81 email: "[email protected]",
82 password: "a-good-passphrase",
83 adminIfFirst: true,
84 });
85 if (!made.ok) throw new Error(made.error);
86 promote(app.db, made.value);
87 aliceId = made.value.id;
88 token = createSession(app.db, aliceId).token;
89 // A connection that offers models, so the head carries the picker as it does for the owner.
90 const spark = saveConnection(app.db, app.config.dataDir, {
91 name: "Spark",
92 protocol: "openai",
93 base: "http://127.0.0.1:9/v1",
94 key: "sk-spark",
95 scope: "forge",
96 userId: aliceId,
97 models: [{ id: "canned/small" }, { id: "canned/large-model" }],
98 said: "2 models listed",
99 });
100 if (!spark.ok) throw new Error(spark.error);
101 const a = openConversation(app.db, aliceId);
102 shortId = a.id;
103 renameConversation(
104 app.db,
105 aliceId,
106 shortId,
107 "A short chat whose title is longer than a phone",
108 );
109 toolTurns(aliceId, a.id, 1);
110 const b = createConversation(app.db, aliceId);
111 if (!b.ok) throw new Error(b.error);
112 manyId = b.value.id;
113 toolTurns(aliceId, manyId, 9);
114 // A long chat: 120 turns, one of them a table wider than any phone.
115 const c = createConversation(app.db, aliceId);
116 if (!c.ok) throw new Error(c.error);
117 longId = c.value.id;
118 for (let i = 0; i < 120; i++)
119 appendTurn(app.db, aliceId, longId, {
120 role: i % 2 === 0 ? "person" : "agent",
121 text: i === 101 ? TABLE : `message ${i}`,
122 });
123 // A second person with twenty chats, to see where the list opens.
124 const bob = await createUser(app.db, {
125 origin: "seed",
126 trusted: true,
127 username: "bob",
128 email: "[email protected]",
129 password: "a-good-passphrase",
130 });
131 if (!bob.ok) throw new Error(bob.error);
132 promote(app.db, bob.value);
133 for (let i = 0; i < 20; i++) {
134 const c = createConversation(app.db, bob.value.id);
135 if (!c.ok) throw new Error(c.error);
136 renameConversation(app.db, bob.value.id, c.value.id, `Chat number ${i}`);
137 appendTurn(app.db, bob.value.id, c.value.id, {
138 role: "person",
139 text: "hello",
140 });
141 }
142 listToken = createSession(app.db, bob.value.id).token;
143 }, 30_000);
144 afterAll(async () => {
145 await browser?.close();
146 servers.stop();
147 app.close();
148 await rm(dir, { recursive: true, force: true });
149 });
150
151 const phone = (
152 width: number,
153 path: string,
154 as: string,
155 expression: string,
156 ): Promise<any> => {
157 if (chromium === undefined)
158 throw new Error(
159 "no Chromium starts in this check, so Talk on a phone is not measured: the check's image must carry one (FORGE_CHROMIUM)",
160 );
161 const started = chromium;
162 return (browser === undefined ? sharedBrowser(started).then((b) => (browser = b)) : Promise.resolve(browser))
163 .then((b) => b.evaluate(`${servers.url}${path}`, { width, height: 740 }, [{ name: "forge_session", value: as }], expression, "light", true))
164 .then((v) => JSON.parse(v));
165 };
166 /** In the page: wait for `f` to hold, checking every 25 ms, at most `ms`. */
167 const WAIT =
168 "const wait = (f, ms = 6000) => new Promise((ok) => { const t0 = performance.now(); const t = setInterval(() => { if (f() || performance.now() - t0 > ms) { clearInterval(t); ok(); } }, 25); });";
169 /** In the page: the log's turns, in the order a person reads them. */
170 const IDS =
171 "const ids = () => [...document.querySelectorAll('.talk-log li[id^=\"t-\"]')].map((l) => l.id);";
21 import { IDS, WAIT, aliceId, app, listToken, longId, phone, servers, shortId, skip, token } from "./helpers/talk-phone.ts";
17222
17323 test("without a browser: the conversation's controls are in a dock beside the composer, plain links and forms, the head the title alone on a phone", async () => {
17424 const res = await fetch(`${servers.url}/talk/${shortId}`, { headers: { cookie: `forge_session=${token}` } });
@@ -241,287 +91,6 @@ test("without a browser: the latest page is the last fifty in order, Earlier the
24191 );
24292 });
24393
244 for (const width of WIDTHS) {
245 test.skipIf(skip)(
246 `${width} px: the message box does not ride when the status line speaks, nor with the tool-call count`,
247 async () => {
248 const at = `(async () => {
249 const box = () => document.querySelector(".talk-box").getBoundingClientRect().bottom;
250 const st = document.querySelector(".talk-status"), form = document.querySelector("form.talk-compose");
251 const quiet = box();
252 st.textContent = "The forge replied.";
253 const spoke = box();
254 form.setAttribute("data-answering", "");
255 st.textContent = "The forge is answering…";
256 const busy = box();
257 return JSON.stringify({ quiet, spoke, busy, sw: document.documentElement.scrollWidth, vh: innerHeight });
258 })()`;
259 const few = await phone(width, `/talk/${shortId}`, token, at);
260 const many = await phone(width, `/talk/${manyId}`, token, at);
261 for (const s of [few, many]) {
262 expect(Math.abs(s.spoke - s.quiet)).toBeLessThanOrEqual(1);
263 expect(Math.abs(s.busy - s.quiet)).toBeLessThanOrEqual(1);
264 expect(s.sw).toBeLessThanOrEqual(width);
265 // A short chat's box sits at the foot of the screen, not under the last turn.
266 expect(s.vh - s.quiet).toBeLessThanOrEqual(48);
267 }
268 expect(Math.abs(few.quiet - many.quiet)).toBeLessThanOrEqual(1);
269 },
270 30_000,
271 );
272
273 test.skipIf(skip)(
274 `${width} px: the controls are one 44 px row in the lower half beside the composer, and the head is the title alone`,
275 async () => {
276 const s = await phone(
277 width,
278 `/talk/${shortId}`,
279 token,
280 `(async () => {
281 const frame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
282 const head = document.querySelector(".talk-head"), dock = document.querySelector(".talk-dock");
283 // A chat beside a live preview: the page splits and the dock carries Chat and Preview.
284 document.querySelector(".talk-page").setAttribute("data-split", "");
285 dock.querySelector("form").insertAdjacentHTML("afterend", '<nav class="seg talk-tabs" aria-label="Chat or preview"><a href="?pane=chat" aria-current="page">Chat</a><a href="?pane=preview">Preview</a></nav>');
286 await frame();
287 const box = (e) => { const r = e.getBoundingClientRect(); return { top: r.top, bottom: r.bottom, left: r.left, right: r.right, w: r.width, h: r.height, cls: String(e.className || e.tagName), text: (e.getAttribute("aria-label") || e.textContent || "").trim().slice(0, 20) }; };
288 const shown = (e) => e.getBoundingClientRect().width > 0;
289 const d = dock.getBoundingClientRect();
290 const kids = [...dock.querySelectorAll(":scope > *")].filter(shown).map(box);
291 const targets = [...dock.querySelectorAll(":scope > a, :scope > form button, :scope > .talk-tabs a, :scope > .menu > summary")].filter(shown).map(box);
292 const headKids = [...head.querySelectorAll(":scope > *")].filter(shown).map((e) => String(e.className || e.tagName));
293 // The model picker is one tap into the menu, and fits above the dock.
294 dock.querySelector(".menu > summary").click();
295 await frame();
296 const sel = dock.querySelector(".talk-model select"), panel = dock.querySelector(".menu-panel");
297 const model = { sel: box(sel), panel: box(panel), tracked: shown(sel) };
298 const ids = [...document.querySelectorAll("[id]")].map((e) => e.id), dup = ids.filter((x, i) => ids.indexOf(x) !== i);
299 return JSON.stringify({ dock: { top: d.top, bottom: d.bottom, h: d.height }, kids, targets, headKids, model, dup, vh: innerHeight, sw: document.documentElement.scrollWidth });
300 })()`,
301 );
302 const seen = JSON.stringify(s);
303 expect(s.dock.h, seen).toBeLessThanOrEqual(52);
304 expect(s.sw, seen).toBeLessThanOrEqual(width);
305 // Every control is reachable in the lower half, a 44 px target, nothing wrapped or past the
306 // edge.
307 expect(s.dock.top, seen).toBeGreaterThan(s.vh / 2);
308 expect(s.dock.bottom, seen).toBeLessThanOrEqual(s.vh);
309 const top = Math.min(...s.kids.map((k: { top: number }) => k.top));
310 for (const k of s.kids) {
311 expect(k.right, seen).toBeLessThanOrEqual(width);
312 expect(k.left, seen).toBeGreaterThanOrEqual(0);
313 expect(k.bottom, seen).toBeLessThanOrEqual(top + 52);
314 }
315 const names = s.targets.map((k: { text: string }) => k.text).join("|");
316 for (const word of ["Chats", "New conversation", "Chat", "Preview", "Conversation menu"]) expect(names, seen).toContain(word);
317 for (const k of s.targets) {
318 expect(Math.min(k.w, k.h), seen).toBeGreaterThanOrEqual(44);
319 expect(k.top, seen).toBeGreaterThan(s.vh / 2);
320 }
321 // The head keeps the title and nothing else.
322 expect(s.headKids, seen).toEqual(["talk-title"]);
323 // The model: in the menu, in the lower half, 44 px tall, on screen, above the bar.
324 expect(s.model.tracked, seen).toBe(true);
325 expect(s.model.sel.h, seen).toBeGreaterThanOrEqual(44);
326 expect(s.model.sel.right, seen).toBeLessThanOrEqual(width);
327 expect(s.model.panel.bottom, seen).toBeLessThanOrEqual(s.dock.top + 8);
328 expect(s.dup, seen).toEqual([]);
329 },
330 30_000,
331 );
332
333 test.skipIf(skip)(
334 `${width} px: with the keyboard open the dock rides with the composer above it and nothing rides under the keyboard`,
335 async () => {
336 const s = await phone(
337 width,
338 `/talk/${longId}`,
339 token,
340 `(async () => {
341 const frame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
342 await frame();
343 const dock = document.querySelector(".talk-dock"), foot = document.querySelector(".talk-base"), box = document.querySelector(".talk-box"), input = document.querySelector(".talk-input");
344 const at = (where) => ({ where, dockTop: dock.getBoundingClientRect().top, dockBottom: dock.getBoundingClientRect().bottom, boxTop: box.getBoundingClientRect().top, boxBottom: box.getBoundingClientRect().bottom, footTop: foot.getBoundingClientRect().top, last: [...document.querySelectorAll(".talk-log li[id^='t-']")].at(-1).getBoundingClientRect().bottom, kb: getComputedStyle(document.documentElement).getPropertyValue("--kb").trim(), vh: innerHeight });
345 const before = at("closed");
346 // A stand-in keyboard: the visual viewport 300 px shorter while the box is focused.
347 Object.defineProperty(visualViewport, "height", { configurable: true, get: () => innerHeight - 300 });
348 input.focus();
349 visualViewport.dispatchEvent(new Event("resize"));
350 await frame();
351 const open = at("open");
352 return JSON.stringify({ before, open });
353 })()`,
354 );
355 const seen = JSON.stringify(s);
356 expect(s.before.dockBottom, seen).toBeLessThanOrEqual(s.before.boxTop + 1);
357 expect(s.before.boxBottom, seen).toBeLessThanOrEqual(s.before.vh);
358 expect(s.open.kb, seen).toBe("300px");
359 // Both stay above the keyboard and the dock stays above the box.
360 expect(s.open.boxBottom, seen).toBeLessThanOrEqual(s.open.vh - 300 + 1);
361 expect(s.open.dockBottom, seen).toBeLessThanOrEqual(s.open.boxTop + 1);
362 },
363 30_000,
364 );
365
366 test.skipIf(skip)(
367 `${width} px: Chats is a labelled 44 px control in the dock, and it opens the list at its top on the newest chat`,
368 async () => {
369 // Bob's Talk opens on his newest chat; the way to the others is in the dock.
370 const at = await phone(
371 width,
372 `/talk`,
373 listToken,
374 `(() => {
375 const dock = document.querySelector(".talk-dock"), a = [...dock.querySelectorAll("a")].find((x) => x.textContent.trim() === "Chats");
376 if (!a) return JSON.stringify({ found: false, dock: dock.innerText });
377 const r = a.getBoundingClientRect(), h = dock.getBoundingClientRect();
378 return JSON.stringify({ found: true, href: a.getAttribute("href"), w: r.width, h: r.height, left: r.left, right: r.right, top: r.top, bottom: r.bottom, vh: innerHeight, dockTop: h.top, dockBottom: h.bottom, shown: getComputedStyle(a).visibility === "visible" && r.width > 0 });
379 })()`,
380 );
381 const seen = JSON.stringify(at);
382 expect(at.found, seen).toBe(true);
383 expect(at.shown, seen).toBe(true);
384 expect(Math.min(at.w, at.h), seen).toBeGreaterThanOrEqual(44);
385 expect(at.left, seen).toBeGreaterThanOrEqual(0);
386 expect(at.right, seen).toBeLessThanOrEqual(width);
387 expect(at.top, seen).toBeGreaterThan(at.vh / 2);
388 expect(at.bottom, seen).toBeLessThanOrEqual(at.dockBottom);
389 expect(at.href, seen).toEndWith("?chats=1");
390 const list = await phone(width, at.href, listToken, `(async () => { await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); const first = document.querySelector(".talk-list .row"); const r = first.getBoundingClientRect(); return JSON.stringify({ y: scrollY, top: r.top, bottom: r.bottom, vh: innerHeight, text: first.textContent }); })()`);
391 const said = JSON.stringify(list);
392 expect(list.y, said).toBe(0);
393 expect(list.top, said).toBeGreaterThanOrEqual(0);
394 expect(list.bottom, said).toBeLessThanOrEqual(list.vh);
395 expect(list.text, said).toContain("Chat number 19");
396 },
397 30_000,
398 );
399
400 test.skipIf(skip)(
401 `${width} px: the chat list opens at its top, the newest chat in view`,
402 async () => {
403 const s = await phone(
404 width,
405 `/talk?chats=1`,
406 listToken,
407 `(async () => { await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); const first = document.querySelector(".talk-list .row"); const r = first.getBoundingClientRect(); return JSON.stringify({ y: window.scrollY, tall: document.documentElement.scrollHeight > innerHeight, top: r.top, text: first.textContent }); })()`,
408 );
409 const seen = JSON.stringify(s);
410 expect(s.y, seen).toBe(0);
411 expect(s.top, seen).toBeGreaterThanOrEqual(0);
412 expect(s.text, seen).toContain("Chat number 19");
413 expect(s.tall, seen).toBe(true);
414 },
415 30_000,
416 );
417
418 test.skipIf(skip)(
419 `${width} px: a long chat reads oldest to newest, opens on the newest, and a wide table scrolls in its bubble`,
420 async () => {
421 const s = await phone(
422 width,
423 `/talk/${longId}`,
424 token,
425 `(async () => {
426 ${IDS}
427 await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
428 const all = [...document.querySelectorAll(".talk-log li[id^='t-']")], last = all.at(-1).getBoundingClientRect();
429 const texts = all.map((l) => (l.querySelector(".talk-body")?.textContent ?? "").trim());
430 return JSON.stringify({ ids: ids(), texts, y: scrollY, max: document.scrollingElement.scrollHeight - innerHeight, lastBottom: last.bottom, vh: innerHeight, vw: innerWidth, sw: document.documentElement.scrollWidth, table: !!document.querySelector(".talk-body table") });
431 })()`,
432 );
433 const seen = JSON.stringify({
434 ...s,
435 ids: s.ids.length,
436 texts: s.texts.slice(0, 3),
437 });
438 expect(s.ids, seen).toEqual([...s.ids].sort());
439 expect(s.texts[0], seen).toBe("message 70");
440 expect(s.texts.at(-1), seen).toBe("message 119");
441 expect(s.table, seen).toBe(true);
442 // The page is the phone's width: a wide table does not zoom the whole page out.
443 expect(s.vw, seen).toBe(width);
444 expect(s.sw, seen).toBeLessThanOrEqual(width);
445 expect(s.max - s.y, seen).toBeLessThanOrEqual(2);
446 expect(s.lastBottom, seen).toBeLessThanOrEqual(s.vh);
447 },
448 30_000,
449 );
450
451 test.skipIf(skip)(
452 `${width} px: the top bar is opaque with the head clear below it, and the composer stays on screen wherever the thread is`,
453 async () => {
454 const s = await phone(
455 width,
456 `/talk/${longId}`,
457 token,
458 `(async () => {
459 const frame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
460 await frame();
461 const bar = document.querySelector(".topbar"), head = document.querySelector(".talk-head"), box = document.querySelector(".talk-box");
462 const cs = getComputedStyle(bar);
463 // A chat beside a live preview: the head carries Chat and Preview, the tallest thing in it.
464 head.querySelector(".talk-model")?.insertAdjacentHTML("afterend", '<nav class="seg talk-tabs" aria-label="Chat or preview"><a href="?pane=chat" aria-current="page">Chat</a><a href="?pane=preview">Preview</a></nav>');
465 const kids = () => Math.min(...[...head.children].filter((e) => e.getBoundingClientRect().width > 0).map((e) => e.getBoundingClientRect().top));
466 const at = (where) => ({ where, barBottom: bar.getBoundingClientRect().bottom, headTop: head.getBoundingClientRect().top, kidsTop: kids(), boxTop: box.getBoundingClientRect().top, boxBottom: box.getBoundingClientRect().bottom, vh: innerHeight });
467 const end = at("end");
468 scrollTo({ top: document.scrollingElement.scrollHeight / 2, behavior: "instant" });
469 await frame();
470 const middle = at("middle");
471 // The visual viewport changing with nothing typed into (a pinch, a toolbar) is not a keyboard.
472 visualViewport.dispatchEvent(new Event("resize"));
473 await frame();
474 return JSON.stringify({ bg: cs.backgroundColor, blur: cs.backdropFilter, kb: getComputedStyle(document.documentElement).getPropertyValue("--kb").trim(), end, middle });
475 })()`,
476 );
477 const seen = JSON.stringify(s);
478 // Opaque: no alpha in the colour, nothing blurred through it.
479 expect(s.bg, seen).not.toMatch(/\/ 0\.|rgba\(.*, 0\.\d+\)/);
480 expect(s.blur, seen).toBe("none");
481 expect(["", "0px"], seen).toContain(s.kb);
482 for (const p of [s.end, s.middle]) {
483 expect(p.headTop, seen).toBeGreaterThanOrEqual(p.barBottom - 0.5);
484 expect(p.kidsTop, seen).toBeGreaterThanOrEqual(p.barBottom + 1);
485 expect(p.boxBottom, seen).toBeLessThanOrEqual(p.vh);
486 expect(p.boxTop, seen).toBeGreaterThan(p.vh - 140);
487 }
488 },
489 30_000,
490 );
491
492 test.skipIf(skip)(
493 `${width} px: Earlier puts the older turns above in order and the turn being read stays put`,
494 async () => {
495 const s = await phone(
496 width,
497 `/talk/${longId}`,
498 token,
499 `(async () => {
500 ${WAIT} ${IDS}
501 scrollTo({ top: 0, behavior: "instant" });
502 await new Promise((r) => requestAnimationFrame(r));
503 const first = document.querySelector(".talk-log li[id^='t-']"), topBefore = first.getBoundingClientRect().top, url = location.href;
504 document.querySelector("a[data-earlier]").click();
505 await wait(() => ids().length >= 100);
506 // How far the turn being read moved, in pixels: a place, not a time.
507 const shift = Math.abs(first.getBoundingClientRect().top - topBefore);
508 document.querySelector("a[data-earlier]").click();
509 await wait(() => ids().length >= 120);
510 return JSON.stringify({ ids: ids(), shift, same: location.href === url, more: !!document.querySelector("a[data-earlier]"), latest: document.querySelector("[data-jump]").hidden === false });
511 })()`,
512 );
513 const seen = JSON.stringify({ ...s, ids: s.ids.length });
514 expect(s.same, seen).toBe(true);
515 expect(s.ids.length, seen).toBe(120);
516 expect(s.ids, seen).toEqual([...s.ids].sort());
517 expect(new Set(s.ids).size, seen).toBe(120);
518 expect(s.shift, seen).toBeLessThanOrEqual(2);
519 expect(s.more, seen).toBe(false);
520 expect(s.latest, seen).toBe(true);
521 },
522 30_000,
523 );
524 }
52594
52695 test.skipIf(skip)(
52796 "a reply arriving while Earlier loads lands at the end; nothing reorders",

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

Keyboard shortcuts

Docs