@g9tm/app-diagnostic 0.0.0-stage → 0.2.1

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.
@@ -0,0 +1,182 @@
1
+ // A tester's report list (G9AppDiagnostic.Maui TesterReportFeedClient + TesterReportsListSheetContentView.Describe): the
2
+ // gateway's list of EVERY tester report (any tester) plus what is still queued on this device, and what each card shows.
3
+ // Same identity as the upload; the gateway answers only a device that has sent a report itself, so a 403 is «not yet»,
4
+ // a plain sentence, never an error.
5
+ import { type DiagnosticFetch, type DiagnosticFiles, type DiagnosticLog, errorText, silentLog, withTimeout } from '../host.ts';
6
+ import { type DeviceHeaderNames, type DeviceIdentity, deviceHeaders, FEED_ROUTE, MANIFEST_ENTRY, NEUTRAL_DEVICE_HEADERS } from '../upload.ts';
7
+ import { isDraft, type TesterReportDraft } from './model.ts';
8
+
9
+ export const TesterReportStates = {
10
+ uploading: 'uploading',
11
+ received: 'received',
12
+ processing: 'processing',
13
+ ready: 'ready',
14
+ filed: 'filed',
15
+ deleted: 'deleted',
16
+ } as const;
17
+
18
+ export const TesterReportOutcomes = {
19
+ jira: 'jira',
20
+ fixedInCode: 'fixed-in-code',
21
+ notABug: 'not-a-bug',
22
+ duplicate: 'duplicate',
23
+ } as const;
24
+
25
+ export interface TesterFeedItem {
26
+ readonly reportId: string;
27
+ readonly code: string;
28
+ readonly title: string;
29
+ readonly username: string;
30
+ readonly platform: string;
31
+ readonly appVersion: string;
32
+ readonly state: string;
33
+ readonly outcome: string;
34
+ readonly jiraKey: string;
35
+ readonly mine: boolean;
36
+ readonly createdAtUtc: string;
37
+ }
38
+
39
+ export interface TesterFeed {
40
+ readonly status: 'loaded' | 'notYet' | 'failed';
41
+ readonly reports: readonly TesterFeedItem[];
42
+ /** The titles of the archives still in this device's outbox (not on the gateway yet, so no code). */
43
+ readonly queued: readonly string[];
44
+ }
45
+
46
+ export interface TesterFeedOptions {
47
+ readonly files: DiagnosticFiles;
48
+ readonly fetch: DiagnosticFetch;
49
+ readonly gateway: string;
50
+ readonly device: DeviceIdentity;
51
+ readonly headers?: DeviceHeaderNames;
52
+ readonly extraHeaders?: (url: string) => Readonly<Record<string, string>>;
53
+ readonly queued: () => Promise<readonly string[]>;
54
+ readonly timeoutMs?: number;
55
+ readonly log?: DiagnosticLog;
56
+ }
57
+
58
+ const str = (v: unknown) => (typeof v === 'string' ? v : '');
59
+
60
+ function item(raw: Record<string, unknown>): TesterFeedItem {
61
+ return {
62
+ reportId: str(raw.reportId),
63
+ code: str(raw.code),
64
+ title: str(raw.title),
65
+ username: str(raw.username),
66
+ platform: str(raw.platform),
67
+ appVersion: str(raw.appVersion),
68
+ state: str(raw.state),
69
+ outcome: str(raw.outcome),
70
+ jiraKey: str(raw.jiraKey),
71
+ mine: raw.mine === true,
72
+ createdAtUtc: str(raw.createdAtUtc),
73
+ };
74
+ }
75
+
76
+ /** The manifest inside an archive (null: unreadable — the zip stays queued, never deleted). */
77
+ export async function readManifest(files: DiagnosticFiles, archivePath: string): Promise<TesterReportDraft | null> {
78
+ try {
79
+ const parsed = JSON.parse(await files.zipReadText(archivePath, MANIFEST_ENTRY, 4 * 1024 * 1024)) as unknown;
80
+ return isDraft(parsed) ? parsed : null;
81
+ } catch {
82
+ return null;
83
+ }
84
+ }
85
+
86
+ export async function loadTesterFeed(o: TesterFeedOptions): Promise<TesterFeed> {
87
+ const log = o.log ?? silentLog;
88
+ const queued = await queuedTitles(o).catch(() => [] as string[]);
89
+ try {
90
+ const url = `${o.gateway.replace(/\/+$/, '')}${FEED_ROUTE}`;
91
+ const headers = { ...(o.extraHeaders?.(url) ?? {}), Accept: 'application/json', ...deviceHeaders(o.device, o.headers ?? NEUTRAL_DEVICE_HEADERS) };
92
+ const response = await withTimeout(o.fetch(url, { method: 'GET', headers }), o.timeoutMs ?? 30_000);
93
+ if (response.status === 403) return { status: 'notYet', reports: [], queued };
94
+ const text = await response.text();
95
+ if (response.status < 200 || response.status >= 300) {
96
+ log.log('warn', 'tester', `the report list → HTTP ${response.status}`);
97
+ return { status: 'failed', reports: [], queued };
98
+ }
99
+ const body = JSON.parse(text) as { reports?: unknown };
100
+ const reports = Array.isArray(body.reports) ? body.reports.filter((r): r is Record<string, unknown> => !!r && typeof r === 'object').map(item) : [];
101
+ return { status: 'loaded', reports, queued };
102
+ } catch (error) {
103
+ log.log('warn', 'tester', `the report list could not be loaded: ${errorText(error)}`);
104
+ return { status: 'failed', reports: [], queued };
105
+ }
106
+ }
107
+
108
+ async function queuedTitles(o: TesterFeedOptions): Promise<string[]> {
109
+ const titles: string[] = [];
110
+ for (const path of await o.queued()) {
111
+ const manifest = await readManifest(o.files, path);
112
+ const name = (path.split('/').pop() ?? path).replace(/\.zip$/, '');
113
+ titles.push(manifest && manifest.title.trim() ? manifest.title : name);
114
+ }
115
+ return titles;
116
+ }
117
+
118
+ // ── what a card shows ────────────────────────────────────────────────────────────────────────────────────────────────
119
+
120
+ /** Sent → received → reviewed → resolved. */
121
+ export const TRACK_STEPS = 4;
122
+
123
+ export type CardTone = 'warning' | 'info' | 'primary' | 'success' | 'muted';
124
+
125
+ export type CardIcon = 'upload' | 'processing' | 'review' | 'received' | 'filed' | 'done' | 'closed';
126
+
127
+ export interface TesterCard {
128
+ readonly code: string;
129
+ readonly title: string;
130
+ /** A package text key. */
131
+ readonly stateKey: string;
132
+ readonly outcomeKey: string | null;
133
+ readonly tone: CardTone;
134
+ readonly icon: CardIcon;
135
+ /** Steps of the track already walked (0..4). */
136
+ readonly step: number;
137
+ readonly inProgress: boolean;
138
+ readonly jiraKey: string | null;
139
+ readonly createdAtUtc: string | null;
140
+ readonly meta: string;
141
+ readonly mine: boolean;
142
+ }
143
+
144
+ const OUTCOME_KEY: Readonly<Record<string, string>> = {
145
+ [TesterReportOutcomes.jira]: 'TesterReportOutcomeJiraFormat',
146
+ [TesterReportOutcomes.fixedInCode]: 'TesterReportOutcomeFixedInCode',
147
+ [TesterReportOutcomes.notABug]: 'TesterReportOutcomeNotABug',
148
+ [TesterReportOutcomes.duplicate]: 'TesterReportOutcomeDuplicate',
149
+ };
150
+
151
+ /** The state a tester reads: what became of the report wins over where its processing is. */
152
+ export function describeReport(r: TesterFeedItem): TesterCard {
153
+ const outcomeKey = OUTCOME_KEY[r.outcome] ?? null;
154
+ // « | », not «·»: a Persian face draws a middle dot like a zero beside Persian digits.
155
+ const meta = [r.username, r.platform, r.appVersion ? `⁦${r.appVersion}⁩` : ''].filter((s) => s.trim().length > 0).join(' | ');
156
+ const jiraKey = r.outcome === TesterReportOutcomes.jira && r.jiraKey.trim() ? r.jiraKey : null;
157
+ const base = { code: r.code, title: r.title, outcomeKey, jiraKey, createdAtUtc: r.createdAtUtc || null, meta, mine: r.mine, inProgress: false };
158
+ if (r.state === TesterReportStates.deleted) return { ...base, stateKey: 'TesterReportStateDeleted', tone: 'muted', icon: 'closed', step: TRACK_STEPS };
159
+ if (outcomeKey) return { ...base, stateKey: outcomeKey, outcomeKey: null, tone: 'success', icon: r.outcome === TesterReportOutcomes.jira ? 'filed' : 'done', step: TRACK_STEPS };
160
+ switch (r.state) {
161
+ case TesterReportStates.uploading:
162
+ return { ...base, stateKey: 'TesterReportStateUploading', tone: 'warning', icon: 'upload', step: 1, inProgress: true };
163
+ case TesterReportStates.processing:
164
+ return { ...base, stateKey: 'TesterReportStateProcessing', tone: 'info', icon: 'processing', step: 2, inProgress: true };
165
+ case TesterReportStates.ready:
166
+ return { ...base, stateKey: 'TesterReportStateReady', tone: 'primary', icon: 'review', step: 3 };
167
+ default:
168
+ return { ...base, stateKey: 'TesterReportStateReceived', tone: 'primary', icon: 'received', step: 2 };
169
+ }
170
+ }
171
+
172
+ /** The four counts across the top: queued · in review · ready · resolved. */
173
+ export function summarize(feed: TesterFeed): { queued: number; review: number; ready: number; done: number } {
174
+ const s = { queued: feed.queued.length, review: 0, ready: 0, done: 0 };
175
+ for (const r of feed.reports) {
176
+ if (r.state === TesterReportStates.deleted || r.outcome) s.done++;
177
+ else if (r.state === TesterReportStates.uploading) s.queued++;
178
+ else if (r.state === TesterReportStates.ready) s.ready++;
179
+ else s.review++;
180
+ }
181
+ return s;
182
+ }
@@ -0,0 +1,61 @@
1
+ // How the tester opens the capture panel (G9AppDiagnostic.Maui TesterGestureMode / TesterGestureService): by default a
2
+ // DOUBLE TAP WITH TWO FINGERS anywhere. The numbers are persisted by apps in the field: never renumber.
3
+ //
4
+ // The recogniser is native and CONSUMES the gesture (the platform package): the second tap cancels the touch for the
5
+ // views under it, so a map never zooms out twice and a list never takes it as a tap. It reports the gesture with its
6
+ // finger count and whether it landed on a surface the app excludes (a map in mode 1); this file decides, for a platform
7
+ // or a test that reports single taps only, whether two of them make one.
8
+
9
+ export const TesterGestureMode = {
10
+ /** Double tap with two fingers, on any screen. */
11
+ TwoFingers: 0,
12
+ /** The same, except on the surfaces the app names (a map, where a two-finger tap zooms out). */
13
+ TwoFingersExceptMap: 1,
14
+ /** Double tap with three fingers: no map conflict, but some phones take a three-finger swipe as a screenshot. */
15
+ ThreeFingers: 2,
16
+ } as const;
17
+ export type TesterGestureMode = (typeof TesterGestureMode)[keyof typeof TesterGestureMode];
18
+
19
+ export const TESTER_GESTURE_MODES: readonly TesterGestureMode[] = [TesterGestureMode.TwoFingers, TesterGestureMode.TwoFingersExceptMap, TesterGestureMode.ThreeFingers];
20
+
21
+ /** Longest gap between the two taps (MAUI MaxGapMs). */
22
+ export const MAX_GAP_MS = 450;
23
+
24
+ export const fingersFor = (mode: TesterGestureMode): number => (mode === TesterGestureMode.ThreeFingers ? 3 : 2);
25
+
26
+ /** A stored mode ("0", 2, garbage) → a mode; anything unknown is the default. */
27
+ export function parseGestureMode(value: unknown): TesterGestureMode {
28
+ const n = Number(value ?? TesterGestureMode.TwoFingers);
29
+ return (TESTER_GESTURE_MODES as readonly number[]).indexOf(n) >= 0 ? (n as TesterGestureMode) : TesterGestureMode.TwoFingers;
30
+ }
31
+
32
+ /** One completed multi-finger tap (x, y: fractions of the window; `excluded`: on a surface the app excludes). */
33
+ export interface TesterTap {
34
+ readonly fingers: number;
35
+ readonly x: number;
36
+ readonly y: number;
37
+ readonly excluded: boolean;
38
+ }
39
+
40
+ /** Whether a whole gesture the native recogniser reports counts in this mode. */
41
+ export function gestureCounts(fingers: number, excluded: boolean, mode: TesterGestureMode): boolean {
42
+ if (fingers < fingersFor(mode)) return false;
43
+ return !(mode === TesterGestureMode.TwoFingersExceptMap && excluded);
44
+ }
45
+
46
+ /**
47
+ * Pairs single taps into the gesture: true when `tap` is the second of two taps with the same finger count within
48
+ * {@link MAX_GAP_MS}. A third tap starts a new pair; it does not fire again.
49
+ */
50
+ export function createTapPairer(now: () => number = Date.now): (tap: TesterTap, mode: TesterGestureMode) => boolean {
51
+ let lastMs = Number.NEGATIVE_INFINITY;
52
+ let lastFingers = 0;
53
+ return (tap, mode) => {
54
+ if (!gestureCounts(tap.fingers, tap.excluded, mode)) return false;
55
+ const t = now();
56
+ const fire = lastFingers === tap.fingers && t - lastMs <= MAX_GAP_MS;
57
+ lastMs = fire ? Number.NEGATIVE_INFINITY : t;
58
+ lastFingers = tap.fingers;
59
+ return fire;
60
+ };
61
+ }
@@ -0,0 +1,125 @@
1
+ // A tester (QA) report on the device — the TypeScript twin of G9AppDiagnostic.Maui TesterReportModels. The JSON shape of
2
+ // `report.json` is the .NET one, key for key and kind for kind (numbers): the gateway, its operator page and the local AI
3
+ // read the archives of every app, so a report from this package is indistinguishable from a .NET one. Add, never rename.
4
+
5
+ /** What a tester captured; the name is the folder inside the report (`<report>/<Kind>/`), the number its value in JSON. */
6
+ export const TesterAttachmentKind = {
7
+ Screenshot: 0,
8
+ Recording: 1,
9
+ Voice: 2,
10
+ File: 3,
11
+ /** Collected by the app, never by the tester (context, logs, a recording's timeline). */
12
+ Diagnostic: 4,
13
+ /** The local-store backup, only when the tester opts in on the send form. */
14
+ DatabaseBackup: 5,
15
+ } as const;
16
+ export type TesterAttachmentKind = (typeof TesterAttachmentKind)[keyof typeof TesterAttachmentKind];
17
+
18
+ const KIND_NAMES = ['Screenshot', 'Recording', 'Voice', 'File', 'Diagnostic', 'DatabaseBackup'] as const;
19
+
20
+ /** The folder name of a kind (.NET `nameof(TesterAttachmentKind.X)`); an unknown number reads as a file. */
21
+ export function kindFolder(kind: number): string {
22
+ return KIND_NAMES[kind] ?? 'File';
23
+ }
24
+
25
+ export interface TesterReportAttachment {
26
+ readonly id: string;
27
+ readonly kind: TesterAttachmentKind;
28
+ /** The file name inside its kind folder — never an absolute path (app data paths move across reinstalls). */
29
+ readonly fileName: string;
30
+ readonly displayName: string;
31
+ readonly sizeBytes: number;
32
+ readonly capturedUtc: string;
33
+ /** When a recording STARTED (a screen recording, its sound, its timeline): the local AI aligns them by these. */
34
+ readonly startedUtc?: string;
35
+ /** The `id` of the screen recording this file belongs to (its sound, its timeline). */
36
+ readonly pairedWith?: string;
37
+ }
38
+
39
+ /** Where the tester was when the report started, as values (report.json `screen`; the app's own facts beside them). */
40
+ export interface TesterScreenSnapshot {
41
+ readonly section?: string | null;
42
+ readonly openSheets: number;
43
+ readonly online: boolean;
44
+ readonly viewPath: readonly string[];
45
+ readonly screenNames: readonly string[];
46
+ readonly capturedUtc: string;
47
+ readonly [extra: string]: unknown;
48
+ }
49
+
50
+ export interface TesterReportDraft {
51
+ readonly id: string;
52
+ /** Becomes the tracker issue's summary (the app's own title since 2026-10-31: there is no title field). */
53
+ readonly title: string;
54
+ readonly description: string;
55
+ readonly createdUtc: string;
56
+ readonly attachments: readonly TesterReportAttachment[];
57
+ /** The opt-in for the database backup (off by default: the one thing that makes a report huge). */
58
+ readonly includeDatabaseBackup: boolean;
59
+ /** Who started it: the outbox uploads later, maybe after a sign-out or an impersonation switch. */
60
+ readonly username: string | null;
61
+ /** false = never to the gateway's local AI; absent = the gateway decides. */
62
+ readonly aiPack?: boolean | null;
63
+ /** The report's kind key (`bug`, `feature`…); absent = the first kind. */
64
+ readonly kind?: string | null;
65
+ /** The build's git branch and commit, set when archived. */
66
+ readonly branch?: string | null;
67
+ readonly commit?: string | null;
68
+ /** Where the report started, for context.txt (English lines). */
69
+ readonly screenContext?: readonly string[] | null;
70
+ /** The title the APP wrote («a problem in …»), so a reader tells it from the tester's words. */
71
+ readonly autoTitle?: string | null;
72
+ /** The labelled block the app put at the head of the description. */
73
+ readonly autoDescription?: string | null;
74
+ readonly screen?: TesterScreenSnapshot | null;
75
+ }
76
+
77
+ /** Pieces of evidence as the tester thinks of them: a recording's own sound and timeline are part of the video. */
78
+ export function evidence(draft: TesterReportDraft | null): readonly TesterReportAttachment[] {
79
+ return draft ? draft.attachments.filter((a) => !a.pairedWith && a.kind !== TesterAttachmentKind.Diagnostic && a.kind !== TesterAttachmentKind.DatabaseBackup) : [];
80
+ }
81
+
82
+ /** The send form's chips: how many of each kind. */
83
+ export function evidenceCounts(draft: TesterReportDraft | null): ReadonlyMap<TesterAttachmentKind, number> {
84
+ const counts = new Map<TesterAttachmentKind, number>();
85
+ for (const a of evidence(draft)) counts.set(a.kind, (counts.get(a.kind) ?? 0) + 1);
86
+ return counts;
87
+ }
88
+
89
+ export function isDraft(value: unknown): value is TesterReportDraft {
90
+ const v = value as Partial<TesterReportDraft> | null;
91
+ return !!v && typeof v.id === 'string' && typeof v.title === 'string' && Array.isArray(v.attachments);
92
+ }
93
+
94
+ /** 32 lower-case hex characters (.NET `Guid.NewGuid().ToString("N")` — the gateway's ids are hex). */
95
+ export function newReportId(random: () => number = Math.random): string {
96
+ let s = '';
97
+ for (let i = 0; i < 32; i++) s += Math.floor(random() * 16).toString(16);
98
+ return s;
99
+ }
100
+
101
+ /** A file name that is safe inside a kind folder (no separators, no leading dots), keeping the extension. */
102
+ export function safeFileName(name: string): string {
103
+ const base = name.split(/[\\/]/).pop() ?? 'file';
104
+ // An explicit unsafe set, not \p{L}: PrimJS (the Lynx engine) rejects Unicode property escapes at bytecode time.
105
+ const cleaned = base.replace(/[\x00-\x1f\x7f<>:"|?*]/g, '_').replace(/^\.+/, '').trim();
106
+ return cleaned.length > 0 ? cleaned.slice(-120) : 'file';
107
+ }
108
+
109
+ /** `name.ext` → `name (2).ext` until `taken` says no. */
110
+ export function uniqueName(name: string, taken: (candidate: string) => boolean): string {
111
+ if (!taken(name)) return name;
112
+ const dot = name.lastIndexOf('.');
113
+ const stem = dot > 0 ? name.slice(0, dot) : name;
114
+ const ext = dot > 0 ? name.slice(dot) : '';
115
+ for (let i = 2; ; i++) {
116
+ const candidate = `${stem} (${i})${ext}`;
117
+ if (!taken(candidate)) return candidate;
118
+ }
119
+ }
120
+
121
+ export function formatBytes(bytes: number): string {
122
+ if (bytes < 1024) return `${bytes} B`;
123
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
124
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
125
+ }
@@ -0,0 +1,131 @@
1
+ // The tester report outbox (G9AppDiagnostic.Maui TesterReportOutboxService): a folder of `*.zip`, uploaded to the
2
+ // gateway and deleted locally once — and only once — the gateway confirmed the WHOLE report.
3
+ //
4
+ // The folder IS the queue: a zip there means "not on the gateway yet", nothing else keeps state, so nothing can disagree
5
+ // with it and a force-close between any two steps leaves the queue as correct as before. Three triggers, one
6
+ // single-flight drain: the periodic loop (the level trigger: a flaky link eventually gets through), the network coming
7
+ // back (the edge trigger), and the tester's "send it now". The automatic triggers skip while a drain runs; the manual
8
+ // one WAITS for it, so it reports what really happened instead of "busy".
9
+ import { type DiagnosticFiles, type DiagnosticLog, errorText, silentLog } from '../host.ts';
10
+ import { createStore, type ReadableStore } from '../store.ts';
11
+
12
+ export interface OutboxState {
13
+ readonly pending: number;
14
+ readonly draining: boolean;
15
+ /** Reports this drain has uploaded so far. */
16
+ readonly sent: number;
17
+ readonly lastFailure: string | null;
18
+ }
19
+
20
+ export interface OutboxOptions {
21
+ readonly files: DiagnosticFiles;
22
+ /** The outbox folder (absolute). */
23
+ readonly dir: () => Promise<string>;
24
+ /** Uploads one archive; true ONLY when the gateway has all of it. */
25
+ readonly upload: (path: string) => Promise<boolean>;
26
+ readonly online: () => Promise<boolean>;
27
+ /** Default 3 minutes (MAUI's loop). */
28
+ readonly intervalMs?: number;
29
+ /** Holds the process while a drain sends (a foreground service); its release is called after. */
30
+ readonly keepAlive?: () => Promise<(() => void | Promise<void>) | null>;
31
+ readonly log?: DiagnosticLog;
32
+ }
33
+
34
+ const nameOf = (p: string) => p.split('/').pop() ?? p;
35
+
36
+ export class TesterOutbox {
37
+ private readonly o: OutboxOptions;
38
+ private readonly store = createStore<OutboxState>({ pending: 0, draining: false, sent: 0, lastFailure: null });
39
+ private running: Promise<number> | null = null;
40
+ private timer: ReturnType<typeof setInterval> | null = null;
41
+
42
+ constructor(options: OutboxOptions) {
43
+ this.o = options;
44
+ }
45
+
46
+ get state(): ReadableStore<OutboxState> {
47
+ return this.store;
48
+ }
49
+
50
+ async queued(): Promise<string[]> {
51
+ try {
52
+ const dir = await this.o.dir();
53
+ return (await this.o.files.list(dir)).filter((f) => !f.dir && f.name.endsWith('.zip')).map((f) => f.path);
54
+ } catch {
55
+ return [];
56
+ }
57
+ }
58
+
59
+ async refresh(): Promise<number> {
60
+ const pending = (await this.queued()).length;
61
+ // an empty queue has no failure to report (the failed file was sent by a later pass, or removed)
62
+ this.store.set((s) => ({ ...s, pending, ...(pending === 0 ? { lastFailure: null } : {}) }));
63
+ return pending;
64
+ }
65
+
66
+ /** The level trigger + one immediate pass. Idempotent. */
67
+ start(): void {
68
+ if (this.timer) return;
69
+ this.timer = setInterval(() => void this.drain(false), this.o.intervalMs ?? 3 * 60_000);
70
+ void this.drain(false);
71
+ }
72
+
73
+ stop(): void {
74
+ if (this.timer) clearInterval(this.timer);
75
+ this.timer = null;
76
+ }
77
+
78
+ /** A report just landed in the outbox (a foreground moment): upload now. */
79
+ notifyQueued(): void {
80
+ void this.refresh().then(() => this.drain(false));
81
+ }
82
+
83
+ /** The tester's "send now": waits for a drain in flight, then sends what is left. Resolves how many went. */
84
+ async flush(): Promise<number> {
85
+ if (this.running) await this.running.catch(() => 0);
86
+ return this.drain(true);
87
+ }
88
+
89
+ drain(manual: boolean): Promise<number> {
90
+ if (this.running) return manual ? this.running.then(() => this.drain(true)) : Promise.resolve(0);
91
+ const run = this.drainOnce().finally(() => {
92
+ this.running = null;
93
+ this.store.set((s) => ({ ...s, draining: false }));
94
+ });
95
+ this.running = run;
96
+ return run;
97
+ }
98
+
99
+ private async drainOnce(): Promise<number> {
100
+ const log = this.o.log ?? silentLog;
101
+ const queue = await this.queued();
102
+ this.store.set((s) => ({ ...s, pending: queue.length, ...(queue.length === 0 ? { lastFailure: null } : {}) }));
103
+ if (queue.length === 0) return 0;
104
+ if (!(await this.o.online().catch(() => true))) return 0;
105
+ this.store.set((s) => ({ ...s, draining: true, sent: 0, lastFailure: null }));
106
+ const release = await this.o.keepAlive?.().catch(() => null);
107
+ let sent = 0;
108
+ try {
109
+ for (const path of queue) {
110
+ let ok = false;
111
+ try {
112
+ ok = await this.o.upload(path);
113
+ } catch (error) {
114
+ log.log('warn', 'tester', `outbox upload threw: ${errorText(error)}`);
115
+ }
116
+ if (!ok) {
117
+ this.store.set((s) => ({ ...s, lastFailure: nameOf(path) }));
118
+ continue; // keep it: the next pass retries
119
+ }
120
+ await this.o.files.remove(path).catch(() => {});
121
+ sent++;
122
+ this.store.set((s) => ({ ...s, sent, pending: Math.max(0, s.pending - 1) }));
123
+ log.log('info', 'tester', `report ${nameOf(path)} uploaded`);
124
+ }
125
+ } finally {
126
+ if (release) await Promise.resolve(release()).catch(() => {});
127
+ }
128
+ await this.refresh();
129
+ return sent;
130
+ }
131
+ }
@@ -0,0 +1,117 @@
1
+ // Where the tester was when a report started (G9AppDiagnostic.Maui TesterScreenContext): read at the moment of the
2
+ // gesture, it gives the report its title («مشکل در بخش نقشه — سایت نمونه») and adds what a log does not record — the
3
+ // screen path, the open sheets, the network, and whatever the app says about its own screen (a site, a map's zoom…).
4
+ // Read-only and best effort: nothing here may stop a report from starting.
5
+ import { type DiagTranslate } from '../strings.ts';
6
+ import type { TesterScreenSnapshot } from './model.ts';
7
+
8
+ /** One fact the app adds about its screen. `data` goes into report.json's `screen` (names are a contract: add, never rename). */
9
+ export interface TesterScreenFact {
10
+ readonly label: string;
11
+ readonly value: string;
12
+ readonly contextLabel: string;
13
+ readonly contextValue?: string;
14
+ readonly data: ReadonlyArray<readonly [string, string | number | boolean | null]>;
15
+ }
16
+
17
+ /** What the app says about its own screen (`describeScreen`). */
18
+ export class TesterScreenDescription {
19
+ /** The tab or page by the name QA reads; the title says «a problem in …» this. */
20
+ section: string | null = null;
21
+ /** Added to the title after the section («… — سایت نمونه»). */
22
+ titleDetail: string | null = null;
23
+ /** The visible views, page first and the topmost sheet last (class or component names, for developers). */
24
+ viewPath: string[] = [];
25
+ /** The same path by the names QA reads («نقشه › کارت درخت»); empty = the view path stands in. */
26
+ screenNames: string[] = [];
27
+ openSheets = 0;
28
+ online = true;
29
+ readonly facts: TesterScreenFact[] = [];
30
+
31
+ /** One fact: its localized label and value, its English label for context.txt, and its values for report.json. */
32
+ add(label: string, value: string, contextLabel: string, options: { readonly contextValue?: string; readonly data?: ReadonlyArray<readonly [string, string | number | boolean | null]> } = {}): this {
33
+ this.facts.push({ label, value, contextLabel, ...(options.contextValue !== undefined ? { contextValue: options.contextValue } : {}), data: options.data ?? [] });
34
+ return this;
35
+ }
36
+ }
37
+
38
+ /** How many of the topmost view names the developer's path keeps. */
39
+ const MAX_PATH = 6;
40
+
41
+ export interface TesterScreenContext {
42
+ readonly section: string | null;
43
+ readonly titleDetail: string | null;
44
+ readonly facts: readonly TesterScreenFact[];
45
+ readonly openSheets: number;
46
+ readonly online: boolean;
47
+ readonly viewPath: readonly string[];
48
+ readonly namedPath: readonly string[];
49
+ readonly capturedUtc: string;
50
+ }
51
+
52
+ /** Reads the screen through the app's `describeScreen`; a throw costs only the app's facts. */
53
+ export function captureScreen(describe: ((d: TesterScreenDescription) => void) | undefined, now: () => number = Date.now): TesterScreenContext {
54
+ const d = new TesterScreenDescription();
55
+ try {
56
+ describe?.(d);
57
+ } catch {
58
+ // the app's facts are optional; the report starts with the rest
59
+ }
60
+ const collapse = (names: readonly string[]) => names.filter((n, i) => n && names[i - 1] !== n);
61
+ const viewPath = collapse(d.viewPath);
62
+ return {
63
+ section: d.section && d.section.trim() ? d.section : null,
64
+ titleDetail: d.titleDetail && d.titleDetail.trim() ? d.titleDetail : null,
65
+ facts: d.facts.slice(),
66
+ openSheets: d.openSheets,
67
+ online: d.online,
68
+ viewPath: viewPath.slice(Math.max(0, viewPath.length - MAX_PATH)),
69
+ namedPath: collapse(d.screenNames),
70
+ capturedUtc: new Date(now()).toISOString(),
71
+ };
72
+ }
73
+
74
+ /** «مشکل در بخش نقشه — سایت نمونه», «مشکل در بخش وظایف»; empty when nothing could be read. */
75
+ export function suggestedTitle(c: TesterScreenContext, t: DiagTranslate): string {
76
+ if (!c.section) return '';
77
+ return c.titleDetail ? t('TesterAutoTitleWithSiteFormat', c.section, c.titleDetail) : t('TesterAutoTitleFormat', c.section);
78
+ }
79
+
80
+ /** The labelled block at the head of the description: localized labels, machine values as they are. */
81
+ export function descriptionBlock(c: TesterScreenContext, t: DiagTranslate): string {
82
+ const line = (label: string, value: string) => `${label}: ${value}`;
83
+ const lines = [t('TesterAutoContextHeader')];
84
+ if (c.section) lines.push(line(t('TesterAutoContextSection'), c.section));
85
+ for (const f of c.facts) lines.push(line(f.label, f.value));
86
+ lines.push(line(t('TesterAutoContextOpenSheets'), String(c.openSheets)));
87
+ lines.push(line(t('TesterAutoContextNetwork'), c.online ? t('TesterAutoContextOnline') : t('TesterAutoContextOffline')));
88
+ // QA reads the named screens; the developer's names stand in only when none is named.
89
+ const shown = c.namedPath.length > 0 ? c.namedPath : c.viewPath;
90
+ if (shown.length > 0) lines.push(line(t('TesterAutoContextScreen'), shown.join(' › ')));
91
+ return lines.join('\n');
92
+ }
93
+
94
+ const pad = (label: string) => (label.length >= 14 ? label : label + ' '.repeat(14 - label.length));
95
+
96
+ /** The same facts for Diagnostic/context.txt (English labels, like the rest of that file). */
97
+ export function contextFileLines(c: TesterScreenContext): string[] {
98
+ return [
99
+ '',
100
+ 'Screen when the report started',
101
+ '------------------------------',
102
+ `CapturedUtc : ${c.capturedUtc}`,
103
+ `Section : ${c.section ?? ''}`,
104
+ ...c.facts.map((f) => `${pad(f.contextLabel)}: ${f.contextValue ?? f.value}`),
105
+ `OpenSheets : ${c.openSheets}`,
106
+ `Online : ${c.online ? 'True' : 'False'}`,
107
+ `ViewPath : ${c.viewPath.join(' > ')}`,
108
+ `ScreenNames : ${c.namedPath.join(' > ')}`,
109
+ ];
110
+ }
111
+
112
+ /** The same facts as data, for report.json (the app's values at the same level as the generic ones). */
113
+ export function toSnapshot(c: TesterScreenContext): TesterScreenSnapshot {
114
+ const extra: Record<string, unknown> = {};
115
+ for (const f of c.facts) for (const [k, v] of f.data) extra[k] = v;
116
+ return { ...extra, section: c.section, openSheets: c.openSheets, online: c.online, viewPath: c.viewPath.slice(), screenNames: c.namedPath.slice(), capturedUtc: c.capturedUtc };
117
+ }