@mentra/cloud-client 3.2.1 → 3.3.0-beta.954

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.
@@ -6,9 +6,8 @@
6
6
  * helper, which attaches the access token from `cloud.auth` as the Bearer, so
7
7
  * core never touches credentials itself.
8
8
  *
9
- * Today it exposes the miniapp lookups the device needs at launch plus the
10
- * unified report submission surface. It is meant to grow as miniapp-service and
11
- * other core resources are specced.
9
+ * Today it exposes the unified report submission surface, the support
10
+ * profile update and the Fleet report.
12
11
  *
13
12
  * Guardrail: this is device-facing only. It deliberately carries none of the
14
13
  * Dev Console / OEM Portal / store web UI surface; those are separate clients.
@@ -17,11 +16,17 @@
17
16
  * ("src/modules/core/core.ts").
18
17
  */
19
18
  import type { HttpClient } from "../../http";
19
+ import type { FleetReport } from "@mentra/cloud-protocol";
20
+ import { Fleet, type FleetReportOutcome } from "./fleet";
20
21
  import {
21
22
  Reports,
22
23
  type AddReportArtifactsResult,
24
+ type AddReportLogsOptions,
23
25
  type ReportAttachmentInput,
24
26
  type ReportLogEntry,
27
+ type ReportLogCollectionUpdate,
28
+ type ReportLogCollectionSnapshot,
29
+ type ReportLogSource,
25
30
  type ReportStatus,
26
31
  type SubmitReportInput,
27
32
  type SubmitReportResult,
@@ -34,186 +39,101 @@ import {
34
39
 
35
40
  export type {
36
41
  AddReportArtifactsResult,
42
+ AddReportLogsOptions,
37
43
  ReportAttachmentInput,
38
44
  ReportContext,
39
45
  ReportDetails,
40
46
  ReportKind,
41
47
  ReportLogEntry,
48
+ ReportLogCollectionUpdate,
49
+ ReportLogCollection,
50
+ ReportLogCollectionSnapshot,
51
+ ReportLogSource,
42
52
  ReportStatus,
43
53
  ReportSystemPriority,
44
54
  ReportTrigger,
45
55
  SubmitReportInput,
46
56
  SubmitReportResult,
47
57
  } from "./reports";
58
+ export type { FleetAck, FleetAckResult, FleetReportOutcome } from "./fleet";
48
59
  export type {
49
60
  SupportConnectionState,
50
61
  SupportProfileUpdateResult,
51
62
  SupportStateInput,
52
63
  } from "./support-profile";
53
64
 
54
- /**
55
- * A single miniapp entry as returned by the listing.
56
- *
57
- * These shapes are owned by miniapp-service, which is not finalized yet, so they
58
- * are defined here against the spec rather than imported. They are intentionally
59
- * NOT taken from `@mentra/cloud-protocol`: that package is the live
60
- * session wire contract (subscriptions, transcripts, the message unions), while
61
- * a miniapp listing is a core REST resource with no place on the runtime wire.
62
- * When miniapp-service locks its schema, move these to the shared package and
63
- * import them here instead.
64
- */
65
- export interface MiniappListing {
66
- /** The reverse-DNS identifier, for example "com.example.notes". */
67
- packageName: string;
68
- /** Human-readable name shown to the user. */
69
- name: string;
70
- /** The version offered to this user (the latest the user is entitled to). */
71
- version: string;
72
- /** Optional one-line summary for a launcher list. */
73
- description?: string;
74
- /** Optional icon URL for a launcher list. */
75
- iconUrl?: string;
76
- }
77
-
78
- /**
79
- * The manifest that ships inside a miniapp bundle.
80
- *
81
- * Same ownership note as `MiniappListing`: this is a miniapp-service shape,
82
- * defined here against the spec until that schema is locked. The fields below
83
- * are the minimum the device needs to identify and describe a fetched bundle;
84
- * miniapp-service is expected to add permission and capability declarations.
85
- */
86
- export interface MiniappManifest {
87
- packageName: string;
88
- name: string;
89
- version: string;
90
- /** Optional permissions the miniapp declares it needs. */
91
- permissions?: string[];
92
- }
93
-
94
- /** What `getBundle` resolves to: where to download the bundle, plus its manifest. */
95
- export interface MiniappBundle {
96
- /** A (typically signed, short-lived) URL the device downloads the bundle from. */
97
- downloadUrl: string;
98
- /** The concrete version resolved, important when the caller omitted `version`. */
99
- version: string;
100
- manifest: MiniappManifest;
101
- }
102
-
103
- export type PreinstalledInstallPolicy =
104
- | "install_once"
105
- | "keep_updated"
106
- | "mandatory";
107
-
108
- export interface PreinstalledMiniappRegistryEntry {
109
- packageName: string;
110
- version: string;
111
- bundleUrl: string;
112
- bundleSha256: string;
113
- required: boolean;
114
- installPolicy: PreinstalledInstallPolicy;
115
- channel: string;
116
- minMobileVersion?: string;
117
- maxMobileVersion?: string;
118
- tenantId?: string;
119
- }
120
-
121
- export interface PreinstalledMiniappRegistry {
122
- generatedAt: string;
123
- entries: PreinstalledMiniappRegistryEntry[];
124
- }
125
-
126
65
  /** The dependencies `cloud.core` is wired with. */
127
66
  export interface CoreDeps {
128
67
  http: HttpClient;
129
68
  }
130
69
 
131
70
  /**
132
- * `cloud.core`. Stateless REST grouped by resource (only `miniapps` so far).
71
+ * `cloud.core`. Stateless REST grouped by resource.
133
72
  *
134
- * The grouping is exposed as a plain object so callers write
135
- * `cloud.core.miniapps.list()`, matching the public `CoreModule` contract in the
136
- * spec. Methods are bound in the constructor so destructuring `miniapps` keeps
137
- * working.
73
+ * Each group is exposed as a plain object so callers write
74
+ * `cloud.core.reports.submit()`. Methods are bound in the constructor so
75
+ * destructuring a group keeps working.
138
76
  */
139
77
  export class Core {
140
- readonly miniapps: {
141
- list(): Promise<MiniappListing[]>;
142
- getBundle(packageName: string, version?: string): Promise<MiniappBundle>;
143
- getRegistry(opts?: { environment?: string }): Promise<PreinstalledMiniappRegistry>;
144
- };
145
78
  readonly reports: {
146
- submit(input: SubmitReportInput): Promise<SubmitReportResult>;
79
+ getLogCollection(reportId: string, signal?: AbortSignal): Promise<ReportLogCollectionSnapshot>;
80
+ submit(input: SubmitReportInput, signal?: AbortSignal): Promise<SubmitReportResult>;
81
+ updateLogCollection(
82
+ reportId: string,
83
+ source: ReportLogSource,
84
+ update: ReportLogCollectionUpdate,
85
+ signal?: AbortSignal,
86
+ ): Promise<void>;
147
87
  addLogs(
148
88
  reportId: string,
149
89
  source: string,
150
90
  entries: ReportLogEntry[],
91
+ options?: AddReportLogsOptions,
151
92
  ): Promise<AddReportArtifactsResult>;
152
93
  addScreenshots(
153
94
  reportId: string,
154
95
  images: ReportAttachmentInput[],
96
+ signal?: AbortSignal,
155
97
  ): Promise<AddReportArtifactsResult>;
156
- complete(reportId: string): Promise<{ status: ReportStatus }>;
98
+ addVideos(
99
+ reportId: string,
100
+ source: string,
101
+ videos: ReportAttachmentInput[],
102
+ ): Promise<AddReportArtifactsResult>;
103
+ complete(reportId: string, signal?: AbortSignal): Promise<{ status: ReportStatus }>;
157
104
  };
158
105
  readonly supportProfile: {
159
106
  update(input: SupportStateInput): Promise<SupportProfileUpdateResult>;
160
107
  };
108
+ readonly fleet: {
109
+ /**
110
+ * Rejects only for an authentication failure (`AuthExpiredError`, or an `HttpError` with status 401) or an abort.
111
+ * Every other result, including any network or unexpected failure, is a `FleetReportOutcome`. `opts.bearer` sends
112
+ * that Core token instead of the token source's.
113
+ */
114
+ report(batch: FleetReport, opts?: { signal?: AbortSignal; bearer?: string }): Promise<FleetReportOutcome>;
115
+ };
161
116
 
162
117
  constructor(deps: CoreDeps) {
163
118
  const { http } = deps;
164
119
  const reports = new Reports({ http });
165
120
  const supportProfiles = new SupportProfiles(http);
121
+ const fleet = new Fleet(http);
166
122
 
167
- this.miniapps = {
168
- /**
169
- * List the miniapps available to the authenticated user.
170
- *
171
- * A GET so it is naturally safe to retry on a transient network error,
172
- * which the shared HTTP helper does for us.
173
- */
174
- list(): Promise<MiniappListing[]> {
175
- return http.get<MiniappListing[]>("/api/client/miniapps");
176
- },
177
-
178
- /**
179
- * Fetch the downloadable bundle for one miniapp.
180
- *
181
- * When `version` is omitted the cloud resolves the version the user is
182
- * entitled to (usually the latest); the resolved value comes back in the
183
- * response so the caller can record exactly what it got. The version is
184
- * passed as a query parameter and URL-encoded so an unusual version string
185
- * cannot break the path.
186
- */
187
- getBundle(packageName: string, version?: string): Promise<MiniappBundle> {
188
- const base = `/api/client/miniapps/${encodeURIComponent(packageName)}/bundle`;
189
- const path =
190
- version === undefined
191
- ? base
192
- : `${base}?version=${encodeURIComponent(version)}`;
193
- return http.get<MiniappBundle>(path);
194
- },
195
-
196
- /**
197
- * Fetch the admin-managed preinstalled miniapp registry for this device.
198
- *
199
- * The mobile client owns reconciliation: Core only returns the desired
200
- * bundle versions and install policy for the current user/OEM/channel.
201
- */
202
- getRegistry(opts?: { environment?: string }): Promise<PreinstalledMiniappRegistry> {
203
- const query = opts?.environment
204
- ? `?environment=${encodeURIComponent(opts.environment)}`
205
- : "";
206
- return http.get<PreinstalledMiniappRegistry>(`/api/client/miniapps/registry${query}`);
207
- },
208
- };
209
123
  this.reports = {
210
124
  submit: reports.submit.bind(reports),
125
+ getLogCollection: reports.getLogCollection.bind(reports),
126
+ updateLogCollection: reports.updateLogCollection.bind(reports),
211
127
  addLogs: reports.addLogs.bind(reports),
212
128
  addScreenshots: reports.addScreenshots.bind(reports),
129
+ addVideos: reports.addVideos.bind(reports),
213
130
  complete: reports.complete.bind(reports),
214
131
  };
215
132
  this.supportProfile = {
216
133
  update: supportProfiles.update.bind(supportProfiles),
217
134
  };
135
+ this.fleet = {
136
+ report: fleet.report.bind(fleet),
137
+ };
218
138
  }
219
139
  }
@@ -0,0 +1,175 @@
1
+ import {FLEET_NOT_INSTALLED, FLEET_SCHEMA_VERSION, type FleetReport} from "@mentra/cloud-protocol"
2
+ import {AuthExpiredError, HttpError} from "../../errors"
3
+ import type {HttpClient} from "../../http"
4
+
5
+ const FLEET_REPORT_PATH = "/api/client/fleet/report"
6
+
7
+ /** Core's whole-response error codes are short snake_case words; anything else is not safe to surface. */
8
+ const ERROR_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/
9
+
10
+ const RESULT_STATUSES = ["accepted", "duplicate", "retryable", "rejected"] as const
11
+
12
+ /**
13
+ * Fleet's answer for one record of the batch, as this client reads it. `index` is the record's position in the batch
14
+ * and `recordId`, when present, names it. A status this client does not know reads as `retryable`, so the record is
15
+ * kept and sent again. `reasonCode` is given only for a rejection, and only when it is a short snake_case code; one
16
+ * this client does not know is kept as given.
17
+ */
18
+ export interface FleetAckResult {
19
+ index: number
20
+ recordId?: string
21
+ status: (typeof RESULT_STATUSES)[number]
22
+ reasonCode?: string
23
+ retryAfterSeconds?: number
24
+ }
25
+
26
+ /** A per-record acknowledgement: one result per record Fleet answered for. */
27
+ export interface FleetAck {
28
+ schemaVersion: typeof FLEET_SCHEMA_VERSION
29
+ results: FleetAckResult[]
30
+ }
31
+
32
+ /**
33
+ * What one `POST /api/client/fleet/report` came to. Every answer Core or Fleet can give is an outcome, so a caller
34
+ * branches on `kind` and never on an exception or a status code.
35
+ */
36
+ export type FleetReportOutcome =
37
+ /** Core answered 200 with a per-record acknowledgement. */
38
+ | {kind: "results"; ack: FleetAck}
39
+ /** Core answered 404 `fleet_not_installed`: Fleet is not installed on this Core. */
40
+ | {kind: "not_installed"}
41
+ /**
42
+ * Something answered 404 without Fleet's own code: a Core from before Fleet, which has no such route, or a proxy in
43
+ * front of it. Not proof that Fleet is not installed, so a caller stops asking for now but keeps what it holds.
44
+ */
45
+ | {kind: "no_fleet_route"}
46
+ /**
47
+ * Fleet or the network is not answering usefully right now: 503, 429, any other server or unexpected failure, a
48
+ * network error or timeout, or a 200 whose body is not an acknowledgement. `retryAfterSeconds` is the server's
49
+ * `Retry-After` in whole seconds, or null when it gave none.
50
+ */
51
+ | {kind: "unavailable"; retryAfterSeconds: number | null}
52
+ /** Core answered 413. */
53
+ | {kind: "batch_too_large"}
54
+ /** Core answered 400. `code` is Core's error code (`invalid_batch`, `invalid_body`, ...), or `unknown`. */
55
+ | {kind: "batch_invalid"; code: string}
56
+ /** Core answered 403. */
57
+ | {kind: "forbidden"}
58
+
59
+ const unavailable = (retryAfterSeconds: number | null = null): FleetReportOutcome => ({
60
+ kind: "unavailable",
61
+ retryAfterSeconds,
62
+ })
63
+
64
+ /** The caller (or the transport) cancelled the request. */
65
+ function isAbortError(error: unknown): boolean {
66
+ return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError"
67
+ }
68
+
69
+ /** The credentials were refused or are gone: the caller must refresh or sign in again, so this is never an outcome. */
70
+ function isAuthFailure(error: unknown): boolean {
71
+ return error instanceof AuthExpiredError || (error instanceof HttpError && error.status === 401)
72
+ }
73
+
74
+ function outcomeForHttpError(error: HttpError): FleetReportOutcome {
75
+ switch (error.status) {
76
+ // A transport failure (DNS, reset, timeout) after the client's own retries. There was no answer.
77
+ case 0:
78
+ return unavailable()
79
+ case 404:
80
+ // Only Fleet's own answer means "not installed". Any other 404 (an older Core without the route, a proxy) must
81
+ // not read as it, because not_installed makes the caller drop its queue.
82
+ return error.code === FLEET_NOT_INSTALLED ? {kind: "not_installed"} : {kind: "no_fleet_route"}
83
+ case 413:
84
+ return {kind: "batch_too_large"}
85
+ case 400:
86
+ return {
87
+ kind: "batch_invalid",
88
+ code: typeof error.code === "string" && ERROR_CODE_PATTERN.test(error.code) ? error.code : "unknown",
89
+ }
90
+ case 403:
91
+ return {kind: "forbidden"}
92
+ // 503, 429, 408, 5xx, and anything else Core was not documented to say: keep the records and try later.
93
+ default:
94
+ return unavailable(error.retryAfterSeconds)
95
+ }
96
+ }
97
+
98
+ export class Fleet {
99
+ constructor(private readonly http: HttpClient) {}
100
+
101
+ /**
102
+ * Reports one batch of Fleet records to the phone's own Core.
103
+ *
104
+ * Rejects in exactly two cases: an authentication failure (`AuthExpiredError`, or an `HttpError` with status 401),
105
+ * or an abort (an `AbortError`, or any error raised once `opts.signal` is aborted). Every other result is a
106
+ * {@link FleetReportOutcome}, including network failures, timeouts, a connection that drops while the response
107
+ * body is being read, a body that is not a valid acknowledgement, and unexpected errors, which are
108
+ * `{kind: "unavailable", retryAfterSeconds: null}`.
109
+ *
110
+ * The request is sent idempotently, so the HTTP client retries a transient network failure before the body is
111
+ * read; that is safe because Fleet records are idempotent by ID.
112
+ *
113
+ * `opts.bearer` sends exactly that Core token instead of asking the token source, for a caller that has already
114
+ * checked whose token it is.
115
+ */
116
+ async report(batch: FleetReport, opts?: {signal?: AbortSignal; bearer?: string}): Promise<FleetReportOutcome> {
117
+ const signal = opts?.signal
118
+ const bearer = opts?.bearer
119
+ let body: unknown
120
+ try {
121
+ body = await this.http.post<unknown>(FLEET_REPORT_PATH, batch, {
122
+ idempotent: true,
123
+ ...(signal ? {signal} : {}),
124
+ ...(bearer ? {bearer} : {}),
125
+ })
126
+ } catch (error) {
127
+ // The caller stopped the request: that is its answer, whatever the transport happened to report.
128
+ if (signal?.aborted || isAbortError(error) || isAuthFailure(error)) throw error
129
+ if (error instanceof HttpError) return outcomeForHttpError(error)
130
+ // Anything else (a body that is not JSON, a socket that closed mid-body, a failing token source) is no answer.
131
+ return unavailable()
132
+ }
133
+
134
+ const ack = readAck(body)
135
+ return ack ? {kind: "results", ack} : unavailable()
136
+ }
137
+ }
138
+
139
+ function isObject(value: unknown): value is Record<string, unknown> {
140
+ return typeof value === "object" && value !== null && !Array.isArray(value)
141
+ }
142
+
143
+ function isWholeNumber(value: unknown): value is number {
144
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
145
+ }
146
+
147
+ /**
148
+ * Reads an acknowledgement the way a client already in the field must: it ignores keys it does not know, reads a
149
+ * status it does not know as `retryable`, and keeps a rejection whose reason it does not know. A newer Fleet can
150
+ * therefore add to the answer without this client reading all of it as no answer and resending the same batch
151
+ * forever. What it cannot do without is the shape that ties a result to a record: a `results` array of objects,
152
+ * each with a whole-number `index`, a text `status`, and a `recordId` that is text when present. Anything else is
153
+ * null, which the caller treats as no answer.
154
+ *
155
+ * Producers are still held to the strict `FleetReportAckSchema` in `@mentra/cloud-protocol`.
156
+ */
157
+ function readAck(body: unknown): FleetAck | null {
158
+ if (!isObject(body) || body.schemaVersion !== FLEET_SCHEMA_VERSION || !Array.isArray(body.results)) return null
159
+ const results: FleetAckResult[] = []
160
+ for (const raw of body.results) {
161
+ if (!isObject(raw) || !isWholeNumber(raw.index) || typeof raw.status !== "string") return null
162
+ if (raw.recordId !== undefined && typeof raw.recordId !== "string") return null
163
+ const status = (RESULT_STATUSES as readonly string[]).includes(raw.status)
164
+ ? (raw.status as FleetAckResult["status"])
165
+ : "retryable"
166
+ const result: FleetAckResult = {index: raw.index, status}
167
+ if (raw.recordId !== undefined) result.recordId = raw.recordId
168
+ if (status === "rejected" && typeof raw.reasonCode === "string" && ERROR_CODE_PATTERN.test(raw.reasonCode)) {
169
+ result.reasonCode = raw.reasonCode
170
+ }
171
+ if (isWholeNumber(raw.retryAfterSeconds)) result.retryAfterSeconds = raw.retryAfterSeconds
172
+ results.push(result)
173
+ }
174
+ return {schemaVersion: FLEET_SCHEMA_VERSION, results}
175
+ }
@@ -7,11 +7,31 @@
7
7
  */
8
8
 
9
9
  import type { HttpClient } from "../../http";
10
+ import type {ReportAutomationCorrelation} from '@mentra/cloud-protocol/report-automation';
10
11
 
11
12
  const REPORTS_PATH = "/api/client/reports";
12
13
 
13
14
  export type ReportKind = "bug" | "feedback" | "automatic";
14
15
  export type ReportStatus = "collecting" | "ready" | "closed";
16
+ export type ReportLogSource = "phone" | "glasses" | "glasses_firmware" | "cloud" | "miniapp_server";
17
+ /** Core storage receipts, independent of the report's UI readiness status. */
18
+ export interface ReportLogCollection {
19
+ state: "requested" | "received" | "unavailable" | "failed" | "timed-out";
20
+ requestedAt: string;
21
+ deadlineAt: string;
22
+ reason?: string;
23
+ receivedAt?: string;
24
+ artifactId?: string;
25
+ entryCount?: number;
26
+ }
27
+ export interface ReportLogCollectionSnapshot {
28
+ reportId: string;
29
+ logCollection: Partial<Record<ReportLogSource, ReportLogCollection>>;
30
+ }
31
+ export interface ReportLogCollectionUpdate {
32
+ state: "requested" | "unavailable" | "failed";
33
+ reason?: string;
34
+ }
15
35
  export type ReportSystemPriority = "low" | "medium" | "high" | "critical";
16
36
 
17
37
  interface BaseReportTrigger {
@@ -42,28 +62,43 @@ export interface ReportContext extends Record<string, unknown> {
42
62
  settings?: Record<string, unknown>;
43
63
  }
44
64
 
45
- export type SubmitReportInput =
46
- | {
65
+ interface IncidentKeyInput {
66
+ /**
67
+ * Identity of one bug or automatic event (`^[A-Za-z0-9._:-]{1,128}$`).
68
+ * Resubmitting the same key returns the caller's existing report. A Cloud
69
+ * that predates the field ignores it and creates a new report.
70
+ */
71
+ incidentKey?: string;
72
+ }
73
+
74
+ export type SubmitReportInput = (
75
+ | ({
47
76
  kind: "bug";
48
77
  trigger: ReportTrigger;
49
78
  report: ReportDetails;
50
79
  context: ReportContext;
51
- }
52
- | {
80
+ } & IncidentKeyInput)
81
+ | ({
53
82
  kind: "automatic";
83
+ automationCorrelation?: ReportAutomationCorrelation;
54
84
  trigger: Extract<ReportTrigger, { type: "automatic" }>;
55
85
  report: ReportDetails;
56
86
  context: ReportContext;
57
- }
87
+ } & IncidentKeyInput)
58
88
  | {
59
89
  kind: "feedback";
90
+ /** Feedback notifies at creation and cannot be safely deduplicated by key. */
91
+ incidentKey?: never;
60
92
  feedback: string | Record<string, unknown>;
61
93
  context: ReportContext;
62
- };
94
+ }
95
+ );
63
96
 
64
97
  export interface SubmitReportResult {
65
98
  reportId: string;
66
99
  status: ReportStatus;
100
+ /** True only when Cloud returned an existing report for `incidentKey`. */
101
+ deduplicated?: true;
67
102
  }
68
103
 
69
104
  export interface ReportLogEntry {
@@ -82,6 +117,18 @@ export interface ReportAttachmentInput {
82
117
 
83
118
  export interface AddReportArtifactsResult {
84
119
  stored: number;
120
+ /** Returned for a log upload sent with a `retryKey`. */
121
+ receipt?: { artifactId: string; sha256: string; sizeBytes: number };
122
+ }
123
+
124
+ export interface AddReportLogsOptions {
125
+ /**
126
+ * Artifact identity (`^[A-Za-z0-9._:-]{1,128}$`). Repeating it with identical
127
+ * entries is idempotent; different entries under the same key fail with
128
+ * HTTP 409. A Cloud that predates the field ignores it and stores a new artifact.
129
+ */
130
+ retryKey?: string;
131
+ signal?: AbortSignal;
85
132
  }
86
133
 
87
134
  export interface ReportsDeps {
@@ -95,14 +142,60 @@ export class Reports {
95
142
  this.http = deps.http;
96
143
  }
97
144
 
98
- submit(input: SubmitReportInput): Promise<SubmitReportResult> {
99
- return this.http.post<SubmitReportResult>(REPORTS_PATH, input);
145
+ submit(input: SubmitReportInput, signal?: AbortSignal): Promise<SubmitReportResult> {
146
+ return this.http.post<SubmitReportResult>(REPORTS_PATH, input, {signal});
147
+ }
148
+
149
+ /** Read the current source receipts with the same user session used to submit. */
150
+ async getLogCollection(reportId: string, signal?: AbortSignal): Promise<ReportLogCollectionSnapshot> {
151
+ const snapshot = await this.http.get<ReportLogCollectionSnapshot>(
152
+ `${REPORTS_PATH}/${encodeURIComponent(reportId)}/log-collection`,
153
+ {signal},
154
+ );
155
+ if (!snapshot || snapshot.reportId !== reportId || !snapshot.logCollection ||
156
+ typeof snapshot.logCollection !== "object" || Array.isArray(snapshot.logCollection)) {
157
+ throw new Error("Invalid report collection response");
158
+ }
159
+ const logCollection: ReportLogCollectionSnapshot["logCollection"] = {};
160
+ for (const source of ["phone", "glasses", "glasses_firmware", "cloud", "miniapp_server"] as const) {
161
+ const receipt = snapshot.logCollection[source];
162
+ if (receipt === undefined) continue;
163
+ if (!receipt || !["requested", "received", "unavailable", "failed", "timed-out"].includes(receipt.state) ||
164
+ typeof receipt.requestedAt !== "string" || typeof receipt.deadlineAt !== "string") {
165
+ throw new Error("Invalid report collection receipt");
166
+ }
167
+ logCollection[source] = {
168
+ state: receipt.state,
169
+ requestedAt: receipt.requestedAt,
170
+ deadlineAt: receipt.deadlineAt,
171
+ ...(typeof receipt.reason === "string" ? {reason: receipt.reason.slice(0, 500)} : {}),
172
+ ...(typeof receipt.receivedAt === "string" ? {receivedAt: receipt.receivedAt} : {}),
173
+ ...(typeof receipt.artifactId === "string" ? {artifactId: receipt.artifactId} : {}),
174
+ ...(typeof receipt.entryCount === "number" ? {entryCount: receipt.entryCount} : {}),
175
+ };
176
+ }
177
+ return {reportId: snapshot.reportId, logCollection};
178
+ }
179
+
180
+ /** Record a local collection attempt; only Core artifact storage confirms receipt. */
181
+ updateLogCollection(
182
+ reportId: string,
183
+ source: ReportLogSource,
184
+ update: ReportLogCollectionUpdate,
185
+ signal?: AbortSignal,
186
+ ): Promise<void> {
187
+ return this.http.post<void>(
188
+ `${REPORTS_PATH}/${encodeURIComponent(reportId)}/log-collection/${source}`,
189
+ update,
190
+ {signal},
191
+ );
100
192
  }
101
193
 
102
194
  async addLogs(
103
195
  reportId: string,
104
196
  source: string,
105
197
  entries: ReportLogEntry[],
198
+ options: AddReportLogsOptions = {},
106
199
  ): Promise<AddReportArtifactsResult> {
107
200
  return await this.http.post<AddReportArtifactsResult>(
108
201
  `${REPORTS_PATH}/${encodeURIComponent(reportId)}/artifacts`,
@@ -110,13 +203,16 @@ export class Reports {
110
203
  type: "logs",
111
204
  source,
112
205
  entries,
206
+ ...(options.retryKey !== undefined ? { retryKey: options.retryKey } : {}),
113
207
  },
208
+ {signal: options.signal},
114
209
  );
115
210
  }
116
211
 
117
212
  addScreenshots(
118
213
  reportId: string,
119
214
  images: ReportAttachmentInput[],
215
+ signal?: AbortSignal,
120
216
  ): Promise<AddReportArtifactsResult> {
121
217
  const form = new FormData();
122
218
  form.append("type", "screenshot");
@@ -138,16 +234,56 @@ export class Reports {
138
234
  } as unknown as Blob);
139
235
  }
140
236
 
237
+ return this.http.postForm<AddReportArtifactsResult>(
238
+ `${REPORTS_PATH}/${encodeURIComponent(reportId)}/artifacts`,
239
+ form,
240
+ {signal},
241
+ );
242
+ }
243
+
244
+ /**
245
+ * Attach MP4 recordings to an existing report through the same artifact
246
+ * route. `source` is the capture source the caller declares (for example
247
+ * `phone` or `host`); the server stores it as given.
248
+ */
249
+ addVideos(
250
+ reportId: string,
251
+ source: string,
252
+ videos: ReportAttachmentInput[],
253
+ ): Promise<AddReportArtifactsResult> {
254
+ const form = new FormData();
255
+ form.append("type", "video");
256
+ form.append("source", source);
257
+ for (const video of videos) {
258
+ const filename = video.fileName || `video-${Date.now()}.mp4`;
259
+ const mimeType = video.mimeType || "video/mp4";
260
+ if (video.blob) {
261
+ // The part's declared type comes from the Blob, so make it the MP4 type.
262
+ const blob = video.blob.type === mimeType ? video.blob : new Blob([video.blob], { type: mimeType });
263
+ form.append("files", blob, filename);
264
+ continue;
265
+ }
266
+ if (!video.uri) {
267
+ throw new Error("report video requires either blob or uri");
268
+ }
269
+ form.append("files", {
270
+ uri: video.uri,
271
+ name: filename,
272
+ type: mimeType,
273
+ } as unknown as Blob);
274
+ }
275
+
141
276
  return this.http.postForm<AddReportArtifactsResult>(
142
277
  `${REPORTS_PATH}/${encodeURIComponent(reportId)}/artifacts`,
143
278
  form,
144
279
  );
145
280
  }
146
281
 
147
- complete(reportId: string): Promise<{ status: ReportStatus }> {
282
+ complete(reportId: string, signal?: AbortSignal): Promise<{ status: ReportStatus }> {
148
283
  return this.http.post<{ status: ReportStatus }>(
149
284
  `${REPORTS_PATH}/${encodeURIComponent(reportId)}/complete`,
150
285
  {},
286
+ {signal},
151
287
  );
152
288
  }
153
289
  }