Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cases.ts

365 lines14.4 KB

1// @effect-diagnostics globalDate:off globalJsonInEffect:off - probe windows are wall-clock; the probe types its own JSON.
2/**
3 * mobile:metrics' interactions. Each measured step opens a probe window, makes one real tap,
4 * swipe or typed string through agent-device, waits until the app is quiet, and reads the window.
5 */
6import type { ThreadId } from "@t3tools/contracts";
7import * as Clock from "effect/Clock";
8import type * as SecureRandom from "effect/crypto/SecureRandom";
9import * as Effect from "effect/Effect";
10import * as Schema from "effect/Schema";
11​
12import type { AxNode, Device, ProbeState } from "../../mobile-behavior/device.ts";
13import type { Session } from "../../mobile-behavior/session.ts";
14import { stepOf, type PerfWindow, type Step } from "./report.ts";
15​
16export class CaseFailure extends Schema.TaggedError<CaseFailure>()("CaseFailure", {
17 message: Schema.String,
18}) {}
19​
20/** Threads the seed creates, by the title their Home row shows. */
21export interface Fixtures {
22 readonly short: { readonly id: ThreadId; readonly title: string };
23 readonly long: { readonly id: ThreadId; readonly title: string };
24 /** A side chat of the short thread. */
25 readonly sideChat: { readonly id: ThreadId; readonly title: string };
27​
28export interface CaseContext {
29 readonly session: Session;
30 readonly device: Device;
31 readonly fixtures: Fixtures;
32 readonly round: number;
33 /** Threads opened so far in this app launch, for first visit versus revisit. */
34 readonly visited: Set<string>;
36​
37/** How long the app must stay without input, commits or new content to end a step. */
38const QUIET_MS = 1_000;
39/** A working thread commits on every streamed chunk, so its steps end this long after content. */
40const AFTER_CONTENT_MS = 1_200;
41const STEP_TIMEOUT_MS = 15_000;
42​
43const Peek = Schema.fromJsonString(
44 Schema.Struct({
45 now: Schema.Number,
46 last: Schema.Number,
47 inputs: Schema.Number,
48 content: Schema.Array(Schema.String),
49 }),
50);
51const decodePeek = Schema.decodeUnknownEffect(Peek);
52​
53/** Runs `act` inside a probe window and returns what it measured. */
54const measure = Effect.fn("metrics.measure")(function* (
55 ctx: CaseContext,
56 step: Pick<Step, "case" | "step" | "visit">,
57 act: Effect.Effect<unknown, { readonly message: string }>,
58 options: { readonly thread?: string } = {},
59) {
60 const { device } = ctx;
61 yield* device.evaluate("__t3Behavior.perfStart()");
62 const acted = yield* Effect.result(act);
63 const deadline = (yield* Clock.currentTimeMillis) + STEP_TIMEOUT_MS;
64 let contentSince: number | null = null;
65 while (acted._tag === "Success" && (yield* Clock.currentTimeMillis) < deadline) {
66 const peek = yield* device.evaluate("__t3Behavior.perfPeek()").pipe(
67 Effect.flatMap((value) => decodePeek(value)),
68 Effect.orElseSucceed(() => null),
69 );
70 if (peek) {
71 const shown = options.thread
72 ? peek.content.some((thread) => thread.endsWith(options.thread!))
73 : true;
74 if (shown && options.thread) contentSince ??= peek.now;
75 const quiet = peek.inputs > 0 && peek.now - peek.last > QUIET_MS;
76 if (shown && (quiet || (contentSince !== null && peek.now - contentSince > AFTER_CONTENT_MS)))
77 break;
78 }
79 yield* Effect.sleep("250 millis");
80 }
81 const window = JSON.parse(
82 String(yield* device.evaluate("__t3Behavior.perfStop()")),
83 ) as PerfWindow;
84 if (acted._tag === "Failure")
85 return yield* new CaseFailure({
86 message: `${step.case} ${step.step}: ${acted.failure.message}`,
87 });
88 return stepOf(window, { ...step, round: ctx.round }, options.thread ?? null);
89});
90​
91const isThread = (state: ProbeState, threadId: string) =>
92 state.route?.name === "Thread" && state.route.params.threadId === threadId;
93​
94/** Back to Home's chat list, unmeasured: phones stack threads over it, and tabs share its route. */
95const toHome = Effect.fn("metrics.toHome")(function* (ctx: CaseContext) {
96 for (let attempt = 0; attempt < 4; attempt++) {
97 const state = yield* ctx.device.state;
98 if (state.route?.name === "Home") break;
99 // UIKit can report an unknown outcome while the pop animates; the next state read decides.
100 yield* ctx.device.back.pipe(Effect.ignore);
101 yield* Effect.sleep("800 millis");
102 }
103 yield* ctx.device.waitFor("Home", (state) => state.route?.name === "Home", 5_000);
104 yield* ctx.device.press('role=button label="Chats"').pipe(Effect.ignore);
105});
106​
107/** Finds an on-screen node, skipping list containers that repeat a row's label. */
108const findNode = Effect.fn("metrics.findNode")(function* (
109 ctx: CaseContext,
110 description: string,
111 match: (label: string) => boolean,
112) {
113 for (let attempt = 0; attempt < 10; attempt++) {
114 const node = (yield* ctx.device.nodes).find(
115 (entry) => entry.label !== undefined && entry.kind !== "scroll-area" && match(entry.label),
116 ) as (AxNode & { readonly ref?: string }) | undefined;
117 if (node?.ref) return `@${node.ref}`;
118 if (node?.label) return `label="${node.label}"`;
119 yield* Effect.sleep("500 millis");
120 }
121 return yield* new CaseFailure({ message: `No ${description} on screen.` });
122});
123​
124/** Taps the shared PR/issues list switcher by the centre of its labelled view. */
125const pressSwitcher = Effect.fn("metrics.pressSwitcher")(function* (
126 ctx: CaseContext,
127 label: string,
128) {
129 for (let attempt = 0; attempt < 10; attempt++) {
130 const node = (yield* ctx.device.nodes).find((entry) => entry.label === label && entry.rect);
131 if (node) {
132 const { x, y } = ctx.device.center(node);
133 return yield* ctx.device.pressAt(x, y);
134 }
135 yield* Effect.sleep("500 millis");
136 }
137 return yield* new CaseFailure({ message: `No "${label}" on screen.` });
138});
139​
140/** A Home row's label is its title and status, e.g. "Bench short, Done". */
141const isRow = (label: string | undefined, title: string) =>
142 label === title || label?.startsWith(`${title}, `) === true;
143​
144/** Waits for a Home row and returns its selector, opening the Working shelf if the row folded into it. */
145const waitForRow = Effect.fn("metrics.waitForRow")(function* (ctx: CaseContext, title: string) {
146 for (let attempt = 0; attempt < 20; attempt++) {
147 const nodes = yield* ctx.device.nodes;
148 const row = nodes.find((node) => isRow(node.label, title)) as
149 | (AxNode & { readonly ref?: string })
150 | undefined;
151 // The label ends in a relative time ("Bench short, 4m") that can tick before the press.
152 if (row?.ref) return `@${row.ref}`;
153 if (row?.label) return `label="${row.label}"`;
154 const shelf = nodes.find((node) => /^\d+ working threads?$/.test(node.label ?? ""));
155 if (shelf?.label && attempt % 4 === 1) yield* ctx.device.press(`label="${shelf.label}"`);
156 yield* Effect.sleep("500 millis");
157 }
158 return yield* new CaseFailure({ message: `Row "${title}" never appeared on Home.` });
159});
160​
161/** Opens a thread by tapping its Home row, measured from the tap to its rows on screen. */
162const openFromHome = Effect.fn("metrics.openFromHome")(function* (
163 ctx: CaseContext,
164 name: string,
165 thread: { readonly id: ThreadId; readonly title: string },
166) {
167 yield* toHome(ctx);
168 const row = yield* waitForRow(ctx, thread.title);
169 const visit = ctx.visited.has(thread.id) ? "revisit" : "first";
170 ctx.visited.add(thread.id);
171 const step = yield* measure(ctx, { case: name, step: "open", visit }, ctx.device.press(row), {
172 thread: thread.id,
173 });
174 yield* ctx.device.waitFor("the tapped thread", (state) => isThread(state, thread.id), 10_000);
175 return step;
176});
177​
178const switchTo = (name: "short" | "long") =>
179 Effect.fn(`metrics.switch.${name}`)(function* (ctx: CaseContext) {
180 return [yield* openFromHome(ctx, `switch-${name}`, ctx.fixtures[name])];
181 });
182​
183/** Opens a thread, unmeasured, and waits for its feed. */
184const openThread = Effect.fn("metrics.openThread")(function* (
185 ctx: CaseContext,
186 thread: Fixtures[keyof Fixtures],
187) {
188 yield* toHome(ctx);
189 yield* ctx.device.press(yield* waitForRow(ctx, thread.title));
190 ctx.visited.add(thread.id);
191 yield* ctx.device.waitFor(
192 "the thread's feed",
193 (state) => isThread(state, thread.id) && state.feed?.ready === true,
194 20_000,
195 );
196 yield* Effect.sleep("1 second");
197});
198​
199const TYPED = "check the helpers";
200​
201type CaseRun = (
202 ctx: CaseContext,
203) => Effect.Effect<ReadonlyArray<Step>, { readonly message: string }, SecureRandom.SecureRandom>;
204​
205export const CASES = {
206 "switch-short": switchTo("short"),
207 "switch-long": switchTo("long"),
208 /**
209 * A thread streaming a reply, opened twice. Each round starts its own and stops it after, since a
210 * stream anywhere keeps Home committing and no other step would ever go quiet.
211 */
212 "switch-working": Effect.fn("metrics.switch.working")(function* (ctx: CaseContext) {
213 const title = `Bench working ${ctx.round}`;
214 const id = yield* ctx.session.env.launch(title, "Write the report. [[eval:stream:3000:120]]");
215 const thread = { id, title };
216 return yield* Effect.gen(function* () {
217 yield* waitForRow(ctx, `${title}, Working`).pipe(Effect.ignore);
218 return [
219 yield* openFromHome(ctx, "switch-working", thread),
220 yield* openFromHome(ctx, "switch-working", thread),
221 ];
222 }).pipe(Effect.ensuring(ctx.session.env.interruptAll().pipe(Effect.ignore)));
223 }),
224​
225 /** The tab bar: pull requests, usage, then back to chats. */
226 tabs: Effect.fn("metrics.tabs")(function* (ctx: CaseContext) {
227 yield* toHome(ctx);
228 const steps: Step[] = [];
229 for (const [step, label] of [
230 ["pulls", "PRs"],
231 ["usage", "Usage"],
232 ["chats", "Chats"],
233 ] as const) {
234 steps.push(
235 yield* measure(
236 ctx,
237 { case: "tabs", step, visit: "step" },
238 ctx.device.press(`role=button label="${label}"`),
239 ),
240 );
241 }
242 return steps;
243 }),
244​
245 /** The pull request list, then the branch's pull request with its body, files and comments. */
246 "pull-request": Effect.fn("metrics.pullRequest")(function* (ctx: CaseContext) {
247 yield* toHome(ctx);
248 const steps: Step[] = [];
249 steps.push(
250 yield* measure(
251 ctx,
252 { case: "pull-request", step: "list", visit: "step" },
253 ctx.device.press('role=button label="PRs"'),
254 ),
255 );
256 const row = yield* findNode(ctx, "pull request row", (label) =>
257 label.includes("Bench change 1"),
258 );
259 steps.push(
260 yield* measure(
261 ctx,
262 { case: "pull-request", step: "details", visit: "step" },
263 ctx.device.press(row),
264 ),
265 );
266 yield* ctx.device.back;
267 yield* Effect.sleep("800 millis");
268 yield* ctx.device.press('role=button label="Chats"');
269 return steps;
270 }),
271​
272 /** The issues list, which shares the pull requests' tab slot through the list switcher. */
273 issues: Effect.fn("metrics.issues")(function* (ctx: CaseContext) {
274 yield* toHome(ctx);
275 yield* ctx.device.press('role=button label="PRs"');
276 // The header title (SharedSlotTitle) is a menu trigger whose whole area belongs to its child
277 // views, so agent-device will not tap it by ref; tap its centre instead.
278 yield* pressSwitcher(ctx, "Pull requests, switch list");
279 const target = yield* findNode(ctx, "Issues menu item", (label) => label === "Issues");
280 const step = yield* measure(
281 ctx,
282 { case: "issues", step: "list", visit: "step" },
283 ctx.device.press(target),
284 );
285 // Hand the slot back, so the pull request case finds its tab.
286 yield* pressSwitcher(ctx, "Issues, switch list");
287 yield* ctx.device.press(
288 yield* findNode(ctx, "Pull requests menu item", (label) => label === "Pull requests"),
289 );
290 return [step];
291 }),
292​
293 /** The thread on the 40-file branch: its git menu, then Review changes. */
294 diff: Effect.fn("metrics.diff")(function* (ctx: CaseContext) {
295 yield* openThread(ctx, ctx.fixtures.short);
296 const git = yield* findNode(ctx, "Git controls menu", (label) => label === "Git controls");
297 yield* ctx.device.press(git);
298 const review = yield* findNode(ctx, "Review changes item", (label) =>
299 label.startsWith("Review changes"),
300 );
301 const step = yield* measure(
302 ctx,
303 { case: "diff", step: "review", visit: "step" },
304 ctx.device.press(review),
305 );
306 yield* ctx.device.back.pipe(Effect.ignore);
307 return [step];
308 }),
309​
310 /** From the short thread, its side chat's chip: tap to the side chat's rows. */
311 "side-chat": Effect.fn("metrics.sideChat")(function* (ctx: CaseContext) {
312 yield* openThread(ctx, ctx.fixtures.short);
313 const chat = ctx.fixtures.sideChat;
314 const visit = ctx.visited.has(chat.id) ? "revisit" : "first";
315 ctx.visited.add(chat.id);
316 const step = yield* measure(
317 ctx,
318 { case: "side-chat", step: "open", visit },
319 ctx.device.press(
320 yield* findNode(ctx, "side chat chip", (label) =>
321 label.startsWith(`Open side chat ${chat.title}`),
322 ),
323 ),
324 { thread: chat.id },
325 );
326 return [step];
327 }),
328​
329 /** Keys typed into a short thread's composer, each to its next JS frame. */
330 type: Effect.fn("metrics.type")(function* (ctx: CaseContext) {
331 yield* openThread(ctx, ctx.fixtures.short);
332 const editor = (yield* ctx.device.nodes).find(
333 (node) => node.kind === "text-view" && node.editable === true,
334 );
335 if (!editor?.rect) return yield* new CaseFailure({ message: "No composer on screen." });
336 const { x, y } = ctx.device.center(editor);
337 yield* ctx.device.pressAt(x, y);
338 yield* ctx.device.waitFor("the keyboard", (state) => state.composer.keyboard, 10_000);
339 yield* Effect.sleep("1 second");
340 const step = yield* measure(
341 ctx,
342 { case: "type", step: "keys", visit: "step" },
343 ctx.device.type(TYPED),
344 );
345 // Clear the draft so the next round types into the same empty composer.
346 yield* ctx.device.run(["fill", String(x), String(y), ""]).pipe(Effect.ignore);
347 yield* ctx.device.run(["keyboard", "dismiss"]).pipe(Effect.ignore);
348 return [step];
349 }),
350​
351 /** Drags the long timeline up through history: frames while the list lays out older rows. */
352 "scroll-long": Effect.fn("metrics.scrollLong")(function* (ctx: CaseContext) {
353 yield* openThread(ctx, ctx.fixtures.long);
354 const root = (yield* ctx.device.nodes)[0]?.rect ?? { x: 0, y: 0, width: 400, height: 870 };
355 const x = Math.round(root.width / 2);
356 const drag = Effect.gen(function* () {
357 for (let swipe = 0; swipe < 4; swipe++)
358 yield* ctx.device.swipe(x, Math.round(root.height * 0.3), Math.round(root.height * 0.8));
359 });
360 return [yield* measure(ctx, { case: "scroll-long", step: "drag-up", visit: "step" }, drag)];
361 }),
362} satisfies Record<string, CaseRun>;
363​
364export type CaseName = keyof typeof CASES;
365export const CASE_NAMES = Object.keys(CASES) as ReadonlyArray<CaseName>;