mixdog 0.9.53 โ†’ 0.9.55

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 (77) hide show
  1. package/package.json +2 -1
  2. package/scripts/agent-model-liveness-test.mjs +68 -0
  3. package/scripts/anthropic-transport-policy-test.mjs +260 -0
  4. package/scripts/desktop-session-bridge-test.mjs +47 -0
  5. package/scripts/gemini-provider-test.mjs +396 -1
  6. package/scripts/grok-oauth-refresh-race-test.mjs +76 -1
  7. package/scripts/interrupted-turn-history-test.mjs +28 -0
  8. package/scripts/openai-oauth-ws-1006-retry-test.mjs +81 -1
  9. package/scripts/pending-completion-drop-test.mjs +160 -4
  10. package/scripts/pending-messages-lock-nonblocking-test.mjs +62 -0
  11. package/scripts/process-lifecycle-test.mjs +18 -4
  12. package/scripts/prompt-input-parity-test.mjs +145 -0
  13. package/scripts/provider-admission-scheduler-test.mjs +4 -5
  14. package/scripts/provider-contract-test.mjs +91 -33
  15. package/scripts/provider-toolcall-test.mjs +97 -17
  16. package/scripts/streaming-tail-window-test.mjs +146 -0
  17. package/scripts/tui-runtime-load-bench-entry.jsx +608 -0
  18. package/scripts/tui-runtime-load-bench.mjs +45 -0
  19. package/scripts/tui-store-frame-batch-test.mjs +99 -0
  20. package/scripts/tui-transcript-perf-test.mjs +367 -2
  21. package/scripts/write-backpressure-test.mjs +147 -0
  22. package/src/cli.mjs +5 -5
  23. package/src/lib/keychain-cjs.cjs +114 -25
  24. package/src/repl.mjs +11 -0
  25. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +62 -25
  26. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +8 -2
  27. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +50 -23
  28. package/src/runtime/agent/orchestrator/providers/gemini-cache.mjs +15 -4
  29. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +136 -27
  30. package/src/runtime/agent/orchestrator/providers/gemini.mjs +104 -20
  31. package/src/runtime/agent/orchestrator/providers/grok-oauth.mjs +96 -75
  32. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +40 -1
  33. package/src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs +5 -0
  34. package/src/runtime/agent/orchestrator/providers/openai-compat-wire.mjs +35 -4
  35. package/src/runtime/agent/orchestrator/providers/openai-compat-xai.mjs +3 -1
  36. package/src/runtime/agent/orchestrator/providers/openai-compat.mjs +49 -9
  37. package/src/runtime/agent/orchestrator/providers/openai-oauth-http-sse.mjs +14 -2
  38. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +9 -4
  39. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +53 -13
  40. package/src/runtime/agent/orchestrator/session/manager/ask-session.mjs +145 -23
  41. package/src/runtime/agent/orchestrator/session/manager/message-sanitize.mjs +20 -4
  42. package/src/runtime/agent/orchestrator/session/manager/pending-messages.mjs +316 -63
  43. package/src/runtime/agent/orchestrator/session/manager/turn-interruption.mjs +23 -1
  44. package/src/runtime/agent/orchestrator/session/store.mjs +46 -1
  45. package/src/runtime/agent/orchestrator/stall-policy.mjs +6 -13
  46. package/src/runtime/memory/lib/trace-store.mjs +66 -4
  47. package/src/runtime/shared/buffered-appender.mjs +83 -4
  48. package/src/runtime/shared/memory-snapshot.mjs +45 -36
  49. package/src/runtime/shared/process-lifecycle.mjs +166 -45
  50. package/src/runtime/shared/process-shutdown.mjs +2 -1
  51. package/src/session-runtime/model-route-api.mjs +4 -1
  52. package/src/session-runtime/native-search.mjs +4 -2
  53. package/src/session-runtime/provider-auth-api.mjs +8 -1
  54. package/src/session-runtime/provider-models.mjs +8 -3
  55. package/src/session-runtime/resource-api.mjs +2 -1
  56. package/src/session-runtime/runtime-core.mjs +32 -0
  57. package/src/session-runtime/session-turn-api.mjs +1 -0
  58. package/src/session-runtime/warmup-schedulers.mjs +5 -1
  59. package/src/standalone/agent-tool.mjs +19 -1
  60. package/src/tui/App.jsx +10 -4
  61. package/src/tui/app/text-layout.mjs +9 -1
  62. package/src/tui/app/transcript-window.mjs +146 -60
  63. package/src/tui/app/use-mouse-input.mjs +16 -8
  64. package/src/tui/app/use-transcript-scroll.mjs +71 -19
  65. package/src/tui/app/use-transcript-window.mjs +21 -10
  66. package/src/tui/components/PromptInput.jsx +13 -6
  67. package/src/tui/dist/index.mjs +1094 -232
  68. package/src/tui/engine/context-state.mjs +31 -31
  69. package/src/tui/engine/frame-batched-store.mjs +75 -0
  70. package/src/tui/engine/session-api-ext.mjs +6 -1
  71. package/src/tui/engine/session-api.mjs +9 -3
  72. package/src/tui/engine/session-flow.mjs +54 -27
  73. package/src/tui/engine/turn.mjs +44 -3
  74. package/src/tui/engine.mjs +515 -36
  75. package/src/tui/input-editing.mjs +33 -13
  76. package/src/tui/markdown/measure-rendered-rows.mjs +117 -5
  77. package/vendor/ink/build/ink.js +8 -16
