@cortexkit/opencode-magic-context 0.49.104 → 0.49.105

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 (149) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +8 -5
  3. package/dist/{context-7hbmnpe8.js → context-wtnrsjkp.js} +113 -136
  4. package/dist/{embedding-backfill-aratv25b.js → embedding-backfill-kqwx0vhj.js} +4 -4
  5. package/dist/features/magic-context/chunk-embedding-write-worker-install-failure.fixture.d.ts +2 -0
  6. package/dist/features/magic-context/chunk-embedding-write-worker-install-failure.fixture.d.ts.map +1 -0
  7. package/dist/features/magic-context/chunk-scope-repair-revision.d.ts +16 -1
  8. package/dist/features/magic-context/chunk-scope-repair-revision.d.ts.map +1 -1
  9. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  10. package/dist/features/magic-context/dreamer/verify-checkout.d.ts +2 -0
  11. package/dist/features/magic-context/dreamer/verify-checkout.d.ts.map +1 -0
  12. package/dist/features/magic-context/memory/embedding-worker-observer.fixture.d.ts +26 -0
  13. package/dist/features/magic-context/memory/embedding-worker-observer.fixture.d.ts.map +1 -0
  14. package/dist/features/magic-context/message-fts-rowid-map-startup-worker-test-support.d.ts +2 -0
  15. package/dist/features/magic-context/message-fts-rowid-map-startup-worker-test-support.d.ts.map +1 -0
  16. package/dist/features/magic-context/project-embedding-registry.d.ts +5 -0
  17. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  18. package/dist/features/magic-context/search-pool-fixture.d.ts +15 -0
  19. package/dist/features/magic-context/search-pool-fixture.d.ts.map +1 -1
  20. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  21. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  22. package/dist/hooks/magic-context/compartment-runner-types.d.ts +4 -1
  23. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/compartment-runner.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/history-boundary-repair.d.ts +7 -2
  26. package/dist/hooks/magic-context/history-boundary-repair.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +1 -0
  28. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/transform.d.ts +1 -0
  30. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  31. package/dist/{index-3nxhxeeg.js → index-1j4q0bd6.js} +4 -4
  32. package/dist/{index-fd3hkyk1.js → index-42fsf88t.js} +1 -1
  33. package/dist/{index-jjxpmypb.js → index-7z5cvfpg.js} +1 -1
  34. package/dist/{index-a9wn0d9h.js → index-8vv7axxg.js} +3 -3
  35. package/dist/{index-8yj4vd7k.js → index-92p5yfpp.js} +1 -1
  36. package/dist/{index-sqvkh5d0.js → index-9m2b5mwf.js} +20 -7
  37. package/dist/{index-mwjvjn0p.js → index-a3t1ck7g.js} +6 -6
  38. package/dist/{index-4ba3zp54.js → index-as8bg7eh.js} +365 -113
  39. package/dist/{index-8eke8yh2.js → index-cxh5g5bt.js} +1 -1
  40. package/dist/{index-vegw385y.js → index-cy5fn70d.js} +89 -1
  41. package/dist/{index-4dywj733.js → index-dzb1yc9w.js} +1 -1
  42. package/dist/{index-tvh3y650.js → index-edafv9d7.js} +5 -5
  43. package/dist/{index-8gzmeyae.js → index-ff1hqh4a.js} +3 -3
  44. package/dist/{index-ke0mkz7g.js → index-g1h1efr0.js} +1 -1
  45. package/dist/{index-f455a0g3.js → index-k37h4yrb.js} +5 -3
  46. package/dist/{index-3rp2b482.js → index-mg6cwqw2.js} +217 -24
  47. package/dist/{index-4536jdzj.js → index-xzs1fxzz.js} +2 -2
  48. package/dist/{index-hyvxmz3e.js → index-y1875y4h.js} +1 -1
  49. package/dist/{index-4v50y0jr.js → index-ydevzvfs.js} +1 -1
  50. package/dist/{index-ab86c21b.js → index-zj0ra8vs.js} +1 -1
  51. package/dist/index.js +50 -59
  52. package/dist/migration-worker.js +3 -3
  53. package/dist/{project-embedding-registry-1n4cexsv.js → project-embedding-registry-0z0nd73p.js} +3 -3
  54. package/dist/raw-ordinal-warmup-worker.js +2 -2
  55. package/dist/{recomp-orchestrator-16rs8aty.js → recomp-orchestrator-zagjzbz5.js} +12 -12
  56. package/dist/{render-f32trg2t.js → render-vwp72qd0.js} +6 -6
  57. package/dist/{search-v9ywqb4f.js → search-7e1rcqb7.js} +9 -9
  58. package/dist/{search-archive-yh6xtvrx.js → search-archive-6tr0gcf7.js} +2 -2
  59. package/dist/shared/sqlite-busy-test-support.d.ts +21 -0
  60. package/dist/shared/sqlite-busy-test-support.d.ts.map +1 -0
  61. package/dist/shared/sqlite-write-locker-test-support.d.ts +12 -0
  62. package/dist/shared/sqlite-write-locker-test-support.d.ts.map +1 -1
  63. package/dist/{store-wpx314rk.js → store-4eeezg83.js} +2 -2
  64. package/dist/{store-reader-c5fwa9qx.js → store-reader-g8w2wp88.js} +1 -1
  65. package/dist/{transform-postprocess-phase-yef4mxk3.js → transform-postprocess-phase-v3p3q2gf.js} +13 -13
  66. package/dist/v2/auto-search-worker.js +3 -3
  67. package/dist/v2/chunk-embedding-write-worker.js +8 -5
  68. package/dist/v2/{context-mk2h2ven.js → context-fbdac7qt.js} +163 -147
  69. package/dist/v2/{embedding-backfill-kyn5sv0f.js → embedding-backfill-e44pv5db.js} +4 -4
  70. package/dist/v2/event-subscription.fixture.d.ts +9 -0
  71. package/dist/v2/event-subscription.fixture.d.ts.map +1 -0
  72. package/dist/v2/hidden-model-activity.d.ts +13 -0
  73. package/dist/v2/hidden-model-activity.d.ts.map +1 -1
  74. package/dist/v2/hooks/context.d.ts +1 -0
  75. package/dist/v2/hooks/context.d.ts.map +1 -1
  76. package/dist/v2/hooks/dream-trigger.d.ts +2 -1
  77. package/dist/v2/hooks/dream-trigger.d.ts.map +1 -1
  78. package/dist/v2/hooks/event-subscription-worker.d.ts +11 -0
  79. package/dist/v2/hooks/event-subscription-worker.d.ts.map +1 -0
  80. package/dist/v2/hooks/types.d.ts +1 -0
  81. package/dist/v2/hooks/types.d.ts.map +1 -1
  82. package/dist/v2/hooks/update-check.d.ts +1 -0
  83. package/dist/v2/hooks/update-check.d.ts.map +1 -1
  84. package/dist/v2/{message-index-bounded-j1sxtefe.js → message-index-bounded-nwqfb1p5.js} +3 -3
  85. package/dist/v2/migration-worker.js +3 -3
  86. package/dist/v2/{project-embedding-registry-1jv2rxhb.js → project-embedding-registry-rhzjnypp.js} +3 -3
  87. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  88. package/dist/v2/{read-session-chunk-p6z3kmdj.js → read-session-chunk-brqatg83.js} +2 -2
  89. package/dist/v2/{recomp-orchestrator-5t2csd46.js → recomp-orchestrator-1ech6k2n.js} +14 -14
  90. package/dist/v2/{render-jpj43axy.js → render-pfe3smhx.js} +10 -10
  91. package/dist/v2/{search-archive-wbhxp0p1.js → search-archive-r8krrz47.js} +5 -5
  92. package/dist/v2/{search-w9m2fd5c.js → search-sffewrs4.js} +12 -12
  93. package/dist/v2/{server-47ajg9xc.js → server-16115spd.js} +1 -1
  94. package/dist/v2/server-28jqb7s0.js +6 -0
  95. package/dist/v2/{server-qg8jyfxa.js → server-5xx10mqe.js} +1 -1
  96. package/dist/v2/{server-t45hgcsg.js → server-7jw608jk.js} +2 -2
  97. package/dist/v2/{server-8f92sd2r.js → server-7pxjk184.js} +6 -4
  98. package/dist/v2/{server-3mb205v9.js → server-83rjf4df.js} +1 -1
  99. package/dist/v2/{server-3gnpqjez.js → server-9t4yjj20.js} +26 -11
  100. package/dist/v2/{server-ga6y57vh.js → server-c32505fr.js} +6 -4
  101. package/dist/v2/{server-8m5wk6aq.js → server-cpb7b1f9.js} +5 -5
  102. package/dist/v2/{server-qdpd8h27.js → server-fn6k1ack.js} +1 -1
  103. package/dist/v2/{server-zsbc0n4v.js → server-ghb2q1z9.js} +1 -1
  104. package/dist/v2/{server-af51b1zg.js → server-hqcdvs2n.js} +11 -11
  105. package/dist/v2/{server-9ms9b75c.js → server-j00jprwm.js} +4 -6
  106. package/dist/v2/{server-xpy46ddq.js → server-jtd5vq5e.js} +3 -3
  107. package/dist/v2/{server-b01a7dhj.js → server-kk2kbzq3.js} +1 -1
  108. package/dist/v2/{server-mc5t7k8v.js → server-ma0qhqg9.js} +1 -1
  109. package/dist/v2/{server-x22jtpna.js → server-n3bfqd0j.js} +4 -2
  110. package/dist/v2/{server-wmpgvvc4.js → server-pjvqyg6g.js} +365 -113
  111. package/dist/v2/{server-jrs4gny6.js → server-qtajgx1e.js} +89 -1
  112. package/dist/v2/server-t104h957.js +177 -0
  113. package/dist/v2/{server-j09jx1n9.js → server-v2r04xds.js} +1 -1
  114. package/dist/v2/{server-7c5p0bh1.js → server-z77hman6.js} +1 -1
  115. package/dist/v2/server.js +31 -40
  116. package/dist/v2/{storage-tags-s7nvvyg8.js → storage-tags-ee72g2zv.js} +1 -1
  117. package/dist/v2/{store-mba47sxn.js → store-9rsrj5pt.js} +2 -2
  118. package/dist/v2/{store-reader-w7w8vfsy.js → store-reader-tb0f9621.js} +1 -1
  119. package/dist/v2/store-reader.d.ts +1 -1
  120. package/dist/v2/store-reader.d.ts.map +1 -1
  121. package/dist/v2/tui/index.d.ts.map +1 -1
  122. package/dist/v2/{v2-archive-reader-5njmg3a3.js → v2-archive-reader-0xysfgxh.js} +1 -1
  123. package/dist/v2/{wrapup-orchestrator-ykgx8hw8.js → wrapup-orchestrator-8d4ak3x3.js} +14 -14
  124. package/dist/{v2-archive-reader-y38khjax.js → v2-archive-reader-fac1zmhj.js} +1 -1
  125. package/dist/{wrapup-orchestrator-a9tshrp4.js → wrapup-orchestrator-wz10b94c.js} +13 -13
  126. package/package.json +1 -1
  127. package/src/config/migrate-config-location.test.ts +41 -29
  128. package/src/shared/model-suggestion-retry.test.ts +137 -90
  129. package/src/shared/off-thread-migration-clock.test.ts +19 -9
  130. package/src/shared/prompt-async-transport.test.ts +125 -42
  131. package/src/shared/rpc-async-probes.test.ts +56 -36
  132. package/src/shared/rpc-client.test.ts +51 -18
  133. package/src/shared/sqlite-acquisition-routing.test.ts +79 -22
  134. package/src/shared/sqlite-busy-budget-review.test.ts +129 -111
  135. package/src/shared/sqlite-busy-test-support.ts +154 -0
  136. package/src/shared/sqlite-foreground-wait.test.ts +213 -156
  137. package/src/shared/sqlite-pass-scope.test.ts +142 -105
  138. package/src/shared/sqlite-turn-deadline.test.ts +149 -124
  139. package/src/shared/sqlite-write-locker-test-support.ts +44 -12
  140. package/src/shared/stable-json-linear.test.ts +29 -11
  141. package/src/shared/startup-maintenance-policy.test.ts +72 -2
  142. package/src/shared/storage-busy.test.ts +45 -18
  143. package/src/shared/storage-file-mutex-review.test.ts +65 -51
  144. package/src/shared/tui-preferences.test.ts +15 -5
  145. package/src/shared/worker-shutdown.test.ts +26 -20
  146. package/src/tui/data/notification-socket.test.ts +220 -108
  147. package/src/v2/tui/index.ts +5 -1
  148. package/src/v2/tui/status-dialog-fallback.test.ts +23 -1
  149. package/dist/v2/server-84w6rvvf.js +0 -14
