@g9tm/app-diagnostic 0.2.0 → 0.2.2

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,117 +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
- }
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
+ }
@@ -1,145 +1,145 @@
1
- // The tester's drafts (G9AppDiagnostic.Maui TesterReportDraftStore): one folder per report — `report.json` at its root
2
- // and one folder per attachment kind — so a force-close or a crash mid-session never costs the evidence: the panel
3
- // re-attaches to the ACTIVE draft (a device-wide pointer; the draft carries its author) on the next launch.
4
- // The root folder and the pointer's preference key are the app's: an app that had tester mode before keeps its own, or
5
- // an update forgets the draft its tester was composing.
6
- import type { DiagnosticFiles, DiagnosticPrefs } from '../host.ts';
7
- import { isDraft, kindFolder, newReportId, safeFileName, type TesterAttachmentKind, type TesterReportAttachment, type TesterReportDraft, uniqueName } from './model.ts';
8
-
9
- export interface DraftStoreOptions {
10
- readonly files: DiagnosticFiles;
11
- readonly prefs: DiagnosticPrefs;
12
- /** The drafts' folder (absolute): `<root>/<id>/report.json`. */
13
- readonly root: () => Promise<string>;
14
- /** The preference that names the active draft. */
15
- readonly activeKey: string;
16
- readonly now?: () => number;
17
- }
18
-
19
- export interface AddAttachmentOptions {
20
- readonly displayName?: string;
21
- /** Our own temporary file: removed after it was copied in. */
22
- readonly deleteSource?: boolean;
23
- /** A recorder wrote the file INTO the kind folder: adopt it by name, never copy it. */
24
- readonly inPlace?: boolean;
25
- /** A recording: when it started (ISO). */
26
- readonly startedUtc?: string;
27
- /** The screen recording this file belongs to (its sound, its timeline). */
28
- readonly pairedWith?: string;
29
- }
30
-
31
- export class TesterDraftStore {
32
- private readonly o: DraftStoreOptions;
33
- private readonly now: () => number;
34
-
35
- constructor(options: DraftStoreOptions) {
36
- this.o = options;
37
- this.now = options.now ?? Date.now;
38
- }
39
-
40
- root(): Promise<string> {
41
- return this.o.root();
42
- }
43
-
44
- async reportDir(id: string): Promise<string> {
45
- return `${await this.o.root()}/${id}`;
46
- }
47
-
48
- async kindDir(id: string, kind: TesterAttachmentKind): Promise<string> {
49
- return `${await this.reportDir(id)}/${kindFolder(kind)}`;
50
- }
51
-
52
- /** A report is started by its first piece of evidence: its title is the app's, written at send. */
53
- async create(fields: Partial<Pick<TesterReportDraft, 'title' | 'description' | 'kind' | 'autoTitle' | 'autoDescription' | 'screen' | 'screenContext'>>, username: string | null): Promise<TesterReportDraft> {
54
- const draft: TesterReportDraft = {
55
- id: newReportId(),
56
- title: (fields.title ?? '').trim(),
57
- description: (fields.description ?? '').trim(),
58
- createdUtc: new Date(this.now()).toISOString(),
59
- attachments: [],
60
- includeDatabaseBackup: false,
61
- username,
62
- ...(fields.kind ? { kind: fields.kind } : {}),
63
- ...(fields.autoTitle ? { autoTitle: fields.autoTitle } : {}),
64
- ...(fields.autoDescription ? { autoDescription: fields.autoDescription } : {}),
65
- ...(fields.screen ? { screen: fields.screen } : {}),
66
- ...(fields.screenContext ? { screenContext: fields.screenContext } : {}),
67
- };
68
- await this.save(draft);
69
- this.o.prefs.set(this.o.activeKey, draft.id);
70
- return draft;
71
- }
72
-
73
- /** The draft the panel should show, or null (a pointer to a vanished folder is cleared). */
74
- async active(): Promise<TesterReportDraft | null> {
75
- const id = this.o.prefs.get(this.o.activeKey);
76
- if (!id) return null;
77
- const draft = await this.read(id);
78
- if (!draft) this.o.prefs.set(this.o.activeKey, null);
79
- return draft;
80
- }
81
-
82
- async read(id: string): Promise<TesterReportDraft | null> {
83
- try {
84
- const parsed = JSON.parse(await this.o.files.readText(`${await this.reportDir(id)}/report.json`, 4 * 1024 * 1024)) as unknown;
85
- return isDraft(parsed) ? parsed : null;
86
- } catch {
87
- return null;
88
- }
89
- }
90
-
91
- async save(draft: TesterReportDraft): Promise<void> {
92
- await this.o.files.writeText(`${await this.reportDir(draft.id)}/report.json`, JSON.stringify(draft, null, 2));
93
- }
94
-
95
- /**
96
- * Adds a file to the draft. A recorder that wrote straight into the kind folder is only registered; anything else is
97
- * COPIED in (a picked file belongs to the user) and the source removed only with `deleteSource` (our own temp files).
98
- */
99
- async addAttachment(draft: TesterReportDraft, kind: TesterAttachmentKind, source: string, options: AddAttachmentOptions = {}): Promise<TesterReportDraft> {
100
- const files = this.o.files;
101
- const dir = await this.kindDir(draft.id, kind);
102
- const existing = new Set((await files.list(dir)).map((f) => f.name));
103
- const sourceName = source.split('/').pop() ?? 'file';
104
- let fileName: string;
105
- // inPlace: adopt by NAME. Hosts canonicalise the folder they are given (Android /data/user/0 → /data/data, iOS
106
- // /var → /private/var), so the returned path need not start with `dir`; a prefix test alone copied every recording
107
- // next to itself ("screen-… (2).mp4", the bytes twice).
108
- if (existing.has(sourceName) && (options.inPlace === true || source.startsWith(`${dir}/`))) {
109
- fileName = sourceName;
110
- } else {
111
- fileName = uniqueName(safeFileName(options.displayName ?? sourceName), (c) => existing.has(c));
112
- await files.copy(source, `${dir}/${fileName}`);
113
- if (options.deleteSource) await files.remove(source).catch(() => {});
114
- }
115
- const sizeBytes = await files.size(`${dir}/${fileName}`).catch(() => 0);
116
- const attachment: TesterReportAttachment = {
117
- id: newReportId(),
118
- kind,
119
- fileName,
120
- displayName: options.displayName ?? fileName,
121
- sizeBytes,
122
- capturedUtc: new Date(this.now()).toISOString(),
123
- ...(options.startedUtc ? { startedUtc: options.startedUtc } : {}),
124
- ...(options.pairedWith ? { pairedWith: options.pairedWith } : {}),
125
- };
126
- const next: TesterReportDraft = { ...draft, attachments: [...draft.attachments, attachment] };
127
- await this.save(next);
128
- return next;
129
- }
130
-
131
- async removeAttachment(draft: TesterReportDraft, attachmentId: string): Promise<TesterReportDraft> {
132
- const a = draft.attachments.find((x) => x.id === attachmentId);
133
- if (!a) return draft;
134
- await this.o.files.remove(`${await this.kindDir(draft.id, a.kind)}/${a.fileName}`).catch(() => {});
135
- const next: TesterReportDraft = { ...draft, attachments: draft.attachments.filter((x) => x.id !== attachmentId) };
136
- await this.save(next);
137
- return next;
138
- }
139
-
140
- /** Deletes the draft folder (after it was archived, or the tester discarded it). */
141
- async discard(id: string): Promise<void> {
142
- await this.o.files.remove(await this.reportDir(id));
143
- if (this.o.prefs.get(this.o.activeKey) === id) this.o.prefs.set(this.o.activeKey, null);
144
- }
145
- }
1
+ // The tester's drafts (G9AppDiagnostic.Maui TesterReportDraftStore): one folder per report — `report.json` at its root
2
+ // and one folder per attachment kind — so a force-close or a crash mid-session never costs the evidence: the panel
3
+ // re-attaches to the ACTIVE draft (a device-wide pointer; the draft carries its author) on the next launch.
4
+ // The root folder and the pointer's preference key are the app's: an app that had tester mode before keeps its own, or
5
+ // an update forgets the draft its tester was composing.
6
+ import type { DiagnosticFiles, DiagnosticPrefs } from '../host.ts';
7
+ import { isDraft, kindFolder, newReportId, safeFileName, type TesterAttachmentKind, type TesterReportAttachment, type TesterReportDraft, uniqueName } from './model.ts';
8
+
9
+ export interface DraftStoreOptions {
10
+ readonly files: DiagnosticFiles;
11
+ readonly prefs: DiagnosticPrefs;
12
+ /** The drafts' folder (absolute): `<root>/<id>/report.json`. */
13
+ readonly root: () => Promise<string>;
14
+ /** The preference that names the active draft. */
15
+ readonly activeKey: string;
16
+ readonly now?: () => number;
17
+ }
18
+
19
+ export interface AddAttachmentOptions {
20
+ readonly displayName?: string;
21
+ /** Our own temporary file: removed after it was copied in. */
22
+ readonly deleteSource?: boolean;
23
+ /** A recorder wrote the file INTO the kind folder: adopt it by name, never copy it. */
24
+ readonly inPlace?: boolean;
25
+ /** A recording: when it started (ISO). */
26
+ readonly startedUtc?: string;
27
+ /** The screen recording this file belongs to (its sound, its timeline). */
28
+ readonly pairedWith?: string;
29
+ }
30
+
31
+ export class TesterDraftStore {
32
+ private readonly o: DraftStoreOptions;
33
+ private readonly now: () => number;
34
+
35
+ constructor(options: DraftStoreOptions) {
36
+ this.o = options;
37
+ this.now = options.now ?? Date.now;
38
+ }
39
+
40
+ root(): Promise<string> {
41
+ return this.o.root();
42
+ }
43
+
44
+ async reportDir(id: string): Promise<string> {
45
+ return `${await this.o.root()}/${id}`;
46
+ }
47
+
48
+ async kindDir(id: string, kind: TesterAttachmentKind): Promise<string> {
49
+ return `${await this.reportDir(id)}/${kindFolder(kind)}`;
50
+ }
51
+
52
+ /** A report is started by its first piece of evidence: its title is the app's, written at send. */
53
+ async create(fields: Partial<Pick<TesterReportDraft, 'title' | 'description' | 'kind' | 'autoTitle' | 'autoDescription' | 'screen' | 'screenContext'>>, username: string | null): Promise<TesterReportDraft> {
54
+ const draft: TesterReportDraft = {
55
+ id: newReportId(),
56
+ title: (fields.title ?? '').trim(),
57
+ description: (fields.description ?? '').trim(),
58
+ createdUtc: new Date(this.now()).toISOString(),
59
+ attachments: [],
60
+ includeDatabaseBackup: false,
61
+ username,
62
+ ...(fields.kind ? { kind: fields.kind } : {}),
63
+ ...(fields.autoTitle ? { autoTitle: fields.autoTitle } : {}),
64
+ ...(fields.autoDescription ? { autoDescription: fields.autoDescription } : {}),
65
+ ...(fields.screen ? { screen: fields.screen } : {}),
66
+ ...(fields.screenContext ? { screenContext: fields.screenContext } : {}),
67
+ };
68
+ await this.save(draft);
69
+ this.o.prefs.set(this.o.activeKey, draft.id);
70
+ return draft;
71
+ }
72
+
73
+ /** The draft the panel should show, or null (a pointer to a vanished folder is cleared). */
74
+ async active(): Promise<TesterReportDraft | null> {
75
+ const id = this.o.prefs.get(this.o.activeKey);
76
+ if (!id) return null;
77
+ const draft = await this.read(id);
78
+ if (!draft) this.o.prefs.set(this.o.activeKey, null);
79
+ return draft;
80
+ }
81
+
82
+ async read(id: string): Promise<TesterReportDraft | null> {
83
+ try {
84
+ const parsed = JSON.parse(await this.o.files.readText(`${await this.reportDir(id)}/report.json`, 4 * 1024 * 1024)) as unknown;
85
+ return isDraft(parsed) ? parsed : null;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+
91
+ async save(draft: TesterReportDraft): Promise<void> {
92
+ await this.o.files.writeText(`${await this.reportDir(draft.id)}/report.json`, JSON.stringify(draft, null, 2));
93
+ }
94
+
95
+ /**
96
+ * Adds a file to the draft. A recorder that wrote straight into the kind folder is only registered; anything else is
97
+ * COPIED in (a picked file belongs to the user) and the source removed only with `deleteSource` (our own temp files).
98
+ */
99
+ async addAttachment(draft: TesterReportDraft, kind: TesterAttachmentKind, source: string, options: AddAttachmentOptions = {}): Promise<TesterReportDraft> {
100
+ const files = this.o.files;
101
+ const dir = await this.kindDir(draft.id, kind);
102
+ const existing = new Set((await files.list(dir)).map((f) => f.name));
103
+ const sourceName = source.split('/').pop() ?? 'file';
104
+ let fileName: string;
105
+ // inPlace: adopt by NAME. Hosts canonicalise the folder they are given (Android /data/user/0 → /data/data, iOS
106
+ // /var → /private/var), so the returned path need not start with `dir`; a prefix test alone copied every recording
107
+ // next to itself ("screen-… (2).mp4", the bytes twice).
108
+ if (existing.has(sourceName) && (options.inPlace === true || source.startsWith(`${dir}/`))) {
109
+ fileName = sourceName;
110
+ } else {
111
+ fileName = uniqueName(safeFileName(options.displayName ?? sourceName), (c) => existing.has(c));
112
+ await files.copy(source, `${dir}/${fileName}`);
113
+ if (options.deleteSource) await files.remove(source).catch(() => {});
114
+ }
115
+ const sizeBytes = await files.size(`${dir}/${fileName}`).catch(() => 0);
116
+ const attachment: TesterReportAttachment = {
117
+ id: newReportId(),
118
+ kind,
119
+ fileName,
120
+ displayName: options.displayName ?? fileName,
121
+ sizeBytes,
122
+ capturedUtc: new Date(this.now()).toISOString(),
123
+ ...(options.startedUtc ? { startedUtc: options.startedUtc } : {}),
124
+ ...(options.pairedWith ? { pairedWith: options.pairedWith } : {}),
125
+ };
126
+ const next: TesterReportDraft = { ...draft, attachments: [...draft.attachments, attachment] };
127
+ await this.save(next);
128
+ return next;
129
+ }
130
+
131
+ async removeAttachment(draft: TesterReportDraft, attachmentId: string): Promise<TesterReportDraft> {
132
+ const a = draft.attachments.find((x) => x.id === attachmentId);
133
+ if (!a) return draft;
134
+ await this.o.files.remove(`${await this.kindDir(draft.id, a.kind)}/${a.fileName}`).catch(() => {});
135
+ const next: TesterReportDraft = { ...draft, attachments: draft.attachments.filter((x) => x.id !== attachmentId) };
136
+ await this.save(next);
137
+ return next;
138
+ }
139
+
140
+ /** Deletes the draft folder (after it was archived, or the tester discarded it). */
141
+ async discard(id: string): Promise<void> {
142
+ await this.o.files.remove(await this.reportDir(id));
143
+ if (this.o.prefs.get(this.o.activeKey) === id) this.o.prefs.set(this.o.activeKey, null);
144
+ }
145
+ }