@quiesco/core 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/device.js +0 -1
  2. package/dist/devices/android.d.ts +4 -0
  3. package/dist/devices/android.d.ts.map +1 -1
  4. package/dist/devices/android.js +10 -0
  5. package/dist/devices/android.js.map +1 -1
  6. package/dist/devices/crash.d.ts +24 -0
  7. package/dist/devices/crash.d.ts.map +1 -0
  8. package/dist/devices/crash.js +132 -0
  9. package/dist/devices/crash.js.map +1 -0
  10. package/dist/devices/ios.d.ts +11 -0
  11. package/dist/devices/ios.d.ts.map +1 -1
  12. package/dist/devices/ios.js +19 -0
  13. package/dist/devices/ios.js.map +1 -1
  14. package/dist/devices/provider.d.ts +8 -0
  15. package/dist/devices/provider.d.ts.map +1 -1
  16. package/dist/devices/provider.js.map +1 -1
  17. package/dist/driver.d.ts +2 -0
  18. package/dist/driver.d.ts.map +1 -1
  19. package/dist/driver.js +8 -3
  20. package/dist/driver.js.map +1 -1
  21. package/dist/errors.d.ts +3 -1
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js.map +1 -1
  24. package/dist/index.d.ts +1 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/server/ws-server.d.ts +3 -2
  28. package/dist/server/ws-server.d.ts.map +1 -1
  29. package/dist/server/ws-server.js +14 -2
  30. package/dist/server/ws-server.js.map +1 -1
  31. package/dist/session.d.ts +29 -1
  32. package/dist/session.d.ts.map +1 -1
  33. package/dist/session.js +117 -7
  34. package/dist/session.js.map +1 -1
  35. package/dist/timeline.d.ts +10 -1
  36. package/dist/timeline.d.ts.map +1 -1
  37. package/dist/timeline.js +25 -11
  38. package/dist/timeline.js.map +1 -1
  39. package/package.json +2 -2
  40. package/src/devices/android.ts +13 -0
  41. package/src/devices/crash.ts +146 -0
  42. package/src/devices/ios.ts +25 -0
  43. package/src/devices/provider.ts +8 -0
  44. package/src/driver.ts +9 -3
  45. package/src/errors.ts +3 -1
  46. package/src/index.ts +1 -0
  47. package/src/server/ws-server.ts +12 -2
  48. package/src/session.ts +119 -9
  49. package/src/timeline.ts +33 -6