@@ -1,4 +1,4 @@
1
- import { describe, expect, it } from "bun:test";
1
+ import { describe, expect, it, spyOn } from "bun:test";
2
2
  import {
3
3
  existsSync,
4
4
  mkdirSync,
@@ -10,6 +10,7 @@ import {
10
10
  } from "node:fs";
11
11
  import { tmpdir } from "node:os";
12
12
  import { join } from "node:path";
13
+ import * as storagePermissions from "../shared/storage-permissions";
13
14
  import { createTestTempDirFromPath } from "../shared/test-temp-dir";
14
15
  import {
15
16
  type LegacyConfigSource,
@@ -25,6 +26,20 @@ function src(path: string, label = "legacy"): LegacyConfigSource {
25
26
  return { path, label };
26
27
  }
27
28
 
29
+ function observeMigrationLock(lockDir: string, age: number) {
30
+ mkdirSync(lockDir, { recursive: true });
31
+ utimesSync(lockDir, 1_700_000_000, 1_700_000_000);
32
+ const now = spyOn(Date, "now").mockReturnValue(statSync(lockDir).mtimeMs + age);
33
+ const mkdir = spyOn(storagePermissions, "ensureStorageDirectorySync");
34
+ return {
35
+ attempts: () => mkdir.mock.calls.filter(([path]) => path === lockDir).length,
36
+ restore() {
37
+ mkdir.mockRestore();
38
+ now.mockRestore();
39
+ },
40
+ };
41
+ }
42
+
28
43
  describe("migrateConfigFile (location migration)", () => {
29
44
  it("writes a user config migration with owner-only permissions", () => {
30
45
  if (process.platform === "win32") return;
@@ -67,58 +82,55 @@ describe("migrateConfigFile (location migration)", () => {
67
82
 
68
83
  it("reclaims a stale (crashed-holder) lock in one shot without blocking init", () => {
69
84
  const dir = tmp();
85
+ const target = join(dir, ".cortexkit", "magic-context.jsonc");
86
+ const lockDir = `${target}.lock`;
87
+ const lock = observeMigrationLock(lockDir, 4_001);
70
88
  try {
71
- const target = join(dir, ".cortexkit", "magic-context.jsonc");
72
89
  const legacy = join(dir, "magic-context.jsonc");
73
90
  writeFileSync(legacy, '{"enabled":false}');
74
- // A leftover lock dir from a crashed holder, aged past the stale
75
- // threshold. The non-blocking lock removes it and re-attempts mkdir
76
- // once (no busy-wait, no synchronous sleep), so migration proceeds
77
- // and init is never frozen.
78
- const lockDir = `${target}.lock`;
79
- mkdirSync(lockDir, { recursive: true });
80
- // Backdate the lock dir's mtime well past CONFIG_LOCK_STALE_MS (4s).
81
- const old = Date.now() - 60_000;
82
- utimesSync(lockDir, new Date(old), new Date(old));
83
- const start = Date.now();
84
91
  const r = migrateConfigFile({
85
92
  scope: "project",
86
93
  targetPath: target,
87
94
  legacySources: [src(legacy)],
88
95
  });
89
- const elapsed = Date.now() - start;
90
- // Effectively instant — no timeout budget is ever waited.
91
- expect(elapsed).toBeLessThan(1_000);
96
+ expect(lock.attempts()).toBe(2);
92
97
  expect(r.migrated).toBe(true);
93
98
  expect(existsSync(target)).toBe(true);
99
+ expect(existsSync(lockDir)).toBe(false);
94
100
  } finally {
101
+ lock.restore();
95
102
  rmSync(dir, { recursive: true, force: true });
96
103
  }
97
104
  });
98
105
 
99
106
  it("skips migration this run (no block) when a LIVE holder owns the lock", () => {
100
107
  const dir = tmp();
108
+ const target = join(dir, ".cortexkit", "magic-context.jsonc");
109
+ const lockDir = `${target}.lock`;
110
+ // Age equal to the stale threshold must still be treated as live. The
111
+ // fixture owns the directory until it explicitly removes it.
112
+ const lock = observeMigrationLock(lockDir, 4_000);
101
113
  try {
102
- const target = join(dir, ".cortexkit", "magic-context.jsonc");
103
114
  const legacy = join(dir, "magic-context.jsonc");
104
115
  writeFileSync(legacy, '{"enabled":false}');
105
- // A FRESH lock dir (live holder, not stale): we must not block waiting
106
- // for it — return immediately with migrated:false and leave the
107
- // target absent (the loader read-legacy-on-conflict covers this run;
108
- // the next init retries once the holder releases).
109
- mkdirSync(`${target}.lock`, { recursive: true });
110
- const start = Date.now();
111
- const r = migrateConfigFile({
112
- scope: "project",
113
- targetPath: target,
114
- legacySources: [src(legacy)],
115
- });
116
- const elapsed = Date.now() - start;
117
- expect(elapsed).toBeLessThan(1_000);
116
+ const migrate = () =>
117
+ migrateConfigFile({
118
+ scope: "project",
119
+ targetPath: target,
120
+ legacySources: [src(legacy)],
121
+ });
122
+ const r = migrate();
123
+ expect(lock.attempts()).toBe(1);
118
124
  expect(r.migrated).toBe(false);
119
125
  expect(r.conflict).toBe(false);
120
126
  expect(existsSync(target)).toBe(false);
127
+ expect(existsSync(lockDir)).toBe(true);
128
+ expect(existsSync(legacy)).toBe(true);
129
+ rmSync(lockDir, { recursive: true });
130
+ expect(migrate().migrated).toBe(true);
131
+ expect(lock.attempts()).toBe(2);
121
132
  } finally {
133
+ lock.restore();
122
134
  rmSync(dir, { recursive: true, force: true });
123
135
  }
124
136
  });
@@ -41,7 +41,34 @@ function createArgs(model?: { providerID: string; modelID: string }) {
41
41
  };
42
42
  }
43
43
 
44
+ function pendingCarrier(onAbort: "resolve" | "reject" | "ignore") {
45
+ const entered = Promise.withResolvers<void>();
46
+ const carrier = ({ signal }: { signal?: AbortSignal }) => {
47
+ const reply = new Promise<void>((resolve, reject) => {
48
+ if (onAbort === "resolve") signal?.addEventListener("abort", () => resolve());
49
+ if (onAbort === "reject")
50
+ signal?.addEventListener("abort", () => reject(new Error("aborted")));
51
+ });
52
+ entered.resolve();
53
+ return reply;
54
+ };
55
+ return { carrier, entered: entered.promise };
56
+ }
57
+
58
+ function freezeTime() {
59
+ jest.useFakeTimers({ doNotFake: ["setImmediate"] });
60
+ jest.setSystemTime(new Date("2026-08-11T12:00:00Z"));
61
+ }
62
+
63
+ async function advance(ms: number) {
64
+ jest.advanceTimersByTime(ms);
65
+ // Let the attempt's rejection and the next attempt's startup settle.
66
+ await new Promise<void>((resolve) => setImmediate(resolve));
67
+ }
68
+
44
69
  describe("promptSyncWithModelSuggestionRetry", () => {
70
+ afterEach(() => jest.useRealTimers());
71
+
45
72
  test("synchronous prompt completion retains await semantics with cancellation", async () => {
46
73
  const prompt = mock(() => undefined);
47
74
  const abort = mock(async () => ({}));
@@ -238,42 +265,44 @@ describe("promptSyncWithModelSuggestionRetry", () => {
238
265
  // session.abort — cancelling our client fetch alone leaves the child looping
239
266
  // the LLM past the timeout (uncancellable, only dies on process exit).
240
267
  test("timeout fires session.abort on the child session", async () => {
241
- // A prompt that respects the AbortController by hanging until aborted,
242
- // then throwing — mirrors a real in-flight request our timeout cancels.
243
- const prompt = mock((opts: { signal?: AbortSignal }) => {
244
- return new Promise((_resolve, reject) => {
245
- opts.signal?.addEventListener("abort", () => reject(new Error("aborted")));
246
- });
247
- });
268
+ freezeTime();
269
+ const { carrier, entered } = pendingCarrier("reject");
270
+ const prompt = mock(carrier);
248
271
  const abort = mock(async () => ({}));
249
- const client = createClient(prompt as never, abort);
272
+ const client = createClient(prompt, abort);
250
273
 
251
- await expect(
252
- promptSyncWithModelSuggestionRetry(client, createArgs(), { timeoutMs: 20 }),
253
- ).rejects.toThrow(/timed out/);
274
+ const run = promptSyncWithModelSuggestionRetry(client, createArgs(), {
275
+ timeoutMs: 20,
276
+ }).catch((error: unknown) => error);
277
+ await entered;
278
+ await advance(19);
279
+ expect(abort).not.toHaveBeenCalled();
280
+ await advance(1);
254
281
  expect(abort).toHaveBeenCalledTimes(1);
255
282
  expect((abort.mock.calls[0]?.[0] as { path: { id: string } }).path.id).toBe("ses-test");
283
+ expect(await run).toEqual(new Error("prompt timed out after 20ms"));
256
284
  });
257
285
 
258
286
  test("timeout with a resolving transport still aborts the child", async () => {
287
+ freezeTime();
259
288
  const abort = mock(async () => ({}));
260
289
  const client = createClient(
261
290
  mock(async () => ({})),
262
291
  abort,
263
292
  );
264
- const transport = Object.assign(
265
- ({ signal }: { signal?: AbortSignal }) =>
266
- new Promise<void>((resolve) => signal?.addEventListener("abort", () => resolve())),
267
- { childSessionId: "child-test" },
268
- );
269
- await expect(
270
- promptSyncWithModelSuggestionRetry(client, createArgs(), {
271
- timeoutMs: 10,
272
- transport,
273
- }),
274
- ).rejects.toThrow("prompt timed out after 10ms");
293
+ const { carrier, entered } = pendingCarrier("resolve");
294
+ const transport = Object.assign(carrier, { childSessionId: "child-test" });
295
+ const run = promptSyncWithModelSuggestionRetry(client, createArgs(), {
296
+ timeoutMs: 10,
297
+ transport,
298
+ }).catch((error: unknown) => error);
299
+ await entered;
300
+ await advance(9);
301
+ expect(abort).not.toHaveBeenCalled();
302
+ await advance(1);
275
303
  expect(abort).toHaveBeenCalledTimes(1);
276
304
  expect((abort.mock.calls[0]?.[0] as { path: { id: string } }).path.id).toBe("child-test");
305
+ expect(await run).toEqual(new Error("prompt timed out after 10ms"));
277
306
  });
278
307
 
279
308
  test("external abort with a resolving transport still aborts the child", async () => {
@@ -283,57 +312,58 @@ describe("promptSyncWithModelSuggestionRetry", () => {
283
312
  mock(async () => ({})),
284
313
  abort,
285
314
  );
286
- const transport = Object.assign(
287
- ({ signal }: { signal?: AbortSignal }) =>
288
- new Promise<void>((resolve) => signal?.addEventListener("abort", () => resolve())),
289
- { childSessionId: "child-test" },
290
- );
291
- setTimeout(() => controller.abort(), 10);
292
- await expect(
293
- promptSyncWithModelSuggestionRetry(client, createArgs(), {
294
- signal: controller.signal,
295
- transport,
296
- }),
297
- ).rejects.toThrow("prompt aborted by external signal");
315
+ const { carrier, entered } = pendingCarrier("resolve");
316
+ const transport = Object.assign(carrier, { childSessionId: "child-test" });
317
+ const run = promptSyncWithModelSuggestionRetry(client, createArgs(), {
318
+ signal: controller.signal,
319
+ transport,
320
+ }).catch((error: unknown) => error);
321
+ await entered;
322
+ controller.abort();
323
+ await new Promise<void>((resolve) => setImmediate(resolve));
298
324
  expect(abort).toHaveBeenCalledTimes(1);
325
+ expect(await run).toEqual(new Error("prompt aborted by external signal"));
299
326
  });
300
327
 
301
328
  // External abort (e.g. dreamer lease loss) mid-flight must also stop the
302
329
  // server-side loop, not just our fetch.
303
330
  test("external abort fires session.abort on the child session", async () => {
304
331
  const controller = new AbortController();
305
- const prompt = mock((opts: { signal?: AbortSignal }) => {
306
- return new Promise((_resolve, reject) => {
307
- opts.signal?.addEventListener("abort", () => reject(new Error("aborted")));
308
- });
309
- });
332
+ const { carrier, entered } = pendingCarrier("reject");
333
+ const prompt = mock(carrier);
310
334
  const abort = mock(async () => ({}));
311
- const client = createClient(prompt as never, abort);
335
+ const client = createClient(prompt, abort);
312
336
 
313
- setTimeout(() => controller.abort(new Error("lease_lost: taken by holder-b")), 10);
314
- await expect(
315
- promptSyncWithModelSuggestionRetry(client, createArgs(), { signal: controller.signal }),
316
- ).rejects.toThrow("prompt aborted by external signal: lease_lost: taken by holder-b");
337
+ const run = promptSyncWithModelSuggestionRetry(client, createArgs(), {
338
+ signal: controller.signal,
339
+ }).catch((error: unknown) => error);
340
+ await entered;
341
+ controller.abort(new Error("lease_lost: taken by holder-b"));
342
+ await new Promise<void>((resolve) => setImmediate(resolve));
317
343
  expect(abort).toHaveBeenCalledTimes(1);
318
344
  expect((abort.mock.calls[0]?.[0] as { path: { id: string } }).path.id).toBe("ses-test");
345
+ expect(await run).toEqual(
346
+ new Error("prompt aborted by external signal: lease_lost: taken by holder-b"),
347
+ );
319
348
  });
320
349
 
321
350
  // A failing session.abort must not mask the original timeout/abort error.
322
351
  test("session.abort failure does not mask the timeout error", async () => {
323
- const prompt = mock((opts: { signal?: AbortSignal }) => {
324
- return new Promise((_resolve, reject) => {
325
- opts.signal?.addEventListener("abort", () => reject(new Error("aborted")));
326
- });
327
- });
352
+ freezeTime();
353
+ const { carrier, entered } = pendingCarrier("reject");
354
+ const prompt = mock(carrier);
328
355
  const abort = mock(async () => {
329
356
  throw new Error("abort endpoint 500");
330
357
  });
331
- const client = createClient(prompt as never, abort);
358
+ const client = createClient(prompt, abort);
332
359
 
333
- await expect(
334
- promptSyncWithModelSuggestionRetry(client, createArgs(), { timeoutMs: 20 }),
335
- ).rejects.toThrow(/timed out/);
360
+ const run = promptSyncWithModelSuggestionRetry(client, createArgs(), {
361
+ timeoutMs: 20,
362
+ }).catch((error: unknown) => error);
363
+ await entered;
364
+ await advance(20);
336
365
  expect(abort).toHaveBeenCalledTimes(1);
366
+ expect(await run).toEqual(new Error("prompt timed out after 20ms"));
337
367
  });
338
368
 
339
369
  test("suggestion retry within attempt succeeds", async () => {
@@ -829,24 +859,22 @@ test("DeepSeek unsupported-model 400 preserves provider status and message rathe
829
859
  });
830
860
 
831
861
  test("timeout rejects an uncooperative carrier and aborts its child", async () => {
862
+ freezeTime();
832
863
  const abort = mock(async () => ({}));
833
- const client = createClient(
834
- mock(() => new Promise(() => {})),
835
- abort,
836
- );
837
- let timer: ReturnType<typeof setTimeout> | undefined;
864
+ const { carrier, entered } = pendingCarrier("ignore");
865
+ const client = createClient(mock(carrier), abort);
838
866
  try {
839
- await expect(
840
- Promise.race([
841
- promptSyncWithModelSuggestionRetry(client, createArgs(), { timeoutMs: 10 }),
842
- new Promise((_, reject) => {
843
- timer = setTimeout(() => reject(new Error("carrier remained stuck")), 200);
844
- }),
845
- ]),
846
- ).rejects.toThrow("prompt timed out after 10ms");
867
+ const run = promptSyncWithModelSuggestionRetry(client, createArgs(), {
868
+ timeoutMs: 10,
869
+ }).catch((error: unknown) => error);
870
+ await entered;
871
+ await advance(9);
872
+ expect(abort).not.toHaveBeenCalled();
873
+ await advance(1);
847
874
  expect(abort).toHaveBeenCalledTimes(1);
875
+ expect(await run).toEqual(new Error("prompt timed out after 10ms"));
848
876
  } finally {
849
- clearTimeout(timer);
877
+ jest.useRealTimers();
850
878
  }
851
879
  });
852
880
 
@@ -856,17 +884,6 @@ describe("first-output deadline", () => {
856
884
 
857
885
  afterEach(() => jest.useRealTimers());
858
886
 
859
- function freezeTime() {
860
- jest.useFakeTimers({ doNotFake: ["setImmediate"] });
861
- jest.setSystemTime(new Date("2026-08-11T12:00:00Z"));
862
- }
863
-
864
- async function advance(ms: number) {
865
- jest.advanceTimersByTime(ms);
866
- // Let the attempt's rejection and the next attempt's startup settle.
867
- await new Promise<void>((resolve) => setImmediate(resolve));
868
- }
869
-
870
887
  /**
871
888
  * A transport double that behaves per model. "silent" watches the child but the
872
889
  * model never answers; "partial" streams something and then hangs; "unmonitored"
@@ -923,6 +940,18 @@ describe("first-output deadline", () => {
923
940
  return { result, caught, calls, elapsedMs: Date.now() - startedAt };
924
941
  }
925
942
 
943
+ async function finishAtAttemptDeadline(pending: ReturnType<typeof run>, timeoutMs: number) {
944
+ let settled = false;
945
+ void pending.then(() => {
946
+ settled = true;
947
+ });
948
+ await advance(timeoutMs - 1);
949
+ expect(settled).toBe(false);
950
+ await advance(1);
951
+ expect(settled).toBe(true);
952
+ return pending;
953
+ }
954
+
926
955
  test("a primary that streams nothing by the deadline moves on to the fallback", async () => {
927
956
  freezeTime();
928
957
  let settled = false;
@@ -948,8 +977,9 @@ describe("first-output deadline", () => {
948
977
  });
949
978
 
950
979
  test("the unvalidated chain also moves on from a silent primary", async () => {
980
+ freezeTime();
951
981
  const { transport, calls } = modelTransport({ "opencode/free-model": "silent" });
952
- await promptSyncWithModelSuggestionRetry(
982
+ const pending = promptSyncWithModelSuggestionRetry(
953
983
  createClient(mock(async () => ({}))),
954
984
  createArgs(primary),
955
985
  {
@@ -958,17 +988,22 @@ describe("first-output deadline", () => {
958
988
  firstOutputTimeoutMs: 40,
959
989
  fallbackModels: ["anthropic/claude-sonnet-5-5"],
960
990
  },
961
- );
991
+ ).catch((error: unknown) => error);
992
+ await advance(39);
993
+ expect(calls.map((call) => call.model)).toEqual(["opencode/free-model"]);
994
+ await advance(1);
962
995
  expect(calls.map((call) => call.model)).toEqual([
963
996
  "opencode/free-model",
964
997
  "anthropic/claude-sonnet-5-5",
965
998
  ]);
999
+ expect(await pending).toBeUndefined();
966
1000
  });
967
1001
 
968
1002
  test("a primary that produced output before timing out does not fall back", async () => {
969
- const outcome = await run(
970
- { "opencode/free-model": "partial" },
971
- { timeoutMs: 120, firstOutputTimeoutMs: 20 },
1003
+ freezeTime();
1004
+ const outcome = await finishAtAttemptDeadline(
1005
+ run({ "opencode/free-model": "partial" }, { timeoutMs: 120, firstOutputTimeoutMs: 20 }),
1006
+ 120,
972
1007
  );
973
1008
  expect((outcome.caught as Error).message).toBe("prompt timed out after 120ms");
974
1009
  expect(outcome.calls).toHaveLength(1);
@@ -1000,18 +1035,26 @@ describe("first-output deadline", () => {
1000
1035
  });
1001
1036
 
1002
1037
  test("the last model in the chain is never cut for silence", async () => {
1003
- const outcome = await run(
1004
- { "opencode/free-model": "silent" },
1005
- { timeoutMs: 120, firstOutputTimeoutMs: 20, fallbackModels: [] },
1038
+ freezeTime();
1039
+ const outcome = await finishAtAttemptDeadline(
1040
+ run(
1041
+ { "opencode/free-model": "silent" },
1042
+ { timeoutMs: 120, firstOutputTimeoutMs: 20, fallbackModels: [] },
1043
+ ),
1044
+ 120,
1006
1045
  );
1007
1046
  expect((outcome.caught as Error).message).toBe("prompt timed out after 120ms");
1008
1047
  expect(outcome.calls).toHaveLength(1);
1009
1048
  });
1010
1049
 
1011
1050
  test("a transport that cannot see model output keeps the plain timeout", async () => {
1012
- const outcome = await run(
1013
- { "opencode/free-model": "unmonitored" },
1014
- { timeoutMs: 120, firstOutputTimeoutMs: 20 },
1051
+ freezeTime();
1052
+ const outcome = await finishAtAttemptDeadline(
1053
+ run(
1054
+ { "opencode/free-model": "unmonitored" },
1055
+ { timeoutMs: 120, firstOutputTimeoutMs: 20 },
1056
+ ),
1057
+ 120,
1015
1058
  );
1016
1059
  expect((outcome.caught as Error).message).toBe("prompt timed out after 120ms");
1017
1060
  expect(outcome.calls).toHaveLength(1);
@@ -1020,7 +1063,11 @@ describe("first-output deadline", () => {
1020
1063
  test("a caller without a first-output deadline keeps timeouts final", async () => {
1021
1064
  // The historian passes no first-output deadline: a silent model still ends
1022
1065
  // its chain at the timeout, exactly as before.
1023
- const outcome = await run({ "opencode/free-model": "silent" }, { timeoutMs: 120 });
1066
+ freezeTime();
1067
+ const outcome = await finishAtAttemptDeadline(
1068
+ run({ "opencode/free-model": "silent" }, { timeoutMs: 120 }),
1069
+ 120,
1070
+ );
1024
1071
  expect((outcome.caught as Error).message).toBe("prompt timed out after 120ms");
1025
1072
  expect(outcome.calls).toHaveLength(1);
1026
1073
  });
@@ -6,12 +6,6 @@ import {
6
6
  startBootDeadline,
7
7
  } from "./off-thread-migration-clock";
8
8
 
9
- const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
10
-
11
- async function expiredWithin(promise: Promise<void>, ms: number): Promise<boolean> {
12
- return Promise.race([promise.then(() => true), sleep(ms).then(() => false)]);
13
- }
14
-
15
9
  function createFakeClock() {
16
10
  let now = 0;
17
11
  let nextTimerId = 0;
@@ -20,6 +14,7 @@ function createFakeClock() {
20
14
 
21
15
  return {
22
16
  now: () => now,
17
+ timerCount: () => timers.size,
23
18
  setTimeout: (callback: () => void, delayMs: number) => {
24
19
  const id = ++nextTimerId;
25
20
  timers.set(id, { at: now + Math.max(0, delayMs), callback });
@@ -52,15 +47,25 @@ function createFakeClock() {
52
47
  }
53
48
 
54
49
  async function isSettled(promise: Promise<void>): Promise<boolean> {
55
- return Promise.race([promise.then(() => true), Promise.resolve(false)]);
50
+ let settled = false;
51
+ void promise.then(() => {
52
+ settled = true;
53
+ });
54
+ await Promise.resolve();
55
+ return settled;
56
56
  }
57
57
 
58
58
  describe("boot deadline that excludes off-thread migration time", () => {
59
59
  afterEach(() => __resetOffThreadMigrationClockForTests());
60
60
 
61
61
  test("expires on time when no migration runs", async () => {
62
+ const clock = createFakeClock();
63
+ __setOffThreadMigrationClockForTests(clock);
62
64
  const deadline = startBootDeadline(30);
63
- expect(await expiredWithin(deadline.expired, 500)).toBe(true);
65
+ clock.advanceBy(29);
66
+ expect(await isSettled(deadline.expired)).toBe(false);
67
+ clock.advanceBy(1);
68
+ expect(await isSettled(deadline.expired)).toBe(true);
64
69
  });
65
70
 
66
71
  test("does not count migration time and resumes with only the pre-migration time spent", async () => {
@@ -118,8 +123,13 @@ describe("boot deadline that excludes off-thread migration time", () => {
118
123
  });
119
124
 
120
125
  test("a cancelled deadline never expires", async () => {
126
+ const clock = createFakeClock();
127
+ __setOffThreadMigrationClockForTests(clock);
121
128
  const deadline = startBootDeadline(20);
129
+ expect(clock.timerCount()).toBe(1);
122
130
  deadline.cancel();
123
- expect(await expiredWithin(deadline.expired, 100)).toBe(false);
131
+ expect(clock.timerCount()).toBe(0);
132
+ clock.advanceBy(21);
133
+ expect(await isSettled(deadline.expired)).toBe(false);
124
134
  });
125
135
  });