@mycadet/assistant 0.12.11 → 0.13.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.
Files changed (176) hide show
  1. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/__tests__/ingress.test.ts +2 -2
  2. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/ingress.ts +2 -2
  3. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/__tests__/ingress.test.ts +2 -2
  4. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/ingress.ts +2 -2
  5. package/node_modules/@mycadet/gateway-client/src/gateway-ipc-contracts.ts +0 -20
  6. package/node_modules/@mycadet/service-contracts/src/__tests__/ingress.test.ts +2 -2
  7. package/node_modules/@mycadet/service-contracts/src/ingress.ts +2 -2
  8. package/openapi.yaml +2 -708
  9. package/package.json +2 -3
  10. package/scripts/sync-web-search-catalog.ts +1 -2
  11. package/src/__tests__/cloud-profile-guard.test.ts +2 -2
  12. package/src/__tests__/config-schema.test.ts +6 -38
  13. package/src/__tests__/conversation-queue.test.ts +45 -6
  14. package/src/__tests__/db-readiness-http-gate.test.ts +0 -6
  15. package/src/__tests__/persist-onboarding-artifacts.test.ts +0 -1
  16. package/src/__tests__/persona-resolver.test.ts +0 -51
  17. package/src/__tests__/provider-cloud-proxy-integration.test.ts +2 -110
  18. package/src/__tests__/run-due-schedules.test.ts +0 -4
  19. package/src/__tests__/schedule-store.test.ts +0 -12
  20. package/src/__tests__/stt-stream-session.test.ts +4 -4
  21. package/src/__tests__/telephony-tts-guard.test.ts +2 -50
  22. package/src/__tests__/voice-config-update.test.ts +12 -167
  23. package/src/__tests__/web-search-catalog-parity.test.ts +0 -2
  24. package/src/__tests__/workspace-migration-130-speech-mode-to-provider.test.ts +9 -7
  25. package/src/__tests__/workspace-migration-132-web-search-mode-to-provider.test.ts +6 -6
  26. package/src/calls/__tests__/voice-session-bridge.test.ts +1 -4
  27. package/src/calls/resolve-call-tts-provider.ts +6 -25
  28. package/src/calls/telephony-credential-preflight.ts +0 -10
  29. package/src/calls/telephony-tts-capability.ts +1 -17
  30. package/src/cli/commands/tts.ts +1 -2
  31. package/src/cli/index.help.ts +0 -2
  32. package/src/cli/program.ts +0 -2
  33. package/src/config/bundled-skills/settings/tools/voice-config-update.ts +4 -42
  34. package/src/config/schemas/__tests__/stt.test.ts +10 -14
  35. package/src/config/schemas/services.ts +5 -6
  36. package/src/config/schemas/stt.ts +1 -3
  37. package/src/config/schemas/tts.ts +1 -30
  38. package/src/daemon/daemon-readiness.ts +4 -29
  39. package/src/daemon/lifecycle.ts +0 -31
  40. package/src/daemon/providers-setup.ts +0 -8
  41. package/src/heartbeat/__tests__/heartbeat-service.test.ts +0 -1
  42. package/src/heartbeat/heartbeat-service.ts +1 -66
  43. package/src/ipc/__tests__/db-readiness-ipc-gate.test.ts +1 -9
  44. package/src/live-voice/__tests__/live-voice-credential-preflight.test.ts +0 -44
  45. package/src/live-voice/__tests__/live-voice-flux-turn-end.test.ts +4 -6
  46. package/src/live-voice/__tests__/live-voice-stt.test.ts +1 -1
  47. package/src/live-voice/live-voice-credential-preflight.ts +9 -33
  48. package/src/live-voice/live-voice-session.ts +10 -6
  49. package/src/live-voice/live-voice-tts.ts +1 -8
  50. package/src/plugins/defaults/memory/worker.ts +3 -3
  51. package/src/prompts/persona-resolver.ts +0 -35
  52. package/src/providers/__tests__/search-provider-catalog.test.ts +5 -8
  53. package/src/providers/__tests__/voice-error-copy.test.ts +9 -10
  54. package/src/providers/search-provider-catalog.ts +7 -39
  55. package/src/providers/speech-to-text/__tests__/provider-catalog.test.ts +3 -47
  56. package/src/providers/speech-to-text/__tests__/resolve.test.ts +6 -372
  57. package/src/providers/speech-to-text/provider-catalog.ts +2 -73
  58. package/src/providers/speech-to-text/resolve.ts +3 -120
  59. package/src/runtime/http-router-types.ts +1 -3
  60. package/src/runtime/http-server.ts +1 -1
  61. package/src/runtime/routes/__tests__/tts-routes.test.ts +2 -6
  62. package/src/runtime/routes/inbound-stages/transcribe-audio.test.ts +7 -7
  63. package/src/runtime/routes/index.ts +0 -4
  64. package/src/runtime/routes/live-voice-routes.test.ts +4 -11
  65. package/src/runtime/routes/live-voice-routes.ts +8 -11
  66. package/src/runtime/routes/secret-routes.ts +0 -6
  67. package/src/runtime/routes/tts-routes.ts +0 -38
  68. package/src/schedule/__tests__/plugin-schedule-reconciler.test.ts +1 -7
  69. package/src/schedule/__tests__/worker-mcp-readiness.test.ts +0 -4
  70. package/src/schedule/schedule-store.ts +0 -7
  71. package/src/schedule/scheduler.ts +0 -5
  72. package/src/schedule/worker.ts +1 -1
  73. package/src/stt/__tests__/daemon-batch-transcriber.test.ts +2 -10
  74. package/src/stt/daemon-batch-transcriber.ts +4 -38
  75. package/src/stt/types.ts +1 -9
  76. package/src/tools/network/__tests__/web-search.test.ts +3 -250
  77. package/src/tools/network/web-search.ts +4 -165
  78. package/src/tts/__tests__/provider-resolution.test.ts +0 -5
  79. package/src/tts/provider-catalog.ts +0 -4
  80. package/src/tts/types.ts +0 -1
  81. package/src/__tests__/cloud-speech-defaults.test.ts +0 -330
  82. package/src/__tests__/migration-cross-version-compatibility.test.ts +0 -1708
  83. package/src/__tests__/migration-export-http.test.ts +0 -557
  84. package/src/__tests__/migration-export-streaming.test.ts +0 -350
  85. package/src/__tests__/migration-export-to-gcs.test.ts +0 -706
  86. package/src/__tests__/migration-import-commit-http.test.ts +0 -1176
  87. package/src/__tests__/migration-import-from-gcs.test.ts +0 -534
  88. package/src/__tests__/migration-import-from-path.test.ts +0 -324
  89. package/src/__tests__/migration-import-from-url.test.ts +0 -588
  90. package/src/__tests__/migration-import-preflight-http.test.ts +0 -739
  91. package/src/__tests__/migration-jobs-status.test.ts +0 -139
  92. package/src/__tests__/migration-parity-persistence.test.ts +0 -1891
  93. package/src/__tests__/migration-transport.test.ts +0 -1089
  94. package/src/__tests__/migration-validate-http.test.ts +0 -634
  95. package/src/__tests__/migration-wizard.test.ts +0 -1395
  96. package/src/__tests__/rebind-secrets-screen.test.ts +0 -876
  97. package/src/__tests__/sanitize-config-for-transfer.test.ts +0 -259
  98. package/src/__tests__/transfer-progress-screen.test.ts +0 -1217
  99. package/src/__tests__/validation-results-screen.test.ts +0 -1130
  100. package/src/__tests__/vbundle-pax-and-symlink.test.ts +0 -147
  101. package/src/background-wake/background-wake-routes.test.ts +0 -906
  102. package/src/background-wake/cloud-client.test.ts +0 -328
  103. package/src/background-wake/cloud-client.ts +0 -196
  104. package/src/background-wake/next-wake.test.ts +0 -335
  105. package/src/background-wake/next-wake.ts +0 -188
  106. package/src/background-wake/publisher.ts +0 -93
  107. package/src/background-wake/wake-intent-hooks.test.ts +0 -234
  108. package/src/cli/commands/__tests__/backup.test.ts +0 -363
  109. package/src/cli/commands/backup.help.ts +0 -180
  110. package/src/cli/commands/backup.ts +0 -398
  111. package/src/cloud/cloud-speech.test.ts +0 -335
  112. package/src/cloud/cloud-speech.ts +0 -300
  113. package/src/config/cloud-speech-defaults.ts +0 -300
  114. package/src/config/sanitize-for-transfer.ts +0 -111
  115. package/src/live-voice/__tests__/live-voice-cloud-speech-fallback.test.ts +0 -250
  116. package/src/providers/speech-to-text/__tests__/cadet-cloud-realtime.test.ts +0 -457
  117. package/src/providers/speech-to-text/__tests__/cadet-cloud.test.ts +0 -271
  118. package/src/providers/speech-to-text/__tests__/cadet-speech-relay-connection.test.ts +0 -126
  119. package/src/providers/speech-to-text/cadet-cloud-flux-realtime.ts +0 -309
  120. package/src/providers/speech-to-text/cadet-cloud-realtime.ts +0 -315
  121. package/src/providers/speech-to-text/cadet-cloud.ts +0 -108
  122. package/src/providers/speech-to-text/cadet-speech-relay-connection.ts +0 -176
  123. package/src/runtime/migrations/__tests__/gcs-signed-url.test.ts +0 -254
  124. package/src/runtime/migrations/__tests__/job-registry.test.ts +0 -346
  125. package/src/runtime/migrations/__tests__/origin-mode.test.ts +0 -62
  126. package/src/runtime/migrations/__tests__/rebind-secrets-credentials.test.ts +0 -184
  127. package/src/runtime/migrations/__tests__/staged-import-path.test.ts +0 -110
  128. package/src/runtime/migrations/__tests__/v1-test-helpers.ts +0 -112
  129. package/src/runtime/migrations/__tests__/vbundle-builder-credentials.test.ts +0 -285
  130. package/src/runtime/migrations/__tests__/vbundle-builder-fd-leak.test.ts +0 -126
  131. package/src/runtime/migrations/__tests__/vbundle-builder-v1-shape.test.ts +0 -253
  132. package/src/runtime/migrations/__tests__/vbundle-import-credentials.test.ts +0 -208
  133. package/src/runtime/migrations/__tests__/vbundle-import-parity.test.ts +0 -485
  134. package/src/runtime/migrations/__tests__/vbundle-import-policy.test.ts +0 -349
  135. package/src/runtime/migrations/__tests__/vbundle-import-version-compat.test.ts +0 -196
  136. package/src/runtime/migrations/__tests__/vbundle-legacy-user-md.test.ts +0 -551
  137. package/src/runtime/migrations/__tests__/vbundle-metadata-merge-integration.test.ts +0 -428
  138. package/src/runtime/migrations/__tests__/vbundle-metadata-merge.test.ts +0 -220
  139. package/src/runtime/migrations/__tests__/vbundle-streaming-importer.test.ts +0 -1823
  140. package/src/runtime/migrations/__tests__/vbundle-streaming-validator.test.ts +0 -598
  141. package/src/runtime/migrations/__tests__/vbundle-symlink-importer.test.ts +0 -463
  142. package/src/runtime/migrations/__tests__/vbundle-symlink-streaming-importer.test.ts +0 -538
  143. package/src/runtime/migrations/__tests__/vbundle-symlink-streaming.test.ts +0 -515
  144. package/src/runtime/migrations/__tests__/vbundle-symlink-tar.test.ts +0 -453
  145. package/src/runtime/migrations/__tests__/vbundle-symlink-walker.test.ts +0 -319
  146. package/src/runtime/migrations/__tests__/vbundle-tar-stream.test.ts +0 -240
  147. package/src/runtime/migrations/__tests__/vbundle-validator-v1-schema.test.ts +0 -473
  148. package/src/runtime/migrations/gcs-signed-url.ts +0 -190
  149. package/src/runtime/migrations/job-registry.ts +0 -297
  150. package/src/runtime/migrations/migration-transport.ts +0 -612
  151. package/src/runtime/migrations/migration-wizard.ts +0 -747
  152. package/src/runtime/migrations/origin-mode.ts +0 -42
  153. package/src/runtime/migrations/rebind-secrets-screen.ts +0 -412
  154. package/src/runtime/migrations/staged-import-path.ts +0 -116
  155. package/src/runtime/migrations/transfer-progress-screen.ts +0 -323
  156. package/src/runtime/migrations/validation-results-screen.ts +0 -469
  157. package/src/runtime/migrations/vbundle-builder.ts +0 -1382
  158. package/src/runtime/migrations/vbundle-import-analyzer.ts +0 -405
  159. package/src/runtime/migrations/vbundle-import-policy.ts +0 -241
  160. package/src/runtime/migrations/vbundle-importer.ts +0 -826
  161. package/src/runtime/migrations/vbundle-metadata-merge.ts +0 -113
  162. package/src/runtime/migrations/vbundle-streaming-importer.ts +0 -2844
  163. package/src/runtime/migrations/vbundle-streaming-validator.ts +0 -426
  164. package/src/runtime/migrations/vbundle-tar-stream.ts +0 -244
  165. package/src/runtime/migrations/vbundle-validator.ts +0 -724
  166. package/src/runtime/routes/__tests__/migration-cadet-metadata-reconcile.test.ts +0 -227
  167. package/src/runtime/routes/__tests__/migration-export-secrets-redacted.test.ts +0 -54
  168. package/src/runtime/routes/__tests__/migration-import-allowed-hosts-env.test.ts +0 -70
  169. package/src/runtime/routes/__tests__/migration-import-credential-filter.test.ts +0 -257
  170. package/src/runtime/routes/background-wake-routes.ts +0 -387
  171. package/src/runtime/routes/migration-routes.ts +0 -2584
  172. package/src/tools/network/__tests__/cloud-search-proxy.test.ts +0 -282
  173. package/src/tools/network/cloud-search-proxy.ts +0 -211
  174. package/src/tts/__tests__/cadet-provider.test.ts +0 -253
  175. package/src/tts/providers/cadet-provider.ts +0 -244
  176. package/src/types/tar-stream.d.ts +0 -66