package/dist/timeline.js CHANGED
@@ -1,8 +1,3 @@
1
- /**
2
- * Timeline of a scenario (Phase 6.9): every call the test made on the app, how long it took and how much
3
- * of it was spent waiting for the app to be idle (as the agent reports it), with the error of a failed
4
- * call. Written as a Chrome trace (chrome://tracing, Perfetto) and a self-contained HTML summary.
5
- */
6
1
  export class Timeline {
7
2
  entries = [];
8
3
  started = Date.now();
@@ -20,16 +15,18 @@ export class Timeline {
20
15
  this.entries.shift();
21
16
  }
22
17
  /** Measure `fn` as one entry. */
23
- async measure(method, label, fn, syncMs) {
18
+ async measure(method, label, fn, timing) {
24
19
  const start = Date.now();
25
20
  try {
26
21
  const r = await fn();
27
- const s = syncMs?.(r);
28
- this.add({ method, label, start, end: Date.now(), ...(s !== undefined ? { syncMs: s } : {}) });
22
+ const t = timing?.(r);
23
+ this.add({ method, label, start, end: Date.now(), ...(t?.syncMs !== undefined ? { syncMs: t.syncMs } : {}), ...(t?.steps !== undefined && t.steps.length > 0 ? { steps: t.steps } : {}) });
29
24
  return r;
30
25
  }
31
26
  catch (e) {
32
- this.add({ method, label, start, end: Date.now(), error: e instanceof Error ? e.message : String(e) });
27
+ // A multi-step action that failed still reports its steps (issue #78).
28
+ const steps = e?.data?.steps;
29
+ this.add({ method, label, start, end: Date.now(), ...(Array.isArray(steps) && steps.length > 0 ? { steps: steps } : {}), error: e instanceof Error ? e.message : String(e) });
33
30
  throw e;
34
31
  }
35
32
  }
@@ -42,7 +39,15 @@ export class Timeline {
42
39
  const events = [{ name: 'process_name', ph: 'M', pid: 1, tid: 1, args: { name: `Quiesco: ${this.name}` } }];
43
40
  for (const e of this.entries) {
44
41
  events.push({ name: `${e.method} ${e.label}`.trim(), cat: e.method, ph: 'X', ts: us(e.start), dur: Math.max(1, us(e.end) - us(e.start)), pid: 1, tid: 1, args: e.error !== undefined ? { error: e.error } : {} });
45
- if (e.syncMs !== undefined && e.syncMs > 0) {
42
+ if (e.steps !== undefined) {
43
+ e.steps.forEach((s, i) => {
44
+ const ts = us(e.start + s.atMs);
45
+ events.push({ name: `step ${i + 1} ${s.label}`.trim(), cat: 'step', ph: 'X', ts, dur: Math.max(1, s.ms * 1000), pid: 1, tid: 1, args: { syncMs: s.syncMs } });
46
+ if (s.syncMs > 0)
47
+ events.push({ name: 'wait for idle', cat: 'sync', ph: 'X', ts: ts + Math.max(0, s.ms - s.syncMs) * 1000, dur: Math.max(1, s.syncMs * 1000), pid: 1, tid: 1 });
48
+ });
49
+ }
50
+ else if (e.syncMs !== undefined && e.syncMs > 0) {
46
51
  events.push({ name: 'wait for idle', cat: 'sync', ph: 'X', ts: us(e.start), dur: Math.max(1, Math.round(e.syncMs * 1000)), pid: 1, tid: 1 });
47
52
  }
48
53
  }
@@ -58,7 +63,15 @@ export class Timeline {
58
63
  const sync = e.syncMs !== undefined ? Math.min(100, (e.syncMs / Math.max(1, e.end - e.start)) * 100) : 0;
59
64
  const cls = e.error !== undefined ? 'row failed' : 'row';
60
65
  const err = e.error !== undefined ? `<div class="err">${esc(e.error)}</div>` : '';
61
- return `<div class="${cls}"><div class="name">${esc(`${e.method} ${e.label}`)}</div><div class="ms">${e.end - e.start} ms${e.syncMs !== undefined ? ` (idle wait ${Math.round(e.syncMs)} ms)` : ''}</div><div class="track"><div class="bar" style="left:${left.toFixed(2)}%;width:${width.toFixed(2)}%"><div class="sync" style="width:${sync.toFixed(1)}%"></div></div></div>${err}</div>`;
66
+ const steps = (e.steps ?? [])
67
+ .map((s, i) => {
68
+ const sLeft = ((e.start + s.atMs - this.started) / total) * 100;
69
+ const sWidth = Math.max(0.2, (s.ms / total) * 100);
70
+ const sSync = Math.min(100, (s.syncMs / Math.max(1, s.ms)) * 100);
71
+ return `<div class="row step"><div class="name">step ${i + 1} ${esc(s.label)}</div><div class="ms">${s.ms} ms (idle wait ${s.syncMs} ms)</div><div class="track"><div class="bar" style="left:${sLeft.toFixed(2)}%;width:${sWidth.toFixed(2)}%"><div class="sync" style="width:${sSync.toFixed(1)}%"></div></div></div></div>`;
72
+ })
73
+ .join('');
74
+ return `<div class="${cls}"><div class="name">${esc(`${e.method} ${e.label}`)}</div><div class="ms">${e.end - e.start} ms${e.syncMs !== undefined ? ` (idle wait ${Math.round(e.syncMs)} ms)` : ''}</div><div class="track"><div class="bar" style="left:${left.toFixed(2)}%;width:${width.toFixed(2)}%"><div class="sync" style="width:${sync.toFixed(1)}%"></div></div></div>${err}</div>${steps}`;
62
75
  })
63
76
  .join('\n');
64
77
  return `<!doctype html><html><head><meta charset="utf-8"><title>${esc(this.name)} — Quiesco timeline</title><style>
@@ -66,6 +79,7 @@ body{font:13px system-ui,sans-serif;margin:16px;color:#222}h1{font-size:16px}
66
79
  .row{display:grid;grid-template-columns:minmax(200px,2fr) 140px 3fr;gap:8px;align-items:center;padding:2px 0;border-bottom:1px solid #eee}
67
80
  .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,monospace}.ms{color:#666;text-align:right}
68
81
  .track{position:relative;height:12px;background:#f4f4f4}.bar{position:absolute;top:0;height:12px;background:#6b8de3}.sync{height:12px;background:#b9c9f3}
82
+ .step .name{padding-left:16px;color:#555}.step .bar{background:#9aa9cc}
69
83
  .failed .bar{background:#d9534f}.failed .name{color:#c00}.err{grid-column:1/-1;color:#c00;white-space:pre-wrap;font-family:ui-monospace,monospace;font-size:12px;padding:4px 0 6px}
70
84
  </style></head><body><h1>${esc(this.name)}</h1><p>${this.entries.length} calls, ${total} ms. Light part of a bar: waiting for the app to be idle.</p>
71
85
  ${rows}
@@ -1 +1 @@
1
- {"version":3,"file":"timeline.js","sourceRoot":"","sources":["../src/timeline.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAeH,MAAM,OAAO,QAAQ;IACX,OAAO,GAAoB,EAAE,CAAC;I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AAC,CAAC;QACd,OAAO,2DAA2D,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;;;;;;;2BAOzD,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,IAAI,CAAC,OAAO,CAAC,MAAM,WAAW,KAAK;EACrF,IAAI;eACS,CAAC;IACd,CAAC;CACF;AAED,SAAS,GAAG,CAAC,CAAS;IACpB,OAAO,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAW,CAAC,CAAC;AAC/G,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quiesco/core",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Quiesco host side: WebSocket server, Driver, device providers (test-runner agnostic)",
5
5
  "license": "MIT",
6
6
  "author": "h2nology",
@@ -50,7 +50,7 @@
50
50
  "ios-runner/QuiescoSystemUI.xcodeproj"
51
51
  ],
52
52
  "dependencies": {
53
- "@quiesco/protocol": "0.9.0",
53
+ "@quiesco/protocol": "0.10.0",
54
54
  "ws": "8.22.1"
55
55
  },
56
56
  "devDependencies": {
@@ -42,6 +42,8 @@ export const DEV_MENU_PREFS =
42
42
  ' <boolean name="motionGestureEnabled" value="false" />\n' +
43
43
  '</map>\n';
44
44
 
45
+ import { androidCrash } from './crash.js';
46
+ import type { CrashReport } from './crash.js';
45
47
  import fs from 'node:fs/promises';
46
48
  import os from 'node:os';
47
49
  import path from 'node:path';
@@ -229,6 +231,17 @@ export class AndroidProvider implements DeviceProvider {
229
231
  return this.adbRun(['shell', command]);
230
232
  }
231
233
 
234
+ async isAppRunning(): Promise<boolean> {
235
+ return (await this.shell(`pidof ${shq(this.pkg)}`).catch(() => '')).trim() !== '';
236
+ }
237
+
238
+ /** The crash in logcat's crash buffer (times as epoch seconds, so the host's clock can pick the recent one). */
239
+ async crashReport(sinceMs: number): Promise<CrashReport | null> {
240
+ const log = await this.adbRun(['logcat', '-d', '-b', 'crash', '-v', 'threadtime', '-v', 'epoch']).catch(() => '');
241
+ const summary = androidCrash(log, this.pkg, sinceMs);
242
+ return summary === null ? null : { summary };
243
+ }
244
+
232
245
  /** Online devices from `adb devices`. */
233
246
  private async devices(): Promise<string[]> {
234
247
  const { stdout } = await this.exec(this.adb, ['devices']);
@@ -0,0 +1,146 @@
1
+ /**
2
+ * What a crashed app left behind (issue #76): the crash in Android's logcat crash buffer, or an iOS
3
+ * crash report (`.ips` in ~/Library/Logs/DiagnosticReports), cut down to the lines that say why.
4
+ */
5
+ import fs from 'node:fs/promises';
6
+ import path from 'node:path';
7
+
8
+ /** A crash of the app under test. */
9
+ export interface CrashReport {
10
+ /** A few lines: the exception and the top of the crashing thread's stack. */
11
+ summary: string;
12
+ /** The full report on this machine (iOS), to copy into the evidence. */
13
+ file?: string;
14
+ }
15
+
16
+ /** Stack frames in a summary. */
17
+ const FRAMES = 8;
18
+ /** Longer symbols (C++ templates) are cut. */
19
+ const SYMBOL_CHARS = 140;
20
+
21
+ const LOGCAT_LINE = /^\s*(\d+(?:\.\d+)?)\s+(\d+)\s+(\d+)\s+[VDIWEF]\s+([^:]*?)\s*:\s?(.*)$/;
22
+
23
+ interface LogcatLine {
24
+ t: number;
25
+ pid: string;
26
+ tag: string;
27
+ message: string;
28
+ }
29
+
30
+ function parseLogcat(text: string): LogcatLine[] {
31
+ const out: LogcatLine[] = [];
32
+ for (const line of text.split('\n')) {
33
+ const m = LOGCAT_LINE.exec(line);
34
+ if (m !== null) out.push({ t: Number(m[1]), pid: m[2] as string, tag: m[4] as string, message: (m[5] as string).replace(/\r$/, '') });
35
+ }
36
+ return out;
37
+ }
38
+
39
+ /**
40
+ * The app's last crash in `adb logcat -b crash -v threadtime -v epoch` output at or after `sinceMs`
41
+ * (ms since the epoch): a Java / Kotlin `FATAL EXCEPTION` (the exception and its first frames, with
42
+ * the `Caused by` lines), or a native `Fatal signal` with the abort message and the first backtrace
43
+ * frames. Null when the app did not crash there.
44
+ */
45
+ export function androidCrash(logcat: string, pkg: string, sinceMs: number): string | null {
46
+ const lines = parseLogcat(logcat).filter((l) => l.t * 1000 >= sinceMs - 1000);
47
+ // Java: "FATAL EXCEPTION: main", then "Process: <pkg>, PID: <pid>".
48
+ let java: string[] | null = null;
49
+ for (let i = 0; i < lines.length; i++) {
50
+ const l = lines[i] as LogcatLine;
51
+ if (l.tag !== 'AndroidRuntime' || !l.message.startsWith('FATAL EXCEPTION')) continue;
52
+ const next = lines[i + 1];
53
+ if (next === undefined || !next.message.startsWith(`Process: ${pkg},`)) continue;
54
+ const block = lines.slice(i).filter((b) => b.pid === l.pid && b.tag === 'AndroidRuntime').map((b) => b.message);
55
+ // The exception, its first frames, and each "Caused by" with its first frame.
56
+ const kept: string[] = [];
57
+ let frames = 0;
58
+ for (const m of block) {
59
+ const frame = /^\s*at /.test(m);
60
+ if (!frame) frames = 0;
61
+ else if (++frames > (kept.some((k) => k.startsWith('Caused by')) ? 2 : FRAMES)) continue;
62
+ kept.push(m.replace(/^\t/, ' '));
63
+ }
64
+ java = kept;
65
+ }
66
+ if (java !== null) return java.join('\n');
67
+ // Native: libc "Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 1 (main), pid 1 (<pkg>)", then the
68
+ // tombstone (tag DEBUG): "Abort message: …", "#00 pc …".
69
+ const signal = [...lines].reverse().find((l) => l.message.startsWith('Fatal signal') && l.message.includes(`(${pkg})`));
70
+ if (signal === undefined) return null;
71
+ const after = lines.slice(lines.indexOf(signal) + 1);
72
+ const abort = after.find((l) => l.message.startsWith('Abort message:'));
73
+ const frames = after.filter((l) => /^\s*#\d+ pc /.test(l.message)).slice(0, FRAMES);
74
+ return [signal.message, ...(abort !== undefined ? [abort.message] : []), ...frames.map((f) => ` ${f.message.trim()}`)].join('\n');
75
+ }
76
+
77
+ interface IpsBody {
78
+ exception?: { type?: string; signal?: string; subtype?: string };
79
+ termination?: { indicator?: string };
80
+ asi?: Record<string, unknown>;
81
+ faultingThread?: number;
82
+ threads?: { frames?: { imageIndex?: number; symbol?: string; imageOffset?: number }[] }[];
83
+ usedImages?: { name?: string }[];
84
+ }
85
+
86
+ /** The header (first line) of an `.ips` report, or null when it is not one. */
87
+ export function ipsHeader(text: string): { bundleID?: string; app_name?: string } | null {
88
+ const end = text.indexOf('\n');
89
+ try {
90
+ return JSON.parse(end < 0 ? text : text.slice(0, end)) as { bundleID?: string; app_name?: string };
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ /** An iOS crash report (`.ips`, JSON) as a few lines: exception, termination reason, crashing thread's top frames. */
97
+ export function summarizeIps(text: string): string | null {
98
+ const end = text.indexOf('\n');
99
+ if (end < 0) return null;
100
+ let body: IpsBody;
101
+ try {
102
+ body = JSON.parse(text.slice(end + 1)) as IpsBody;
103
+ } catch {
104
+ return null;
105
+ }
106
+ const lines: string[] = [];
107
+ const e = body.exception;
108
+ if (e?.type !== undefined) lines.push(`${e.type}${e.signal !== undefined ? ` (${e.signal})` : ''}${e.subtype !== undefined ? `: ${e.subtype}` : ''}${body.termination?.indicator !== undefined ? `, ${body.termination.indicator}` : ''}`);
109
+ for (const v of Object.values(body.asi ?? {})) {
110
+ for (const s of Array.isArray(v) ? v : [v]) if (typeof s === 'string' && s.trim() !== '') lines.push(s.trim());
111
+ }
112
+ const n = body.faultingThread;
113
+ const frames = n === undefined ? undefined : body.threads?.[n]?.frames;
114
+ if (frames !== undefined && frames.length > 0) {
115
+ lines.push(`Thread ${n} crashed:`);
116
+ frames.slice(0, FRAMES).forEach((f, i) => {
117
+ const image = (f.imageIndex !== undefined ? body.usedImages?.[f.imageIndex]?.name : undefined) ?? '???';
118
+ const symbol = f.symbol ?? (f.imageOffset !== undefined ? `+${f.imageOffset}` : '');
119
+ lines.push(` ${i} ${image} ${symbol.length > SYMBOL_CHARS ? `${symbol.slice(0, SYMBOL_CHARS)}…` : symbol}`);
120
+ });
121
+ }
122
+ return lines.length > 0 ? lines.join('\n') : null;
123
+ }
124
+
125
+ /** The newest `.ips` report in `dir` for `bundleId` written at or after `sinceMs`. */
126
+ export async function newestIosCrash(dir: string, bundleId: string, sinceMs: number): Promise<CrashReport | null> {
127
+ let names: string[];
128
+ try {
129
+ names = (await fs.readdir(dir)).filter((n) => n.endsWith('.ips'));
130
+ } catch {
131
+ return null;
132
+ }
133
+ const candidates: { file: string; mtime: number }[] = [];
134
+ for (const n of names) {
135
+ const file = path.join(dir, n);
136
+ const stat = await fs.stat(file).catch(() => null);
137
+ if (stat !== null && stat.mtimeMs >= sinceMs - 1000) candidates.push({ file, mtime: stat.mtimeMs });
138
+ }
139
+ candidates.sort((a, b) => b.mtime - a.mtime);
140
+ for (const c of candidates) {
141
+ const text = await fs.readFile(c.file, 'utf8').catch(() => '');
142
+ if (ipsHeader(text)?.bundleID !== bundleId) continue;
143
+ return { summary: summarizeIps(text) ?? 'The crash report could not be read.', file: c.file };
144
+ }
145
+ return null;
146
+ }
@@ -19,6 +19,8 @@
19
19
  * screen), or opening the Settings app for apps without @quiesco/native; foreground = `simctl launch`
20
20
  * without terminating (the running process is activated, its arguments are ignored).
21
21
  */
22
+ import { newestIosCrash } from './crash.js';
23
+ import type { CrashReport } from './crash.js';
22
24
  import fs from 'node:fs/promises';
23
25
  import os from 'node:os';
24
26
  import path from 'node:path';
@@ -136,6 +138,10 @@ export interface IosProviderOptions {
136
138
  worker?: WorkerInfo;
137
139
  /** How long match() / fail() wait for the app's authentication to start (tests). Default 10 s. */
138
140
  biometricWaitMs?: number;
141
+ /** Where crash reports are written (tests). Default ~/Library/Logs/DiagnosticReports. */
142
+ crashReportDir?: string;
143
+ /** How long crashReport() waits for the report to appear (tests). Default 5 s. */
144
+ crashReportWaitMs?: number;
139
145
  }
140
146
 
141
147
  /** What IosProvider uses of IosSystemRunner. */
@@ -1102,6 +1108,25 @@ export class IosProvider implements DeviceProvider {
1102
1108
  if (this.bootedByUs && this.options.device?.shutdown === true) await this.simctl(['shutdown', this.sim.udid]).catch(() => undefined);
1103
1109
  }
1104
1110
 
1111
+ async isAppRunning(): Promise<boolean> {
1112
+ const services = await this.simctl(['spawn', this.udid, 'launchctl', 'list']);
1113
+ return services.split('\n').some((l) => l.includes(`UIKitApplication:${this.bundleId}[`) && /^\d+\s/.test(l));
1114
+ }
1115
+
1116
+ /**
1117
+ * The app's crash report (`.ips`), written by ReportCrash about a second after the crash: waits up to
1118
+ * `crashReportWaitMs` for it.
1119
+ */
1120
+ async crashReport(sinceMs: number): Promise<CrashReport | null> {
1121
+ const dir = this.options.crashReportDir ?? path.join(os.homedir(), 'Library', 'Logs', 'DiagnosticReports');
1122
+ const deadline = Date.now() + (this.options.crashReportWaitMs ?? 5_000);
1123
+ for (;;) {
1124
+ const report = await newestIosCrash(dir, this.bundleId, sinceMs);
1125
+ if (report !== null || Date.now() >= deadline) return report;
1126
+ await new Promise((r) => setTimeout(r, 250));
1127
+ }
1128
+ }
1129
+
1105
1130
  async diagnose(params: LaunchParams): Promise<string[]> {
1106
1131
  const lines = [`The simulator shares the Mac's network: the app connects to ws://localhost:${params.port} directly.`];
1107
1132
  const services = await this.simctl(['spawn', this.udid, 'launchctl', 'list']).catch(() => '');
@@ -1,4 +1,5 @@
1
1
  /** Device abstraction (requirements.md §6.9). One implementation per platform; platform branches live here. */
2
+ import type { CrashReport } from './crash.js';
2
3
  import type { GestureSlop, HostInput, Orientation, Platform, Rect } from '@quiesco/protocol';
3
4
 
4
5
  import type { Permission } from './permissions.js';
@@ -115,6 +116,13 @@ export interface DeviceProvider {
115
116
  /** Perform input the agent cannot do itself (system back, opening a URL, web real input). */
116
117
  injectInput?(input: HostInput): Promise<void>;
117
118
  shutdown(): Promise<void>;
119
+ /**
120
+ * Whether the app's process is alive (issue #76/#77): after a disconnect, a dead process means a crash
121
+ * (no point waiting for the app to reconnect). Missing where the platform cannot tell (web).
122
+ */
123
+ isAppRunning?(): Promise<boolean>;
124
+ /** The app's crash at or after `sinceMs` (ms since the epoch): the reason in a few lines, and the report file (issue #76). */
125
+ crashReport?(sinceMs: number): Promise<CrashReport | null>;
118
126
  /** Extra lines for the "app did not connect" message (e.g. adb reverse state). */
119
127
  diagnose?(params: LaunchParams): Promise<string[]>;
120
128
 
package/src/driver.ts CHANGED
@@ -43,7 +43,7 @@ import { ElementExpectation, checkRatio } from './expect.js';
43
43
  import type { AgentConnection } from './server/ws-server.js';
44
44
  import type { AppRunState, DeviceApi } from './device.js';
45
45
  import type { SyncApi } from './sync-api.js';
46
- import type { Timeline } from './timeline.js';
46
+ import type { CallTiming, Timeline } from './timeline.js';
47
47
  import { WebView } from './webview.js';
48
48
  import { cropToRect } from './screenshots.js';
49
49
  import type { WebViewHost } from './webview.js';
@@ -67,6 +67,8 @@ export interface DriverOptions {
67
67
  appState?: () => AppRunState;
68
68
  /** Where calls are recorded (Phase 6.9 timeline). */
69
69
  timeline?: Timeline;
70
+ /** A call lost its connection: say whether the app crashed (APP_CRASHED, issue #76), else return the error. */
71
+ explainDisconnect?: (e: QuiescoError) => Promise<QuiescoError>;
70
72
  }
71
73
 
72
74
  /** type({ perCharacter: true }): time between two characters, about a quick typist's (issue #52). */
@@ -663,12 +665,16 @@ export class Driver {
663
665
  } catch (e) {
664
666
  // A page reload / relaunch dropped the connection mid-call: read-only calls are safe to repeat
665
667
  // once the app is back (requirements.md §6.2: reconnecting is not an error).
666
- if (e instanceof QuiescoError && e.errorName === 'AGENT_DISCONNECTED' && RETRYABLE.has(method)) return send();
668
+ if (e instanceof QuiescoError && e.errorName === 'AGENT_DISCONNECTED') {
669
+ // send() waits for the app to reconnect, and fails at once when it crashed (issue #77).
670
+ if (RETRYABLE.has(method)) return send();
671
+ if (this.options.explainDisconnect !== undefined) throw await this.options.explainDisconnect(e);
672
+ }
667
673
  throw e;
668
674
  }
669
675
  };
670
676
  const timeline = this.options.timeline;
671
- const run = timeline === undefined || !TIMELINED.has(method) ? attempt() : timeline.measure(method, describeCall(method, params), attempt, (r) => (r as { syncMs?: number }).syncMs);
677
+ const run = timeline === undefined || !TIMELINED.has(method) ? attempt() : timeline.measure(method, describeCall(method, params), attempt, (r) => r as CallTiming);
672
678
  try {
673
679
  return await run;
674
680
  } catch (e) {
package/src/errors.ts CHANGED
@@ -13,7 +13,9 @@ export type HostErrorName =
13
13
  /** The app was sent to the background by the test; bring it to the foreground first. */
14
14
  | 'APP_IN_BACKGROUND'
15
15
  /** A web page is blocked on a JS dialog (alert / confirm / prompt); answer it with app.device.system.tap first. */
16
- | 'DIALOG_OPEN';
16
+ | 'DIALOG_OPEN'
17
+ /** The app's process died (issue #76): the message carries the crash's reason when the device kept one. */
18
+ | 'APP_CRASHED';
17
19
 
18
20
  /**
19
21
  * Every failure surfaced by @quiesco/core. Agent errors keep their protocol code and structured data
package/src/index.ts CHANGED
@@ -25,6 +25,7 @@ export { AndroidProvider } from './devices/android.js';
25
25
  export { IosProvider, IOS_DEV_MENU_ARGS } from './devices/ios.js';
26
26
  export type { IosProviderOptions } from './devices/ios.js';
27
27
  export type { ColorScheme, DeviceProvider, InAppControls, LaunchParams, LaunchUrlHandling, NotificationSpec, StateChange, StatusBarOptions, SystemNode, WorkerInfo } from './devices/provider.js';
28
+ export type { CrashReport } from './devices/crash.js';
28
29
  export type { SystemQuery, SystemWaitOptions } from './system-ui.js';
29
30
  export { DeviceApi } from './device.js';
30
31
  export type { AppRunState, RelaunchOptions } from './device.js';
@@ -216,23 +216,33 @@ export class QuiescoServer {
216
216
 
217
217
  /**
218
218
  * Resolves with the current connection, or the next one for this session. `exclude` skips a
219
- * connection that is about to go away (the old app process during a hard reset).
219
+ * connection that is about to go away (the old app process during a hard reset). `signal`: stop
220
+ * waiting (rejects with its reason).
220
221
  */
221
- waitForConnection(sessionId: string, timeoutMs: number, describeTimeout: () => string, exclude: AgentConnection | null = null): Promise<AgentConnection> {
222
+ waitForConnection(sessionId: string, timeoutMs: number, describeTimeout: () => string, exclude: AgentConnection | null = null, signal?: AbortSignal): Promise<AgentConnection> {
222
223
  const s = this.sessions.get(sessionId);
223
224
  if (s === undefined) return Promise.reject(new Error(`unknown session ${sessionId}`));
224
225
  const current = this.connection(sessionId);
225
226
  if (current !== null && current !== exclude) return Promise.resolve(current);
226
227
  return new Promise((resolve, reject) => {
228
+ const onAbort = (): void => {
229
+ clearTimeout(timer);
230
+ s.waiters = s.waiters.filter((w) => w !== waiter);
231
+ reject(signal?.reason);
232
+ };
227
233
  const waiter = (c: AgentConnection): void => {
228
234
  clearTimeout(timer);
235
+ signal?.removeEventListener('abort', onAbort);
229
236
  resolve(c);
230
237
  };
231
238
  const timer = setTimeout(() => {
232
239
  s.waiters = s.waiters.filter((w) => w !== waiter);
240
+ signal?.removeEventListener('abort', onAbort);
233
241
  reject(new QuiescoError('CONNECT_TIMEOUT', describeTimeout(), { sessionId, timeoutMs, port: this._port }));
234
242
  }, timeoutMs);
235
243
  s.waiters.push(waiter);
244
+ if (signal?.aborted === true) onAbort();
245
+ else signal?.addEventListener('abort', onAbort, { once: true });
236
246
  });
237
247
  }
238
248