Open History to see the last commit
1// @effect-diagnostics globalDate:off - scenario windows are wall-clock by nature.
2/**
3 * Scenarios drive one flow on the device and return metrics. Cases in `cases.ts` name a
4 * scenario and check its metrics, so one flow can serve several issues.
5 */
6import type { ThreadId } from "@t3tools/contracts";
7import type * as SecureRandom from "effect/crypto/SecureRandom";
8import * as Effect from "effect/Effect";
9import * as Schema from "effect/Schema";
10
11import {
12 APP_ID,
13 SCHEME,
14 type AxNode,
15 type Device,
16 type FeedSample,
17 type ProbeState,
18} from "./device.ts";
19import { uuid, type EvalEnvironment } from "./environment.ts";
20import { feedMotion, frameStats, type Metrics } from "./grade.ts";
21
22export type Pose = "phone" | "duo-closed" | "duo-open" | "ipad";
23
24export interface ScenarioContext {
25 readonly env: EvalEnvironment;
26 readonly device: Device;
27 readonly pose: Pose;
28 readonly fixtures: { readonly longThread: ThreadId };
29}
30
31// Child thread ids carry `:`, so each segment is encoded.
32const threadPath = (ctx: ScenarioContext, threadId: string) =>
33 `threads/${encodeURIComponent(ctx.env.environmentId)}/${encodeURIComponent(threadId)}`;
34
35const isThread = (state: ProbeState, threadId: string) =>
36 state.route?.name === "Thread" && state.route.params.threadId === threadId;
37
38const openThread = Effect.fn("scenario.openThread")(function* (
39 ctx: ScenarioContext,
40 threadId: string,
41) {
42 yield* ctx.device.open(threadPath(ctx, threadId));
43 return yield* ctx.device.waitFor(
44 `thread ${threadId} with a ready feed`,
45 (state) => isThread(state, threadId) && state.feed?.threadId === threadId && state.feed.ready,
46 20_000,
47 );
48});
49
50/** Screen size in points, and the x of the thread column (the right column in split view). */
51const geometry = Effect.fn("scenario.geometry")(function* (ctx: ScenarioContext) {
52 const nodes = yield* ctx.device.nodes;
53 const rect = nodes[0]?.rect ?? { x: 0, y: 0, width: 400, height: 870 };
54 const state = yield* ctx.device.state;
55 return {
56 width: rect.width,
57 height: rect.height,
58 threadX: Math.round(rect.width * (state.route?.columns ? 0.72 : 0.5)),
59 };
60});
61
62const findNode = Effect.fn("scenario.findNode")(function* (
63 ctx: ScenarioContext,
64 description: string,
65 match: (node: { label?: string; value?: string; kind?: string; editable?: boolean }) => boolean,
66) {
67 const node = (yield* ctx.device.nodes).find(match);
68 if (!node?.rect) return yield* new ScenarioFailure({ message: `No ${description} on screen.` });
69 return node;
70});
71
72const composerNode = (ctx: ScenarioContext) =>
73 findNode(
74 ctx,
75 "composer text view",
76 (node) => node.kind === "text-view" && node.editable === true,
77 );
78
79/** The text the native editor shows, read from the accessibility tree rather than React props. */
80const composerText = Effect.fn("scenario.composerText")(function* (ctx: ScenarioContext) {
81 const node = yield* composerNode(ctx);
82 return node.value ?? node.label ?? "";
83});
84
85/** A fresh settled thread, so drafts left by earlier samples never mix in. */
86const freshThread = Effect.fn("scenario.freshThread")(function* (
87 ctx: ScenarioContext,
88 prompt = "Hi. [[eval:reply]]",
89) {
90 const threadId = yield* ctx.env.launch(`Fresh ${(yield* uuid).slice(0, 6)}`, prompt);
91 if (!prompt.includes("[[eval:stream")) yield* ctx.env.settled(threadId);
92 return threadId;
93});
94
95/** Replaces the composer's text, the way a person would after clearing it. */
96const typeInComposer = Effect.fn("scenario.typeInComposer")(function* (
97 ctx: ScenarioContext,
98 text: string,
99) {
100 const { x, y } = ctx.device.center(yield* composerNode(ctx));
101 yield* ctx.device.run(["fill", String(x), String(y), text]);
102 // The composer slides up with the keyboard; a tap before it settles lands on the keyboard.
103 yield* ctx.device.waitFor("the keyboard", (state) => state.composer.keyboard, 10_000);
104 yield* Effect.sleep("1 second");
105});
106
107const countUserText = (
108 projection: { readonly messages: ReadonlyArray<{ readonly text?: string }> },
109 text: string,
110) => projection.messages.filter((message) => message.text === text).length;
111
112/** Starts a scripted reply in `threadId` and waits until the app shows it streaming. */
113const startStream = Effect.fn("scenario.startStream")(function* (
114 ctx: ScenarioContext,
115 threadId: ThreadId,
116 script: string,
117) {
118 const before = (yield* ctx.device.state).feed?.content ?? 0;
119 yield* ctx.env.send(threadId, `Write the long report. ${script}`);
120 yield* ctx.device.waitFor(
121 "the reply to start streaming in the feed",
122 (state) => (state.feed?.content ?? 0) > before + 200,
123 20_000,
124 );
125});
126
127/** Records frames (and the visible feed) while `action` runs; the action's failure is not the metric. */
128/** Records frames (and the visible feed) while `action` runs; stops recording even if it fails. */
129const recordFor = <E, R>(
130 ctx: ScenarioContext,
131 withFeed: boolean,
132 action: Effect.Effect<unknown, E, R>,
133) =>
134 ctx.device.recordStart(withFeed).pipe(
135 Effect.andThen(Effect.exit(action)),
136 Effect.flatMap((exit) =>
137 ctx.device.recordStop.pipe(Effect.flatMap((recording) => Effect.as(exit, recording))),
138 ),
139 );
140
141/** JS frame times jitter, so the display's refresh rate comes from the UI thread's vsync times. */
142const frameMetrics = (recording: { js: ReadonlyArray<number>; ui: ReadonlyArray<number> }) => {
143 const ui = frameStats(recording.ui, "ui");
144 const refreshMs = typeof ui.uiRefreshHz === "number" ? 1000 / ui.uiRefreshHz : undefined;
145 return { ...frameStats(recording.js, "js", refreshMs), ...ui };
146};
147
148/** Every scenario fails with this one error, so the table has a single function type. */
149export class ScenarioFailure extends Schema.TaggedError<ScenarioFailure>()("ScenarioFailure", {
150 message: Schema.String,
151}) {}
152
153const failure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
154 Effect.mapError(
155 effect,
156 (error) =>
157 new ScenarioFailure({ message: error instanceof Error ? error.message : String(error) }),
158 );
159
160type Scenario = (
161 ctx: ScenarioContext,
162) => Effect.Effect<Metrics, ScenarioFailure, SecureRandom.SecureRandom>;
163
164export const SCENARIOS = {
165 /** Six upward flings in the long settled thread. */
166 scrollUpLongThread: Effect.fn("scenario.scrollUpLongThread")(function* (ctx: ScenarioContext) {
167 yield* openThread(ctx, ctx.fixtures.longThread);
168 const { height, threadX } = yield* geometry(ctx);
169 const recording = yield* recordFor(
170 ctx,
171 true,
172 Effect.gen(function* () {
173 for (let fling = 0; fling < 6; fling++)
174 yield* ctx.device.swipe(threadX, Math.round(height * 0.35), Math.round(height * 0.8));
175 yield* Effect.sleep("1 second");
176 }),
177 );
178 return { ...feedMotion(recording.feed, 1), ...frameMetrics(recording) } satisfies Metrics;
179 }, failure),
180
181 /** A long reply streams into the open thread for eight seconds. */
182 streamInView: Effect.fn("scenario.streamInView")(function* (ctx: ScenarioContext) {
183 yield* openThread(ctx, ctx.fixtures.longThread);
184 yield* startStream(ctx, ctx.fixtures.longThread, "[[eval:stream:4000:25]]");
185 const recording = yield* recordFor(ctx, true, Effect.sleep("8 seconds"));
186 const after = yield* ctx.device.state;
187 yield* ctx.env.interruptAll();
188 const motion = feedMotion(recording.feed, 0);
189 return {
190 ...motion,
191 ...frameMetrics(recording),
192 settledFromEndPx: settledFromEnd(recording.feed),
193 contentGrewPx: (recording.feed.at(-1)?.content ?? 0) - (recording.feed[0]?.content ?? 0),
194 followingAtEnd: after.feed?.following === true,
195 } satisfies Metrics;
196 }, failure),
197
198 /** Types and sends a message from the composer at the end of the long thread. */
199 sendInLongThread: Effect.fn("scenario.sendInLongThread")(function* (ctx: ScenarioContext) {
200 yield* openThread(ctx, ctx.fixtures.longThread);
201 const text = `Follow-up ${(yield* uuid).slice(0, 8)} [[eval:reply]]`;
202 yield* typeInComposer(ctx, text);
203 const recording = yield* recordFor(
204 ctx,
205 true,
206 Effect.gen(function* () {
207 yield* ctx.device.press('label="Send"');
208 yield* Effect.sleep("4 seconds");
209 }),
210 );
211 const after = yield* ctx.device.state;
212 const nativeText = yield* composerText(ctx);
213 const projection = yield* ctx.env.settled(ctx.fixtures.longThread);
214 const motion = feedMotion(recording.feed, 0);
215 return {
216 maxFromEndPx: motion.maxFromEndPx ?? null,
217 finalFromEndPx: motion.finalFromEndPx ?? null,
218 serverMessages: countUserText(projection, text),
219 draftCleared: after.composer.draft === "",
220 editorCleared: nativeText === "",
221 } satisfies Metrics;
222 }, failure),
223
224 /** Types a message, scrolls up, taps "Scroll to end", then taps Send once. */
225 scrollToEndThenSend: Effect.fn("scenario.scrollToEndThenSend")(function* (ctx: ScenarioContext) {
226 yield* openThread(ctx, ctx.fixtures.longThread);
227 const text = `Follow-up ${(yield* uuid).slice(0, 8)} [[eval:reply]]`;
228 yield* typeInComposer(ctx, text);
229 const { height, threadX } = yield* geometry(ctx);
230 yield* ctx.device.swipe(threadX, Math.round(height * 0.2), Math.round(height * 0.45));
231 yield* waitForStill(ctx);
232 yield* ctx.device.press('label="Scroll to end"');
233 yield* waitForStill(ctx);
234 const scrolledToEnd = (yield* ctx.device.state).feed?.atEnd === true;
235 // Nothing may touch the screen between these taps. The bug lost the first touch after the arrow.
236 yield* ctx.device.press('label="Send"');
237 if (!(yield* ctx.env.delivered(ctx.fixtures.longThread, text)))
238 return { scrolledToEnd, serverMessages: 0 } satisfies Metrics;
239 const projection = yield* ctx.env.settled(ctx.fixtures.longThread);
240 return { scrolledToEnd, serverMessages: countUserText(projection, text) } satisfies Metrics;
241 }, failure),
242
243 /** A thread in the background finishes while the long thread sits mid-scroll. */
244 backgroundFinish: Effect.fn("scenario.backgroundFinish")(function* (ctx: ScenarioContext) {
245 const key = `bg-${(yield* uuid).slice(0, 8)}`;
246 const other = yield* ctx.env.launch("Background work", `Run the job. [[eval:hold:${key}]]`);
247 yield* openThread(ctx, ctx.fixtures.longThread);
248 const { height, threadX } = yield* geometry(ctx);
249 for (let fling = 0; fling < 2; fling++)
250 yield* ctx.device.swipe(threadX, Math.round(height * 0.4), Math.round(height * 0.7));
251 yield* waitForStill(ctx);
252 const recording = yield* recordFor(
253 ctx,
254 true,
255 Effect.gen(function* () {
256 yield* ctx.env.release(key);
257 yield* ctx.env.settled(other);
258 yield* Effect.sleep("2 seconds");
259 }),
260 );
261 return { ...feedMotion(recording.feed, 0) } satisfies Metrics;
262 }, failure),
263
264 /** Types in a streaming thread, switches to another thread, and comes back. */
265 draftThreadSwitch: Effect.fn("scenario.draftThreadSwitch")(function* (ctx: ScenarioContext) {
266 const text = `Draft ${(yield* uuid).slice(0, 8)}`;
267 const other = yield* freshThread(ctx);
268 const streaming = yield* freshThread(ctx, "Write the long report. [[eval:stream:4000:25]]");
269 yield* openThread(ctx, streaming);
270 yield* typeInComposer(ctx, text);
271 yield* openThread(ctx, other);
272 yield* Effect.sleep("1 second");
273 const onOther = yield* ctx.device.state;
274 const otherText = yield* composerText(ctx);
275 yield* openThread(ctx, streaming);
276 yield* Effect.sleep("1 second");
277 const back = yield* ctx.device.state;
278 const backText = yield* composerText(ctx);
279 yield* ctx.env.interruptAll();
280 const otherKey = `${ctx.env.environmentId}:${other}`;
281 return {
282 draftKept: back.composer.draft === text,
283 editorShowsDraft: backText === text,
284 leakedIntoOtherDraft: (onOther.composer.drafts[otherKey] ?? "") !== "",
285 leakedIntoOtherEditor: otherText.includes(text),
286 } satisfies Metrics;
287 }, failure),
288
289 /** Types a draft, sends the app to the background, and brings it back. */
290 draftBackground: Effect.fn("scenario.draftBackground")(function* (ctx: ScenarioContext) {
291 const text = `Draft ${(yield* uuid).slice(0, 8)}`;
292 const threadId = yield* freshThread(ctx);
293 yield* openThread(ctx, threadId);
294 yield* typeInComposer(ctx, text);
295 yield* ctx.device.home;
296 yield* Effect.sleep("3 seconds");
297 // A link back to the thread foregrounds the running app; a plain open would reload its JS.
298 yield* ctx.device.run([
299 "open",
300 APP_ID,
301 "--launch-url",
302 `${SCHEME}://${threadPath(ctx, threadId)}`,
303 ]);
304 const back = yield* ctx.device.waitFor("the thread after foreground", (state) =>
305 isThread(state, threadId),
306 );
307 return {
308 draftKept: back.composer.draft === text,
309 editorShowsDraft: (yield* composerText(ctx)) === text,
310 } satisfies Metrics;
311 }, failure),
312
313 /** Taps the middle of the composer's text area. */
314 tapComposer: Effect.fn("scenario.tapComposer")(function* (ctx: ScenarioContext) {
315 const threadId = yield* freshThread(ctx);
316 yield* openThread(ctx, threadId);
317 const node = yield* composerNode(ctx);
318 const { x, y } = ctx.device.center(node);
319 yield* ctx.device.pressAt(x, y);
320 yield* Effect.sleep("1500 millis");
321 const after = yield* ctx.device.state;
322 return {
323 stayedOnThread: isThread(after, threadId),
324 editorFocused:
325 after.composer.editors.some((editor) => editor.expanded) && after.composer.keyboard,
326 } satisfies Metrics;
327 }, failure),
328
329 /** Types `/eval`, picks the workspace's `eval-notes` skill, and checks the editor keeps focus. */
330 skillPick: Effect.fn("scenario.skillPick")(function* (ctx: ScenarioContext) {
331 yield* openThread(ctx, yield* freshThread(ctx));
332 // Short screens fit one menu row above the keyboard, so filter the menu to one row.
333 yield* typeInComposer(ctx, "/eval");
334 const composer = yield* composerNode(ctx);
335 // Menu rows read "<icon>, skill:<name>, <description>". Skills arrive with a workspace
336 // snapshot the draft change requests.
337 let item: AxNode | undefined;
338 for (let attempt = 0; attempt < 10 && !item?.rect; attempt++) {
339 yield* Effect.sleep("1 second");
340 item = (yield* ctx.device.nodes).find(
341 (node) =>
342 node.rect !== undefined &&
343 node.rect.y + node.rect.height <= composer.rect!.y &&
344 node.label?.includes(", skill:eval-notes") === true,
345 );
346 }
347 if (!item?.rect)
348 return yield* new ScenarioFailure({ message: "The / menu did not list skill:eval-notes." });
349 const { x, y } = ctx.device.center(item);
350 yield* ctx.device.pressAt(x, y);
351 yield* Effect.sleep("1500 millis");
352 const after = yield* ctx.device.state;
353 return {
354 editorFocused:
355 after.composer.editors.some((editor) => editor.expanded) && after.composer.keyboard,
356 } satisfies Metrics;
357 }, failure),
358
359 /** Sends from a thread whose provider instance the server no longer has. */
360 failedSend: Effect.fn("scenario.failedSend")(function* (ctx: ScenarioContext) {
361 const { threadId, lock } = yield* ctx.env.launchLockable("Locked thread");
362 yield* openThread(ctx, threadId);
363 const text = `Will fail ${(yield* uuid).slice(0, 8)}`;
364 yield* typeInComposer(ctx, text);
365 yield* lock;
366 // The app learns of the setting a moment after the server commits it.
367 yield* Effect.sleep("2 seconds");
368 // Either outcome is honest: Send turns off, or the rejected send shows an error.
369 const sendBlocked =
370 (yield* ctx.device.nodes).find((node) => node.label === "Send")?.enabled === false;
371 if (!sendBlocked) yield* ctx.device.press('label="Send"');
372 const shown = sendBlocked
373 ? false
374 : (yield* ctx.device
375 .waitFor("a composer error", (state) => state.composer.error !== null, 8_000)
376 .pipe(Effect.option))._tag === "Some";
377 return {
378 sendBlocked,
379 errorShown: shown,
380 silentFailure: !sendBlocked && !shown,
381 } satisfies Metrics;
382 }, failure),
383
384 /** A working thread finishes while Home is open. */
385 workingShelfFinish: Effect.fn("scenario.workingShelfFinish")(function* (ctx: ScenarioContext) {
386 const key = `shelf-${(yield* uuid).slice(0, 8)}`;
387 const threadId = yield* ctx.env.launch("Shelf work", `Run the job. [[eval:hold:${key}]]`);
388 const working = yield* ctx.device.waitFor(
389 "the thread to show as working",
390 (state) => state.threads[threadId] === "working",
391 );
392 yield* ctx.env.release(key);
393 yield* ctx.env.settled(threadId);
394 // The shelf keeps a finished row for WORKING_EXIT_GRACE_MS (2 s) on purpose.
395 yield* Effect.sleep("5 seconds");
396 const after = yield* ctx.device.state;
397 return {
398 shelfShownWhileWorking: shelfCount(working) > 0,
399 shelfCountAfter: shelfCount(after),
400 // For diagnosis: threads the app itself calls working, beside the shelf's count.
401 appWorkingThreads: Object.values(after.threads).filter((status) => status === "working")
402 .length,
403 statusAfter: after.threads[threadId] ?? "missing",
404 } satisfies Metrics;
405 }, failure),
406
407 /** A thread asks a question while Home is open. */
408 pendingQuestion: Effect.fn("scenario.pendingQuestion")(function* (ctx: ScenarioContext) {
409 const threadId = yield* ctx.env.launch("Question", `Ask me first. [[eval:question]]`);
410 yield* ctx.env.waitForPendingInput(threadId);
411 yield* Effect.sleep("2 seconds");
412 const after = yield* ctx.device.state;
413 yield* ctx.env.interruptAll();
414 return {
415 status: after.threads[threadId] ?? "missing",
416 shelfCount: shelfCount(after),
417 } satisfies Metrics;
418 }, failure),
419
420 /** A thread runs two subagents; Home and the thread must not look idle. */
421 subagentsRunning: Effect.fn("scenario.subagentsRunning")(function* (ctx: ScenarioContext) {
422 const key = `sub-${(yield* uuid).slice(0, 8)}`;
423 const threadId = yield* ctx.env.launch("Subagents", `Fan out. [[eval:subagents:${key}]]`);
424 yield* ctx.env.waitForSubagents(threadId);
425 yield* Effect.sleep("2 seconds");
426 const home = yield* ctx.device.state;
427 yield* openThread(ctx, threadId);
428 yield* Effect.sleep("1500 millis");
429 const thread = yield* ctx.device.state;
430 yield* ctx.env.release(key);
431 yield* ctx.env.settled(threadId);
432 return {
433 status: home.threads[threadId] ?? "missing",
434 threadShowsStatus: thread.floatingStatus !== null,
435 } satisfies Metrics;
436 }, failure),
437
438 /** Scrolls a finished subagent's child thread. */
439 openSubagentThread: Effect.fn("scenario.openSubagentThread")(function* (ctx: ScenarioContext) {
440 const key = `child-${(yield* uuid).slice(0, 8)}`;
441 const threadId = yield* ctx.env.launch("Parent", `Fan out. [[eval:subagents:${key}]]`);
442 yield* ctx.env.waitForSubagents(threadId);
443 yield* ctx.env.release(key);
444 const projection = yield* ctx.env.settled(threadId);
445 const child = projection.subagents.find(
446 (subagent) => subagent.childThreadId !== null,
447 )?.childThreadId;
448 if (!child)
449 return yield* new ScenarioFailure({ message: "The subagent made no child thread." });
450 yield* openThread(ctx, child);
451 const { height, threadX } = yield* geometry(ctx);
452 const recording = yield* recordFor(
453 ctx,
454 true,
455 Effect.gen(function* () {
456 yield* ctx.device.swipe(threadX, Math.round(height * 0.7), Math.round(height * 0.3));
457 yield* ctx.device.swipe(threadX, Math.round(height * 0.3), Math.round(height * 0.7));
458 }),
459 );
460 return {
461 movedPx: feedMotion(recording.feed, 0).movedPx ?? 0,
462 ...frameMetrics(recording),
463 } satisfies Metrics;
464 }, failure),
465
466 /** Long-presses a row on Home and picks Pin. */
467 pinFromLongPress: Effect.fn("scenario.pinFromLongPress")(function* (ctx: ScenarioContext) {
468 const title = `Pin target ${(yield* uuid).slice(0, 6)}`;
469 const target = yield* ctx.env.launch(title, "Hi. [[eval:reply]]");
470 yield* ctx.env.settled(target);
471 yield* waitForRow(ctx, title);
472 // A just-inserted row can swallow the first long-press while it animates in.
473 for (let attempt = 0; attempt < 2; attempt++) {
474 yield* ctx.device.longPress(rowSelector(title));
475 yield* Effect.sleep("1 second");
476 if ((yield* ctx.device.nodes).some((node) => node.label === "Pin")) break;
477 }
478 yield* ctx.device.press('label="Pin"');
479 yield* Effect.sleep("2 seconds");
480 const shell = yield* ctx.env.shell();
481 const pinned = shell.threads
482 .filter((thread) => thread.pinnedAt != null)
483 .map((thread) => thread.id);
484 for (const id of pinned) yield* ctx.env.unpin(id);
485 return {
486 targetPinned: pinned.includes(target),
487 otherPinned: pinned.filter((id) => id !== target).length,
488 } satisfies Metrics;
489 }, failure),
490
491 /** Opens a link to a thread created after the app loaded its list. */
492 linkToNewThread: Effect.fn("scenario.linkToNewThread")(function* (ctx: ScenarioContext) {
493 const threadId = yield* ctx.env.launch("Linked thread", "Hi. [[eval:reply]]");
494 yield* ctx.device.open(threadPath(ctx, threadId));
495 yield* Effect.sleep("4 seconds");
496 const after = yield* ctx.device.state;
497 return { opensTarget: isThread(after, threadId) } satisfies Metrics;
498 }, failure),
499
500 /** Opens a link to an archived thread. */
501 linkToArchivedThread: Effect.fn("scenario.linkToArchivedThread")(function* (
502 ctx: ScenarioContext,
503 ) {
504 const threadId = yield* ctx.env.launch("Archived thread", "Hi. [[eval:reply]]");
505 yield* ctx.env.settled(threadId);
506 yield* ctx.env.archive(threadId);
507 yield* Effect.sleep("1 second");
508 yield* ctx.device.open(threadPath(ctx, threadId));
509 yield* Effect.sleep("4 seconds");
510 const after = yield* ctx.device.state;
511 return { opensTarget: isThread(after, threadId) } satisfies Metrics;
512 }, failure),
513
514 /** Taps a row on Home. */
515 openFromList: Effect.fn("scenario.openFromList")(function* (ctx: ScenarioContext) {
516 const title = `Open me ${(yield* uuid).slice(0, 6)}`;
517 const target = yield* ctx.env.launch(title, "Hi. [[eval:reply]]");
518 yield* ctx.env.settled(target);
519 yield* waitForRow(ctx, title);
520 // A just-inserted row animates in, and a tap during that misses it.
521 yield* Effect.sleep("1 second");
522 yield* ctx.device.press(rowSelector(title));
523 const after = yield* ctx.device
524 .waitFor("the tapped thread", (state) => isThread(state, target))
525 .pipe(Effect.option);
526 return { opensTarget: after._tag === "Some" } satisfies Metrics;
527 }, failure),
528
529 /** On a folded Duo: open a thread from the list, go back, and open another. */
530 duoBackThenOpen: Effect.fn("scenario.duoBackThenOpen")(function* (ctx: ScenarioContext) {
531 const tag = (yield* uuid).slice(0, 6);
532 const first = yield* ctx.env.launch(`Duo first ${tag}`, "Hi. [[eval:reply]]");
533 const next = yield* ctx.env.launch(`Duo next ${tag}`, "Hi. [[eval:reply]]");
534 yield* ctx.env.settled(first);
535 yield* ctx.env.settled(next);
536 yield* waitForRow(ctx, `Duo first ${tag}`);
537 yield* ctx.device.press(rowSelector(`Duo first ${tag}`));
538 yield* ctx.device.waitFor("the first thread", (state) => isThread(state, first));
539 yield* ctx.device.back;
540 yield* ctx.device.waitFor("Home", (state) => state.route?.name === "Home");
541 yield* ctx.device.press(rowSelector(`Duo next ${tag}`));
542 yield* Effect.sleep("2 seconds");
543 const after = yield* ctx.device.state;
544 // A thread can mount in a hidden column, so its title must sit inside the visible screen.
545 const nodes = yield* ctx.device.nodes;
546 const screen = nodes[0]?.rect;
547 // The header title is a text node inside a navigation bar; a Home row with the title is not.
548 const bars = nodes.flatMap((node) =>
549 node.kind === "navigation-bar" && node.rect ? [node.rect] : [],
550 );
551 const title = nodes.find(
552 (node) =>
553 node.label === `Duo next ${tag}` &&
554 bars.some((bar) => node.rect && node.rect.y >= bar.y && node.rect.y < bar.y + bar.height),
555 )?.rect;
556 return {
557 opensTarget: isThread(after, next),
558 titleOnScreen:
559 screen !== undefined &&
560 title !== undefined &&
561 title.x >= screen.x &&
562 title.x + title.width <= screen.x + screen.width,
563 } satisfies Metrics;
564 }, failure),
565} satisfies Record<string, Scenario>;
566
567export type ScenarioName = keyof typeof SCENARIOS;
568
569/** Row rects are relative to their list, so rows are tapped by label, not by point. */
570function rowSelector(title: string) {
571 return `label="${title}"`;
572}
573
574/** Waits until fling momentum ends: the feed's offset holds still across half a second. */
575const waitForStill = Effect.fn("scenario.waitForStill")(function* (ctx: ScenarioContext) {
576 let previous = -1;
577 for (let attempt = 0; attempt < 20; attempt++) {
578 const scroll = (yield* ctx.device.state).feed?.scroll ?? -1;
579 if (scroll === previous) return;
580 previous = scroll;
581 yield* Effect.sleep("500 millis");
582 }
583});
584
585/** Largest distance from the end on frames where the content did not just grow. */
586function settledFromEnd(samples: ReadonlyArray<FeedSample>) {
587 let worst = 0;
588 for (let index = 1; index < samples.length; index++)
589 if (samples[index]!.content === samples[index - 1]!.content)
590 worst = Math.max(worst, samples[index]!.fromEnd ?? 0);
591 return worst;
592}
593
594/** Waits until a row with this title is on screen. */
595const waitForRow = Effect.fn("scenario.waitForRow")(function* (
596 ctx: ScenarioContext,
597 title: string,
598) {
599 for (let attempt = 0; attempt < 20; attempt++) {
600 const nodes = yield* ctx.device.nodes;
601 if (nodes.some((node) => node.label?.includes(title))) return;
602 // A crowded list can hold the new row below the fold; scroll to the top once.
603 if (attempt === 4) yield* ctx.device.run(["scroll", "top"]).pipe(Effect.ignore);
604 // A finished row can stay folded in the Working shelf; open it once if it is collapsed.
605 const shelf = nodes.find((node) => /^\d+ working threads?$/.test(node.label ?? ""));
606 const collapsed = (yield* ctx.device.state).homeList?.some(
607 (entry) => entry.type === "v2-working-shelf" && entry.expanded === false,
608 );
609 if (attempt === 10 && collapsed && shelf?.label)
610 yield* ctx.device.press(`label="${shelf.label}"`);
611 yield* Effect.sleep("500 millis");
612 }
613 return yield* new ScenarioFailure({ message: `Row "${title}" never appeared on Home.` });
614});
615
616function shelfCount(state: ProbeState) {
617 return state.homeList?.find((entry) => entry.type === "v2-working-shelf")?.count ?? 0;
618}