@g9tm/app-diagnostic 0.3.1 → 0.4.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.
@@ -1,854 +1,854 @@
1
- // Tester mode without a UI (G9AppDiagnostic.Maui TesterMode + TesterCaptureOverlay's actions + TesterReportSendFlow): the
2
- // draft, the captures, the two recorders, the send and the outbox, so a panel, a QA command and a test drive exactly what
3
- // the buttons do. The app only configures it (ITesterHost, folders, preference keys, its facts and hooks).
4
- //
5
- // gesture a double tap with two (or three) fingers = a screenshot NOW, which starts a report if none is open
6
- // screenshot the window FIRST (the panel hides for that frame), then the report, then the file — no editor between
7
- // the tap and the evidence (owner, 2026-10-31)
8
- // screen the window as an MP4 → Recording/, with its sound (the microphone, started after the video: a refused
9
- // microphone costs the sound, never the video) → Voice/ and the app timeline → Diagnostic/, both paired
10
- // with the video and stamped with when they started
11
- // voice a spoken NOTE → Voice/, never paired
12
- // attach any file the system picker returns, COPIED in → File/
13
- // send no title field: the title is the app's, worded by the kind; the description is the app's block and the
14
- // tester's words; → the archive in the outbox → the draft folder removed → the outbox poked; once the
15
- // gateway has it the tester is told its code: «گزارش TR-0042 به سرور رسید.»
16
- //
17
- // Both recorders go through a RecordingSession: a Stop tapped while the start still runs is kept, a Stop has a time limit
18
- // (30 s screen, 10 s voice) and a start or stop that throws ends idle — the button is never stuck and never drops a tap.
19
- import { base64ToBytes } from '../bytes.ts';
20
- import { type DiagnosticFetch, type DiagnosticFiles, type DiagnosticLog, type DiagnosticPrefs, type DiagnosticSendRange, type DiagnosticZipEntry, errorText, silentLog, type Unsubscribe } from '../host.ts';
21
- import { RecordingSession, type RecordingState } from '../recording.ts';
22
- import { createStore, type ReadableStore, type Store } from '../store.ts';
23
- import { type DiagLanguage, type DiagStringKey, translator } from '../strings.ts';
24
- import { type DeviceHeaderNames, type DeviceIdentity, TesterReportUploader, type UploadInit } from '../upload.ts';
25
- import { buildTesterArchive, outboxName, type TesterArchiveHooks } from './archive.ts';
26
- import { compose, DEFAULT_REPORT_KINDS, descriptionRequired, screenFacts, type TesterDescriptionRule, type TesterReportKind } from './compose.ts';
27
- import { loadTesterFeed, readManifest, type TesterFeed } from './feed.ts';
28
- import { createTapPairer, fingersFor, gestureCounts, parseGestureMode, TesterGestureMode } from './gesture.ts';
29
- import { TesterAttachmentKind, type TesterReportDraft } from './model.ts';
30
- import { TesterOutbox } from './outbox.ts';
31
- import type { TesterScreenDescription } from './screen.ts';
32
- import { TesterDraftStore } from './store.ts';
33
- import { type SubscribeLog, TesterTimeline, timelineFileName } from './timeline.ts';
34
-
35
- /** What tester mode needs from the app, and nothing more (ITesterHost). */
36
- export interface ITesterHost {
37
- /** The gateway's base address, read at every send (an admin may change it at runtime). */
38
- gatewayUrl(): string;
39
- /** The device's id (hex, stable per install) — the same it announces on the live channel. */
40
- clientId(): Promise<string>;
41
- /** The secret the gateway issued on the device's first contact; null before that. */
42
- deviceSecret(): Promise<string | null>;
43
- /** Who is signed in now, for a report's author (null when nobody). */
44
- username(): Promise<string | null>;
45
- readonly environmentName: string;
46
- readonly platform: string;
47
- /** The app's version as reports carry it. */
48
- readonly appVersion: string;
49
- }
50
-
51
- /** A finished recording: the file stays where the recorder wrote it. */
52
- export interface MediaRecording {
53
- readonly path: string;
54
- readonly bytes: number;
55
- readonly durationMs: number;
56
- readonly capped?: boolean;
57
- }
58
-
59
- /** One event of the native gesture observer (x, y: fractions of the window). */
60
- export interface TesterTouchEvent {
61
- /** `gesture`: the whole double tap (the native recogniser consumed it); `tap`: one multi-finger tap; `down`: a finger landed. */
62
- readonly type: 'gesture' | 'tap' | 'down';
63
- readonly fingers: number;
64
- readonly x: number;
65
- readonly y: number;
66
- /** On a surface the app excludes from the gesture (a map). */
67
- readonly excluded?: boolean;
68
- }
69
-
70
- /** The platform's recorders and capture (the native module of the platform package). */
71
- export interface TesterMedia {
72
- support(): Promise<{ readonly screen: boolean; readonly voice: boolean }>;
73
- state(): Promise<{ readonly screen: boolean; readonly voice: boolean }>;
74
- startScreen(dir: string, options: { readonly maxFps: number }): Promise<void>;
75
- stopScreen(): Promise<MediaRecording | null>;
76
- startVoice(dir: string): Promise<void>;
77
- stopVoice(): Promise<MediaRecording | null>;
78
- /** The app window as a JPEG (long edge ≤ maxEdge). */
79
- screenshot(maxEdge: number, quality: number): Promise<{ readonly path: string }>;
80
- /** The system picker; the picked file is copied into the app's folders; null when cancelled. */
81
- pick(mimeTypes: readonly string[]): Promise<string | null>;
82
- /**
83
- * Switches the observer: the gesture (with the fingers it needs) and every finger down (a recording's timeline).
84
- * `consume` holds a multi-finger touch away from the views while tester mode is on, so the gesture never also presses
85
- * what is under it; `excludeSurfaces` never holds it over a surface the app excludes (its map, in the «except the map»
86
- * mode). A platform that cannot hold a touch ignores both.
87
- */
88
- watchTouches(options: {
89
- readonly gesture: boolean;
90
- readonly touches: boolean;
91
- readonly fingers: number;
92
- readonly consume?: boolean;
93
- readonly excludeSurfaces?: boolean;
94
- }): Promise<void>;
95
- onTouch(listener: (event: TesterTouchEvent) => void): Unsubscribe;
96
- /** A recording that ended by itself (its maximum length). */
97
- onCaptureEnded?(listener: (kind: 'screen' | 'voice') => void): Unsubscribe;
98
- }
99
-
100
- /** The preference keys tester mode keeps (an app that had tester mode before keeps its own; flags are '1' or absent). */
101
- export interface TesterPrefKeys {
102
- readonly activeReportId: string;
103
- readonly debugMode: string;
104
- readonly gestureMode: string;
105
- readonly showButton: string;
106
- /** The fleet's frame-rate ceiling (a live-channel device setting the app caches). */
107
- readonly captureMaxFps: string;
108
- }
109
-
110
- export const NEUTRAL_TESTER_PREF_KEYS: TesterPrefKeys = {
111
- activeReportId: 'g9.tester.activeReportId',
112
- debugMode: 'g9.tester.debugMode',
113
- gestureMode: 'g9.tester.gestureMode',
114
- showButton: 'g9.tester.showButton',
115
- captureMaxFps: 'g9.tester.captureMaxFps',
116
- };
117
-
118
- export type TesterAiProcessing = 'allowed' | 'off' | 'askTester';
119
-
120
- export type TesterNotice = { readonly text: string; readonly tone: 'success' | 'error' | 'information' | 'warning' };
121
-
122
- export interface TesterEngineOptions {
123
- readonly host: ITesterHost;
124
- readonly files: DiagnosticFiles;
125
- readonly prefs: DiagnosticPrefs;
126
- readonly media: TesterMedia;
127
- /** The drafts' folder and the outbox folder (absolute). */
128
- readonly folders: { readonly drafts: () => Promise<string>; readonly outbox: () => Promise<string> };
129
- readonly prefKeys?: TesterPrefKeys;
130
- readonly http: {
131
- readonly fetch: DiagnosticFetch;
132
- /** The native range request (a chunk never crosses the bridge); without it chunks are read with files.readChunk. */
133
- readonly sendRange?: DiagnosticSendRange;
134
- readonly headers?: DeviceHeaderNames;
135
- readonly extraHeaders?: (url: string) => Readonly<Record<string, string>>;
136
- readonly stepTimeoutMs?: number;
137
- };
138
- readonly language: () => DiagLanguage;
139
- /** «<Product> tester report context». */
140
- readonly productName: string;
141
- /** The app's facts about its screen when a report starts (a section, a site, a map's zoom…). */
142
- readonly describeScreen?: (d: TesterScreenDescription) => void;
143
- /** The app's log, for a recording's timeline. */
144
- readonly subscribeLog?: SubscribeLog;
145
- readonly archive?: TesterArchiveHooks;
146
- /** Holds the process while the outbox sends; resolves the release, or null when it cannot. */
147
- readonly keepAliveWhileSending?: (title: string, subtitle: string) => Promise<(() => void | Promise<void>) | null>;
148
- readonly reportKinds?: readonly TesterReportKind[];
149
- readonly descriptionRule?: TesterDescriptionRule;
150
- readonly aiProcessing?: TesterAiProcessing;
151
- /** The build's git branch and commit: every report carries them. */
152
- readonly branch?: string | null;
153
- readonly commit?: string | null;
154
- readonly online?: () => Promise<boolean>;
155
- readonly notify?: (notice: TesterNotice) => void;
156
- readonly log?: DiagnosticLog;
157
- readonly onError?: (where: string, error: unknown) => void;
158
- /** Lets the panel's hide land before the readback (MAUI waited 80 ms). Default 120. */
159
- readonly settleMs?: number;
160
- readonly stopTimeoutMs?: { readonly screen: number; readonly voice: number };
161
- readonly outboxIntervalMs?: number;
162
- readonly now?: () => number;
163
- }
164
-
165
- export interface TesterState {
166
- readonly enabled: boolean;
167
- readonly draft: TesterReportDraft | null;
168
- /** Active (starting, recording or stopping) — `voice` = a voice NOTE; a screen recording's own sound is `companion`. */
169
- readonly recording: { readonly screen: boolean; readonly voice: boolean };
170
- readonly screenState: RecordingState;
171
- readonly voiceState: RecordingState;
172
- readonly companion: boolean;
173
- /** When the running capture started (the pill's clock), or null. */
174
- readonly recordingStartedMs: number | null;
175
- readonly support: { readonly screen: boolean; readonly voice: boolean };
176
- /** The native gesture observer answered: false keeps the pill's + on screen (no way to open it otherwise). */
177
- readonly gestureSupported: boolean;
178
- readonly gestureMode: TesterGestureMode;
179
- /** Keep the + on screen with no report open. */
180
- readonly showButton: boolean;
181
- /** A capture is in flight: the panel hides itself (not in its own screenshot). */
182
- readonly capturing: boolean;
183
- readonly busy: string | null;
184
- }
185
-
186
- /** What the send form returns. */
187
- export interface TesterSendInput {
188
- /** The tester's own words (the one box). */
189
- readonly words: string;
190
- readonly kind?: string | null;
191
- readonly includeDatabaseBackup: boolean;
192
- /** The form's AI switch (askTester only). */
193
- readonly useAi?: boolean;
194
- }
195
-
196
- export const DEFAULT_CAPTURE_MAX_FPS = 10;
197
-
198
- /** The fleet's frame-rate ceiling for a screen recording (2..20, default 10). */
199
- export function captureMaxFps(raw: string | null): number {
200
- const n = Number(raw);
201
- return raw !== null && Number.isFinite(n) && n > 0 ? Math.min(20, Math.max(2, Math.round(n))) : DEFAULT_CAPTURE_MAX_FPS;
202
- }
203
-
204
- interface ScreenResult {
205
- readonly video: MediaRecording | null;
206
- readonly audio: MediaRecording | null;
207
- readonly timeline: string | null;
208
- }
209
-
210
- const iso = (ms: number) => new Date(ms).toISOString();
211
-
212
- export class TesterEngine {
213
- readonly store: TesterDraftStore;
214
- readonly outbox: TesterOutbox;
215
- private readonly o: TesterEngineOptions;
216
- private readonly keys: TesterPrefKeys;
217
- private readonly state$: Store<TesterState>;
218
- private readonly timeline = new TesterTimeline();
219
- private readonly pairTap: ReturnType<typeof createTapPairer>;
220
- private readonly now: () => number;
221
- private readonly t: ReturnType<typeof translator>;
222
- private readonly log: DiagnosticLog;
223
- private readonly screen: RecordingSession<ScreenResult>;
224
- private readonly voice: RecordingSession<MediaRecording>;
225
- private readonly offs: Unsubscribe[] = [];
226
- private loaded = false;
227
- private quiet = false;
228
- private screenStartedMs = 0;
229
- private companionStartedMs = 0;
230
- private lastOk = false;
231
-
232
- constructor(options: TesterEngineOptions) {
233
- this.o = options;
234
- this.keys = options.prefKeys ?? NEUTRAL_TESTER_PREF_KEYS;
235
- this.now = options.now ?? Date.now;
236
- this.t = translator(options.language);
237
- this.log = options.log ?? silentLog;
238
- this.pairTap = createTapPairer(this.now);
239
- this.store = new TesterDraftStore({ files: options.files, prefs: options.prefs, root: options.folders.drafts, activeKey: this.keys.activeReportId, now: this.now });
240
- this.outbox = new TesterOutbox({
241
- files: options.files,
242
- dir: options.folders.outbox,
243
- online: options.online ?? (async () => true),
244
- upload: (path) => this.uploadArchive(path),
245
- ...(options.outboxIntervalMs !== undefined ? { intervalMs: options.outboxIntervalMs } : {}),
246
- ...(options.keepAliveWhileSending ? { keepAlive: () => options.keepAliveWhileSending!(this.t('TesterReportUploadTitle'), this.t('TesterReportUploadSubtitle')) } : {}),
247
- log: this.log,
248
- });
249
- const flag = (k: string) => options.prefs.get(k) === '1';
250
- this.state$ = createStore<TesterState>({
251
- enabled: flag(this.keys.debugMode),
252
- draft: null,
253
- recording: { screen: false, voice: false },
254
- screenState: 'idle',
255
- voiceState: 'idle',
256
- companion: false,
257
- recordingStartedMs: null,
258
- support: { screen: false, voice: false },
259
- gestureSupported: true,
260
- gestureMode: parseGestureMode(options.prefs.get(this.keys.gestureMode)),
261
- showButton: flag(this.keys.showButton),
262
- capturing: false,
263
- busy: null,
264
- });
265
- const stopMs = options.stopTimeoutMs ?? { screen: 30_000, voice: 10_000 };
266
- this.screen = new RecordingSession<ScreenResult>({
267
- start: () => this.startScreen(),
268
- stop: () => this.stopScreenRecorders(),
269
- finished: (r, timedOut) => this.screenFinished(r, timedOut),
270
- stopTimeoutMs: stopMs.screen,
271
- onStateChanged: (s) => this.recorderState('screen', s),
272
- onFaulted: (e) => this.error('tester.screen', e),
273
- now: this.now,
274
- });
275
- this.voice = new RecordingSession<MediaRecording>({
276
- start: () => this.startVoiceNote(),
277
- stop: () => options.media.stopVoice(),
278
- finished: (r, timedOut) => this.voiceFinished(r, timedOut),
279
- stopTimeoutMs: stopMs.voice,
280
- onStateChanged: (s) => this.recorderState('voice', s),
281
- onFaulted: (e) => this.error('tester.voice', e),
282
- now: this.now,
283
- });
284
- this.offs.push(options.media.onTouch((e) => this.onTouch(e)));
285
- if (options.media.onCaptureEnded) this.offs.push(options.media.onCaptureEnded((k) => void (k === 'screen' ? this.screen.stop() : this.voice.stop())));
286
- }
287
-
288
- get state(): ReadableStore<TesterState> {
289
- return this.state$;
290
- }
291
-
292
- get kinds(): readonly TesterReportKind[] {
293
- return this.o.reportKinds ?? DEFAULT_REPORT_KINDS;
294
- }
295
-
296
- get translate(): ReturnType<typeof translator> {
297
- return this.t;
298
- }
299
-
300
- /** Whether the send form shows the database-backup switch (the app can make one). */
301
- get offersDatabaseBackup(): boolean {
302
- return !!this.o.archive?.createDatabaseBackup;
303
- }
304
-
305
- /** Whether the send form shows the AI switch. */
306
- get asksAboutAi(): boolean {
307
- return this.o.aiProcessing === 'askTester';
308
- }
309
-
310
- /** Stops listening (the app outlives the instance in tests). */
311
- dispose(): void {
312
- for (const off of this.offs.splice(0)) off();
313
- this.timeline.stop();
314
- this.outbox.stop();
315
- }
316
-
317
- /** Re-attaches to the draft a previous run left open and reads what the device supports. Idempotent. */
318
- async load(): Promise<void> {
319
- if (this.loaded) return;
320
- this.loaded = true;
321
- const media = this.o.media;
322
- const [draft, support, native] = await Promise.all([
323
- this.store.active(),
324
- media.support().catch(() => ({ screen: false, voice: false })),
325
- media.state().catch(() => ({ screen: false, voice: false })),
326
- ]);
327
- this.state$.set((s) => ({ ...s, draft, support }));
328
- // A recorder that outlived a reload of the app's script is taken over: both running = a screen recording with its
329
- // sound, so the next Stop keeps the video (its timeline died with the old script).
330
- if (draft && native.screen) {
331
- this.screenStartedMs = this.now();
332
- this.companionStartedMs = this.screenStartedMs;
333
- this.state$.set((s) => ({ ...s, companion: native.voice }));
334
- this.screen.adopt(this.screenStartedMs);
335
- } else if (draft && native.voice) {
336
- this.voice.adopt();
337
- }
338
- await this.applyWatch();
339
- await this.outbox.refresh();
340
- }
341
-
342
- setEnabled(on: boolean): void {
343
- this.o.prefs.set(this.keys.debugMode, on ? '1' : null);
344
- this.state$.set((s) => ({ ...s, enabled: on }));
345
- if (on) void this.load().then(() => this.applyWatch());
346
- else void this.applyWatch();
347
- }
348
-
349
- setGestureMode(mode: TesterGestureMode): void {
350
- this.o.prefs.set(this.keys.gestureMode, String(mode));
351
- this.state$.set((s) => ({ ...s, gestureMode: mode }));
352
- void this.applyWatch();
353
- }
354
-
355
- setShowButton(on: boolean): void {
356
- this.o.prefs.set(this.keys.showButton, on ? '1' : null);
357
- this.state$.set((s) => ({ ...s, showButton: on }));
358
- }
359
-
360
- /** Whether this draft needs the tester's words before it can be sent. */
361
- descriptionRequired(draft: TesterReportDraft | null = this.state$.get().draft): boolean {
362
- return !!draft && descriptionRequired(draft, this.o.descriptionRule ?? 'optional');
363
- }
364
-
365
- // ── the gesture ───────────────────────────────────────────────────────────────────────────────────────────────────
366
-
367
- /** The gesture is observed only while tester mode is on; touch-downs only while a recording's timeline runs. */
368
- private async applyWatch(): Promise<void> {
369
- const s = this.state$.get();
370
- try {
371
- await this.o.media.watchTouches({
372
- gesture: s.enabled,
373
- touches: s.enabled && this.timeline.isRunning,
374
- fingers: fingersFor(s.gestureMode),
375
- consume: s.enabled,
376
- excludeSurfaces: s.gestureMode === TesterGestureMode.TwoFingersExceptMap,
377
- });
378
- if (!this.state$.get().gestureSupported) this.state$.set((x) => ({ ...x, gestureSupported: true }));
379
- } catch (error) {
380
- // A build without the observer: the + stays on screen, the only way in.
381
- if (this.state$.get().gestureSupported) this.state$.set((x) => ({ ...x, gestureSupported: false }));
382
- this.log.log('warn', 'tester', `gesture observer: ${errorText(error)}`);
383
- }
384
- }
385
-
386
- private onTouch(e: TesterTouchEvent): void {
387
- if (e.type === 'down') {
388
- this.timeline.touch(e.x, e.y, e.fingers, this.now());
389
- return;
390
- }
391
- // Only a tap or a whole gesture counts: a watcher may report more (a `seq` trace of a touch, 2026-11-15).
392
- if (e.type !== 'tap' && e.type !== 'gesture') return;
393
- const s = this.state$.get();
394
- if (!s.enabled) return;
395
- const excluded = e.excluded === true;
396
- const fire = e.type === 'gesture' ? gestureCounts(e.fingers, excluded, s.gestureMode) : this.pairTap({ fingers: e.fingers, x: e.x, y: e.y, excluded }, s.gestureMode);
397
- if (!fire) return;
398
- this.log.log('debug', 'tester', `gesture (${e.fingers} fingers)`);
399
- void this.gesture();
400
- }
401
-
402
- /** The gesture: a screenshot NOW, starting a report if none is open. Ignored mid-recording (Stop is the way out). */
403
- async gesture(): Promise<boolean> {
404
- const s = this.state$.get();
405
- if (!s.enabled || s.recording.screen) return false;
406
- return this.screenshot();
407
- }
408
-
409
- // ── helpers ───────────────────────────────────────────────────────────────────────────────────────────────────────
410
-
411
- private notify(key: DiagStringKey, tone: TesterNotice['tone'], ...args: unknown[]): void {
412
- if (this.quiet) return;
413
- const text = this.t(key, ...args);
414
- try {
415
- if (this.o.notify) this.o.notify({ text, tone });
416
- else this.log.log('info', 'tester', text);
417
- } catch {
418
- this.log.log('info', 'tester', text);
419
- }
420
- }
421
-
422
- private error(where: string, error: unknown): void {
423
- if (this.o.onError) this.o.onError(where, error);
424
- else this.log.log('error', 'tester', `${where}: ${errorText(error)}`);
425
- }
426
-
427
- /** One non-recording action at a time (a capture, a send); the record buttons never wait here. */
428
- private async run<T>(name: string, work: () => Promise<T>): Promise<T | null> {
429
- if (this.state$.get().busy) return null;
430
- this.state$.set((s) => ({ ...s, busy: name }));
431
- try {
432
- return await work();
433
- } catch (error) {
434
- this.error(`tester.${name}`, error);
435
- return null;
436
- } finally {
437
- this.state$.set((s) => ({ ...s, busy: null, capturing: false }));
438
- }
439
- }
440
-
441
- private requireDraft(): TesterReportDraft | null {
442
- const draft = this.state$.get().draft;
443
- if (!draft) this.notify('TesterPanelNoDraft', 'warning');
444
- return draft;
445
- }
446
-
447
- /** Opens a report if none is, with where the tester is NOW (its title). True when one was started. */
448
- private async ensureDraft(): Promise<boolean> {
449
- if (this.state$.get().draft) return false;
450
- const facts = screenFacts(this.o.describeScreen, this.t, this.now);
451
- const draft = await this.store.create(
452
- { ...(facts.autoTitle ? { autoTitle: facts.autoTitle } : {}), ...(facts.autoDescription ? { autoDescription: facts.autoDescription } : {}), screen: facts.screen, screenContext: facts.screenContext },
453
- await this.o.host.username().catch(() => null),
454
- );
455
- this.state$.set((s) => ({ ...s, draft }));
456
- this.log.log('debug', 'tester', `draft ${draft.id} started`);
457
- return true;
458
- }
459
-
460
- /** A report with words already written (QA, a test): no capture needed. */
461
- async create(words = ''): Promise<TesterReportDraft | null> {
462
- return this.run('create', async () => {
463
- await this.ensureDraft();
464
- let draft = this.state$.get().draft!;
465
- if (words.trim()) {
466
- draft = { ...draft, description: words.trim() };
467
- await this.store.save(draft);
468
- this.state$.set((s) => ({ ...s, draft }));
469
- }
470
- return draft;
471
- });
472
- }
473
-
474
- // ── captures ──────────────────────────────────────────────────────────────────────────────────────────────────────
475
-
476
- /** The window first, then the report, then the file — attached as it was taken. */
477
- async screenshot(): Promise<boolean> {
478
- const done = await this.run('screenshot', async () => {
479
- this.state$.set((s) => ({ ...s, capturing: true }));
480
- await new Promise((r) => setTimeout(r, this.o.settleMs ?? 120));
481
- let shot: string;
482
- try {
483
- shot = (await this.o.media.screenshot(2160, 92)).path;
484
- } catch {
485
- this.notify('TesterPanelScreenshotFailed', 'error');
486
- return false;
487
- } finally {
488
- this.state$.set((s) => ({ ...s, capturing: false }));
489
- }
490
- // The gesture opens the PANEL as well as the shot: the report starts here.
491
- const started = await this.ensureDraft();
492
- const draft = this.state$.get().draft!;
493
- const next = await this.store.addAttachment(draft, TesterAttachmentKind.Screenshot, shot, { deleteSource: true, displayName: `screenshot-${this.now()}.jpg` });
494
- this.state$.set((s) => ({ ...s, draft: next }));
495
- if (started) this.log.log('info', 'tester', `report ${next.id} started by a screenshot`);
496
- this.notify('TesterPanelScreenshotAdded', 'success');
497
- return true;
498
- });
499
- return done === true;
500
- }
501
-
502
- /** Start / stop the screen recording with its sound and timeline. Never dropped: a stop while starting is kept. */
503
- async toggleScreen(): Promise<boolean> {
504
- if (this.voice.isActive) return false; // a voice note runs: its Stop comes first (the panel offers only it)
505
- return this.toggle(this.screen);
506
- }
507
-
508
- /** A voice NOTE: start on the first tap, stop and attach on the second. Never paired with anything. */
509
- async toggleVoice(): Promise<boolean> {
510
- if (this.screen.isActive) return false;
511
- return this.toggle(this.voice);
512
- }
513
-
514
- /** True when the tap did what it says: started, stopped and attached, or (while starting / stopping) was kept. */
515
- private async toggle(session: { readonly state: RecordingState; toggle(): Promise<void> }): Promise<boolean> {
516
- const before = session.state;
517
- if (before === 'idle' && !this.requireDraft()) return false;
518
- this.lastOk = false;
519
- await session.toggle();
520
- return before === 'starting' || before === 'stopping' ? true : this.lastOk;
521
- }
522
-
523
- /** Tests and QA: resolves when both recorders are settled. */
524
- async settled(): Promise<void> {
525
- await this.screen.settled();
526
- await this.voice.settled();
527
- }
528
-
529
- private recorderState(which: 'screen' | 'voice', state: RecordingState): void {
530
- this.state$.set((s) => {
531
- const screenState = which === 'screen' ? state : s.screenState;
532
- const voiceState = which === 'voice' ? state : s.voiceState;
533
- const active = { screen: screenState !== 'idle', voice: voiceState !== 'idle' };
534
- const started = which === 'screen' ? this.screen.startedAtMs : this.voice.startedAtMs;
535
- const recordingStartedMs = !active.screen && !active.voice ? null : state === 'recording' ? (started ?? this.now()) : (s.recordingStartedMs ?? this.now());
536
- return { ...s, screenState, voiceState, recording: active, recordingStartedMs };
537
- });
538
- }
539
-
540
- private async startScreen(): Promise<boolean> {
541
- const draft = this.state$.get().draft;
542
- if (!draft) return false;
543
- const media = this.o.media;
544
- const dir = await this.store.kindDir(draft.id, TesterAttachmentKind.Recording);
545
- this.screenStartedMs = this.now();
546
- try {
547
- await media.startScreen(dir, { maxFps: captureMaxFps(this.o.prefs.get(this.keys.captureMaxFps)) });
548
- } catch (error) {
549
- const denied = (error as { code?: string })?.code === 'permission';
550
- this.notify('TesterPanelRecordingFailed', 'error');
551
- if (denied) this.log.log('warn', 'tester', `screen recording refused: ${errorText(error)}`);
552
- return false;
553
- }
554
- this.timeline.start(this.screenStartedMs, this.o.subscribeLog);
555
- await this.applyWatch();
556
- this.notify('TesterPanelRecordingStarted', 'information');
557
- // The sound, after the video runs: a refused or busy microphone costs the sound, never the video.
558
- let companion = false;
559
- if (this.state$.get().support.voice) {
560
- try {
561
- await media.startVoice(await this.store.kindDir(draft.id, TesterAttachmentKind.Voice));
562
- // Stamped AFTER the start: the first one waits for the microphone permission prompt, and a stamp taken before it
563
- // put the sound ~30 s early against the video (iPhone, 2026-10-23).
564
- this.companionStartedMs = this.now();
565
- companion = true;
566
- } catch {
567
- companion = false;
568
- }
569
- }
570
- this.state$.set((s) => ({ ...s, companion }));
571
- if (!companion) this.notify('TesterRecordingNoVoice', 'warning');
572
- this.lastOk = true;
573
- return true;
574
- }
575
-
576
- private async stopScreenRecorders(): Promise<ScreenResult> {
577
- const media = this.o.media;
578
- const video = await media.stopScreen().catch(() => null);
579
- const audio = this.state$.get().companion ? await media.stopVoice().catch(() => null) : null;
580
- return { video, audio, timeline: this.timeline.stop() };
581
- }
582
-
583
- /**
584
- * The video, then its sound and timeline paired with it. A video that produced nothing attaches NOTHING (no sound or
585
- * timeline of a video that does not exist); a stop that never returned frees the button and says so.
586
- */
587
- private async screenFinished(r: ScreenResult | null, timedOut: boolean): Promise<void> {
588
- const media = this.o.media;
589
- const companion = this.state$.get().companion;
590
- this.state$.set((s) => ({ ...s, companion: false }));
591
- if (timedOut) {
592
- this.timeline.stop();
593
- if (companion) await media.stopVoice().then((a) => (a ? this.o.files.remove(a.path) : undefined)).catch(() => {});
594
- await this.applyWatch();
595
- this.notify('TesterRecordingStopTimedOut', 'warning');
596
- return;
597
- }
598
- await this.applyWatch();
599
- if (!r?.video) {
600
- if (r?.audio) await this.o.files.remove(r.audio.path).catch(() => {});
601
- this.notify('TesterPanelRecordingFailed', 'error');
602
- return;
603
- }
604
- const base = this.state$.get().draft;
605
- if (!base) return;
606
- let current = await this.store.addAttachment(base, TesterAttachmentKind.Recording, r.video.path, { inPlace: true, startedUtc: iso(this.screenStartedMs) });
607
- const videoId = current.attachments[current.attachments.length - 1]?.id;
608
- if (r.audio && videoId) {
609
- current = await this.store.addAttachment(current, TesterAttachmentKind.Voice, r.audio.path, {
610
- inPlace: true,
611
- displayName: this.t('TesterRecordingVoiceDisplayName'),
612
- startedUtc: iso(this.companionStartedMs),
613
- pairedWith: videoId,
614
- });
615
- }
616
- if (r.timeline && videoId) {
617
- try {
618
- const path = `${await this.store.kindDir(current.id, TesterAttachmentKind.Diagnostic)}/${timelineFileName(this.screenStartedMs)}`;
619
- await this.o.files.writeText(path, r.timeline);
620
- current = await this.store.addAttachment(current, TesterAttachmentKind.Diagnostic, path, {
621
- inPlace: true,
622
- displayName: this.t('TesterRecordingTimelineDisplayName'),
623
- startedUtc: iso(this.screenStartedMs),
624
- pairedWith: videoId,
625
- });
626
- } catch (error) {
627
- // A timeline is a bonus beside the video; failing to write it must not cost the recording.
628
- this.error('tester.timeline', error);
629
- }
630
- }
631
- this.state$.set((s) => ({ ...s, draft: current }));
632
- this.notify('TesterPanelRecordingSaved', 'success');
633
- this.lastOk = true;
634
- }
635
-
636
- private async startVoiceNote(): Promise<boolean> {
637
- const draft = this.state$.get().draft;
638
- if (!draft) return false;
639
- try {
640
- await this.o.media.startVoice(await this.store.kindDir(draft.id, TesterAttachmentKind.Voice));
641
- } catch (error) {
642
- this.notify('TesterPanelVoiceFailed', 'error');
643
- this.log.log('warn', 'tester', `voice note refused: ${errorText(error)}`);
644
- return false;
645
- }
646
- this.notify('TesterPanelVoiceStarted', 'information');
647
- this.lastOk = true;
648
- return true;
649
- }
650
-
651
- private async voiceFinished(file: MediaRecording | null, timedOut: boolean): Promise<void> {
652
- if (timedOut) {
653
- this.notify('TesterRecordingStopTimedOut', 'warning');
654
- return;
655
- }
656
- const draft = this.state$.get().draft;
657
- if (!file || !draft) {
658
- // nothing usable: attach nothing (an empty file in a QA report reads as evidence)
659
- this.notify('TesterPanelVoiceFailed', 'error');
660
- return;
661
- }
662
- const next = await this.store.addAttachment(draft, TesterAttachmentKind.Voice, file.path, { inPlace: true });
663
- this.state$.set((s) => ({ ...s, draft: next }));
664
- this.notify('TesterPanelVoiceSaved', 'success');
665
- this.lastOk = true;
666
- }
667
-
668
- /** Any file the system picker returns, COPIED in (the file belongs to the user). */
669
- async attach(): Promise<boolean> {
670
- if (!this.requireDraft()) return false;
671
- const done = await this.run('attach', async () => {
672
- const picked = await this.o.media.pick(['*/*']);
673
- if (!picked) return false;
674
- return this.addFile(picked);
675
- });
676
- return done === true;
677
- }
678
-
679
- /** A file already in the app's folders (the picker's copy, a QA note) → File/, the source removed. */
680
- async addFile(path: string, displayName?: string): Promise<boolean> {
681
- const draft = this.state$.get().draft;
682
- if (!draft) return false;
683
- const next = await this.store.addAttachment(draft, TesterAttachmentKind.File, path, { deleteSource: true, ...(displayName ? { displayName } : {}) });
684
- this.state$.set((s) => ({ ...s, draft: next }));
685
- this.notify('TesterPanelAttachmentAdded', 'success');
686
- return true;
687
- }
688
-
689
- /** Removes a piece of evidence — and whatever is paired with it (a video's sound and timeline). */
690
- async removeAttachment(attachmentId: string): Promise<void> {
691
- let draft = this.state$.get().draft;
692
- if (!draft) return;
693
- for (const paired of draft.attachments.filter((a) => a.pairedWith === attachmentId)) draft = await this.store.removeAttachment(draft, paired.id);
694
- const next = await this.store.removeAttachment(draft, attachmentId);
695
- this.state$.set((s) => ({ ...s, draft: next }));
696
- }
697
-
698
- /** Drops the draft and everything in it (the caller confirmed). Stops a recorder that still runs. */
699
- async discard(): Promise<void> {
700
- const draft = this.state$.get().draft;
701
- if (!draft) return;
702
- // A recording that is going away with its report is stopped without its «saved» toast.
703
- this.quiet = true;
704
- try {
705
- await this.stopRecorders();
706
- } finally {
707
- this.quiet = false;
708
- }
709
- await this.run('discard', async () => {
710
- await this.store.discard(draft.id);
711
- this.state$.set((x) => ({ ...x, draft: null }));
712
- await this.applyWatch();
713
- this.notify('TesterPanelDiscarded', 'information');
714
- });
715
- }
716
-
717
- /** Stops whatever records and waits for its file (attached to the draft). */
718
- private async stopRecorders(): Promise<void> {
719
- await this.screen.stop();
720
- await this.voice.stop();
721
- await this.settled();
722
- }
723
-
724
- // ── send ──────────────────────────────────────────────────────────────────────────────────────────────────────────
725
-
726
- /**
727
- * The form's confirm: a recorder still running belongs in the report (stopped and attached first); the title and the
728
- * description composed; the archive into the outbox; the draft folder removed (in THAT order: a crash between the two
729
- * costs a stale folder, never the report); the outbox poked. False (with the reason said) when the words are required.
730
- */
731
- async send(input: TesterSendInput): Promise<boolean> {
732
- if (!this.state$.get().draft) return false;
733
- await this.stopRecorders();
734
- const draft = this.state$.get().draft;
735
- if (!draft) return false;
736
- if (!input.words.trim() && this.descriptionRequired(draft)) {
737
- this.notify('TesterPanelDescriptionRequired', 'warning');
738
- return false;
739
- }
740
- const done = await this.run('send', async () => {
741
- const kind = input.kind ?? draft.kind ?? this.kinds[0]?.key ?? null;
742
- const aiPack = this.o.aiProcessing === 'off' ? false : this.o.aiProcessing === 'askTester' && input.useAi === false ? false : null;
743
- const composed = compose({ ...draft, kind }, input.words, { kinds: this.kinds, t: this.t, ...(this.o.describeScreen ? { describe: this.o.describeScreen } : {}), now: this.now });
744
- const final: TesterReportDraft = {
745
- ...composed,
746
- includeDatabaseBackup: input.includeDatabaseBackup && this.offersDatabaseBackup,
747
- branch: this.o.branch ?? null,
748
- commit: this.o.commit ?? null,
749
- ...(aiPack === false ? { aiPack: false } : {}),
750
- };
751
- await this.store.save(final);
752
- this.notify('TesterPanelPreparing', 'information');
753
- const out = `${await this.o.folders.outbox()}/${outboxName(final.id)}`;
754
- await buildTesterArchive({
755
- files: this.o.files,
756
- draft: final,
757
- reportDir: await this.store.reportDir(final.id),
758
- out,
759
- productName: this.o.productName,
760
- app: { appVersion: this.o.host.appVersion, environment: this.o.host.environmentName, platform: this.o.host.platform },
761
- ...(this.o.archive ? { hooks: this.o.archive } : {}),
762
- });
763
- await this.store.discard(final.id);
764
- this.state$.set((s) => ({ ...s, draft: null }));
765
- this.notify('TesterPanelSendQueued', 'success');
766
- this.log.log('info', 'tester', `report ${final.id} archived → ${out}`);
767
- this.outbox.notifyQueued();
768
- return true;
769
- });
770
- if (done !== true) this.notify('TesterPanelSendFailed', 'error');
771
- return done === true;
772
- }
773
-
774
- // ── the gateway ───────────────────────────────────────────────────────────────────────────────────────────────────
775
-
776
- private async device(): Promise<DeviceIdentity> {
777
- const clientId = await this.o.host.clientId();
778
- const secret = await this.o.host.deviceSecret().catch(() => null);
779
- return { clientId, ...(secret ? { deviceSecret: secret } : {}) };
780
- }
781
-
782
- /** Uploads ONE archived report; true only when the gateway has all of it (the outbox then deletes it). */
783
- async uploadArchive(path: string): Promise<boolean> {
784
- const files = this.o.files;
785
- const manifest = await readManifest(files, path);
786
- if (!manifest) {
787
- this.log.log('warn', 'tester', `${path} has no readable report.json; leaving it queued`);
788
- return false;
789
- }
790
- try {
791
- const totalBytes = await files.size(path);
792
- const sha256 = (await files.sha256(path)).toLowerCase();
793
- const host = this.o.host;
794
- const init: UploadInit = {
795
- reportId: manifest.id,
796
- fileName: path.split('/').pop() ?? outboxName(manifest.id),
797
- totalBytes,
798
- sha256,
799
- title: manifest.title,
800
- description: manifest.description,
801
- // The author recorded when the report started — not whoever is signed in now.
802
- username: manifest.username || ((await host.username().catch(() => null)) ?? ''),
803
- platform: host.platform,
804
- appVersion: host.appVersion,
805
- environment: host.environmentName,
806
- attachmentCount: manifest.attachments.length,
807
- includesDatabaseBackup: manifest.includeDatabaseBackup,
808
- capturedUtc: manifest.createdUtc,
809
- ...(manifest.kind ? { kind: manifest.kind } : {}),
810
- ...(manifest.branch ? { branch: manifest.branch } : {}),
811
- ...(manifest.commit ? { commit: manifest.commit } : {}),
812
- };
813
- const http = this.o.http;
814
- const uploader = new TesterReportUploader({
815
- gateway: host.gatewayUrl(),
816
- device: await this.device(),
817
- fetch: http.fetch,
818
- ...(http.headers ? { headers: http.headers } : {}),
819
- ...(http.extraHeaders ? { extraHeaders: http.extraHeaders } : {}),
820
- ...(http.sendRange ? { sendRange: http.sendRange } : {}),
821
- stepTimeoutMs: http.stepTimeoutMs ?? 180_000,
822
- });
823
- const body = http.sendRange ? { path } : async (offset: number, length: number) => base64ToBytes(await files.readChunk(path, offset, length));
824
- const result = await uploader.upload(init, body);
825
- if (!result.sent) {
826
- this.log.log('warn', 'tester', `upload of ${init.fileName} → ${result.status ?? '-'} ${result.error ?? ''}`.trim());
827
- return false;
828
- }
829
- // The moment a tester learns what to call the report: the operator, the agent and the tracker use the code.
830
- if (result.code) this.notify('TesterReportReceivedFormat', 'success', result.code);
831
- return true;
832
- } catch (error) {
833
- this.log.log('warn', 'tester', `${path} could not be uploaded: ${errorText(error)}`);
834
- return false;
835
- }
836
- }
837
-
838
- /** Every report on the gateway, and what is still queued here. */
839
- async feed(): Promise<TesterFeed> {
840
- const http = this.o.http;
841
- return loadTesterFeed({
842
- files: this.o.files,
843
- fetch: http.fetch,
844
- gateway: this.o.host.gatewayUrl(),
845
- device: await this.device(),
846
- ...(http.headers ? { headers: http.headers } : {}),
847
- ...(http.extraHeaders ? { extraHeaders: http.extraHeaders } : {}),
848
- queued: () => this.outbox.queued(),
849
- log: this.log,
850
- });
851
- }
852
- }
853
-
854
- export type { DiagnosticZipEntry };
1
+ // Tester mode without a UI (G9AppDiagnostic.Maui TesterMode + TesterCaptureOverlay's actions + TesterReportSendFlow): the
2
+ // draft, the captures, the two recorders, the send and the outbox, so a panel, a QA command and a test drive exactly what
3
+ // the buttons do. The app only configures it (ITesterHost, folders, preference keys, its facts and hooks).
4
+ //
5
+ // gesture a double tap with two (or three) fingers = a screenshot NOW, which starts a report if none is open
6
+ // screenshot the window FIRST (the panel hides for that frame), then the report, then the file — no editor between
7
+ // the tap and the evidence (owner, 2026-10-31)
8
+ // screen the window as an MP4 → Recording/, with its sound (the microphone, started after the video: a refused
9
+ // microphone costs the sound, never the video) → Voice/ and the app timeline → Diagnostic/, both paired
10
+ // with the video and stamped with when they started
11
+ // voice a spoken NOTE → Voice/, never paired
12
+ // attach any file the system picker returns, COPIED in → File/
13
+ // send no title field: the title is the app's, worded by the kind; the description is the app's block and the
14
+ // tester's words; → the archive in the outbox → the draft folder removed → the outbox poked; once the
15
+ // gateway has it the tester is told its code: «گزارش TR-0042 به سرور رسید.»
16
+ //
17
+ // Both recorders go through a RecordingSession: a Stop tapped while the start still runs is kept, a Stop has a time limit
18
+ // (30 s screen, 10 s voice) and a start or stop that throws ends idle — the button is never stuck and never drops a tap.
19
+ import { base64ToBytes } from '../bytes.ts';
20
+ import { type DiagnosticFetch, type DiagnosticFiles, type DiagnosticLog, type DiagnosticPrefs, type DiagnosticSendRange, type DiagnosticZipEntry, errorText, silentLog, type Unsubscribe } from '../host.ts';
21
+ import { RecordingSession, type RecordingState } from '../recording.ts';
22
+ import { createStore, type ReadableStore, type Store } from '../store.ts';
23
+ import { type DiagLanguage, type DiagStringKey, translator } from '../strings.ts';
24
+ import { type DeviceHeaderNames, type DeviceIdentity, TesterReportUploader, type UploadInit } from '../upload.ts';
25
+ import { buildTesterArchive, outboxName, type TesterArchiveHooks } from './archive.ts';
26
+ import { compose, DEFAULT_REPORT_KINDS, descriptionRequired, screenFacts, type TesterDescriptionRule, type TesterReportKind } from './compose.ts';
27
+ import { loadTesterFeed, readManifest, type TesterFeed } from './feed.ts';
28
+ import { createTapPairer, fingersFor, gestureCounts, parseGestureMode, TesterGestureMode } from './gesture.ts';
29
+ import { TesterAttachmentKind, type TesterReportDraft } from './model.ts';
30
+ import { TesterOutbox } from './outbox.ts';
31
+ import type { TesterScreenDescription } from './screen.ts';
32
+ import { TesterDraftStore } from './store.ts';
33
+ import { type SubscribeLog, TesterTimeline, timelineFileName } from './timeline.ts';
34
+
35
+ /** What tester mode needs from the app, and nothing more (ITesterHost). */
36
+ export interface ITesterHost {
37
+ /** The gateway's base address, read at every send (an admin may change it at runtime). */
38
+ gatewayUrl(): string;
39
+ /** The device's id (hex, stable per install) — the same it announces on the live channel. */
40
+ clientId(): Promise<string>;
41
+ /** The secret the gateway issued on the device's first contact; null before that. */
42
+ deviceSecret(): Promise<string | null>;
43
+ /** Who is signed in now, for a report's author (null when nobody). */
44
+ username(): Promise<string | null>;
45
+ readonly environmentName: string;
46
+ readonly platform: string;
47
+ /** The app's version as reports carry it. */
48
+ readonly appVersion: string;
49
+ }
50
+
51
+ /** A finished recording: the file stays where the recorder wrote it. */
52
+ export interface MediaRecording {
53
+ readonly path: string;
54
+ readonly bytes: number;
55
+ readonly durationMs: number;
56
+ readonly capped?: boolean;
57
+ }
58
+
59
+ /** One event of the native gesture observer (x, y: fractions of the window). */
60
+ export interface TesterTouchEvent {
61
+ /** `gesture`: the whole double tap (the native recogniser consumed it); `tap`: one multi-finger tap; `down`: a finger landed. */
62
+ readonly type: 'gesture' | 'tap' | 'down';
63
+ readonly fingers: number;
64
+ readonly x: number;
65
+ readonly y: number;
66
+ /** On a surface the app excludes from the gesture (a map). */
67
+ readonly excluded?: boolean;
68
+ }
69
+
70
+ /** The platform's recorders and capture (the native module of the platform package). */
71
+ export interface TesterMedia {
72
+ support(): Promise<{ readonly screen: boolean; readonly voice: boolean }>;
73
+ state(): Promise<{ readonly screen: boolean; readonly voice: boolean }>;
74
+ startScreen(dir: string, options: { readonly maxFps: number }): Promise<void>;
75
+ stopScreen(): Promise<MediaRecording | null>;
76
+ startVoice(dir: string): Promise<void>;
77
+ stopVoice(): Promise<MediaRecording | null>;
78
+ /** The app window as a JPEG (long edge ≤ maxEdge). */
79
+ screenshot(maxEdge: number, quality: number): Promise<{ readonly path: string }>;
80
+ /** The system picker; the picked file is copied into the app's folders; null when cancelled. */
81
+ pick(mimeTypes: readonly string[]): Promise<string | null>;
82
+ /**
83
+ * Switches the observer: the gesture (with the fingers it needs) and every finger down (a recording's timeline).
84
+ * `consume` holds a multi-finger touch away from the views while tester mode is on, so the gesture never also presses
85
+ * what is under it; `excludeSurfaces` never holds it over a surface the app excludes (its map, in the «except the map»
86
+ * mode). A platform that cannot hold a touch ignores both.
87
+ */
88
+ watchTouches(options: {
89
+ readonly gesture: boolean;
90
+ readonly touches: boolean;
91
+ readonly fingers: number;
92
+ readonly consume?: boolean;
93
+ readonly excludeSurfaces?: boolean;
94
+ }): Promise<void>;
95
+ onTouch(listener: (event: TesterTouchEvent) => void): Unsubscribe;
96
+ /** A recording that ended by itself (its maximum length). */
97
+ onCaptureEnded?(listener: (kind: 'screen' | 'voice') => void): Unsubscribe;
98
+ }
99
+
100
+ /** The preference keys tester mode keeps (an app that had tester mode before keeps its own; flags are '1' or absent). */
101
+ export interface TesterPrefKeys {
102
+ readonly activeReportId: string;
103
+ readonly debugMode: string;
104
+ readonly gestureMode: string;
105
+ readonly showButton: string;
106
+ /** The fleet's frame-rate ceiling (a live-channel device setting the app caches). */
107
+ readonly captureMaxFps: string;
108
+ }
109
+
110
+ export const NEUTRAL_TESTER_PREF_KEYS: TesterPrefKeys = {
111
+ activeReportId: 'g9.tester.activeReportId',
112
+ debugMode: 'g9.tester.debugMode',
113
+ gestureMode: 'g9.tester.gestureMode',
114
+ showButton: 'g9.tester.showButton',
115
+ captureMaxFps: 'g9.tester.captureMaxFps',
116
+ };
117
+
118
+ export type TesterAiProcessing = 'allowed' | 'off' | 'askTester';
119
+
120
+ export type TesterNotice = { readonly text: string; readonly tone: 'success' | 'error' | 'information' | 'warning' };
121
+
122
+ export interface TesterEngineOptions {
123
+ readonly host: ITesterHost;
124
+ readonly files: DiagnosticFiles;
125
+ readonly prefs: DiagnosticPrefs;
126
+ readonly media: TesterMedia;
127
+ /** The drafts' folder and the outbox folder (absolute). */
128
+ readonly folders: { readonly drafts: () => Promise<string>; readonly outbox: () => Promise<string> };
129
+ readonly prefKeys?: TesterPrefKeys;
130
+ readonly http: {
131
+ readonly fetch: DiagnosticFetch;
132
+ /** The native range request (a chunk never crosses the bridge); without it chunks are read with files.readChunk. */
133
+ readonly sendRange?: DiagnosticSendRange;
134
+ readonly headers?: DeviceHeaderNames;
135
+ readonly extraHeaders?: (url: string) => Readonly<Record<string, string>>;
136
+ readonly stepTimeoutMs?: number;
137
+ };
138
+ readonly language: () => DiagLanguage;
139
+ /** «<Product> tester report context». */
140
+ readonly productName: string;
141
+ /** The app's facts about its screen when a report starts (a section, a site, a map's zoom…). */
142
+ readonly describeScreen?: (d: TesterScreenDescription) => void;
143
+ /** The app's log, for a recording's timeline. */
144
+ readonly subscribeLog?: SubscribeLog;
145
+ readonly archive?: TesterArchiveHooks;
146
+ /** Holds the process while the outbox sends; resolves the release, or null when it cannot. */
147
+ readonly keepAliveWhileSending?: (title: string, subtitle: string) => Promise<(() => void | Promise<void>) | null>;
148
+ readonly reportKinds?: readonly TesterReportKind[];
149
+ readonly descriptionRule?: TesterDescriptionRule;
150
+ readonly aiProcessing?: TesterAiProcessing;
151
+ /** The build's git branch and commit: every report carries them. */
152
+ readonly branch?: string | null;
153
+ readonly commit?: string | null;
154
+ readonly online?: () => Promise<boolean>;
155
+ readonly notify?: (notice: TesterNotice) => void;
156
+ readonly log?: DiagnosticLog;
157
+ readonly onError?: (where: string, error: unknown) => void;
158
+ /** Lets the panel's hide land before the readback (MAUI waited 80 ms). Default 120. */
159
+ readonly settleMs?: number;
160
+ readonly stopTimeoutMs?: { readonly screen: number; readonly voice: number };
161
+ readonly outboxIntervalMs?: number;
162
+ readonly now?: () => number;
163
+ }
164
+
165
+ export interface TesterState {
166
+ readonly enabled: boolean;
167
+ readonly draft: TesterReportDraft | null;
168
+ /** Active (starting, recording or stopping) — `voice` = a voice NOTE; a screen recording's own sound is `companion`. */
169
+ readonly recording: { readonly screen: boolean; readonly voice: boolean };
170
+ readonly screenState: RecordingState;
171
+ readonly voiceState: RecordingState;
172
+ readonly companion: boolean;
173
+ /** When the running capture started (the pill's clock), or null. */
174
+ readonly recordingStartedMs: number | null;
175
+ readonly support: { readonly screen: boolean; readonly voice: boolean };
176
+ /** The native gesture observer answered: false keeps the pill's + on screen (no way to open it otherwise). */
177
+ readonly gestureSupported: boolean;
178
+ readonly gestureMode: TesterGestureMode;
179
+ /** Keep the + on screen with no report open. */
180
+ readonly showButton: boolean;
181
+ /** A capture is in flight: the panel hides itself (not in its own screenshot). */
182
+ readonly capturing: boolean;
183
+ readonly busy: string | null;
184
+ }
185
+
186
+ /** What the send form returns. */
187
+ export interface TesterSendInput {
188
+ /** The tester's own words (the one box). */
189
+ readonly words: string;
190
+ readonly kind?: string | null;
191
+ readonly includeDatabaseBackup: boolean;
192
+ /** The form's AI switch (askTester only). */
193
+ readonly useAi?: boolean;
194
+ }
195
+
196
+ export const DEFAULT_CAPTURE_MAX_FPS = 10;
197
+
198
+ /** The fleet's frame-rate ceiling for a screen recording (2..20, default 10). */
199
+ export function captureMaxFps(raw: string | null): number {
200
+ const n = Number(raw);
201
+ return raw !== null && Number.isFinite(n) && n > 0 ? Math.min(20, Math.max(2, Math.round(n))) : DEFAULT_CAPTURE_MAX_FPS;
202
+ }
203
+
204
+ interface ScreenResult {
205
+ readonly video: MediaRecording | null;
206
+ readonly audio: MediaRecording | null;
207
+ readonly timeline: string | null;
208
+ }
209
+
210
+ const iso = (ms: number) => new Date(ms).toISOString();
211
+
212
+ export class TesterEngine {
213
+ readonly store: TesterDraftStore;
214
+ readonly outbox: TesterOutbox;
215
+ private readonly o: TesterEngineOptions;
216
+ private readonly keys: TesterPrefKeys;
217
+ private readonly state$: Store<TesterState>;
218
+ private readonly timeline = new TesterTimeline();
219
+ private readonly pairTap: ReturnType<typeof createTapPairer>;
220
+ private readonly now: () => number;
221
+ private readonly t: ReturnType<typeof translator>;
222
+ private readonly log: DiagnosticLog;
223
+ private readonly screen: RecordingSession<ScreenResult>;
224
+ private readonly voice: RecordingSession<MediaRecording>;
225
+ private readonly offs: Unsubscribe[] = [];
226
+ private loaded = false;
227
+ private quiet = false;
228
+ private screenStartedMs = 0;
229
+ private companionStartedMs = 0;
230
+ private lastOk = false;
231
+
232
+ constructor(options: TesterEngineOptions) {
233
+ this.o = options;
234
+ this.keys = options.prefKeys ?? NEUTRAL_TESTER_PREF_KEYS;
235
+ this.now = options.now ?? Date.now;
236
+ this.t = translator(options.language);
237
+ this.log = options.log ?? silentLog;
238
+ this.pairTap = createTapPairer(this.now);
239
+ this.store = new TesterDraftStore({ files: options.files, prefs: options.prefs, root: options.folders.drafts, activeKey: this.keys.activeReportId, now: this.now });
240
+ this.outbox = new TesterOutbox({
241
+ files: options.files,
242
+ dir: options.folders.outbox,
243
+ online: options.online ?? (async () => true),
244
+ upload: (path) => this.uploadArchive(path),
245
+ ...(options.outboxIntervalMs !== undefined ? { intervalMs: options.outboxIntervalMs } : {}),
246
+ ...(options.keepAliveWhileSending ? { keepAlive: () => options.keepAliveWhileSending!(this.t('TesterReportUploadTitle'), this.t('TesterReportUploadSubtitle')) } : {}),
247
+ log: this.log,
248
+ });
249
+ const flag = (k: string) => options.prefs.get(k) === '1';
250
+ this.state$ = createStore<TesterState>({
251
+ enabled: flag(this.keys.debugMode),
252
+ draft: null,
253
+ recording: { screen: false, voice: false },
254
+ screenState: 'idle',
255
+ voiceState: 'idle',
256
+ companion: false,
257
+ recordingStartedMs: null,
258
+ support: { screen: false, voice: false },
259
+ gestureSupported: true,
260
+ gestureMode: parseGestureMode(options.prefs.get(this.keys.gestureMode)),
261
+ showButton: flag(this.keys.showButton),
262
+ capturing: false,
263
+ busy: null,
264
+ });
265
+ const stopMs = options.stopTimeoutMs ?? { screen: 30_000, voice: 10_000 };
266
+ this.screen = new RecordingSession<ScreenResult>({
267
+ start: () => this.startScreen(),
268
+ stop: () => this.stopScreenRecorders(),
269
+ finished: (r, timedOut) => this.screenFinished(r, timedOut),
270
+ stopTimeoutMs: stopMs.screen,
271
+ onStateChanged: (s) => this.recorderState('screen', s),
272
+ onFaulted: (e) => this.error('tester.screen', e),
273
+ now: this.now,
274
+ });
275
+ this.voice = new RecordingSession<MediaRecording>({
276
+ start: () => this.startVoiceNote(),
277
+ stop: () => options.media.stopVoice(),
278
+ finished: (r, timedOut) => this.voiceFinished(r, timedOut),
279
+ stopTimeoutMs: stopMs.voice,
280
+ onStateChanged: (s) => this.recorderState('voice', s),
281
+ onFaulted: (e) => this.error('tester.voice', e),
282
+ now: this.now,
283
+ });
284
+ this.offs.push(options.media.onTouch((e) => this.onTouch(e)));
285
+ if (options.media.onCaptureEnded) this.offs.push(options.media.onCaptureEnded((k) => void (k === 'screen' ? this.screen.stop() : this.voice.stop())));
286
+ }
287
+
288
+ get state(): ReadableStore<TesterState> {
289
+ return this.state$;
290
+ }
291
+
292
+ get kinds(): readonly TesterReportKind[] {
293
+ return this.o.reportKinds ?? DEFAULT_REPORT_KINDS;
294
+ }
295
+
296
+ get translate(): ReturnType<typeof translator> {
297
+ return this.t;
298
+ }
299
+
300
+ /** Whether the send form shows the database-backup switch (the app can make one). */
301
+ get offersDatabaseBackup(): boolean {
302
+ return !!this.o.archive?.createDatabaseBackup;
303
+ }
304
+
305
+ /** Whether the send form shows the AI switch. */
306
+ get asksAboutAi(): boolean {
307
+ return this.o.aiProcessing === 'askTester';
308
+ }
309
+
310
+ /** Stops listening (the app outlives the instance in tests). */
311
+ dispose(): void {
312
+ for (const off of this.offs.splice(0)) off();
313
+ this.timeline.stop();
314
+ this.outbox.stop();
315
+ }
316
+
317
+ /** Re-attaches to the draft a previous run left open and reads what the device supports. Idempotent. */
318
+ async load(): Promise<void> {
319
+ if (this.loaded) return;
320
+ this.loaded = true;
321
+ const media = this.o.media;
322
+ const [draft, support, native] = await Promise.all([
323
+ this.store.active(),
324
+ media.support().catch(() => ({ screen: false, voice: false })),
325
+ media.state().catch(() => ({ screen: false, voice: false })),
326
+ ]);
327
+ this.state$.set((s) => ({ ...s, draft, support }));
328
+ // A recorder that outlived a reload of the app's script is taken over: both running = a screen recording with its
329
+ // sound, so the next Stop keeps the video (its timeline died with the old script).
330
+ if (draft && native.screen) {
331
+ this.screenStartedMs = this.now();
332
+ this.companionStartedMs = this.screenStartedMs;
333
+ this.state$.set((s) => ({ ...s, companion: native.voice }));
334
+ this.screen.adopt(this.screenStartedMs);
335
+ } else if (draft && native.voice) {
336
+ this.voice.adopt();
337
+ }
338
+ await this.applyWatch();
339
+ await this.outbox.refresh();
340
+ }
341
+
342
+ setEnabled(on: boolean): void {
343
+ this.o.prefs.set(this.keys.debugMode, on ? '1' : null);
344
+ this.state$.set((s) => ({ ...s, enabled: on }));
345
+ if (on) void this.load().then(() => this.applyWatch());
346
+ else void this.applyWatch();
347
+ }
348
+
349
+ setGestureMode(mode: TesterGestureMode): void {
350
+ this.o.prefs.set(this.keys.gestureMode, String(mode));
351
+ this.state$.set((s) => ({ ...s, gestureMode: mode }));
352
+ void this.applyWatch();
353
+ }
354
+
355
+ setShowButton(on: boolean): void {
356
+ this.o.prefs.set(this.keys.showButton, on ? '1' : null);
357
+ this.state$.set((s) => ({ ...s, showButton: on }));
358
+ }
359
+
360
+ /** Whether this draft needs the tester's words before it can be sent. */
361
+ descriptionRequired(draft: TesterReportDraft | null = this.state$.get().draft): boolean {
362
+ return !!draft && descriptionRequired(draft, this.o.descriptionRule ?? 'optional');
363
+ }
364
+
365
+ // ── the gesture ───────────────────────────────────────────────────────────────────────────────────────────────────
366
+
367
+ /** The gesture is observed only while tester mode is on; touch-downs only while a recording's timeline runs. */
368
+ private async applyWatch(): Promise<void> {
369
+ const s = this.state$.get();
370
+ try {
371
+ await this.o.media.watchTouches({
372
+ gesture: s.enabled,
373
+ touches: s.enabled && this.timeline.isRunning,
374
+ fingers: fingersFor(s.gestureMode),
375
+ consume: s.enabled,
376
+ excludeSurfaces: s.gestureMode === TesterGestureMode.TwoFingersExceptMap,
377
+ });
378
+ if (!this.state$.get().gestureSupported) this.state$.set((x) => ({ ...x, gestureSupported: true }));
379
+ } catch (error) {
380
+ // A build without the observer: the + stays on screen, the only way in.
381
+ if (this.state$.get().gestureSupported) this.state$.set((x) => ({ ...x, gestureSupported: false }));
382
+ this.log.log('warn', 'tester', `gesture observer: ${errorText(error)}`);
383
+ }
384
+ }
385
+
386
+ private onTouch(e: TesterTouchEvent): void {
387
+ if (e.type === 'down') {
388
+ this.timeline.touch(e.x, e.y, e.fingers, this.now());
389
+ return;
390
+ }
391
+ // Only a tap or a whole gesture counts: a watcher may report more (a `seq` trace of a touch, 2026-11-15).
392
+ if (e.type !== 'tap' && e.type !== 'gesture') return;
393
+ const s = this.state$.get();
394
+ if (!s.enabled) return;
395
+ const excluded = e.excluded === true;
396
+ const fire = e.type === 'gesture' ? gestureCounts(e.fingers, excluded, s.gestureMode) : this.pairTap({ fingers: e.fingers, x: e.x, y: e.y, excluded }, s.gestureMode);
397
+ if (!fire) return;
398
+ this.log.log('debug', 'tester', `gesture (${e.fingers} fingers)`);
399
+ void this.gesture();
400
+ }
401
+
402
+ /** The gesture: a screenshot NOW, starting a report if none is open. Ignored mid-recording (Stop is the way out). */
403
+ async gesture(): Promise<boolean> {
404
+ const s = this.state$.get();
405
+ if (!s.enabled || s.recording.screen) return false;
406
+ return this.screenshot();
407
+ }
408
+
409
+ // ── helpers ───────────────────────────────────────────────────────────────────────────────────────────────────────
410
+
411
+ private notify(key: DiagStringKey, tone: TesterNotice['tone'], ...args: unknown[]): void {
412
+ if (this.quiet) return;
413
+ const text = this.t(key, ...args);
414
+ try {
415
+ if (this.o.notify) this.o.notify({ text, tone });
416
+ else this.log.log('info', 'tester', text);
417
+ } catch {
418
+ this.log.log('info', 'tester', text);
419
+ }
420
+ }
421
+
422
+ private error(where: string, error: unknown): void {
423
+ if (this.o.onError) this.o.onError(where, error);
424
+ else this.log.log('error', 'tester', `${where}: ${errorText(error)}`);
425
+ }
426
+
427
+ /** One non-recording action at a time (a capture, a send); the record buttons never wait here. */
428
+ private async run<T>(name: string, work: () => Promise<T>): Promise<T | null> {
429
+ if (this.state$.get().busy) return null;
430
+ this.state$.set((s) => ({ ...s, busy: name }));
431
+ try {
432
+ return await work();
433
+ } catch (error) {
434
+ this.error(`tester.${name}`, error);
435
+ return null;
436
+ } finally {
437
+ this.state$.set((s) => ({ ...s, busy: null, capturing: false }));
438
+ }
439
+ }
440
+
441
+ private requireDraft(): TesterReportDraft | null {
442
+ const draft = this.state$.get().draft;
443
+ if (!draft) this.notify('TesterPanelNoDraft', 'warning');
444
+ return draft;
445
+ }
446
+
447
+ /** Opens a report if none is, with where the tester is NOW (its title). True when one was started. */
448
+ private async ensureDraft(): Promise<boolean> {
449
+ if (this.state$.get().draft) return false;
450
+ const facts = screenFacts(this.o.describeScreen, this.t, this.now);
451
+ const draft = await this.store.create(
452
+ { ...(facts.autoTitle ? { autoTitle: facts.autoTitle } : {}), ...(facts.autoDescription ? { autoDescription: facts.autoDescription } : {}), screen: facts.screen, screenContext: facts.screenContext },
453
+ await this.o.host.username().catch(() => null),
454
+ );
455
+ this.state$.set((s) => ({ ...s, draft }));
456
+ this.log.log('debug', 'tester', `draft ${draft.id} started`);
457
+ return true;
458
+ }
459
+
460
+ /** A report with words already written (QA, a test): no capture needed. */
461
+ async create(words = ''): Promise<TesterReportDraft | null> {
462
+ return this.run('create', async () => {
463
+ await this.ensureDraft();
464
+ let draft = this.state$.get().draft!;
465
+ if (words.trim()) {
466
+ draft = { ...draft, description: words.trim() };
467
+ await this.store.save(draft);
468
+ this.state$.set((s) => ({ ...s, draft }));
469
+ }
470
+ return draft;
471
+ });
472
+ }
473
+
474
+ // ── captures ──────────────────────────────────────────────────────────────────────────────────────────────────────
475
+
476
+ /** The window first, then the report, then the file — attached as it was taken. */
477
+ async screenshot(): Promise<boolean> {
478
+ const done = await this.run('screenshot', async () => {
479
+ this.state$.set((s) => ({ ...s, capturing: true }));
480
+ await new Promise((r) => setTimeout(r, this.o.settleMs ?? 120));
481
+ let shot: string;
482
+ try {
483
+ shot = (await this.o.media.screenshot(2160, 92)).path;
484
+ } catch {
485
+ this.notify('TesterPanelScreenshotFailed', 'error');
486
+ return false;
487
+ } finally {
488
+ this.state$.set((s) => ({ ...s, capturing: false }));
489
+ }
490
+ // The gesture opens the PANEL as well as the shot: the report starts here.
491
+ const started = await this.ensureDraft();
492
+ const draft = this.state$.get().draft!;
493
+ const next = await this.store.addAttachment(draft, TesterAttachmentKind.Screenshot, shot, { deleteSource: true, displayName: `screenshot-${this.now()}.jpg` });
494
+ this.state$.set((s) => ({ ...s, draft: next }));
495
+ if (started) this.log.log('info', 'tester', `report ${next.id} started by a screenshot`);
496
+ this.notify('TesterPanelScreenshotAdded', 'success');
497
+ return true;
498
+ });
499
+ return done === true;
500
+ }
501
+
502
+ /** Start / stop the screen recording with its sound and timeline. Never dropped: a stop while starting is kept. */
503
+ async toggleScreen(): Promise<boolean> {
504
+ if (this.voice.isActive) return false; // a voice note runs: its Stop comes first (the panel offers only it)
505
+ return this.toggle(this.screen);
506
+ }
507
+
508
+ /** A voice NOTE: start on the first tap, stop and attach on the second. Never paired with anything. */
509
+ async toggleVoice(): Promise<boolean> {
510
+ if (this.screen.isActive) return false;
511
+ return this.toggle(this.voice);
512
+ }
513
+
514
+ /** True when the tap did what it says: started, stopped and attached, or (while starting / stopping) was kept. */
515
+ private async toggle(session: { readonly state: RecordingState; toggle(): Promise<void> }): Promise<boolean> {
516
+ const before = session.state;
517
+ if (before === 'idle' && !this.requireDraft()) return false;
518
+ this.lastOk = false;
519
+ await session.toggle();
520
+ return before === 'starting' || before === 'stopping' ? true : this.lastOk;
521
+ }
522
+
523
+ /** Tests and QA: resolves when both recorders are settled. */
524
+ async settled(): Promise<void> {
525
+ await this.screen.settled();
526
+ await this.voice.settled();
527
+ }
528
+
529
+ private recorderState(which: 'screen' | 'voice', state: RecordingState): void {
530
+ this.state$.set((s) => {
531
+ const screenState = which === 'screen' ? state : s.screenState;
532
+ const voiceState = which === 'voice' ? state : s.voiceState;
533
+ const active = { screen: screenState !== 'idle', voice: voiceState !== 'idle' };
534
+ const started = which === 'screen' ? this.screen.startedAtMs : this.voice.startedAtMs;
535
+ const recordingStartedMs = !active.screen && !active.voice ? null : state === 'recording' ? (started ?? this.now()) : (s.recordingStartedMs ?? this.now());
536
+ return { ...s, screenState, voiceState, recording: active, recordingStartedMs };
537
+ });
538
+ }
539
+
540
+ private async startScreen(): Promise<boolean> {
541
+ const draft = this.state$.get().draft;
542
+ if (!draft) return false;
543
+ const media = this.o.media;
544
+ const dir = await this.store.kindDir(draft.id, TesterAttachmentKind.Recording);
545
+ this.screenStartedMs = this.now();
546
+ try {
547
+ await media.startScreen(dir, { maxFps: captureMaxFps(this.o.prefs.get(this.keys.captureMaxFps)) });
548
+ } catch (error) {
549
+ const denied = (error as { code?: string })?.code === 'permission';
550
+ this.notify('TesterPanelRecordingFailed', 'error');
551
+ if (denied) this.log.log('warn', 'tester', `screen recording refused: ${errorText(error)}`);
552
+ return false;
553
+ }
554
+ this.timeline.start(this.screenStartedMs, this.o.subscribeLog);
555
+ await this.applyWatch();
556
+ this.notify('TesterPanelRecordingStarted', 'information');
557
+ // The sound, after the video runs: a refused or busy microphone costs the sound, never the video.
558
+ let companion = false;
559
+ if (this.state$.get().support.voice) {
560
+ try {
561
+ await media.startVoice(await this.store.kindDir(draft.id, TesterAttachmentKind.Voice));
562
+ // Stamped AFTER the start: the first one waits for the microphone permission prompt, and a stamp taken before it
563
+ // put the sound ~30 s early against the video (iPhone, 2026-10-23).
564
+ this.companionStartedMs = this.now();
565
+ companion = true;
566
+ } catch {
567
+ companion = false;
568
+ }
569
+ }
570
+ this.state$.set((s) => ({ ...s, companion }));
571
+ if (!companion) this.notify('TesterRecordingNoVoice', 'warning');
572
+ this.lastOk = true;
573
+ return true;
574
+ }
575
+
576
+ private async stopScreenRecorders(): Promise<ScreenResult> {
577
+ const media = this.o.media;
578
+ const video = await media.stopScreen().catch(() => null);
579
+ const audio = this.state$.get().companion ? await media.stopVoice().catch(() => null) : null;
580
+ return { video, audio, timeline: this.timeline.stop() };
581
+ }
582
+
583
+ /**
584
+ * The video, then its sound and timeline paired with it. A video that produced nothing attaches NOTHING (no sound or
585
+ * timeline of a video that does not exist); a stop that never returned frees the button and says so.
586
+ */
587
+ private async screenFinished(r: ScreenResult | null, timedOut: boolean): Promise<void> {
588
+ const media = this.o.media;
589
+ const companion = this.state$.get().companion;
590
+ this.state$.set((s) => ({ ...s, companion: false }));
591
+ if (timedOut) {
592
+ this.timeline.stop();
593
+ if (companion) await media.stopVoice().then((a) => (a ? this.o.files.remove(a.path) : undefined)).catch(() => {});
594
+ await this.applyWatch();
595
+ this.notify('TesterRecordingStopTimedOut', 'warning');
596
+ return;
597
+ }
598
+ await this.applyWatch();
599
+ if (!r?.video) {
600
+ if (r?.audio) await this.o.files.remove(r.audio.path).catch(() => {});
601
+ this.notify('TesterPanelRecordingFailed', 'error');
602
+ return;
603
+ }
604
+ const base = this.state$.get().draft;
605
+ if (!base) return;
606
+ let current = await this.store.addAttachment(base, TesterAttachmentKind.Recording, r.video.path, { inPlace: true, startedUtc: iso(this.screenStartedMs) });
607
+ const videoId = current.attachments[current.attachments.length - 1]?.id;
608
+ if (r.audio && videoId) {
609
+ current = await this.store.addAttachment(current, TesterAttachmentKind.Voice, r.audio.path, {
610
+ inPlace: true,
611
+ displayName: this.t('TesterRecordingVoiceDisplayName'),
612
+ startedUtc: iso(this.companionStartedMs),
613
+ pairedWith: videoId,
614
+ });
615
+ }
616
+ if (r.timeline && videoId) {
617
+ try {
618
+ const path = `${await this.store.kindDir(current.id, TesterAttachmentKind.Diagnostic)}/${timelineFileName(this.screenStartedMs)}`;
619
+ await this.o.files.writeText(path, r.timeline);
620
+ current = await this.store.addAttachment(current, TesterAttachmentKind.Diagnostic, path, {
621
+ inPlace: true,
622
+ displayName: this.t('TesterRecordingTimelineDisplayName'),
623
+ startedUtc: iso(this.screenStartedMs),
624
+ pairedWith: videoId,
625
+ });
626
+ } catch (error) {
627
+ // A timeline is a bonus beside the video; failing to write it must not cost the recording.
628
+ this.error('tester.timeline', error);
629
+ }
630
+ }
631
+ this.state$.set((s) => ({ ...s, draft: current }));
632
+ this.notify('TesterPanelRecordingSaved', 'success');
633
+ this.lastOk = true;
634
+ }
635
+
636
+ private async startVoiceNote(): Promise<boolean> {
637
+ const draft = this.state$.get().draft;
638
+ if (!draft) return false;
639
+ try {
640
+ await this.o.media.startVoice(await this.store.kindDir(draft.id, TesterAttachmentKind.Voice));
641
+ } catch (error) {
642
+ this.notify('TesterPanelVoiceFailed', 'error');
643
+ this.log.log('warn', 'tester', `voice note refused: ${errorText(error)}`);
644
+ return false;
645
+ }
646
+ this.notify('TesterPanelVoiceStarted', 'information');
647
+ this.lastOk = true;
648
+ return true;
649
+ }
650
+
651
+ private async voiceFinished(file: MediaRecording | null, timedOut: boolean): Promise<void> {
652
+ if (timedOut) {
653
+ this.notify('TesterRecordingStopTimedOut', 'warning');
654
+ return;
655
+ }
656
+ const draft = this.state$.get().draft;
657
+ if (!file || !draft) {
658
+ // nothing usable: attach nothing (an empty file in a QA report reads as evidence)
659
+ this.notify('TesterPanelVoiceFailed', 'error');
660
+ return;
661
+ }
662
+ const next = await this.store.addAttachment(draft, TesterAttachmentKind.Voice, file.path, { inPlace: true });
663
+ this.state$.set((s) => ({ ...s, draft: next }));
664
+ this.notify('TesterPanelVoiceSaved', 'success');
665
+ this.lastOk = true;
666
+ }
667
+
668
+ /** Any file the system picker returns, COPIED in (the file belongs to the user). */
669
+ async attach(): Promise<boolean> {
670
+ if (!this.requireDraft()) return false;
671
+ const done = await this.run('attach', async () => {
672
+ const picked = await this.o.media.pick(['*/*']);
673
+ if (!picked) return false;
674
+ return this.addFile(picked);
675
+ });
676
+ return done === true;
677
+ }
678
+
679
+ /** A file already in the app's folders (the picker's copy, a QA note) → File/, the source removed. */
680
+ async addFile(path: string, displayName?: string): Promise<boolean> {
681
+ const draft = this.state$.get().draft;
682
+ if (!draft) return false;
683
+ const next = await this.store.addAttachment(draft, TesterAttachmentKind.File, path, { deleteSource: true, ...(displayName ? { displayName } : {}) });
684
+ this.state$.set((s) => ({ ...s, draft: next }));
685
+ this.notify('TesterPanelAttachmentAdded', 'success');
686
+ return true;
687
+ }
688
+
689
+ /** Removes a piece of evidence — and whatever is paired with it (a video's sound and timeline). */
690
+ async removeAttachment(attachmentId: string): Promise<void> {
691
+ let draft = this.state$.get().draft;
692
+ if (!draft) return;
693
+ for (const paired of draft.attachments.filter((a) => a.pairedWith === attachmentId)) draft = await this.store.removeAttachment(draft, paired.id);
694
+ const next = await this.store.removeAttachment(draft, attachmentId);
695
+ this.state$.set((s) => ({ ...s, draft: next }));
696
+ }
697
+
698
+ /** Drops the draft and everything in it (the caller confirmed). Stops a recorder that still runs. */
699
+ async discard(): Promise<void> {
700
+ const draft = this.state$.get().draft;
701
+ if (!draft) return;
702
+ // A recording that is going away with its report is stopped without its «saved» toast.
703
+ this.quiet = true;
704
+ try {
705
+ await this.stopRecorders();
706
+ } finally {
707
+ this.quiet = false;
708
+ }
709
+ await this.run('discard', async () => {
710
+ await this.store.discard(draft.id);
711
+ this.state$.set((x) => ({ ...x, draft: null }));
712
+ await this.applyWatch();
713
+ this.notify('TesterPanelDiscarded', 'information');
714
+ });
715
+ }
716
+
717
+ /** Stops whatever records and waits for its file (attached to the draft). */
718
+ private async stopRecorders(): Promise<void> {
719
+ await this.screen.stop();
720
+ await this.voice.stop();
721
+ await this.settled();
722
+ }
723
+
724
+ // ── send ──────────────────────────────────────────────────────────────────────────────────────────────────────────
725
+
726
+ /**
727
+ * The form's confirm: a recorder still running belongs in the report (stopped and attached first); the title and the
728
+ * description composed; the archive into the outbox; the draft folder removed (in THAT order: a crash between the two
729
+ * costs a stale folder, never the report); the outbox poked. False (with the reason said) when the words are required.
730
+ */
731
+ async send(input: TesterSendInput): Promise<boolean> {
732
+ if (!this.state$.get().draft) return false;
733
+ await this.stopRecorders();
734
+ const draft = this.state$.get().draft;
735
+ if (!draft) return false;
736
+ if (!input.words.trim() && this.descriptionRequired(draft)) {
737
+ this.notify('TesterPanelDescriptionRequired', 'warning');
738
+ return false;
739
+ }
740
+ const done = await this.run('send', async () => {
741
+ const kind = input.kind ?? draft.kind ?? this.kinds[0]?.key ?? null;
742
+ const aiPack = this.o.aiProcessing === 'off' ? false : this.o.aiProcessing === 'askTester' && input.useAi === false ? false : null;
743
+ const composed = compose({ ...draft, kind }, input.words, { kinds: this.kinds, t: this.t, ...(this.o.describeScreen ? { describe: this.o.describeScreen } : {}), now: this.now });
744
+ const final: TesterReportDraft = {
745
+ ...composed,
746
+ includeDatabaseBackup: input.includeDatabaseBackup && this.offersDatabaseBackup,
747
+ branch: this.o.branch ?? null,
748
+ commit: this.o.commit ?? null,
749
+ ...(aiPack === false ? { aiPack: false } : {}),
750
+ };
751
+ await this.store.save(final);
752
+ this.notify('TesterPanelPreparing', 'information');
753
+ const out = `${await this.o.folders.outbox()}/${outboxName(final.id)}`;
754
+ await buildTesterArchive({
755
+ files: this.o.files,
756
+ draft: final,
757
+ reportDir: await this.store.reportDir(final.id),
758
+ out,
759
+ productName: this.o.productName,
760
+ app: { appVersion: this.o.host.appVersion, environment: this.o.host.environmentName, platform: this.o.host.platform },
761
+ ...(this.o.archive ? { hooks: this.o.archive } : {}),
762
+ });
763
+ await this.store.discard(final.id);
764
+ this.state$.set((s) => ({ ...s, draft: null }));
765
+ this.notify('TesterPanelSendQueued', 'success');
766
+ this.log.log('info', 'tester', `report ${final.id} archived → ${out}`);
767
+ this.outbox.notifyQueued();
768
+ return true;
769
+ });
770
+ if (done !== true) this.notify('TesterPanelSendFailed', 'error');
771
+ return done === true;
772
+ }
773
+
774
+ // ── the gateway ───────────────────────────────────────────────────────────────────────────────────────────────────
775
+
776
+ private async device(): Promise<DeviceIdentity> {
777
+ const clientId = await this.o.host.clientId();
778
+ const secret = await this.o.host.deviceSecret().catch(() => null);
779
+ return { clientId, ...(secret ? { deviceSecret: secret } : {}) };
780
+ }
781
+
782
+ /** Uploads ONE archived report; true only when the gateway has all of it (the outbox then deletes it). */
783
+ async uploadArchive(path: string): Promise<boolean> {
784
+ const files = this.o.files;
785
+ const manifest = await readManifest(files, path);
786
+ if (!manifest) {
787
+ this.log.log('warn', 'tester', `${path} has no readable report.json; leaving it queued`);
788
+ return false;
789
+ }
790
+ try {
791
+ const totalBytes = await files.size(path);
792
+ const sha256 = (await files.sha256(path)).toLowerCase();
793
+ const host = this.o.host;
794
+ const init: UploadInit = {
795
+ reportId: manifest.id,
796
+ fileName: path.split('/').pop() ?? outboxName(manifest.id),
797
+ totalBytes,
798
+ sha256,
799
+ title: manifest.title,
800
+ description: manifest.description,
801
+ // The author recorded when the report started — not whoever is signed in now.
802
+ username: manifest.username || ((await host.username().catch(() => null)) ?? ''),
803
+ platform: host.platform,
804
+ appVersion: host.appVersion,
805
+ environment: host.environmentName,
806
+ attachmentCount: manifest.attachments.length,
807
+ includesDatabaseBackup: manifest.includeDatabaseBackup,
808
+ capturedUtc: manifest.createdUtc,
809
+ ...(manifest.kind ? { kind: manifest.kind } : {}),
810
+ ...(manifest.branch ? { branch: manifest.branch } : {}),
811
+ ...(manifest.commit ? { commit: manifest.commit } : {}),
812
+ };
813
+ const http = this.o.http;
814
+ const uploader = new TesterReportUploader({
815
+ gateway: host.gatewayUrl(),
816
+ device: await this.device(),
817
+ fetch: http.fetch,
818
+ ...(http.headers ? { headers: http.headers } : {}),
819
+ ...(http.extraHeaders ? { extraHeaders: http.extraHeaders } : {}),
820
+ ...(http.sendRange ? { sendRange: http.sendRange } : {}),
821
+ stepTimeoutMs: http.stepTimeoutMs ?? 180_000,
822
+ });
823
+ const body = http.sendRange ? { path } : async (offset: number, length: number) => base64ToBytes(await files.readChunk(path, offset, length));
824
+ const result = await uploader.upload(init, body);
825
+ if (!result.sent) {
826
+ this.log.log('warn', 'tester', `upload of ${init.fileName} → ${result.status ?? '-'} ${result.error ?? ''}`.trim());
827
+ return false;
828
+ }
829
+ // The moment a tester learns what to call the report: the operator, the agent and the tracker use the code.
830
+ if (result.code) this.notify('TesterReportReceivedFormat', 'success', result.code);
831
+ return true;
832
+ } catch (error) {
833
+ this.log.log('warn', 'tester', `${path} could not be uploaded: ${errorText(error)}`);
834
+ return false;
835
+ }
836
+ }
837
+
838
+ /** Every report on the gateway, and what is still queued here. */
839
+ async feed(): Promise<TesterFeed> {
840
+ const http = this.o.http;
841
+ return loadTesterFeed({
842
+ files: this.o.files,
843
+ fetch: http.fetch,
844
+ gateway: this.o.host.gatewayUrl(),
845
+ device: await this.device(),
846
+ ...(http.headers ? { headers: http.headers } : {}),
847
+ ...(http.extraHeaders ? { extraHeaders: http.extraHeaders } : {}),
848
+ queued: () => this.outbox.queued(),
849
+ log: this.log,
850
+ });
851
+ }
852
+ }
853
+
854
+ export type { DiagnosticZipEntry };