@@ -1,1089 +0,0 @@
1
- /**
2
- * Tests for the shared migration transport module.
3
- *
4
- * Covers:
5
- * - Runtime and managed target URL construction (trailing slashes, path format)
6
- * - Auth header injection (Authorization for runtime, X-Session-Token for managed)
7
- * - validate: success, validation failure, HTTP error
8
- * - export: runtime binary download, managed async job initiation
9
- * - import-preflight: success with report, validation failure
10
- * - import: success, failure response, HTTP error
11
- * - pollExportStatus / pollImportStatus: pending, complete, failed states
12
- * - pollUntilComplete: polls until terminal, progress callback, timeout
13
- * - Error handling: MigrationTransportError with status and body
14
- * - Retry/disabled: transport errors expose statusCode for retry decisions
15
- */
16
-
17
- import { describe, expect, test } from "bun:test";
18
-
19
- import type {
20
- ExportManagedResult,
21
- ExportRuntimeResult,
22
- ImportCommitResponse,
23
- ImportPreflightResponse,
24
- JobStatusResponse,
25
- TransportConfig,
26
- ValidateResponse,
27
- } from "../runtime/migrations/migration-transport.js";
28
- import {
29
- exportBundle,
30
- importCommit,
31
- importPreflight,
32
- MigrationTransportError,
33
- pollExportStatus,
34
- pollImportStatus,
35
- pollUntilComplete,
36
- validateBundle,
37
- } from "../runtime/migrations/migration-transport.js";
38
-
39
- // ---------------------------------------------------------------------------
40
- // Test helpers
41
- // ---------------------------------------------------------------------------
42
-
43
- /** Create a mock fetch function that returns a predefined response. */
44
- function mockFetch(
45
- status: number,
46
- body: unknown,
47
- headers?: Record<string, string>,
48
- ): typeof fetch {
49
- return (async (_url: string | URL | Request, _init?: RequestInit) => {
50
- const responseHeaders = new Headers(headers);
51
- if (
52
- typeof body === "object" &&
53
- body !== undefined &&
54
- !(body instanceof ArrayBuffer)
55
- ) {
56
- responseHeaders.set("Content-Type", "application/json");
57
- return new Response(JSON.stringify(body), {
58
- status,
59
- headers: responseHeaders,
60
- });
61
- }
62
- if (body instanceof ArrayBuffer) {
63
- return new Response(body, { status, headers: responseHeaders });
64
- }
65
- return new Response(String(body), { status, headers: responseHeaders });
66
- }) as unknown as typeof fetch;
67
- }
68
-
69
- /** Create a mock fetch that captures the request for inspection. */
70
- function capturingFetch(
71
- status: number,
72
- body: unknown,
73
- headers?: Record<string, string>,
74
- ): { fetchFn: typeof fetch; captured: { url: string; init: RequestInit }[] } {
75
- const captured: { url: string; init: RequestInit }[] = [];
76
- const fetchFn = (async (url: string | URL | Request, init?: RequestInit) => {
77
- captured.push({ url: String(url), init: init ?? {} });
78
- return mockFetch(status, body, headers)(url, init);
79
- }) as unknown as typeof fetch;
80
- return { fetchFn, captured };
81
- }
82
-
83
- function runtimeConfig(overrides?: Partial<TransportConfig>): TransportConfig {
84
- return {
85
- baseURL: "http://localhost:7821",
86
- target: "runtime",
87
- authHeader: "Bearer test-jwt",
88
- fetchFn: mockFetch(200, {}),
89
- ...overrides,
90
- };
91
- }
92
-
93
- function managedConfig(overrides?: Partial<TransportConfig>): TransportConfig {
94
- return {
95
- baseURL: "https://cloud.mycadet.ai",
96
- target: "managed",
97
- authHeader: "test-session-token",
98
- fetchFn: mockFetch(200, {}),
99
- ...overrides,
100
- };
101
- }
102
-
103
- const sampleFileData = new ArrayBuffer(16);
104
-
105
- // ---------------------------------------------------------------------------
106
- // URL construction
107
- // ---------------------------------------------------------------------------
108
-
109
- describe("URL construction", () => {
110
- test("runtime URLs have no trailing slash", async () => {
111
- const { fetchFn, captured } = capturingFetch(200, {
112
- is_valid: true,
113
- errors: [],
114
- manifest: {},
115
- });
116
- await validateBundle(runtimeConfig({ fetchFn }), sampleFileData);
117
- expect(captured[0].url).toBe(
118
- "http://localhost:7821/v1/migrations/validate",
119
- );
120
- });
121
-
122
- test("managed URLs have trailing slash", async () => {
123
- const { fetchFn, captured } = capturingFetch(200, {
124
- is_valid: true,
125
- errors: [],
126
- manifest: {},
127
- });
128
- await validateBundle(managedConfig({ fetchFn }), sampleFileData);
129
- expect(captured[0].url).toBe(
130
- "https://cloud.mycadet.ai/v1/migrations/validate/",
131
- );
132
- });
133
-
134
- test("base URL trailing slashes are normalized", async () => {
135
- const { fetchFn, captured } = capturingFetch(200, {
136
- is_valid: true,
137
- errors: [],
138
- manifest: {},
139
- });
140
- await validateBundle(
141
- runtimeConfig({ baseURL: "http://localhost:7821///", fetchFn }),
142
- sampleFileData,
143
- );
144
- expect(captured[0].url).toBe(
145
- "http://localhost:7821/v1/migrations/validate",
146
- );
147
- });
148
- });
149
-
150
- // ---------------------------------------------------------------------------
151
- // Auth headers
152
- // ---------------------------------------------------------------------------
153
-
154
- describe("Auth headers", () => {
155
- test("runtime uses Authorization header by default", async () => {
156
- const { fetchFn, captured } = capturingFetch(200, {
157
- is_valid: true,
158
- errors: [],
159
- manifest: {},
160
- });
161
- await validateBundle(runtimeConfig({ fetchFn }), sampleFileData);
162
- const headers = captured[0].init.headers as Record<string, string>;
163
- expect(headers["Authorization"]).toBe("Bearer test-jwt");
164
- expect(headers["X-Session-Token"]).toBeUndefined();
165
- });
166
-
167
- test("managed uses X-Session-Token header by default", async () => {
168
- const { fetchFn, captured } = capturingFetch(200, {
169
- is_valid: true,
170
- errors: [],
171
- manifest: {},
172
- });
173
- await validateBundle(managedConfig({ fetchFn }), sampleFileData);
174
- const headers = captured[0].init.headers as Record<string, string>;
175
- expect(headers["X-Session-Token"]).toBe("test-session-token");
176
- expect(headers["Authorization"]).toBeUndefined();
177
- });
178
-
179
- test("custom authHeaderName is respected", async () => {
180
- const { fetchFn, captured } = capturingFetch(200, {
181
- is_valid: true,
182
- errors: [],
183
- manifest: {},
184
- });
185
- await validateBundle(
186
- runtimeConfig({ authHeaderName: "X-Custom-Auth", fetchFn }),
187
- sampleFileData,
188
- );
189
- const headers = captured[0].init.headers as Record<string, string>;
190
- expect(headers["X-Custom-Auth"]).toBe("Bearer test-jwt");
191
- expect(headers["Authorization"]).toBeUndefined();
192
- });
193
-
194
- test("managed request includes Cadet-Organization-Id from defaultHeaders", async () => {
195
- const { fetchFn, captured } = capturingFetch(200, {
196
- is_valid: true,
197
- errors: [],
198
- manifest: {},
199
- });
200
- await validateBundle(
201
- managedConfig({
202
- fetchFn,
203
- defaultHeaders: { "Cadet-Organization-Id": "org-123" },
204
- }),
205
- sampleFileData,
206
- );
207
- const headers = captured[0].init.headers as Record<string, string>;
208
- expect(headers["Cadet-Organization-Id"]).toBe("org-123");
209
- // Managed auth header should still be present
210
- expect(headers["X-Session-Token"]).toBe("test-session-token");
211
- });
212
-
213
- test("runtime request is unchanged when no defaultHeaders provided", async () => {
214
- const { fetchFn, captured } = capturingFetch(200, {
215
- is_valid: true,
216
- errors: [],
217
- manifest: {},
218
- });
219
- await validateBundle(runtimeConfig({ fetchFn }), sampleFileData);
220
- const headers = captured[0].init.headers as Record<string, string>;
221
- expect(headers["Authorization"]).toBe("Bearer test-jwt");
222
- expect(headers["Cadet-Organization-Id"]).toBeUndefined();
223
- });
224
-
225
- test("auth header wins over same-named entry in defaultHeaders", async () => {
226
- const { fetchFn, captured } = capturingFetch(200, {
227
- is_valid: true,
228
- errors: [],
229
- manifest: {},
230
- });
231
- // defaultHeaders sets X-Session-Token, but authHeader should override it
232
- await validateBundle(
233
- managedConfig({
234
- fetchFn,
235
- defaultHeaders: { "X-Session-Token": "should-be-overridden" },
236
- }),
237
- sampleFileData,
238
- );
239
- const headers = captured[0].init.headers as Record<string, string>;
240
- expect(headers["X-Session-Token"]).toBe("test-session-token");
241
- });
242
-
243
- test("auth header wins over case-insensitive entry in defaultHeaders", async () => {
244
- const managed = capturingFetch(200, {
245
- is_valid: true,
246
- errors: [],
247
- manifest: {},
248
- });
249
-
250
- await validateBundle(
251
- managedConfig({
252
- fetchFn: managed.fetchFn,
253
- defaultHeaders: { "x-session-token": "should-be-overridden" },
254
- }),
255
- sampleFileData,
256
- );
257
-
258
- const managedHeaders = managed.captured[0].init.headers as Record<
259
- string,
260
- string
261
- >;
262
- expect(managedHeaders["X-Session-Token"]).toBe("test-session-token");
263
- expect(managedHeaders["x-session-token"]).toBeUndefined();
264
-
265
- const runtime = capturingFetch(200, {
266
- is_valid: true,
267
- errors: [],
268
- manifest: {},
269
- });
270
-
271
- await validateBundle(
272
- runtimeConfig({
273
- fetchFn: runtime.fetchFn,
274
- defaultHeaders: { authorization: "should-be-overridden" },
275
- }),
276
- sampleFileData,
277
- );
278
-
279
- const runtimeHeaders = runtime.captured[0].init.headers as Record<
280
- string,
281
- string
282
- >;
283
- expect(runtimeHeaders.Authorization).toBe("Bearer test-jwt");
284
- expect(runtimeHeaders.authorization).toBeUndefined();
285
- });
286
-
287
- test("no auth header when authHeader is not provided", async () => {
288
- const { fetchFn, captured } = capturingFetch(200, {
289
- is_valid: true,
290
- errors: [],
291
- manifest: {},
292
- });
293
- await validateBundle(
294
- { baseURL: "http://localhost:7821", target: "runtime", fetchFn },
295
- sampleFileData,
296
- );
297
- const headers = captured[0].init.headers as Record<string, string>;
298
- expect(headers["Authorization"]).toBeUndefined();
299
- expect(headers["X-Session-Token"]).toBeUndefined();
300
- });
301
- });
302
-
303
- // ---------------------------------------------------------------------------
304
- // validateBundle
305
- // ---------------------------------------------------------------------------
306
-
307
- describe("validateBundle", () => {
308
- test("success — valid bundle returns is_valid: true with manifest", async () => {
309
- const responseBody: ValidateResponse = {
310
- is_valid: true,
311
- errors: [],
312
- manifest: {
313
- schema_version: 1,
314
- bundle_id: "00000000-0000-4000-8000-000000000000",
315
- created_at: "2026-03-01T00:00:00Z",
316
- assistant: { id: "self", name: "Test", runtime_version: "0.0.0-test" },
317
- origin: { mode: "self-hosted-local" },
318
- compatibility: {
319
- min_runtime_version: "0.0.0-test",
320
- max_runtime_version: null,
321
- },
322
- contents: [
323
- { path: "data/db/assistant.db", sha256: "abc", size_bytes: 100 },
324
- ],
325
- checksum: "def",
326
- secrets_redacted: false,
327
- export_options: {
328
- include_logs: false,
329
- include_browser_state: false,
330
- include_memory_vectors: false,
331
- },
332
- },
333
- };
334
- const config = runtimeConfig({ fetchFn: mockFetch(200, responseBody) });
335
- const result = await validateBundle(config, sampleFileData);
336
- expect(result.is_valid).toBe(true);
337
- if (result.is_valid) {
338
- expect(result.manifest.schema_version).toBe(1);
339
- expect(result.manifest.contents).toHaveLength(1);
340
- }
341
- });
342
-
343
- test("failure — invalid bundle returns is_valid: false with errors", async () => {
344
- const responseBody: ValidateResponse = {
345
- is_valid: false,
346
- errors: [{ code: "INVALID_GZIP", message: "Not a valid gzip file" }],
347
- };
348
- const config = runtimeConfig({ fetchFn: mockFetch(200, responseBody) });
349
- const result = await validateBundle(config, sampleFileData);
350
- expect(result.is_valid).toBe(false);
351
- expect(result.errors).toHaveLength(1);
352
- expect(result.errors[0].code).toBe("INVALID_GZIP");
353
- });
354
-
355
- test("HTTP error throws MigrationTransportError", async () => {
356
- const config = runtimeConfig({
357
- fetchFn: mockFetch(400, "Bad Request"),
358
- });
359
- try {
360
- await validateBundle(config, sampleFileData);
361
- expect(true).toBe(false); // Should not reach here
362
- } catch (err) {
363
- expect(err).toBeInstanceOf(MigrationTransportError);
364
- const transportErr = err as MigrationTransportError;
365
- expect(transportErr.statusCode).toBe(400);
366
- expect(transportErr.responseBody).toBe("Bad Request");
367
- }
368
- });
369
-
370
- test("sends binary body with correct content type", async () => {
371
- const { fetchFn, captured } = capturingFetch(200, {
372
- is_valid: true,
373
- errors: [],
374
- });
375
- await validateBundle(runtimeConfig({ fetchFn }), sampleFileData);
376
- expect(captured[0].init.method).toBe("POST");
377
- const headers = captured[0].init.headers as Record<string, string>;
378
- expect(headers["Content-Type"]).toBe("application/octet-stream");
379
- });
380
- });
381
-
382
- // ---------------------------------------------------------------------------
383
- // exportBundle
384
- // ---------------------------------------------------------------------------
385
-
386
- describe("exportBundle", () => {
387
- test("runtime — returns binary archive with metadata", async () => {
388
- const archiveBytes = new ArrayBuffer(128);
389
- const config = runtimeConfig({
390
- fetchFn: mockFetch(200, archiveBytes, {
391
- "Content-Disposition": 'attachment; filename="export-2026.vbundle"',
392
- "X-Vbundle-Schema-Version": "1",
393
- "X-Vbundle-Manifest-Sha256": "abc123",
394
- }),
395
- });
396
-
397
- const result = await exportBundle(config, { description: "Test export" });
398
- expect(result.ok).toBe(true);
399
- const runtimeResult = result as ExportRuntimeResult;
400
- expect(runtimeResult.archive).toBeDefined();
401
- expect(runtimeResult.filename).toBe("export-2026.vbundle");
402
- expect(runtimeResult.schemaVersion).toBe(1);
403
- expect(runtimeResult.checksum).toBe("abc123");
404
- });
405
-
406
- test("managed — returns job ID for async processing", async () => {
407
- const responseBody = { job_id: "job-123", status: "pending" };
408
- const config = managedConfig({ fetchFn: mockFetch(200, responseBody) });
409
-
410
- const result = await exportBundle(config);
411
- expect(result.ok).toBe(true);
412
- const managedResult = result as ExportManagedResult;
413
- expect(managedResult.jobId).toBe("job-123");
414
- expect(managedResult.status).toBe("pending");
415
- });
416
-
417
- test("sends description in JSON body when provided", async () => {
418
- const { fetchFn, captured } = capturingFetch(200, new ArrayBuffer(0), {
419
- "Content-Disposition": 'attachment; filename="test.vbundle"',
420
- });
421
- await exportBundle(runtimeConfig({ fetchFn }), {
422
- description: "My export",
423
- });
424
- const headers = captured[0].init.headers as Record<string, string>;
425
- expect(headers["Content-Type"]).toBe("application/json");
426
- const body = captured[0].init.body as string;
427
- expect(JSON.parse(body)).toEqual({ description: "My export" });
428
- });
429
-
430
- test("HTTP error throws MigrationTransportError", async () => {
431
- const config = runtimeConfig({
432
- fetchFn: mockFetch(500, "Internal Server Error"),
433
- });
434
- try {
435
- await exportBundle(config);
436
- expect(true).toBe(false);
437
- } catch (err) {
438
- expect(err).toBeInstanceOf(MigrationTransportError);
439
- expect((err as MigrationTransportError).statusCode).toBe(500);
440
- }
441
- });
442
- });
443
-
444
- // ---------------------------------------------------------------------------
445
- // importPreflight
446
- // ---------------------------------------------------------------------------
447
-
448
- describe("importPreflight", () => {
449
- test("success — returns dry-run report", async () => {
450
- const responseBody: ImportPreflightResponse = {
451
- can_import: true,
452
- summary: {
453
- total_files: 2,
454
- files_to_create: 0,
455
- files_to_overwrite: 2,
456
- files_unchanged: 0,
457
- files_to_skip: 0,
458
- },
459
- files: [
460
- {
461
- path: "data/db/assistant.db",
462
- action: "overwrite",
463
- bundle_size: 1024,
464
- current_size: 512,
465
- bundle_sha256: "abc",
466
- current_sha256: "def",
467
- },
468
- ],
469
- conflicts: [],
470
- manifest: {
471
- schema_version: 1,
472
- bundle_id: "00000000-0000-4000-8000-000000000000",
473
- created_at: "2026-03-01T00:00:00Z",
474
- assistant: { id: "self", name: "Test", runtime_version: "0.0.0-test" },
475
- origin: { mode: "self-hosted-local" },
476
- compatibility: {
477
- min_runtime_version: "0.0.0-test",
478
- max_runtime_version: null,
479
- },
480
- contents: [],
481
- checksum: "ghi",
482
- secrets_redacted: false,
483
- export_options: {
484
- include_logs: false,
485
- include_browser_state: false,
486
- include_memory_vectors: false,
487
- },
488
- },
489
- };
490
- const config = runtimeConfig({ fetchFn: mockFetch(200, responseBody) });
491
- const result = await importPreflight(config, sampleFileData);
492
- expect(result.can_import).toBe(true);
493
- if (result.can_import) {
494
- expect(result.summary.total_files).toBe(2);
495
- expect(result.files[0].action).toBe("overwrite");
496
- }
497
- });
498
-
499
- test("validation failure — returns can_import: false with errors", async () => {
500
- const responseBody: ImportPreflightResponse = {
501
- can_import: false,
502
- validation: {
503
- is_valid: false,
504
- errors: [{ code: "INVALID_GZIP", message: "Not a gzip file" }],
505
- },
506
- };
507
- const config = runtimeConfig({ fetchFn: mockFetch(200, responseBody) });
508
- const result = await importPreflight(config, sampleFileData);
509
- expect(result.can_import).toBe(false);
510
- if (!result.can_import && "validation" in result) {
511
- expect(result.validation.errors).toHaveLength(1);
512
- }
513
- });
514
-
515
- test("HTTP error throws MigrationTransportError", async () => {
516
- const config = runtimeConfig({
517
- fetchFn: mockFetch(400, "Empty body"),
518
- });
519
- try {
520
- await importPreflight(config, sampleFileData);
521
- expect(true).toBe(false);
522
- } catch (err) {
523
- expect(err).toBeInstanceOf(MigrationTransportError);
524
- }
525
- });
526
- });
527
-
528
- // ---------------------------------------------------------------------------
529
- // importCommit
530
- // ---------------------------------------------------------------------------
531
-
532
- describe("importCommit", () => {
533
- test("success — returns import report", async () => {
534
- const responseBody: ImportCommitResponse = {
535
- success: true,
536
- summary: {
537
- total_files: 2,
538
- files_created: 0,
539
- files_overwritten: 2,
540
- files_skipped: 0,
541
- backups_created: 2,
542
- },
543
- files: [
544
- {
545
- path: "data/db/assistant.db",
546
- disk_path: "/home/.cadet/data/db/assistant.db",
547
- action: "overwritten",
548
- size: 1024,
549
- sha256: "abc",
550
- backup_path: "/home/.cadet/data/db/assistant.db.bak",
551
- },
552
- ],
553
- manifest: {
554
- schema_version: 1,
555
- bundle_id: "00000000-0000-4000-8000-000000000000",
556
- created_at: "2026-03-01T00:00:00Z",
557
- assistant: { id: "self", name: "Test", runtime_version: "0.0.0-test" },
558
- origin: { mode: "self-hosted-local" },
559
- compatibility: {
560
- min_runtime_version: "0.0.0-test",
561
- max_runtime_version: null,
562
- },
563
- contents: [],
564
- checksum: "def",
565
- secrets_redacted: false,
566
- export_options: {
567
- include_logs: false,
568
- include_browser_state: false,
569
- include_memory_vectors: false,
570
- },
571
- },
572
- warnings: [],
573
- };
574
- const config = runtimeConfig({ fetchFn: mockFetch(200, responseBody) });
575
- const result = await importCommit(config, sampleFileData);
576
- expect(result.success).toBe(true);
577
- if (result.success) {
578
- expect(result.summary.files_overwritten).toBe(2);
579
- expect(result.summary.backups_created).toBe(2);
580
- }
581
- });
582
-
583
- test("validation failure — returns success: false", async () => {
584
- const responseBody: ImportCommitResponse = {
585
- success: false,
586
- reason: "validation_failed",
587
- errors: [{ code: "INVALID_GZIP", message: "Not gzip" }],
588
- };
589
- const config = runtimeConfig({ fetchFn: mockFetch(200, responseBody) });
590
- const result = await importCommit(config, sampleFileData);
591
- expect(result.success).toBe(false);
592
- if (!result.success) {
593
- expect(result.reason).toBe("validation_failed");
594
- expect(result.errors).toHaveLength(1);
595
- }
596
- });
597
-
598
- test("500 error throws MigrationTransportError", async () => {
599
- const config = runtimeConfig({
600
- fetchFn: mockFetch(500, "Server error"),
601
- });
602
- try {
603
- await importCommit(config, sampleFileData);
604
- expect(true).toBe(false);
605
- } catch (err) {
606
- expect(err).toBeInstanceOf(MigrationTransportError);
607
- expect((err as MigrationTransportError).statusCode).toBe(500);
608
- }
609
- });
610
-
611
- test("400 error throws MigrationTransportError", async () => {
612
- const config = runtimeConfig({
613
- fetchFn: mockFetch(400, "Bad request"),
614
- });
615
- try {
616
- await importCommit(config, sampleFileData);
617
- expect(true).toBe(false);
618
- } catch (err) {
619
- expect(err).toBeInstanceOf(MigrationTransportError);
620
- expect((err as MigrationTransportError).statusCode).toBe(400);
621
- }
622
- });
623
- });
624
-
625
- // ---------------------------------------------------------------------------
626
- // pollExportStatus
627
- // ---------------------------------------------------------------------------
628
-
629
- describe("pollExportStatus", () => {
630
- test("returns pending status", async () => {
631
- const responseBody = { status: "pending", job_id: "job-1", progress: 0.5 };
632
- const config = managedConfig({ fetchFn: mockFetch(200, responseBody) });
633
- const result = await pollExportStatus(config, "job-1");
634
- expect(result.status).toBe("pending");
635
- expect(result.jobId).toBe("job-1");
636
- if (result.status === "pending") {
637
- expect(result.progress).toBe(0.5);
638
- }
639
- });
640
-
641
- test("returns complete status with download URL", async () => {
642
- const responseBody = {
643
- status: "complete",
644
- job_id: "job-2",
645
- download_url: "https://cdn.example.com/export.vbundle",
646
- };
647
- const config = managedConfig({ fetchFn: mockFetch(200, responseBody) });
648
- const result = await pollExportStatus(config, "job-2");
649
- expect(result.status).toBe("complete");
650
- if (result.status === "complete") {
651
- expect(result.downloadUrl).toBe("https://cdn.example.com/export.vbundle");
652
- }
653
- });
654
-
655
- test("returns failed status with error", async () => {
656
- const responseBody = {
657
- status: "failed",
658
- job_id: "job-3",
659
- error: "Export timed out",
660
- };
661
- const config = managedConfig({ fetchFn: mockFetch(200, responseBody) });
662
- const result = await pollExportStatus(config, "job-3");
663
- expect(result.status).toBe("failed");
664
- if (result.status === "failed") {
665
- expect(result.error).toBe("Export timed out");
666
- }
667
- });
668
-
669
- test("throws for runtime target", async () => {
670
- const config = runtimeConfig();
671
- try {
672
- await pollExportStatus(config, "job-1");
673
- expect(true).toBe(false);
674
- } catch (err) {
675
- expect((err as Error).message).toContain("only supported for managed");
676
- }
677
- });
678
-
679
- test("constructs correct URL with encoded job ID", async () => {
680
- const { fetchFn, captured } = capturingFetch(200, {
681
- status: "pending",
682
- job_id: "job/special",
683
- });
684
- const config = managedConfig({ fetchFn });
685
- await pollExportStatus(config, "job/special");
686
- expect(captured[0].url).toBe(
687
- "https://cloud.mycadet.ai/v1/migrations/export/job%2Fspecial/status/",
688
- );
689
- expect(captured[0].init.method).toBe("GET");
690
- });
691
- });
692
-
693
- // ---------------------------------------------------------------------------
694
- // pollImportStatus
695
- // ---------------------------------------------------------------------------
696
-
697
- describe("pollImportStatus", () => {
698
- test("returns processing status", async () => {
699
- const responseBody = {
700
- status: "processing",
701
- job_id: "imp-1",
702
- progress: 0.8,
703
- };
704
- const config = managedConfig({ fetchFn: mockFetch(200, responseBody) });
705
- const result = await pollImportStatus(config, "imp-1");
706
- expect(result.status).toBe("processing");
707
- expect(result.jobId).toBe("imp-1");
708
- });
709
-
710
- test("returns complete status", async () => {
711
- const responseBody = {
712
- status: "complete",
713
- job_id: "imp-2",
714
- result: { files_imported: 3 },
715
- };
716
- const config = managedConfig({ fetchFn: mockFetch(200, responseBody) });
717
- const result = await pollImportStatus(config, "imp-2");
718
- expect(result.status).toBe("complete");
719
- if (result.status === "complete") {
720
- expect(result.result).toEqual({ files_imported: 3 });
721
- }
722
- });
723
-
724
- test("throws for runtime target", async () => {
725
- const config = runtimeConfig();
726
- try {
727
- await pollImportStatus(config, "imp-1");
728
- expect(true).toBe(false);
729
- } catch (err) {
730
- expect((err as Error).message).toContain("only supported for managed");
731
- }
732
- });
733
-
734
- test("HTTP error throws MigrationTransportError", async () => {
735
- const config = managedConfig({
736
- fetchFn: mockFetch(404, "Not found"),
737
- });
738
- try {
739
- await pollImportStatus(config, "unknown-job");
740
- expect(true).toBe(false);
741
- } catch (err) {
742
- expect(err).toBeInstanceOf(MigrationTransportError);
743
- expect((err as MigrationTransportError).statusCode).toBe(404);
744
- }
745
- });
746
- });
747
-
748
- // ---------------------------------------------------------------------------
749
- // pollUntilComplete
750
- // ---------------------------------------------------------------------------
751
-
752
- describe("pollUntilComplete", () => {
753
- test("polls until complete status", async () => {
754
- let callCount = 0;
755
- const fetchFn = (async () => {
756
- callCount++;
757
- const status = callCount < 3 ? "pending" : "complete";
758
- return new Response(
759
- JSON.stringify({
760
- status,
761
- job_id: "job-poll",
762
- ...(status === "complete"
763
- ? { download_url: "https://cdn.example.com/test.vbundle" }
764
- : {}),
765
- }),
766
- { status: 200 },
767
- );
768
- }) as unknown as typeof fetch;
769
-
770
- const progressCalls: JobStatusResponse[] = [];
771
- const result = await pollUntilComplete(
772
- managedConfig({ fetchFn }),
773
- "export",
774
- "job-poll",
775
- {
776
- intervalMs: 10,
777
- maxAttempts: 10,
778
- onProgress: (s) => progressCalls.push(s),
779
- },
780
- );
781
-
782
- expect(result.status).toBe("complete");
783
- expect(callCount).toBe(3);
784
- expect(progressCalls).toHaveLength(3);
785
- expect(progressCalls[0].status).toBe("pending");
786
- expect(progressCalls[2].status).toBe("complete");
787
- });
788
-
789
- test("returns failed status when job fails", async () => {
790
- let callCount = 0;
791
- const fetchFn = (async () => {
792
- callCount++;
793
- const status = callCount < 2 ? "processing" : "failed";
794
- return new Response(
795
- JSON.stringify({
796
- status,
797
- job_id: "job-fail",
798
- ...(status === "failed" ? { error: "Disk full" } : {}),
799
- }),
800
- { status: 200 },
801
- );
802
- }) as unknown as typeof fetch;
803
-
804
- const result = await pollUntilComplete(
805
- managedConfig({ fetchFn }),
806
- "import",
807
- "job-fail",
808
- { intervalMs: 10, maxAttempts: 10 },
809
- );
810
-
811
- expect(result.status).toBe("failed");
812
- if (result.status === "failed") {
813
- expect(result.error).toBe("Disk full");
814
- }
815
- });
816
-
817
- test("throws when maxAttempts exceeded", async () => {
818
- const fetchFn = (async () => {
819
- return new Response(
820
- JSON.stringify({ status: "pending", job_id: "job-slow" }),
821
- { status: 200 },
822
- );
823
- }) as unknown as typeof fetch;
824
-
825
- try {
826
- await pollUntilComplete(
827
- managedConfig({ fetchFn }),
828
- "export",
829
- "job-slow",
830
- { intervalMs: 10, maxAttempts: 3 },
831
- );
832
- expect(true).toBe(false);
833
- } catch (err) {
834
- expect(err).toBeInstanceOf(MigrationTransportError);
835
- expect((err as MigrationTransportError).message).toContain(
836
- "did not complete",
837
- );
838
- }
839
- });
840
- });
841
-
842
- // ---------------------------------------------------------------------------
843
- // MigrationTransportError
844
- // ---------------------------------------------------------------------------
845
-
846
- describe("MigrationTransportError", () => {
847
- test("exposes statusCode and responseBody for retry decisions", () => {
848
- const err = new MigrationTransportError(
849
- "test error",
850
- 503,
851
- "Service Unavailable",
852
- );
853
- expect(err.name).toBe("MigrationTransportError");
854
- expect(err.statusCode).toBe(503);
855
- expect(err.responseBody).toBe("Service Unavailable");
856
- expect(err.message).toBe("test error");
857
- });
858
-
859
- test("is instanceof Error", () => {
860
- const err = new MigrationTransportError("test", 500, "");
861
- expect(err instanceof Error).toBe(true);
862
- expect(err instanceof MigrationTransportError).toBe(true);
863
- });
864
-
865
- test("retryable status codes can be detected by callers", () => {
866
- const retryable = [429, 502, 503, 504];
867
- const nonRetryable = [400, 401, 403, 404, 422];
868
-
869
- for (const code of retryable) {
870
- const err = new MigrationTransportError("test", code, "");
871
- expect(
872
- err.statusCode >= 429 ||
873
- (err.statusCode >= 500 && err.statusCode <= 504),
874
- ).toBe(true);
875
- }
876
-
877
- for (const code of nonRetryable) {
878
- const _err = new MigrationTransportError("test", code, "");
879
- expect(code >= 400 && code < 500 && code !== 429).toBe(true);
880
- }
881
- });
882
- });
883
-
884
- // ---------------------------------------------------------------------------
885
- // State persistence / multi-step flow behavior
886
- // ---------------------------------------------------------------------------
887
-
888
- describe("Multi-step flow behavior", () => {
889
- test("validate → import-preflight → import uses consistent config", async () => {
890
- const calls: string[] = [];
891
- const fetchFn = (async (url: string | URL | Request) => {
892
- const urlStr = String(url);
893
- if (urlStr.includes("validate")) {
894
- calls.push("validate");
895
- return new Response(
896
- JSON.stringify({
897
- is_valid: true,
898
- errors: [],
899
- manifest: {
900
- schema_version: 1,
901
- bundle_id: "00000000-0000-4000-8000-000000000000",
902
- created_at: "2026-01-01T00:00:00Z",
903
- assistant: {
904
- id: "self",
905
- name: "Test",
906
- runtime_version: "0.0.0-test",
907
- },
908
- origin: { mode: "self-hosted-local" },
909
- compatibility: {
910
- min_runtime_version: "0.0.0-test",
911
- max_runtime_version: null,
912
- },
913
- contents: [],
914
- checksum: "abc",
915
- secrets_redacted: false,
916
- export_options: {
917
- include_logs: false,
918
- include_browser_state: false,
919
- include_memory_vectors: false,
920
- },
921
- },
922
- }),
923
- { status: 200 },
924
- );
925
- }
926
- if (urlStr.includes("import-preflight")) {
927
- calls.push("import-preflight");
928
- return new Response(
929
- JSON.stringify({
930
- can_import: true,
931
- summary: {
932
- total_files: 1,
933
- files_to_create: 1,
934
- files_to_overwrite: 0,
935
- files_unchanged: 0,
936
- files_to_skip: 0,
937
- },
938
- files: [],
939
- conflicts: [],
940
- manifest: {
941
- schema_version: 1,
942
- bundle_id: "00000000-0000-4000-8000-000000000000",
943
- created_at: "2026-01-01T00:00:00Z",
944
- assistant: {
945
- id: "self",
946
- name: "Test",
947
- runtime_version: "0.0.0-test",
948
- },
949
- origin: { mode: "self-hosted-local" },
950
- compatibility: {
951
- min_runtime_version: "0.0.0-test",
952
- max_runtime_version: null,
953
- },
954
- contents: [],
955
- checksum: "abc",
956
- secrets_redacted: false,
957
- export_options: {
958
- include_logs: false,
959
- include_browser_state: false,
960
- include_memory_vectors: false,
961
- },
962
- },
963
- }),
964
- { status: 200 },
965
- );
966
- }
967
- if (urlStr.includes("/import") && !urlStr.includes("preflight")) {
968
- calls.push("import");
969
- return new Response(
970
- JSON.stringify({
971
- success: true,
972
- summary: {
973
- total_files: 1,
974
- files_created: 1,
975
- files_overwritten: 0,
976
- files_skipped: 0,
977
- backups_created: 0,
978
- },
979
- files: [],
980
- manifest: {
981
- schema_version: 1,
982
- bundle_id: "00000000-0000-4000-8000-000000000000",
983
- created_at: "2026-01-01T00:00:00Z",
984
- assistant: {
985
- id: "self",
986
- name: "Test",
987
- runtime_version: "0.0.0-test",
988
- },
989
- origin: { mode: "self-hosted-local" },
990
- compatibility: {
991
- min_runtime_version: "0.0.0-test",
992
- max_runtime_version: null,
993
- },
994
- contents: [],
995
- checksum: "abc",
996
- secrets_redacted: false,
997
- export_options: {
998
- include_logs: false,
999
- include_browser_state: false,
1000
- include_memory_vectors: false,
1001
- },
1002
- },
1003
- warnings: [],
1004
- }),
1005
- { status: 200 },
1006
- );
1007
- }
1008
- return new Response("Not found", { status: 404 });
1009
- }) as unknown as typeof fetch;
1010
-
1011
- const config = runtimeConfig({ fetchFn });
1012
- const fileData = new ArrayBuffer(8);
1013
-
1014
- // Step 1: Validate
1015
- const validateResult = await validateBundle(config, fileData);
1016
- expect(validateResult.is_valid).toBe(true);
1017
-
1018
- // Step 2: Preflight
1019
- const preflightResult = await importPreflight(config, fileData);
1020
- expect(preflightResult.can_import).toBe(true);
1021
-
1022
- // Step 3: Import
1023
- const importResult = await importCommit(config, fileData);
1024
- expect(importResult.success).toBe(true);
1025
-
1026
- // All three steps were called in order
1027
- expect(calls).toEqual(["validate", "import-preflight", "import"]);
1028
- });
1029
-
1030
- test("managed export → poll flow works end-to-end", async () => {
1031
- let fetchCallCount = 0;
1032
- const fetchFn = (async (url: string | URL | Request) => {
1033
- fetchCallCount++;
1034
- const urlStr = String(url);
1035
- if (urlStr.includes("/export/") && urlStr.includes("/status/")) {
1036
- // Status poll
1037
- if (fetchCallCount <= 3) {
1038
- return new Response(
1039
- JSON.stringify({
1040
- status: "processing",
1041
- job_id: "exp-1",
1042
- progress: fetchCallCount * 0.25,
1043
- }),
1044
- { status: 200 },
1045
- );
1046
- }
1047
- return new Response(
1048
- JSON.stringify({
1049
- status: "complete",
1050
- job_id: "exp-1",
1051
- download_url: "https://cdn.example.com/result.vbundle",
1052
- }),
1053
- { status: 200 },
1054
- );
1055
- }
1056
- if (urlStr.endsWith("/export/")) {
1057
- // Initial export request
1058
- return new Response(
1059
- JSON.stringify({ job_id: "exp-1", status: "pending" }),
1060
- { status: 200 },
1061
- );
1062
- }
1063
- return new Response("Not found", { status: 404 });
1064
- }) as unknown as typeof fetch;
1065
-
1066
- const config = managedConfig({ fetchFn });
1067
-
1068
- // Step 1: Initiate export
1069
- const exportResult = await exportBundle(config);
1070
- expect(exportResult.ok).toBe(true);
1071
- const managedExport = exportResult as ExportManagedResult;
1072
- expect(managedExport.jobId).toBe("exp-1");
1073
-
1074
- // Step 2: Poll until complete
1075
- const finalStatus = await pollUntilComplete(
1076
- config,
1077
- "export",
1078
- managedExport.jobId,
1079
- { intervalMs: 10, maxAttempts: 10 },
1080
- );
1081
-
1082
- expect(finalStatus.status).toBe("complete");
1083
- if (finalStatus.status === "complete") {
1084
- expect(finalStatus.downloadUrl).toBe(
1085
- "https://cdn.example.com/result.vbundle",
1086
- );
1087
- }
1088
- });
1089
- });