@quiesco/core 0.10.0 → 0.11.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.
- package/dist/device.d.ts +5 -0
- package/dist/device.d.ts.map +1 -1
- package/dist/device.js +48 -2
- package/dist/device.js.map +1 -1
- package/dist/devices/ios-runner.d.ts +10 -1
- package/dist/devices/ios-runner.d.ts.map +1 -1
- package/dist/devices/ios-runner.js +17 -6
- package/dist/devices/ios-runner.js.map +1 -1
- package/dist/devices/ios.d.ts +17 -1
- package/dist/devices/ios.d.ts.map +1 -1
- package/dist/devices/ios.js +83 -26
- package/dist/devices/ios.js.map +1 -1
- package/dist/devices/provider.d.ts +15 -0
- package/dist/devices/provider.d.ts.map +1 -1
- package/dist/driver.d.ts.map +1 -1
- package/dist/driver.js +13 -3
- package/dist/driver.js.map +1 -1
- package/dist/server/ws-server.d.ts +1 -0
- package/dist/server/ws-server.d.ts.map +1 -1
- package/dist/server/ws-server.js +2 -0
- package/dist/server/ws-server.js.map +1 -1
- package/dist/timeline.d.ts +9 -0
- package/dist/timeline.d.ts.map +1 -1
- package/dist/timeline.js +34 -7
- package/dist/timeline.js.map +1 -1
- package/package.json +2 -2
- package/src/device.ts +44 -2
- package/src/devices/ios-runner.ts +19 -6
- package/src/devices/ios.ts +94 -25
- package/src/devices/provider.ts +15 -0
- package/src/driver.ts +11 -3
- package/src/server/ws-server.ts +2 -0
- package/src/timeline.ts +33 -7
package/src/devices/ios.ts
CHANGED
|
@@ -36,7 +36,7 @@ import type { Exec } from './exec.js';
|
|
|
36
36
|
import { execCommand } from './exec.js';
|
|
37
37
|
import { LogBuffer, exited, spawnProcess } from './streams.js';
|
|
38
38
|
import type { ChildLike, SpawnProcess } from './streams.js';
|
|
39
|
-
import { IosSystemRunner, PERMISSION_ALLOW, PERMISSION_DENY, backButton, dismissButton, screenNodes } from './ios-runner.js';
|
|
39
|
+
import { IosSystemRunner, PERMISSION_ALLOW, PERMISSION_DENY, backButton, describeAlert, dismissButton, isPermissionAlert, screenNodes } from './ios-runner.js';
|
|
40
40
|
import type { RunnerScreen } from './ios-runner.js';
|
|
41
41
|
import type { Permission } from './permissions.js';
|
|
42
42
|
import { SERIAL_WORKER } from './provider.js';
|
|
@@ -229,7 +229,7 @@ export function uikitNodes(elements: readonly { type: number; label: string; id:
|
|
|
229
229
|
}
|
|
230
230
|
|
|
231
231
|
/**
|
|
232
|
-
* Whether `frame` ([x, y, w, h]) looks like the "Open" button a locked device shows beside the tapped
|
|
232
|
+
* Whether `frame` ([x, y, w, h]) looks like the "Open" button a locked device (or iOS 27 Notification Center, #82) shows beside the tapped
|
|
233
233
|
* notification `b`: in its row, on its left, less than half its width.
|
|
234
234
|
*/
|
|
235
235
|
function revealedOpen(frame: number[], b: { x1: number; x2: number; y1: number; y2: number }): boolean {
|
|
@@ -241,9 +241,16 @@ function revealedOpen(frame: number[], b: { x1: number; x2: number; y1: number;
|
|
|
241
241
|
/** Darwin notification state BiometricKit_Sim reads for "enrolled" (1 / 0). */
|
|
242
242
|
const BIOMETRIC_ENROLLMENT = 'com.apple.BiometricKit.enrollmentChanged';
|
|
243
243
|
|
|
244
|
-
/**
|
|
245
|
-
|
|
244
|
+
/**
|
|
245
|
+
* openNotification: after BANNER_WAIT_MS (at most half the timeout) without a banner, it looks in
|
|
246
|
+
* Notification Center. Long enough for a notification scheduled a few seconds ahead to show as a banner:
|
|
247
|
+
* opened earlier, Notification Center receives it, and on iOS 27 a tap on a notification that just
|
|
248
|
+
* arrived there does nothing (2 s: 1 run in 4 failed once the runner was warm, issue #82).
|
|
249
|
+
*/
|
|
250
|
+
const BANNER_WAIT_MS = 5_000;
|
|
246
251
|
const NOTIFICATION_POLL_MS = 250;
|
|
252
|
+
/** System UI slides in for ~430–615 ms: two reads this far apart must agree before a touch (issue #87). */
|
|
253
|
+
const SYSTEM_UI_SETTLE_MS = 250;
|
|
247
254
|
/** openUrlFromOutside: how long SpringBoard's "Open in …?" confirmation may take to show up. */
|
|
248
255
|
const OPEN_URL_CONFIRM_MS = 5_000;
|
|
249
256
|
/**
|
|
@@ -272,6 +279,8 @@ export class IosProvider implements DeviceProvider {
|
|
|
272
279
|
private readonly logger: Logger;
|
|
273
280
|
/** XCUITest runner for SpringBoard's UI, started on first use (Phase 6.7 batch C). */
|
|
274
281
|
private runnerInstance: SystemRunnerLike | null = null;
|
|
282
|
+
/** A runner start in progress: a warm-up (sendToBackground) and a system UI call share it. */
|
|
283
|
+
private runnerStarting: Promise<void> | null = null;
|
|
275
284
|
/** Phase 6.9 artifacts: the running recorder and log stream. */
|
|
276
285
|
private recorder: { child: ChildLike; file: string } | null = null;
|
|
277
286
|
private logStream: ChildLike | null = null;
|
|
@@ -489,6 +498,9 @@ export class IosProvider implements DeviceProvider {
|
|
|
489
498
|
}
|
|
490
499
|
|
|
491
500
|
async sendToBackground(app: InAppControls): Promise<void> {
|
|
501
|
+
// What follows is often openNotification: a runner that starts only then (7–15 s cold) misses the
|
|
502
|
+
// banner (issue #82). Started in the background; a failure shows up when the runner is used.
|
|
503
|
+
this.startRunner().catch((e: unknown) => this.logger.debug(`warming up the iOS system UI runner failed: ${(e as Error).message}`));
|
|
492
504
|
if (await app.suspend().catch(() => false)) return;
|
|
493
505
|
// No @quiesco/native (or an older one): another app in front puts ours in the background too.
|
|
494
506
|
this.logger.debug('sendToBackground: the app cannot suspend itself; opening the Settings app instead');
|
|
@@ -731,9 +743,18 @@ export class IosProvider implements DeviceProvider {
|
|
|
731
743
|
*/
|
|
732
744
|
/** Start the system UI runner: system UI waits start their clock after it (a cold start takes 7–15 s, issue #64). */
|
|
733
745
|
async prepareSystemUi(): Promise<void> {
|
|
734
|
-
await this.
|
|
746
|
+
await this.startRunner();
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
private startRunner(): Promise<void> {
|
|
750
|
+
this.runnerStarting ??= (async () => this.runner.start?.())().finally(() => {
|
|
751
|
+
this.runnerStarting = null;
|
|
752
|
+
});
|
|
753
|
+
return this.runnerStarting;
|
|
735
754
|
}
|
|
736
755
|
|
|
756
|
+
readonly systemUiSettleMs = SYSTEM_UI_SETTLE_MS;
|
|
757
|
+
|
|
737
758
|
async systemNodes(): Promise<SystemNode[]> {
|
|
738
759
|
const runner = this.runner;
|
|
739
760
|
const nodes = screenNodes(await runner.screen());
|
|
@@ -745,6 +766,15 @@ export class IosProvider implements DeviceProvider {
|
|
|
745
766
|
return nodes;
|
|
746
767
|
}
|
|
747
768
|
|
|
769
|
+
/**
|
|
770
|
+
* SpringBoard's UI (alerts, the Face ID prompt, banners) slides in: read it again. Not a node of an app's
|
|
771
|
+
* element tree: a read of that takes seconds (18 s with a web page in it), the animation is over by then.
|
|
772
|
+
*/
|
|
773
|
+
systemNodeReread(node: SystemNode): (() => Promise<SystemNode[]>) | null {
|
|
774
|
+
if (node.app !== undefined) return null;
|
|
775
|
+
return async () => screenNodes(await this.runner.screen());
|
|
776
|
+
}
|
|
777
|
+
|
|
748
778
|
async tapSystemNode(node: SystemNode): Promise<void> {
|
|
749
779
|
await this.runner.tap((node.bounds.x1 + node.bounds.x2) / 2, (node.bounds.y1 + node.bounds.y2) / 2);
|
|
750
780
|
}
|
|
@@ -863,28 +893,26 @@ export class IosProvider implements DeviceProvider {
|
|
|
863
893
|
taps++;
|
|
864
894
|
// A stack that expanded shows more matching notifications: look again right away.
|
|
865
895
|
const expanded = async () => (await find(), shown.filter(matches).length > matching);
|
|
866
|
-
|
|
867
|
-
//
|
|
868
|
-
//
|
|
869
|
-
//
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
if (revealed !== undefined) {
|
|
873
|
-
const r = screenNodes({ alerts: [], others: [revealed] })[0]!.bounds;
|
|
874
|
-
this.logger.warn(`openNotification: tapping "${title}" showed ${JSON.stringify(revealed.label)} (a locked device); tapping it`);
|
|
875
|
-
await runner.tap((r.x1 + r.x2) / 2, (r.y1 + r.y2) / 2);
|
|
876
|
-
if (await this.tapOpened(appState !== undefined, inFront, find, deadline, async () => false)) return;
|
|
877
|
-
}
|
|
896
|
+
// On a locked device, and in Notification Center on iOS 27 (the Cover Sheet), a tap may only slide
|
|
897
|
+
// the notification to the right and show an "Open" button on its left (in the device's language),
|
|
898
|
+
// withdrawn ~3 s later (issue #82): a new, small button, not a notification, left in that row. Not
|
|
899
|
+
// one on the right ("Clear", "Options"), nor another notification. Read from the last `find`.
|
|
900
|
+
const revealed = () => shown.find((o) => !before.has(o.label) && !matches(o) && !o.label.includes(', ') && revealedOpen(o.frame, b));
|
|
901
|
+
if (await this.tapOpened(appState !== undefined, inFront, find, deadline, expanded, revealed, title)) return;
|
|
878
902
|
this.logger.warn(`openNotification: the app did not come to the front after tapping "${title}"; looking again`);
|
|
879
903
|
continue;
|
|
880
904
|
}
|
|
881
905
|
if (taps > 0 && (await inFront())) return;
|
|
882
906
|
if (Date.now() > deadline) {
|
|
883
|
-
const
|
|
907
|
+
const screen = await runner.screen().catch((): RunnerScreen => ({ alerts: [], others: [] }));
|
|
908
|
+
// A system alert is often the reason (issue #85: the permission prompt, so nothing was scheduled).
|
|
909
|
+
const alerts = screen.alerts.length === 0 ? '' : `; a system alert is up: ${screen.alerts.map(describeAlert).join(', ')}`;
|
|
910
|
+
const seen = `${screen.others.map((o) => JSON.stringify(o.label)).slice(0, 8).join(', ') || 'nothing'}${alerts}`;
|
|
884
911
|
if (taps > 0) {
|
|
885
|
-
throw new QuiescoError('DEVICE_ERROR', `openNotification: tapped "${title}" ${taps} time(s), but the app did not come to the front within ${timeoutMs}ms (seen: ${seen
|
|
912
|
+
throw new QuiescoError('DEVICE_ERROR', `openNotification: tapped "${title}" ${taps} time(s), but the app did not come to the front within ${timeoutMs}ms (seen: ${seen})`);
|
|
886
913
|
}
|
|
887
|
-
|
|
914
|
+
const hint = screen.alerts.some(isPermissionAlert) ? 'Answer the permission alert first (system.allowPermission())' : 'Can the app show notifications (system.allowPermission())?';
|
|
915
|
+
throw new QuiescoError('DEVICE_ERROR', `openNotification: no notification "${title}" in a banner or Notification Center within ${timeoutMs}ms (seen: ${seen}). ${hint}`);
|
|
888
916
|
}
|
|
889
917
|
// The banner goes away after a few seconds (also after a tap that missed it); then the notification is in Notification Center.
|
|
890
918
|
if (!centerOpened && (taps > 0 || Date.now() > start + Math.min(BANNER_WAIT_MS, timeoutMs / 2))) {
|
|
@@ -898,27 +926,62 @@ export class IosProvider implements DeviceProvider {
|
|
|
898
926
|
/**
|
|
899
927
|
* Whether a notification tap opened the app: the app is in front within NOTIFICATION_FRONT_MS
|
|
900
928
|
* (`knowsState`), else (a runner that cannot tell) the notification went away within NOTIFICATION_TAP_CONFIRM_MS.
|
|
929
|
+
* An "Open" button the tap revealed (`revealed`, read after each look) is tapped as soon as two looks
|
|
930
|
+
* agree on where it is, and the wait starts again (issue #82: it is withdrawn ~3 s later).
|
|
901
931
|
*/
|
|
902
|
-
private async tapOpened(
|
|
932
|
+
private async tapOpened(
|
|
933
|
+
knowsState: boolean,
|
|
934
|
+
inFront: () => Promise<boolean>,
|
|
935
|
+
find: () => Promise<unknown>,
|
|
936
|
+
deadline: number,
|
|
937
|
+
expanded: () => Promise<boolean>,
|
|
938
|
+
revealed: () => RunnerScreen['others'][number] | undefined,
|
|
939
|
+
title: string,
|
|
940
|
+
): Promise<boolean> {
|
|
903
941
|
// Not past the call's deadline (but one look at least).
|
|
904
|
-
const
|
|
942
|
+
const waitUntil = () => Math.min(Date.now() + (knowsState ? NOTIFICATION_FRONT_MS : NOTIFICATION_TAP_CONFIRM_MS), Math.max(deadline, Date.now()));
|
|
943
|
+
let until = waitUntil();
|
|
944
|
+
let openAt: string | undefined;
|
|
945
|
+
let openTapped = false;
|
|
905
946
|
for (;;) {
|
|
906
947
|
if (knowsState ? await inFront() : (await find()) === undefined) return true;
|
|
907
948
|
if (knowsState && (await expanded())) return false;
|
|
949
|
+
const open = openTapped ? undefined : revealed();
|
|
950
|
+
const at = open === undefined ? undefined : JSON.stringify(open.frame);
|
|
951
|
+
if (open !== undefined && at === openAt) {
|
|
952
|
+
const r = screenNodes({ alerts: [], others: [open] })[0]!.bounds;
|
|
953
|
+
this.logger.warn(`openNotification: tapping "${title}" showed ${JSON.stringify(open.label)} (Notification Center on iOS 27, or a locked device); tapping it`);
|
|
954
|
+
await this.runner.tap((r.x1 + r.x2) / 2, (r.y1 + r.y2) / 2);
|
|
955
|
+
openTapped = true;
|
|
956
|
+
until = waitUntil();
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
openAt = at;
|
|
908
960
|
if (Date.now() >= until) return false;
|
|
909
961
|
await new Promise((r) => setTimeout(r, NOTIFICATION_POLL_MS));
|
|
910
962
|
}
|
|
911
963
|
}
|
|
912
964
|
|
|
913
|
-
/**
|
|
965
|
+
/**
|
|
966
|
+
* Alerts outlive the app (a relaunch keeps a permission alert up): dismiss what an earlier scenario left.
|
|
967
|
+
* Not a permission alert (issue #86): either answer sticks (a denied notification permission only goes
|
|
968
|
+
* away with a reinstall), so the scenario fails, saying which alert is up.
|
|
969
|
+
*/
|
|
914
970
|
private async dismissLeftoverAlerts(): Promise<void> {
|
|
915
971
|
if (this.runnerInstance?.running !== true) return;
|
|
916
972
|
for (let i = 0; i < 3; i++) {
|
|
917
973
|
const alert = (await this.runner.screen().catch(() => null))?.alerts[0];
|
|
918
974
|
if (alert === undefined) return;
|
|
975
|
+
if (isPermissionAlert(alert)) {
|
|
976
|
+
const message =
|
|
977
|
+
`a system permission alert left by the previous scenario is still up: ${describeAlert(alert)}. Quiesco does not answer it for you ` +
|
|
978
|
+
`(on iOS "Don't Allow" for notifications sticks until the app is reinstalled). Answer it in the scenario that brings it up ` +
|
|
979
|
+
`(app.device.system.allowPermission() / denyPermission()), or grant the permission before the app starts (config \`permissions\`)`;
|
|
980
|
+
throw new QuiescoError('RESET_FAILED', message, { step: 'system alert', message });
|
|
981
|
+
}
|
|
919
982
|
const button = dismissButton(alert);
|
|
920
983
|
if (button === undefined) return;
|
|
921
|
-
this.logger.warn(`dismissing a system alert left by the previous scenario: ${JSON.stringify(
|
|
984
|
+
this.logger.warn(`dismissing a system alert left by the previous scenario: ${describeAlert(alert)}; tapping ${JSON.stringify(button.label)}`);
|
|
922
985
|
const [x = 0, y = 0, w = 0, h = 0] = button.frame;
|
|
923
986
|
await this.runner.tap(x + w / 2, y + h / 2).catch(() => undefined);
|
|
924
987
|
}
|
|
@@ -936,7 +999,7 @@ export class IosProvider implements DeviceProvider {
|
|
|
936
999
|
if (alert === undefined) break;
|
|
937
1000
|
const button = dismissButton(alert);
|
|
938
1001
|
if (button === undefined) break;
|
|
939
|
-
this.logger.warn(`dismissing a system alert covering the app: ${JSON.stringify(
|
|
1002
|
+
this.logger.warn(`dismissing a system alert covering the app: ${describeAlert(alert)}; tapping ${JSON.stringify(button.label)}`);
|
|
940
1003
|
const [x = 0, y = 0, w = 0, h = 0] = button.frame;
|
|
941
1004
|
await this.runner.tap(x + w / 2, y + h / 2).catch(() => undefined);
|
|
942
1005
|
closed.push(alert.label);
|
|
@@ -944,6 +1007,12 @@ export class IosProvider implements DeviceProvider {
|
|
|
944
1007
|
return closed;
|
|
945
1008
|
}
|
|
946
1009
|
|
|
1010
|
+
async unansweredSystemAlert(): Promise<string | undefined> {
|
|
1011
|
+
const alert = (await this.runner.screen().catch(() => null))?.alerts.find(isPermissionAlert);
|
|
1012
|
+
if (alert === undefined) return undefined;
|
|
1013
|
+
return `A system permission alert is up over the app: ${describeAlert(alert)}. Quiesco does not answer it for you: answer it in the scenario (app.device.system.allowPermission() / denyPermission())`;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
947
1016
|
async resetDeviceState(app: InAppControls): Promise<StateChange> {
|
|
948
1017
|
await this.dismissLeftoverAlerts();
|
|
949
1018
|
for (const [what, value] of this.changed) {
|
package/src/devices/provider.ts
CHANGED
|
@@ -193,6 +193,21 @@ export interface DeviceProvider {
|
|
|
193
193
|
prepareSystemUi?(): Promise<void>;
|
|
194
194
|
/** System UI on screen now that does not belong to the app (dialogs, prompts), topmost window first. */
|
|
195
195
|
systemNodes?(): Promise<SystemNode[]>;
|
|
196
|
+
/**
|
|
197
|
+
* System UI slides or fades in here and a touch during that animation is lost (iOS, issue #87): system
|
|
198
|
+
* taps, types and expectVisible act on a match only once two reads this many ms apart agree on where it is.
|
|
199
|
+
*/
|
|
200
|
+
readonly systemUiSettleMs?: number;
|
|
201
|
+
/**
|
|
202
|
+
* The settle check's second read (issue #87): only the part of the system UI `node` came from, or null
|
|
203
|
+
* for none (act on it now). Without this method: systemNodes().
|
|
204
|
+
*/
|
|
205
|
+
systemNodeReread?(node: SystemNode): (() => Promise<SystemNode[]>) | null;
|
|
206
|
+
/**
|
|
207
|
+
* A system alert over the app that dismissSystemAlerts leaves up (iOS: a permission alert, issue #86),
|
|
208
|
+
* described for an error message; undefined when there is none.
|
|
209
|
+
*/
|
|
210
|
+
unansweredSystemAlert?(): Promise<string | undefined>;
|
|
196
211
|
tapSystemNode?(node: SystemNode): Promise<void>;
|
|
197
212
|
/**
|
|
198
213
|
* Tap the field `node` and type `text` into it with the device's input (issues #51): iOS through the
|
package/src/driver.ts
CHANGED
|
@@ -563,8 +563,11 @@ export class Driver {
|
|
|
563
563
|
const covered = e instanceof QuiescoError && (e.errorName === 'ELEMENT_OBSCURED' || (e.errorName === 'ELEMENT_NOT_FOUND' && e.data['reason'] === 'not-in-window'));
|
|
564
564
|
if (!covered || dismiss === undefined) throw e;
|
|
565
565
|
const closed = await dismiss().catch(() => [] as string[]);
|
|
566
|
-
if (closed.length
|
|
567
|
-
|
|
566
|
+
if (closed.length > 0) return this.call('action', params, timeoutMs, steps);
|
|
567
|
+
// One Quiesco leaves up (a permission alert, issue #86) is the likely reason: say so.
|
|
568
|
+
const unanswered = await this.options.provider.unansweredSystemAlert?.().catch(() => undefined);
|
|
569
|
+
if (unanswered === undefined) throw e;
|
|
570
|
+
throw new QuiescoError(e.errorName, `${e.message}\n${unanswered}`, e.data as never);
|
|
568
571
|
}
|
|
569
572
|
}
|
|
570
573
|
|
|
@@ -733,6 +736,10 @@ export class Driver {
|
|
|
733
736
|
this.logErrors.push(l.message);
|
|
734
737
|
if (this.logErrors.length > MAX_APP_LOG_ERRORS) this.logErrors.shift();
|
|
735
738
|
});
|
|
739
|
+
// Steps of the running call, in the timeline before the call returns (issue #84).
|
|
740
|
+
conn.on('step', (s) => {
|
|
741
|
+
if (this.watched === conn) this.options.timeline?.step(s);
|
|
742
|
+
});
|
|
736
743
|
conn.on('appError', (e) => {
|
|
737
744
|
if (this.watched !== conn) return;
|
|
738
745
|
if (this.options.ignoreAppErrors?.some((re) => re.test(e.message)) === true) {
|
|
@@ -749,7 +756,8 @@ export class Driver {
|
|
|
749
756
|
function describeCall(method: string, params: unknown): string {
|
|
750
757
|
const p = (params ?? {}) as Record<string, unknown>;
|
|
751
758
|
const spec = (p['action'] ?? p['assertion']) as Record<string, unknown> | undefined;
|
|
752
|
-
|
|
759
|
+
// scrollTo: the element it looks for.
|
|
760
|
+
const matcher = spec?.['matcher'] ?? spec?.['target'] ?? p['matcher'];
|
|
753
761
|
const what = spec !== undefined ? String(spec['type']) : method === 'backdoor' ? String(p['name']) : '';
|
|
754
762
|
const m = matcher === undefined ? '' : JSON.stringify(matcher);
|
|
755
763
|
return [what, m.length > 120 ? `${m.slice(0, 117)}...` : m].filter((x) => x !== '').join(' ');
|
package/src/server/ws-server.ts
CHANGED
|
@@ -31,6 +31,7 @@ interface Pending {
|
|
|
31
31
|
export class AgentConnection extends EventEmitter<{
|
|
32
32
|
log: [AgentEvents['log']];
|
|
33
33
|
appError: [AgentEvents['error']];
|
|
34
|
+
step: [AgentEvents['step']];
|
|
34
35
|
close: [code: number, reason: string];
|
|
35
36
|
}> {
|
|
36
37
|
private nextId = 1;
|
|
@@ -120,6 +121,7 @@ export class AgentConnection extends EventEmitter<{
|
|
|
120
121
|
}
|
|
121
122
|
if (msg.method === 'log') this.emit('log', msg.params as AgentEvents['log']);
|
|
122
123
|
else if (msg.method === 'error') this.emit('appError', msg.params as AgentEvents['error']);
|
|
124
|
+
else if (msg.method === 'step') this.emit('step', msg.params as AgentEvents['step']);
|
|
123
125
|
}
|
|
124
126
|
|
|
125
127
|
/** @internal */
|
package/src/timeline.ts
CHANGED
|
@@ -27,14 +27,23 @@ export interface CallTiming {
|
|
|
27
27
|
steps?: StepTiming[];
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
/** What a call still running when the timeline is written says (issue #84). */
|
|
31
|
+
export const STILL_RUNNING = 'still running when the scenario ended (the test ended it first: its timeout?)';
|
|
32
|
+
|
|
30
33
|
export class Timeline {
|
|
31
34
|
private entries: TimelineEntry[] = [];
|
|
35
|
+
/** Calls not returned yet, with the steps the agent reported so far (issue #84). */
|
|
36
|
+
private running: TimelineEntry[] = [];
|
|
37
|
+
/** Bumped by reset: a call of an earlier scenario that returns late does not land in this one. */
|
|
38
|
+
private generation = 0;
|
|
32
39
|
private started = Date.now();
|
|
33
40
|
private name = '';
|
|
34
41
|
|
|
35
42
|
/** Start a new scenario's timeline. */
|
|
36
43
|
reset(name: string): void {
|
|
37
44
|
this.entries = [];
|
|
45
|
+
this.running = [];
|
|
46
|
+
this.generation++;
|
|
38
47
|
this.started = Date.now();
|
|
39
48
|
this.name = name;
|
|
40
49
|
}
|
|
@@ -48,28 +57,44 @@ export class Timeline {
|
|
|
48
57
|
/** Measure `fn` as one entry. */
|
|
49
58
|
async measure<T>(method: string, label: string, fn: () => Promise<T>, timing?: (r: T) => CallTiming | undefined): Promise<T> {
|
|
50
59
|
const start = Date.now();
|
|
60
|
+
const running: TimelineEntry = { method, label, start, end: start, steps: [] };
|
|
61
|
+
this.running.push(running);
|
|
62
|
+
const generation = this.generation;
|
|
63
|
+
const add = (entry: TimelineEntry): void => {
|
|
64
|
+
if (generation === this.generation) this.add(entry);
|
|
65
|
+
};
|
|
51
66
|
try {
|
|
52
67
|
const r = await fn();
|
|
53
68
|
const t = timing?.(r);
|
|
54
|
-
|
|
69
|
+
add({ method, label, start, end: Date.now(), ...(t?.syncMs !== undefined ? { syncMs: t.syncMs } : {}), ...(t?.steps !== undefined && t.steps.length > 0 ? { steps: t.steps } : {}) });
|
|
55
70
|
return r;
|
|
56
71
|
} catch (e) {
|
|
57
72
|
// A multi-step action that failed still reports its steps (issue #78).
|
|
58
73
|
const steps = (e as { data?: { steps?: unknown } } | null)?.data?.steps;
|
|
59
|
-
|
|
74
|
+
add({ method, label, start, end: Date.now(), ...(Array.isArray(steps) && steps.length > 0 ? { steps: steps as StepTiming[] } : {}), error: e instanceof Error ? e.message : String(e) });
|
|
60
75
|
throw e;
|
|
76
|
+
} finally {
|
|
77
|
+
this.running = this.running.filter((r) => r !== running);
|
|
61
78
|
}
|
|
62
79
|
}
|
|
63
80
|
|
|
81
|
+
/** A step of the running call (calls to the agent run one at a time), reported before it returns (issue #84). */
|
|
82
|
+
step(s: StepTiming): void {
|
|
83
|
+
this.running.at(-1)?.steps?.push(s);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The calls, then those still running (ending now, with the steps so far). */
|
|
64
87
|
get all(): readonly TimelineEntry[] {
|
|
65
|
-
return this.entries;
|
|
88
|
+
if (this.running.length === 0) return this.entries;
|
|
89
|
+
const now = Date.now();
|
|
90
|
+
return [...this.entries, ...this.running.map(({ steps, ...r }) => ({ ...r, end: now, ...(steps !== undefined && steps.length > 0 ? { steps: [...steps] } : {}), error: STILL_RUNNING }))];
|
|
66
91
|
}
|
|
67
92
|
|
|
68
93
|
/** Chrome trace event format: complete events ("X"), sync waits nested inside their calls. */
|
|
69
94
|
toTrace(): string {
|
|
70
95
|
const us = (t: number): number => Math.round((t - this.started) * 1000);
|
|
71
96
|
const events: Record<string, unknown>[] = [{ name: 'process_name', ph: 'M', pid: 1, tid: 1, args: { name: `Quiesco: ${this.name}` } }];
|
|
72
|
-
for (const e of this.
|
|
97
|
+
for (const e of this.all) {
|
|
73
98
|
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 } : {} });
|
|
74
99
|
if (e.steps !== undefined) {
|
|
75
100
|
e.steps.forEach((s, i) => {
|
|
@@ -86,8 +111,9 @@ export class Timeline {
|
|
|
86
111
|
|
|
87
112
|
/** One page: a bar per call (sync wait shaded), failed calls in red with their message. */
|
|
88
113
|
toHtml(): string {
|
|
89
|
-
const
|
|
90
|
-
const
|
|
114
|
+
const entries = this.all;
|
|
115
|
+
const total = Math.max(1, ...entries.map((e) => e.end - this.started));
|
|
116
|
+
const rows = entries
|
|
91
117
|
.map((e) => {
|
|
92
118
|
const left = ((e.start - this.started) / total) * 100;
|
|
93
119
|
const width = Math.max(0.3, ((e.end - e.start) / total) * 100);
|
|
@@ -112,7 +138,7 @@ body{font:13px system-ui,sans-serif;margin:16px;color:#222}h1{font-size:16px}
|
|
|
112
138
|
.track{position:relative;height:12px;background:#f4f4f4}.bar{position:absolute;top:0;height:12px;background:#6b8de3}.sync{height:12px;background:#b9c9f3}
|
|
113
139
|
.step .name{padding-left:16px;color:#555}.step .bar{background:#9aa9cc}
|
|
114
140
|
.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}
|
|
115
|
-
</style></head><body><h1>${esc(this.name)}</h1><p>${
|
|
141
|
+
</style></head><body><h1>${esc(this.name)}</h1><p>${entries.length} calls, ${total} ms. Light part of a bar: waiting for the app to be idle.</p>
|
|
116
142
|
${rows}
|
|
117
143
|
</body></html>`;
|
|
118
144
|
}
|