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

cases.ts

486 lines18.5 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 readonly platform: "ios" | "android";
34 /** Threads opened so far in this app launch, for first visit versus revisit. */
35 readonly visited: Set<string>;
37​
38/** How long the app must stay without input, commits or new content to end a step. */
39const QUIET_MS = 1_000;
40/** A working thread commits on every streamed chunk, so its steps end this long after content. */
41const AFTER_CONTENT_MS = 1_200;
42const STEP_TIMEOUT_MS = 15_000;
43​
44const Peek = Schema.fromJsonString(
45 Schema.Struct({
46 now: Schema.Number,
47 last: Schema.Number,
48 inputs: Schema.Number,
49 content: Schema.Array(Schema.String),
50 }),
51);
52const decodePeek = Schema.decodeUnknownEffect(Peek);
53​
54/** Runs `act` inside a probe window and returns what it measured. */
55const measure = Effect.fn("metrics.measure")(function* (
56 ctx: CaseContext,
57 step: Pick<Step, "case" | "step" | "visit">,
58 act: Effect.Effect<unknown, { readonly message: string }>,
59 options: { readonly thread?: string } = {},
60) {
61 const { device } = ctx;
62 yield* device.evaluate("__t3Behavior.perfStart()");
63 const acted = yield* Effect.result(act);
64 const deadline = (yield* Clock.currentTimeMillis) + STEP_TIMEOUT_MS;
65 let contentSince: number | null = null;
66 while (acted._tag === "Success" && (yield* Clock.currentTimeMillis) < deadline) {
67 const peek = yield* device.evaluate("__t3Behavior.perfPeek()").pipe(
68 Effect.flatMap((value) => decodePeek(value)),
69 Effect.orElseSucceed(() => null),
70 );
71 if (peek) {
72 const shown = options.thread
73 ? peek.content.some((thread) => thread.endsWith(options.thread!))
74 : true;
75 if (shown && options.thread) contentSince ??= peek.now;
76 const quiet = peek.inputs > 0 && peek.now - peek.last > QUIET_MS;
77 if (shown && (quiet || (contentSince !== null && peek.now - contentSince > AFTER_CONTENT_MS)))
78 break;
79 }
80 yield* Effect.sleep("250 millis");
81 }
82 const window = JSON.parse(
83 String(yield* device.evaluate("__t3Behavior.perfStop()")),
84 ) as PerfWindow;
85 if (acted._tag === "Failure")
86 return yield* new CaseFailure({
87 message: `${step.case} ${step.step}: ${acted.failure.message}`,
88 });
89 return stepOf(window, { ...step, round: ctx.round }, options.thread ?? null);
90});
91​
92const isThread = (state: ProbeState, threadId: string) =>
93 state.route?.name === "Thread" && state.route.params.threadId === threadId;
94​
95/** Back to Home's chat list, unmeasured: phones stack threads over it, and tabs share its route. */
96const toHome = Effect.fn("metrics.toHome")(function* (ctx: CaseContext) {
97 for (let attempt = 0; attempt < 4; attempt++) {
98 const state = yield* ctx.device.state;
99 if (state.route?.name === "Home") break;
100 // UIKit can report an unknown outcome while the pop animates; the next state read decides.
101 yield* ctx.device.back.pipe(Effect.ignore);
102 yield* Effect.sleep("800 millis");
103 }
104 yield* ctx.device.waitFor("Home", (state) => state.route?.name === "Home", 5_000);
105 yield* ctx.device.press('role=button label="Chats"').pipe(Effect.ignore);
106});
107​
108/** Finds an on-screen node, skipping list containers that repeat a row's label. */
109const findNode = Effect.fn("metrics.findNode")(function* (
110 ctx: CaseContext,
111 description: string,
112 match: (label: string) => boolean,
113) {
114 for (let attempt = 0; attempt < 10; attempt++) {
115 const node = (yield* ctx.device.nodes).find(
116 (entry) => entry.label !== undefined && entry.kind !== "scroll-area" && match(entry.label),
117 ) as (AxNode & { readonly ref?: string }) | undefined;
118 if (node?.ref) return `@${node.ref}`;
119 if (node?.label) return `label="${node.label}"`;
120 yield* Effect.sleep("500 millis");
121 }
122 return yield* new CaseFailure({ message: `No ${description} on screen.` });
123});
124​
125/** Taps the shared PR/issues list switcher by the centre of its labelled view. */
126const pressSwitcher = Effect.fn("metrics.pressSwitcher")(function* (
127 ctx: CaseContext,
128 label: string,
129) {
130 for (let attempt = 0; attempt < 10; attempt++) {
131 const node = (yield* ctx.device.nodes).find((entry) => entry.label === label && entry.rect);
132 if (node) {
133 const { x, y } = ctx.device.center(node);
134 return yield* ctx.device.pressAt(x, y);
135 }
136 yield* Effect.sleep("500 millis");
137 }
138 return yield* new CaseFailure({ message: `No "${label}" on screen.` });
139});
140​
141/** A Home row's label is its title and status, e.g. "Bench short, Done". */
142const isRow = (label: string | undefined, title: string) =>
143 label === title || label?.startsWith(`${title}, `) === true;
144​
145/** Waits for a Home row and returns its selector, opening the Working shelf if the row folded into it. */
146const waitForRow = Effect.fn("metrics.waitForRow")(function* (ctx: CaseContext, title: string) {
147 for (let attempt = 0; attempt < 20; attempt++) {
148 const nodes = yield* ctx.device.nodes;
149 const row = nodes.find((node) => isRow(node.label, title)) as
150 | (AxNode & { readonly ref?: string })
151 | undefined;
152 // The label ends in a relative time ("Bench short, 4m") that can tick before the press.
153 if (row?.ref) return `@${row.ref}`;
154 if (row?.label) return `label="${row.label}"`;
155 const shelf = nodes.find((node) => /^\d+ working threads?$/.test(node.label ?? ""));
156 if (shelf?.label && attempt % 4 === 1) yield* ctx.device.press(`label="${shelf.label}"`);
157 yield* Effect.sleep("500 millis");
158 }
159 return yield* new CaseFailure({ message: `Row "${title}" never appeared on Home.` });
160});
161​
162/** Opens a thread by tapping its Home row, measured from the tap to its rows on screen. */
163const openFromHome = Effect.fn("metrics.openFromHome")(function* (
164 ctx: CaseContext,
165 name: string,
166 thread: { readonly id: ThreadId; readonly title: string },
167) {
168 yield* toHome(ctx);
169 const row = yield* waitForRow(ctx, thread.title);
170 const visit = ctx.visited.has(thread.id) ? "revisit" : "first";
171 ctx.visited.add(thread.id);
172 const step = yield* measure(ctx, { case: name, step: "open", visit }, ctx.device.press(row), {
173 thread: thread.id,
174 });
175 yield* ctx.device.waitFor("the tapped thread", (state) => isThread(state, thread.id), 10_000);
176 return step;
177});
178​
179const switchTo = (name: "short" | "long") =>
180 Effect.fn(`metrics.switch.${name}`)(function* (ctx: CaseContext) {
181 return [yield* openFromHome(ctx, `switch-${name}`, ctx.fixtures[name])];
182 });
183​
184/** Opens a thread, unmeasured, and waits for its feed. */
185const openThread = Effect.fn("metrics.openThread")(function* (
186 ctx: CaseContext,
187 thread: Fixtures[keyof Fixtures],
188) {
189 yield* toHome(ctx);
190 yield* ctx.device.press(yield* waitForRow(ctx, thread.title));
191 ctx.visited.add(thread.id);
192 yield* ctx.device.waitFor(
193 "the thread's feed",
194 (state) => isThread(state, thread.id) && state.feed?.ready === true,
195 20_000,
196 );
197 yield* Effect.sleep("1 second");
198});
199​
200const TYPED = "check the helpers";
201export const SCROLL_HOME_THREAD_COUNT = 60;
202​
203type CaseRun = (
204 ctx: CaseContext,
205) => Effect.Effect<ReadonlyArray<Step>, { readonly message: string }, SecureRandom.SecureRandom>;
206​
207const NativeFrameSample = Schema.fromJsonString(
208 Schema.Struct({
209 data: Schema.Struct({
210 metrics: Schema.Struct({
211 fps: Schema.Struct({
212 available: Schema.Literal(true),
213 droppedFramePercent: Schema.Number,
214 totalFrameCount: Schema.Number,
215 }),
216 }),
217 }),
218 }),
219);
220const decodeNativeFrameSample = Schema.decodeEffect(NativeFrameSample);
221​
222/** Exercises recycling with spaced swipes or a single burst without command round trips. */
223const scrollHome = (name: "scroll-home" | "fling-home") =>
224 Effect.fn(`metrics.${name}`)(function* (ctx: CaseContext) {
225 yield* toHome(ctx);
226 yield* ctx.device.waitFor(
227 "the populated chat list",
228 (state) =>
229 (state.homeList?.filter((item) => item.type === "v2-thread").length ?? 0) >=
230 SCROLL_HOME_THREAD_COUNT,
231 15_000,
232 );
233 const nodes = yield* ctx.device.nodes;
234 const viewport =
235 ctx.platform === "android"
236 ? nodes.reduce<AxNode["rect"]>(
237 (largest, { rect }) =>
238 rect && (!largest || rect.width * rect.height > largest.width * largest.height)
239 ? rect
240 : largest,
241 undefined,
242 )
243 : nodes[0]?.rect;
244 if (!viewport)
245 return yield* new CaseFailure({ message: "Could not locate the inbox viewport." });
246 const root = viewport;
247 const x = Math.round(root.x + root.width / 2);
248 const top = Math.round(root.y + root.height * 0.3);
249 const bottom = Math.round(root.y + root.height * 0.8);
250 const scroll = Effect.fn("metrics.scrollHome.drag")(function* (from: number, to: number) {
251 if (name === "fling-home") {
252 yield* ctx.device.run([
253 "swipe",
254 String(x),
255 String(from),
256 String(x),
257 String(to),
258 "--count",
259 "4",
260 "--pause-ms",
261 "300",
262 ]);
263 return;
264 }
265 for (let index = 0; index < 4; index++) yield* ctx.device.swipe(x, from, to);
266 });
267 const measureNativeFrames = name === "fling-home" && ctx.platform === "android";
268 const readNativeFrames = ctx.device.run(["perf", "frames", "--json"]);
269 // Reading Android frame stats resets the counters. Read again before scrolling back.
270 if (measureNativeFrames) yield* readNativeFrames;
271 const step = yield* measure(
272 ctx,
273 { case: name, step: "drag-down", visit: "step" },
274 scroll(bottom, top),
275 );
276 const nativeFrames = measureNativeFrames
277 ? (yield* readNativeFrames.pipe(
278 Effect.flatMap(decodeNativeFrameSample),
279 Effect.mapError(
280 () => new CaseFailure({ message: "Android native frame metrics were unavailable." }),
281 ),
282 )).data.metrics.fps
283 : undefined;
284 if (nativeFrames?.totalFrameCount === 0)
285 return yield* new CaseFailure({
286 message: "Android recorded no rendered frames for the fling.",
287 });
288 if (name === "fling-home") {
289 const firstInboxRow = (entries: ReadonlyArray<AxNode>) =>
290 entries
291 .find(
292 ({ label, rect }) =>
293 label?.startsWith("Bench inbox thread ") &&
294 rect !== undefined &&
295 rect.x < root.x + root.width &&
296 rect.x + rect.width > root.x &&
297 rect.y < root.y + root.height &&
298 rect.y + rect.height > root.y,
299 )
300 ?.label?.split(",")[0];
301 const before = firstInboxRow(nodes);
302 const after = firstInboxRow(yield* ctx.device.nodes);
303 if (!before || !after || before === after)
304 return yield* new CaseFailure({
305 message: "The fling did not advance the visible inbox rows.",
306 });
307 }
308 yield* scroll(top, bottom);
309 return [
310 nativeFrames
311 ? {
312 ...step,
313 nativeDroppedPct: nativeFrames.droppedFramePercent,
314 nativeFrameCount: nativeFrames.totalFrameCount,
315 }
316 : step,
317 ];
318 });
319​
320export const CASES = {
321 "switch-short": switchTo("short"),
322 "switch-long": switchTo("long"),
323 /**
324 * A thread streaming a reply, opened twice. Each round starts its own and stops it after, since a
325 * stream anywhere keeps Home committing and no other step would ever go quiet.
326 */
327 "switch-working": Effect.fn("metrics.switch.working")(function* (ctx: CaseContext) {
328 const title = `Bench working ${ctx.round}`;
329 const id = yield* ctx.session.env.launch(title, "Write the report. [[eval:stream:3000:120]]");
330 const thread = { id, title };
331 return yield* Effect.gen(function* () {
332 yield* ctx.device.waitFor(
333 "the scripted reply to start",
334 (state) => state.threads[id] === "working",
335 );
336 return [
337 yield* openFromHome(ctx, "switch-working", thread),
338 yield* openFromHome(ctx, "switch-working", thread),
339 ];
340 }).pipe(Effect.ensuring(ctx.session.env.interruptAll().pipe(Effect.ignore)));
341 }),
342​
343 /** The tab bar: pull requests, usage, then back to chats. */
344 tabs: Effect.fn("metrics.tabs")(function* (ctx: CaseContext) {
345 yield* toHome(ctx);
346 const steps: Step[] = [];
347 for (const [step, label] of [
348 ["pulls", "PRs"],
349 ["usage", "Usage"],
350 ["chats", "Chats"],
351 ] as const) {
352 steps.push(
353 yield* measure(
354 ctx,
355 { case: "tabs", step, visit: "step" },
356 ctx.device.press(`role=button label="${label}"`),
357 ),
358 );
359 }
360 return steps;
361 }),
362​
363 /** The pull request list, then the branch's pull request with its body, files and comments. */
364 "pull-request": Effect.fn("metrics.pullRequest")(function* (ctx: CaseContext) {
365 yield* toHome(ctx);
366 const steps: Step[] = [];
367 steps.push(
368 yield* measure(
369 ctx,
370 { case: "pull-request", step: "list", visit: "step" },
371 ctx.device.press('role=button label="PRs"'),
372 ),
373 );
374 const row = yield* findNode(ctx, "pull request row", (label) =>
375 label.includes("Bench change 1"),
376 );
377 steps.push(
378 yield* measure(
379 ctx,
380 { case: "pull-request", step: "details", visit: "step" },
381 ctx.device.press(row),
382 ),
383 );
384 yield* ctx.device.back;
385 yield* Effect.sleep("800 millis");
386 yield* ctx.device.press('role=button label="Chats"');
387 return steps;
388 }),
389​
390 /** The issues list, which shares the pull requests' tab slot through the list switcher. */
391 issues: Effect.fn("metrics.issues")(function* (ctx: CaseContext) {
392 yield* toHome(ctx);
393 yield* ctx.device.press('role=button label="PRs"');
394 // The header title (SharedSlotTitle) is a menu trigger whose whole area belongs to its child
395 // views, so agent-device will not tap it by ref; tap its centre instead.
396 yield* pressSwitcher(ctx, "Pull requests, switch list");
397 const target = yield* findNode(ctx, "Issues menu item", (label) => label === "Issues");
398 const step = yield* measure(
399 ctx,
400 { case: "issues", step: "list", visit: "step" },
401 ctx.device.press(target),
402 );
403 // Hand the slot back, so the pull request case finds its tab.
404 yield* pressSwitcher(ctx, "Issues, switch list");
405 yield* ctx.device.press(
406 yield* findNode(ctx, "Pull requests menu item", (label) => label === "Pull requests"),
407 );
408 return [step];
409 }),
410​
411 /** The thread on the 40-file branch: its git menu, then Review changes. */
412 diff: Effect.fn("metrics.diff")(function* (ctx: CaseContext) {
413 yield* openThread(ctx, ctx.fixtures.short);
414 const git = yield* findNode(ctx, "Git controls menu", (label) => label === "Git controls");
415 yield* ctx.device.press(git);
416 const review = yield* findNode(ctx, "Review changes item", (label) =>
417 label.startsWith("Review changes"),
418 );
419 const step = yield* measure(
420 ctx,
421 { case: "diff", step: "review", visit: "step" },
422 ctx.device.press(review),
423 );
424 yield* ctx.device.back.pipe(Effect.ignore);
425 return [step];
426 }),
427​
428 /** From the short thread, its side chat's chip: tap to the side chat's rows. */
429 "side-chat": Effect.fn("metrics.sideChat")(function* (ctx: CaseContext) {
430 yield* openThread(ctx, ctx.fixtures.short);
431 const chat = ctx.fixtures.sideChat;
432 const visit = ctx.visited.has(chat.id) ? "revisit" : "first";
433 ctx.visited.add(chat.id);
434 const step = yield* measure(
435 ctx,
436 { case: "side-chat", step: "open", visit },
437 ctx.device.press(
438 yield* findNode(ctx, "side chat chip", (label) =>
439 label.startsWith(`Open side chat ${chat.title}`),
440 ),
441 ),
442 { thread: chat.id },
443 );
444 return [step];
445 }),
446​
447 /** Keys typed into a short thread's composer, each to its next JS frame. */
448 type: Effect.fn("metrics.type")(function* (ctx: CaseContext) {
449 yield* openThread(ctx, ctx.fixtures.short);
450 const editor = (yield* ctx.device.nodes).find(
451 (node) => node.kind === "text-view" && node.editable === true,
452 );
453 if (!editor?.rect) return yield* new CaseFailure({ message: "No composer on screen." });
454 const { x, y } = ctx.device.center(editor);
455 yield* ctx.device.pressAt(x, y);
456 yield* ctx.device.waitFor("the keyboard", (state) => state.composer.keyboard, 10_000);
457 yield* Effect.sleep("1 second");
458 const step = yield* measure(
459 ctx,
460 { case: "type", step: "keys", visit: "step" },
461 ctx.device.type(TYPED),
462 );
463 // Clear the draft so the next round types into the same empty composer.
464 yield* ctx.device.run(["fill", String(x), String(y), ""]).pipe(Effect.ignore);
465 yield* ctx.device.run(["keyboard", "dismiss"]).pipe(Effect.ignore);
466 return [step];
467 }),
468​
469 /** Drags the long timeline up through history: frames while the list lays out older rows. */
470 "scroll-long": Effect.fn("metrics.scrollLong")(function* (ctx: CaseContext) {
471 yield* openThread(ctx, ctx.fixtures.long);
472 const root = (yield* ctx.device.nodes)[0]?.rect ?? { x: 0, y: 0, width: 400, height: 870 };
473 const x = Math.round(root.width / 2);
474 const drag = Effect.gen(function* () {
475 for (let swipe = 0; swipe < 4; swipe++)
476 yield* ctx.device.swipe(x, Math.round(root.height * 0.3), Math.round(root.height * 0.8));
477 });
478 return [yield* measure(ctx, { case: "scroll-long", step: "drag-up", visit: "step" }, drag)];
479 }),
480​
481 "scroll-home": scrollHome("scroll-home"),
482 "fling-home": scrollHome("fling-home"),
483} satisfies Record<string, CaseRun>;
484​
485export type CaseName = keyof typeof CASES;
486export const CASE_NAMES = Object.keys(CASES) as ReadonlyArray<CaseName>;