@@ -6,7 +6,7 @@
6
6
  // Genuine user/steering messages survive with order preserved in both paths.
7
7
  import test from 'node:test';
8
8
  import assert from 'node:assert/strict';
9
- import { mkdtempSync, rmSync, readFileSync } from 'node:fs';
9
+ import { mkdtempSync, rmSync, readFileSync, writeFileSync } from 'node:fs';
10
10
  import { tmpdir } from 'node:os';
11
11
  import { join } from 'node:path';
12
12
 
@@ -18,10 +18,16 @@ process.env.MIXDOG_DATA_DIR = dataDir;
18
18
  const {
19
19
  enqueuePendingMessage,
20
20
  drainPendingMessages,
21
+ hydratePendingMessages,
22
+ acknowledgePendingMessages,
23
+ recordPendingMessageDelivery,
24
+ finalizePendingMessageDelivery,
25
+ releasePendingMessages,
21
26
  COMPLETION_NOTIFICATION_KIND,
22
27
  markCompletionEntry,
23
28
  _dropPendingMessageState,
24
29
  } = await import('../src/runtime/agent/orchestrator/session/manager/pending-messages.mjs');
30
+ const texts = (entries) => entries.map((m) => (typeof m === 'string' ? m : m.text));
25
31
 
26
32
  test('live drain delivers the completion notification and keeps user order', () => {
27
33
  const sid = 'sess_live_1';
@@ -30,10 +36,12 @@ test('live drain delivers the completion notification and keeps user order', ()
30
36
  enqueuePendingMessage(sid, 'user second');
31
37
 
32
38
  // In-memory queue is populated (live, same process) โ†’ completion survives.
33
- const drained = drainPendingMessages(sid).map((m) => (typeof m === 'string' ? m : m.text));
39
+ const delivered = drainPendingMessages(sid);
40
+ const drained = texts(delivered);
34
41
  assert.ok(drained.includes('user first') && drained.includes('user second'), 'user messages kept');
35
42
  assert.ok(drained.some((t) => /finished/.test(t)), 'live completion delivered, not dropped');
36
43
  assert.ok(drained.indexOf('user first') < drained.indexOf('user second'), 'user order preserved');
44
+ acknowledgePendingMessages(sid, delivered);
37
45
  });
38
46
 
39
47
  test('live drain preserves interleaved [user, completion, user] order', () => {
@@ -46,12 +54,28 @@ test('live drain preserves interleaved [user, completion, user] order', () => {
46
54
  enqueuePendingMessage(sid, markCompletionEntry('Async agent task zzz finished.\n\nResult:\n> done'));
47
55
  enqueuePendingMessage(sid, 'user second');
48
56
 
49
- const drained = drainPendingMessages(sid).map((m) => (typeof m === 'string' ? m : m.text));
57
+ const delivered = drainPendingMessages(sid);
58
+ const drained = texts(delivered);
50
59
  const first = drained.indexOf('user first');
51
60
  const second = drained.indexOf('user second');
52
61
  const completion = drained.findIndex((t) => /finished/.test(t));
53
62
  assert.ok(completion !== -1, 'completion present in live drain');
54
63
  assert.ok(first < completion && completion < second, 'completion stays between the two users');
64
+ acknowledgePendingMessages(sid, delivered);
65
+ });
66
+
67
+ test('live drain asynchronously removes already-flushed persisted copies', async () => {
68
+ const sid = 'sess_live_flushed';
69
+ enqueuePendingMessage(sid, 'already flushed');
70
+ await new Promise((r) => setImmediate(r));
71
+ await new Promise((r) => setTimeout(r, 30));
72
+
73
+ const delivered = drainPendingMessages(sid);
74
+ assert.deepEqual(texts(delivered), ['already flushed']);
75
+ acknowledgePendingMessages(sid, delivered);
76
+ await new Promise((r) => setTimeout(r, 30));
77
+ const store = JSON.parse(readFileSync(join(dataDir, 'session-pending-messages.json'), 'utf8'));
78
+ assert.equal(store.sessions[sid], undefined, 'delivered live copy removed without a sync drain');
55
79
  });
56
80
 
57
81
  test('resume drain drops the completion notification, keeps user messages in order', async () => {
@@ -70,14 +94,146 @@ test('resume drain drops the completion notification, keeps user messages in ord
70
94
  assert.equal(marked.length, 1, 'completion notification persisted as a marked object');
71
95
  _dropPendingMessageState(sid, { clearPersisted: false });
72
96
 
73
- const drained = drainPendingMessages(sid).map((m) => (typeof m === 'string' ? m : m.text));
97
+ await hydratePendingMessages(sid);
98
+ const delivered = drainPendingMessages(sid);
99
+ const drained = texts(delivered);
74
100
  assert.deepEqual(drained, ['user first', 'user second'], 'completion dropped on resume; user order kept');
75
101
  assert.ok(!drained.some((t) => /finished/.test(t)), 'no completion prose replayed on resume');
102
+ acknowledgePendingMessages(sid, delivered);
76
103
 
77
104
  // A second drain yields nothing โ€” the completion was discarded, not deferred.
78
105
  assert.deepEqual(drainPendingMessages(sid), []);
79
106
  });
80
107
 
108
+ test('hydrate crash before publish leaves durable entries for replay', async () => {
109
+ const sid = 'sess_hydrate_crash';
110
+ enqueuePendingMessage(sid, 'survives crash window');
111
+ await new Promise((r) => setImmediate(r));
112
+ await new Promise((r) => setTimeout(r, 30));
113
+ await hydratePendingMessages(sid, { beforePublish: () => { throw new Error('simulated crash'); } });
114
+ const store = JSON.parse(readFileSync(join(dataDir, 'session-pending-messages.json'), 'utf8'));
115
+ assert.equal(store.sessions[sid].length, 1, 'hydrate never deletes before memory publish');
116
+ await hydratePendingMessages(sid);
117
+ const delivered = drainPendingMessages(sid);
118
+ assert.deepEqual(texts(delivered), ['survives crash window']);
119
+ acknowledgePendingMessages(sid, delivered);
120
+ });
121
+
122
+ test('ids preserve identical foreign messages and dedupe only replay copies', async () => {
123
+ const sid = 'sess_identical_ids';
124
+ enqueuePendingMessage(sid, 'identical');
125
+ enqueuePendingMessage(sid, 'identical');
126
+ await new Promise((r) => setImmediate(r));
127
+ await new Promise((r) => setTimeout(r, 30));
128
+ await hydratePendingMessages(sid);
129
+ const delivered = drainPendingMessages(sid);
130
+ assert.equal(delivered.length, 2, 'same text with distinct ids is delivered twice');
131
+ assert.notEqual(delivered[0].id, delivered[1].id);
132
+ acknowledgePendingMessages(sid, [delivered[0]]);
133
+ releasePendingMessages(sid, [delivered[1]]);
134
+ await new Promise((r) => setTimeout(r, 30));
135
+ const store = JSON.parse(readFileSync(join(dataDir, 'session-pending-messages.json'), 'utf8'));
136
+ assert.deepEqual(store.sessions[sid].map((entry) => entry.id), [delivered[1].id], 'ack removes only the matching id');
137
+ });
138
+
139
+ test('post-completion hydration sweep picks up a late foreign spool entry', async () => {
140
+ const sid = 'sess_late_foreign';
141
+ await hydratePendingMessages(sid);
142
+ const spool = join(dataDir, 'session-pending-messages.json');
143
+ const store = JSON.parse(readFileSync(spool, 'utf8'));
144
+ store.sessions[sid] = [{ id: 'foreign_late_id', message: 'late foreign message', enqueuedAt: Date.now() }];
145
+ store.sessionTouchedAt[sid] = Date.now();
146
+ writeFileSync(spool, JSON.stringify(store));
147
+
148
+ assert.equal(await hydratePendingMessages(sid), 1);
149
+ const delivered = drainPendingMessages(sid);
150
+ assert.deepEqual(texts(delivered), ['late foreign message']);
151
+ acknowledgePendingMessages(sid, delivered);
152
+ });
153
+
154
+ test('enqueue replaces caller ids and delivery tracking stays session-scoped', () => {
155
+ const firstSid = 'sess_untrusted_id_a';
156
+ const secondSid = 'sess_untrusted_id_b';
157
+ enqueuePendingMessage(firstSid, { id: 'caller_id', content: 'first', text: 'first' });
158
+ enqueuePendingMessage(secondSid, { id: 'caller_id', content: 'second', text: 'second' });
159
+ const first = drainPendingMessages(firstSid);
160
+ const second = drainPendingMessages(secondSid);
161
+ assert.notEqual(first[0].id, 'caller_id');
162
+ assert.notEqual(second[0].id, 'caller_id');
163
+ assert.notEqual(first[0].id, second[0].id);
164
+ releasePendingMessages(firstSid, first);
165
+ releasePendingMessages(secondSid, second);
166
+ });
167
+
168
+ test('over-512 unconfirmed ledger IDs are retained and suppress restart replay', async () => {
169
+ const sid = 'sess_delivered_ledger';
170
+ const session = { id: sid, deliveredPendingMessageIds: [] };
171
+ const entries = Array.from({ length: 600 }, (_, i) => ({
172
+ id: `delivered_${i}`,
173
+ content: `message ${i}`,
174
+ text: `message ${i}`,
175
+ enqueuedAt: i + 1,
176
+ }));
177
+ recordPendingMessageDelivery(session, entries);
178
+ assert.equal(session.deliveredPendingMessageIds.length, 600, 'unconfirmed ids are never evicted');
179
+
180
+ const { saveSession, setLiveSession, loadSession } = await import('../src/runtime/agent/orchestrator/session/store.mjs');
181
+ saveSession({ ...session, owner: 'user', createdAt: Date.now(), updatedAt: Date.now(), messages: [] });
182
+ setLiveSession(null);
183
+ const spool = join(dataDir, 'session-pending-messages.json');
184
+ const store = JSON.parse(readFileSync(spool, 'utf8'));
185
+ store.sessions[sid] = [{ id: 'delivered_0', message: 'old surviving spool entry', enqueuedAt: Date.now() }];
186
+ store.sessionTouchedAt[sid] = Date.now();
187
+ writeFileSync(spool, JSON.stringify(store));
188
+ assert.equal(await hydratePendingMessages(sid), 0);
189
+ assert.deepEqual(drainPendingMessages(sid), []);
190
+ setLiveSession(null);
191
+ assert.equal(
192
+ loadSession(sid).deliveredPendingMessageIds.includes('delivered_0'),
193
+ false,
194
+ 'restart cleanup prunes its now-confirmed id from the durable ledger',
195
+ );
196
+ assert.equal(loadSession(sid).deliveredPendingMessageIds.length, 0, 'spool-absent ledger ids are stale too');
197
+ });
198
+
199
+ test('hydration prunes a ledger id whose spool entry was already deleted', async () => {
200
+ const sid = 'sess_orphaned_ledger_id';
201
+ const { saveSession, setLiveSession, loadSession } = await import('../src/runtime/agent/orchestrator/session/store.mjs');
202
+ saveSession({
203
+ id: sid,
204
+ owner: 'user',
205
+ createdAt: Date.now(),
206
+ updatedAt: Date.now(),
207
+ messages: [],
208
+ deliveredPendingMessageIds: ['cleanup_committed_before_crash'],
209
+ });
210
+ setLiveSession(null);
211
+ assert.equal(await hydratePendingMessages(sid), 0);
212
+ setLiveSession(null);
213
+ assert.deepEqual(loadSession(sid).deliveredPendingMessageIds, []);
214
+ });
215
+
216
+ test('spool cleanup waits for durable ledger save', async () => {
217
+ const sid = 'sess_durable_before_ack';
218
+ enqueuePendingMessage(sid, 'ordered cleanup');
219
+ await new Promise((r) => setImmediate(r));
220
+ await new Promise((r) => setTimeout(r, 30));
221
+ const delivered = drainPendingMessages(sid);
222
+ const session = { id: sid, deliveredPendingMessageIds: [] };
223
+ recordPendingMessageDelivery(session, delivered);
224
+ let releaseSave;
225
+ const durableSave = new Promise((resolve) => { releaseSave = resolve; });
226
+ const completing = finalizePendingMessageDelivery(session, delivered, durableSave);
227
+ await new Promise((r) => setImmediate(r));
228
+ let store = JSON.parse(readFileSync(join(dataDir, 'session-pending-messages.json'), 'utf8'));
229
+ assert.equal(store.sessions[sid].length, 1, 'spool remains until ledger save is durable');
230
+ releaseSave();
231
+ await completing;
232
+ store = JSON.parse(readFileSync(join(dataDir, 'session-pending-messages.json'), 'utf8'));
233
+ assert.equal(store.sessions[sid], undefined);
234
+ assert.deepEqual(session.deliveredPendingMessageIds, []);
235
+ });
236
+
81
237
  test.after(() => {
82
238
  try { rmSync(dataDir, { recursive: true, force: true }); } catch { /* ignore */ }
83
239
  });
@@ -0,0 +1,62 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, rmSync, writeFileSync, unlinkSync, readFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+
7
+ const dataDir = mkdtempSync(join(tmpdir(), 'mixpend-lock-'));
8
+ process.env.MIXDOG_DATA_DIR = dataDir;
9
+
10
+ const {
11
+ hydratePendingMessages,
12
+ drainPendingMessages,
13
+ acknowledgePendingMessages,
14
+ } = await import('../src/runtime/agent/orchestrator/session/manager/pending-messages.mjs');
15
+
16
+ test('held pending spool lock does not block the completion-loop drain', async () => {
17
+ const sid = 'sess_lock_held';
18
+ const spool = join(dataDir, 'session-pending-messages.json');
19
+ const lock = `${spool}.lock`;
20
+ // Let the module's one-shot orphan sweep complete before reproducing the
21
+ // runtime completion scenario; the debugger lock is acquired mid-session.
22
+ await new Promise((resolve) => setImmediate(resolve));
23
+ writeFileSync(spool, JSON.stringify({
24
+ version: 1,
25
+ updatedAt: Date.now(),
26
+ sessions: { [sid]: ['persisted steering'] },
27
+ sessionTouchedAt: { [sid]: Date.now() },
28
+ }));
29
+ // A live-pid foreign token is deliberately not stale-reclaimable.
30
+ writeFileSync(lock, `${process.pid} ${Date.now()} debugger-held-lock\n`);
31
+
32
+ const started = Date.now();
33
+ let loopTickAt = 0;
34
+ const loopTick = new Promise((resolve) => {
35
+ setTimeout(() => {
36
+ loopTickAt = Date.now();
37
+ resolve();
38
+ }, 25);
39
+ });
40
+ const hydration = hydratePendingMessages(sid);
41
+
42
+ // The terminal path is synchronous but now memory-only.
43
+ assert.deepEqual(drainPendingMessages(sid), []);
44
+ await loopTick;
45
+ assert.ok(loopTickAt - started < 250, `event loop stalled ${loopTickAt - started}ms`);
46
+
47
+ await new Promise((resolve) => setTimeout(resolve, 1000));
48
+ unlinkSync(lock);
49
+ await hydration;
50
+ const delivered = drainPendingMessages(sid);
51
+ assert.deepEqual(delivered.map((entry) => entry.text), ['persisted steering']);
52
+ const stored = JSON.parse(readFileSync(spool, 'utf8'));
53
+ assert.equal(stored.sessions[sid].length, 1, 'hydrate is read-only until delivery ack');
54
+ acknowledgePendingMessages(sid, delivered);
55
+ await new Promise((resolve) => setTimeout(resolve, 30));
56
+ const acknowledged = JSON.parse(readFileSync(spool, 'utf8'));
57
+ assert.equal(acknowledged.sessions[sid], undefined);
58
+ });
59
+
60
+ test.after(() => {
61
+ try { rmSync(dataDir, { recursive: true, force: true }); } catch {}
62
+ });
@@ -104,7 +104,7 @@ test('vanished evidence uses only old-process fields and both ledger files stay
104
104
  }
105
105
  });
106
106
 
107
- test('PID reuse is detected by process identity while uncertain live identity is preserved', async () => {
107
+ test('PID reuse is detected once across a finish/rebegin while uncertain live identity is preserved', async () => {
108
108
  const root = tempRoot();
109
109
  let child;
110
110
  try {
@@ -126,7 +126,12 @@ test('PID reuse is detected by process identity while uncertain live identity is
126
126
  const name = readdirSync(paths.markerDir).find((entry) => entry.startsWith(`${child.pid}-`));
127
127
  if (name) {
128
128
  childMarker = join(paths.markerDir, name);
129
- currentIdentity = JSON.parse(readFileSync(childMarker, 'utf8')).processIdentity;
129
+ try {
130
+ currentIdentity = JSON.parse(readFileSync(childMarker, 'utf8')).processIdentity;
131
+ } catch {
132
+ await new Promise((resolve) => setTimeout(resolve, 50));
133
+ continue;
134
+ }
130
135
  if (currentIdentity?.kind === 'linux-start-ticks' || currentIdentity?.method === 'powershell') break;
131
136
  }
132
137
  await new Promise((resolve) => setTimeout(resolve, 50));
@@ -191,6 +196,12 @@ test('PID reuse is detected by process identity while uncertain live identity is
191
196
  processIdentity: currentIdentity,
192
197
  }));
193
198
  beginProcessLifecycle({ directory: root, configureReports: false });
199
+ assert.equal(finishProcessLifecycle('clean-shutdown', 0), true);
200
+ beginProcessLifecycle({ directory: root, configureReports: false });
201
+ const reapDeadline = Date.now() + 5000;
202
+ while (existsSync(reused) && Date.now() < reapDeadline) {
203
+ await new Promise((resolve) => setTimeout(resolve, 25));
204
+ }
194
205
  finishProcessLifecycle('clean-shutdown', 0);
195
206
  assert.equal(entries(paths.ledger).filter((row) => row.reason === 'prior-process-vanished').length, 2);
196
207
  assert.equal(existsSync(reused), false);
@@ -278,7 +289,7 @@ test('concurrent writers serialize rotation', async () => {
278
289
  import { beginProcessLifecycle, finishProcessLifecycle, recordCatchableFatal } from './src/runtime/shared/process-lifecycle.mjs';
279
290
  beginProcessLifecycle({ directory: process.env.LEDGER_DIR, configureReports: false });
280
291
  for (let i = 0; i < 120; i++) recordCatchableFatal(1);
281
- if (!finishProcessLifecycle('catchable-fatal-error', 1)) process.exit(4);
292
+ finishProcessLifecycle('catchable-fatal-error', 1);
282
293
  `;
283
294
  const children = Array.from({ length: 3 }, () => spawn(
284
295
  process.execPath,
@@ -295,10 +306,13 @@ test('concurrent writers serialize rotation', async () => {
295
306
  { code: 0, signal: null },
296
307
  { code: 0, signal: null },
297
308
  ]);
309
+ let records = 0;
298
310
  for (const path of [paths.ledger, paths.previousLedger]) {
311
+ if (!existsSync(path)) continue;
299
312
  assert.ok(readFileSync(path).byteLength <= LIFECYCLE_LEDGER_MAX_BYTES);
300
- entries(path);
313
+ records += entries(path).length;
301
314
  }
315
+ assert.ok(records > 0);
302
316
  assert.equal(existsSync(paths.lock), false);
303
317
  } finally {
304
318
  rmSync(root, { recursive: true, force: true });
@@ -0,0 +1,145 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+
4
+ import {
5
+ caretPosition,
6
+ offsetAtCell,
7
+ verticalOffset,
8
+ } from '../src/tui/input-editing.mjs';
9
+ import {
10
+ promptContentRows,
11
+ wrappedTextRows,
12
+ } from '../src/tui/app/text-layout.mjs';
13
+
14
+ const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
15
+
16
+ // Reference the pre-optimization behavior: enumerate every grapheme boundary,
17
+ // then independently rescan its prefix through caretPosition().
18
+ function referenceBoundaryPositions(text, width) {
19
+ const value = String(text || '');
20
+ const offsets = [0];
21
+ for (const { index, segment } of graphemeSegmenter.segment(value)) {
22
+ offsets.push(index + segment.length);
23
+ }
24
+ return [...new Set(offsets)]
25
+ .map((offset) => ({ offset, ...caretPosition(value, offset, width) }));
26
+ }
27
+
28
+ function referenceOffsetAtCell(text, row, col, width) {
29
+ const positions = referenceBoundaryPositions(text, width);
30
+ let best = positions[0];
31
+ let bestScore = Infinity;
32
+ for (const position of positions) {
33
+ const score = Math.abs(position.row - row) * 100000
34
+ + Math.abs(position.col - col);
35
+ if (score < bestScore) {
36
+ best = position;
37
+ bestScore = score;
38
+ }
39
+ }
40
+ return best.offset;
41
+ }
42
+
43
+ function referenceVerticalOffset(text, offset, width, direction, preferredColumn = null) {
44
+ const current = caretPosition(text, offset, width);
45
+ const targetColumn = Number.isFinite(preferredColumn) ? preferredColumn : current.col;
46
+ const targetRow = current.row + direction;
47
+ if (targetRow < 0) return { cursor: offset, preferredColumn: targetColumn };
48
+
49
+ const candidates = referenceBoundaryPositions(text, width)
50
+ .filter((position) => position.row === targetRow);
51
+ if (candidates.length === 0) return { cursor: offset, preferredColumn: targetColumn };
52
+
53
+ let best = candidates[0];
54
+ for (const candidate of candidates) {
55
+ const bestDistance = Math.abs(best.col - targetColumn);
56
+ const candidateDistance = Math.abs(candidate.col - targetColumn);
57
+ if (
58
+ candidateDistance < bestDistance
59
+ || (
60
+ candidateDistance === bestDistance
61
+ && candidate.col <= targetColumn
62
+ && candidate.col > best.col
63
+ )
64
+ ) {
65
+ best = candidate;
66
+ }
67
+ }
68
+ return { cursor: best.offset, preferredColumn: targetColumn };
69
+ }
70
+
71
+ const parityCases = [
72
+ { name: 'combining marks', text: 'Ae\u0301o\u0308Z' },
73
+ { name: 'emoji ZWJ sequences', text: 'a๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆb๐Ÿ‘ฉ๐Ÿฝโ€๐Ÿ’ปc' },
74
+ { name: 'wide CJK', text: 'ab็•Œ่ชžcdๆผขๅญ—' },
75
+ { name: 'newlines at wrap boundaries', text: 'abc\n123456\n็•Œa\nxyz' },
76
+ { name: 'trailing spaces', text: 'abc \nxy ' },
77
+ { name: 'tabs', text: 'a\tbc\t\n\tde' },
78
+ { name: 'ambiguous-width characters', text: 'Aยทฮฉโ€”ฮฑโ€ปB' },
79
+ ];
80
+
81
+ test('mouse hit-testing matches prefix-rescan reference for complex graphemes and wrapping', () => {
82
+ const widths = [1, 2, 3, 4, 5, 7];
83
+ for (const { name, text } of parityCases) {
84
+ for (const width of widths) {
85
+ const positions = referenceBoundaryPositions(text, width);
86
+ const lastRow = Math.max(...positions.map((position) => position.row));
87
+ for (let row = -1; row <= lastRow + 2; row += 1) {
88
+ for (let col = -1; col <= width + 2; col += 1) {
89
+ assert.equal(
90
+ offsetAtCell(text, row, col, width),
91
+ referenceOffsetAtCell(text, row, col, width),
92
+ `${name}: width=${width}, row=${row}, col=${col}`,
93
+ );
94
+ }
95
+ }
96
+ }
97
+ }
98
+ });
99
+
100
+ test('prompt row cache stays isolated across alternating text and width keys', () => {
101
+ const alternatingPairs = [
102
+ ['x', 4],
103
+ ['abcdefghijkl', 4],
104
+ ['x', 4],
105
+ ['abc็•Œ', 3],
106
+ ['abc็•Œ', 7],
107
+ ['Ae\u0301o\u0308Z', 7],
108
+ ['abc็•Œ', 3],
109
+ ['Ae\u0301o\u0308Z', 2],
110
+ ['๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ trailing ', 5],
111
+ ['abc็•Œ', 7],
112
+ ['๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ trailing ', 1],
113
+ ['Ae\u0301o\u0308Z', 2],
114
+ ];
115
+
116
+ for (const [text, width] of alternatingPairs) {
117
+ assert.equal(
118
+ promptContentRows(text, width),
119
+ wrappedTextRows(`${text} `, width),
120
+ `prompt rows: text=${JSON.stringify(text)}, width=${width}`,
121
+ );
122
+ }
123
+ });
124
+
125
+ test('vertical navigation matches reference while widths alternate between calls', () => {
126
+ // Deliberately revisit values non-consecutively so a future single-entry
127
+ // boundary/layout cache cannot accidentally reuse positions from another width.
128
+ const alternatingWidths = [2, 7, 3, 6, 1, 5, 2, 4, 7, 3];
129
+ const preferredColumns = [null, 0, 1, 3, 8];
130
+ for (const { name, text } of parityCases) {
131
+ for (const width of alternatingWidths) {
132
+ for (let offset = 0; offset <= text.length; offset += 1) {
133
+ for (const direction of [-1, 1]) {
134
+ for (const preferredColumn of preferredColumns) {
135
+ assert.deepEqual(
136
+ verticalOffset(text, offset, width, direction, preferredColumn),
137
+ referenceVerticalOffset(text, offset, width, direction, preferredColumn),
138
+ `${name}: width=${width}, offset=${offset}, direction=${direction}, preferred=${preferredColumn}`,
139
+ );
140
+ }
141
+ }
142
+ }
143
+ }
144
+ }
145
+ });
@@ -340,14 +340,14 @@ test('xAI legacy cache-lane knobs cannot create a secondary queue or timeout', a
340
340
  assert.deepEqual((await Promise.all([first, second])).map((item) => item.value), [0, 1]);
341
341
  });
342
342
 
343
- test('Anthropic providers retry request-local pre-output 429 responses', async () => {
343
+ test('Anthropic OAuth subscription 429 fails fast while API-key 429 retries request-locally', async () => {
344
344
  const oauth = Object.create(AnthropicOAuthProvider.prototype);
345
345
  oauth.credentials = { accessToken: 'fixture', expiresAt: Date.now() + 60_000 };
346
346
  oauth.config = {};
347
347
  oauth.fastModeBetaHeaderLatched = false;
348
348
  oauth.ensureAuth = async () => oauth.credentials;
349
349
  let oauthAttempts = 0;
350
- const oauthResult = await oauth.send([], 'claude-sonnet-4-5', [], {
350
+ await assert.rejects(oauth.send([], 'claude-sonnet-4-5', [], {
351
351
  _doRequestFn: async () => {
352
352
  oauthAttempts += 1;
353
353
  return {
@@ -364,9 +364,8 @@ test('Anthropic providers retry request-local pre-output 429 responses', async (
364
364
  _parseSSEFn: async () => ({
365
365
  content: 'oauth-ok', model: 'claude', toolCalls: [], usage: {},
366
366
  }),
367
- });
368
- assert.equal(oauthResult.content, 'oauth-ok');
369
- assert.equal(oauthAttempts, 2);
367
+ }), (error) => error?.status === 429 && error?.retryAfterMs === 0);
368
+ assert.equal(oauthAttempts, 1);
370
369
 
371
370
  const direct = Object.create(AnthropicProvider.prototype);
372
371
  direct.name = 'anthropic';