@alexwkleung/reika 0.8.0 → 0.9.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.
@@ -183,7 +183,7 @@ function ageLowFraction() {
183
183
  // not tokens, deliberately — it is compared against `payload.length`, and the threshold's token
184
184
  // units are a different scale.
185
185
  const SMALL_PAYLOAD_CHARS = 2000;
186
- export function batchAgePayloads(history, estimate, // calibrated request-token estimate; re-read after each mark
186
+ export function batchAgePayloads(history, estimate, // calibrated request-token estimate; read at each probe of the stop point
187
187
  contextWindow, minGen = DEFAULT_MIN_GEN_TOKENS,
188
188
  // Whether marking reasoning can still move the estimate this sweep is chasing. False once the
189
189
  // endpoint has demanded every reasoning byte back (latches.ts): serialization then keeps
@@ -239,50 +239,105 @@ shedReasoning = true) {
239
239
  // the tail IS that message and this loop never reaches it. Promoting the tail into `content` is
240
240
  // what makes it visible to the chat template; this is what keeps that promotion from becoming a
241
241
  // standing window cost only a fold could clear.
242
- for (let i = 0; i < protect; i++) {
243
- if (estimate() <= target) {
244
- out.kept = survivingCrumbs();
245
- return out;
242
+ const marks = shedOrder(history, protect, specIdx, shedReasoning);
243
+ let applied = 0;
244
+ const applyTo = (k) => {
245
+ while (applied < k)
246
+ marks[applied++].apply();
247
+ while (applied > k)
248
+ marks[--applied].undo();
249
+ };
250
+ // #894: the marks fall in a fixed order and the estimate only decides where to stop, so the stop
251
+ // is searched for rather than walked to. Re-estimating at every index cost a full serialization
252
+ // per message — about 1,400 of them, ~5s with the UI frozen, when a resumed session shed whole.
253
+ // Search finds the first stop only while marking never grows the request, which holds unless a
254
+ // fit-to-window cap gives freed room back to another live payload.
255
+ applyTo(marks.length);
256
+ const floor = estimate();
257
+ if (floor > target) {
258
+ out.short = Math.max(0, Math.round(floor - target));
259
+ }
260
+ else {
261
+ let lo = 0;
262
+ let hi = marks.length;
263
+ while (hi - lo > 1) {
264
+ const mid = (lo + hi) >>> 1;
265
+ applyTo(mid);
266
+ if (estimate() <= target)
267
+ hi = mid;
268
+ else
269
+ lo = mid;
246
270
  }
271
+ applyTo(hi);
272
+ }
273
+ for (let i = 0; i < applied; i++) {
274
+ out.marked++;
275
+ if (marks[i].kind === 'bulk')
276
+ out.bulk++;
277
+ else if (marks[i].kind === 'crumb')
278
+ out.crumbs++;
279
+ }
280
+ out.kept = survivingCrumbs();
281
+ return out;
282
+ }
283
+ // The marks batchAgePayloads would make if it never reached its watermark, in the order it makes
284
+ // them: spent continuation tails, then reasoning and bulk payloads oldest-first, then crumbs.
285
+ function shedOrder(history, protect, specIdx, shedReasoning) {
286
+ const marks = [];
287
+ for (let i = 0; i < protect; i++) {
247
288
  const m = history[i];
248
289
  if (m.role === 'assistant' && m.continuationTail && m.content !== CONTINUATION_SHED_NOTE) {
249
- m.content = CONTINUATION_SHED_NOTE;
250
- out.marked++;
290
+ const content = m.content;
291
+ marks.push({
292
+ kind: 'tail',
293
+ apply: () => (m.content = CONTINUATION_SHED_NOTE),
294
+ undo: () => (m.content = content),
295
+ });
251
296
  }
252
297
  }
253
298
  for (const takeCrumbs of [false, true]) {
254
299
  for (let i = 0; i < protect; i++) {
255
- if (estimate() <= target) {
256
- out.kept = survivingCrumbs();
257
- return out;
258
- }
259
300
  if (i === specIdx)
260
301
  continue;
261
302
  const m = history[i];
262
- if (m.role === 'assistant' && m.reasoning && !m.reasoningAged) {
303
+ if (!takeCrumbs && m.role === 'assistant' && m.reasoning && !m.reasoningAged) {
263
304
  if (!shedReasoning)
264
305
  continue;
265
- m.reasoningAged = true;
266
- out.marked++;
306
+ const had = 'reasoningAged' in m;
307
+ const was = m.reasoningAged;
308
+ marks.push({
309
+ kind: 'reasoning',
310
+ apply: () => (m.reasoningAged = true),
311
+ undo: () => (had ? (m.reasoningAged = was) : delete m.reasoningAged),
312
+ });
267
313
  }
268
314
  else if (m.role === 'tool' && m.payload && !m.aged) {
269
- if (!takeCrumbs && m.payload.length < SMALL_PAYLOAD_CHARS)
315
+ const small = m.payload.length < SMALL_PAYLOAD_CHARS;
316
+ if (small !== takeCrumbs)
270
317
  continue;
271
- m.aged = true;
272
- delete m.rendered;
273
- out.marked++;
274
- if (takeCrumbs)
275
- out.crumbs++;
276
- else
277
- out.bulk++;
318
+ const hadAged = 'aged' in m;
319
+ const wasAged = m.aged;
320
+ const hadRendered = 'rendered' in m;
321
+ const rendered = m.rendered;
322
+ marks.push({
323
+ kind: takeCrumbs ? 'crumb' : 'bulk',
324
+ apply: () => {
325
+ m.aged = true;
326
+ delete m.rendered;
327
+ },
328
+ undo: () => {
329
+ if (hadAged)
330
+ m.aged = wasAged;
331
+ else
332
+ delete m.aged;
333
+ if (hadRendered)
334
+ m.rendered = rendered;
335
+ },
336
+ });
278
337
  }
279
338
  }
280
339
  }
281
- out.kept = survivingCrumbs();
282
- // Ran out of candidates while still over: everything sheddable outside the protected tail is
283
- // aged, and what remains is the active round plus whatever the floors hold.
284
- out.short = Math.max(0, Math.round(estimate() - target));
285
- return out;
340
+ return marks;
286
341
  }
287
342
  // Index of the assistant message that issued the trailing tool block's calls (or the final
288
343
  // assistant message when the history ends without tool results) — everything from there on is the
@@ -1,3 +1,4 @@
1
+ import { isAbsolute, relative } from 'node:path';
1
2
  import { buildSystemPrompt } from './prompt.js';
2
3
  import { callModel } from '../provider/client.js';
3
4
  import { latchesFor } from '../provider/latches.js';
@@ -973,6 +974,22 @@ export function buildEditRecoveryLedger(failure) {
973
974
  'here after all, say so and stop instead of retrying.',
974
975
  ].join('\n');
975
976
  }
977
+ // The edit-recovery dead-end's report. A `diverged` failure names the line that differs: the
978
+ // target is there, so "the plan may reference code that doesn't exist" would send the user hunting
979
+ // for a problem the file does not have.
980
+ export function buildEditRecoveryStopMessage(failure) {
981
+ const file = failure ? `\`${failure.path}\`` : 'the file';
982
+ if (failure?.kind === 'diverged') {
983
+ return (`My edit to ${file} didn't apply: line ${failure.divergentLine} differs from the text I ` +
984
+ `expected (expected \`${failure.expected}\`, the file has \`${failure.actual}\`). I've ` +
985
+ `stopped instead of looping. Ask me to continue and I'll re-read that part of the file and ` +
986
+ `retry the edit from its current text.`);
987
+ }
988
+ return (`I kept trying to edit ${file} but the text I expected isn't in the file, so the change can't ` +
989
+ `be applied as planned — the plan may reference code that doesn't exist there. I've stopped ` +
990
+ `instead of looping. Please confirm the change belongs in that file, or point me at the right ` +
991
+ `location.`);
992
+ }
976
993
  // Payload attached to an `absent` edit failure when the file's bytes are not in the model's context
977
994
  // (see the call site). Rides the tool result rather than the system suffix: unlike the diverged
978
995
  // recovery ledger — which must survive several rounds to reach a period-2 loop — this is consumed by
@@ -1184,6 +1201,8 @@ export async function runTurn(opts) {
1184
1201
  // line off) gets exactly ONE round with the divergence lifted into the system suffix before the
1185
1202
  // dead-end stop — the same "each tier gets one round" discipline as the rumination ladder. Set when
1186
1203
  // that round fires so a still-looping turn falls through to the stop instead of grounding forever.
1204
+ // Per failure, not per turn: a landed edit clears it, so a later failure on other code gets its own
1205
+ // round (a turn-wide guard stopped a second, unrelated failure on its first attempt).
1187
1206
  let editRecoveryGroundingTried = false;
1188
1207
  // One-shot guard for the Tier 2 logit-recovery round (REIKA_LOGIT_RECOVERY): the rumination
1189
1208
  // dead-end gets exactly ONE biased round before the terminal stop. Set when it fires so a
@@ -1295,6 +1314,24 @@ export async function runTurn(opts) {
1295
1314
  latches: latchesFor(opts.config),
1296
1315
  trailingNote: roundSuffix,
1297
1316
  });
1317
+ // A stream cut short never reaches its final usage chunk, but a hosted API has still billed it
1318
+ // (#906), so a cut round is counted from what streamed. A cut before any output counts nothing:
1319
+ // no decode happened. Goes to onUsage only, never onto the response: calibration, the decode rate
1320
+ // and the reserve read `response.usage`, and a learned value must not be fitted to our own guess.
1321
+ const reportUsage = (response, cut, promptEstimate) => {
1322
+ if (response.usage) {
1323
+ opts.onUsage?.(response.usage);
1324
+ return;
1325
+ }
1326
+ const output = (response.reasoning ?? '') + (response.content ?? '');
1327
+ if (!cut || !output)
1328
+ return;
1329
+ opts.onUsage?.({
1330
+ promptTokens: Math.round(promptEstimate() * calibration),
1331
+ completionTokens: Math.round(estimateTokens(output) * Math.max(calibration, COMPACTION_CALIBRATION_FLOOR)),
1332
+ estimated: true,
1333
+ });
1334
+ };
1298
1335
  // Run a typecheck while pulsing the UI indicator around it (and clearing on any exit). The
1299
1336
  // pulse is human-only; the CheckOutcome flows to the gate logic, never to the model.
1300
1337
  const typecheck = async () => {
@@ -1614,11 +1651,7 @@ export async function runTurn(opts) {
1614
1651
  debugLog(`[reika:debug] round=${i} edit-recovery-stuck file=${file ?? '?'}\n`);
1615
1652
  const stuck = {
1616
1653
  role: 'assistant',
1617
- content: `I kept trying to edit ${file ? `\`${file}\`` : 'the file'} but the text I expected ` +
1618
- `isn't in the file, so the change can't be applied as planned — the plan may reference ` +
1619
- `code that doesn't exist there. I've stopped instead of looping. Please confirm the ` +
1620
- `change belongs in that file, or point me at the right location.` +
1621
- (await reportTypecheckAtStop()),
1654
+ content: buildEditRecoveryStopMessage(lastEditFailure) + (await reportTypecheckAtStop()),
1622
1655
  durationMs: Date.now() - turnStart,
1623
1656
  ...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
1624
1657
  };
@@ -1860,6 +1893,17 @@ export async function runTurn(opts) {
1860
1893
  // REIKA_COMPACTION_REPORT=0 is the ledger-only baseline arm; /compact honors it too, and then
1861
1894
  // folds without a note exactly as an automatic fold would.
1862
1895
  const reportEnabled = compactionReportEnabled();
1896
+ // The note is written from the unfolded history, which a resumed session (folds are not
1897
+ // restored) or a /model switch to a smaller window can leave over the window: the engine
1898
+ // refuses the request and its retries, or one that truncates spends a whole window of prefill
1899
+ // on the backstop's 256 tokens. Last in the gate, so only a fold that is really due logs it.
1900
+ const noteFitsWindow = (contextWindow) => {
1901
+ const promptTokens = Math.round(rawEstimate() * compactCalibration);
1902
+ if (promptTokens < contextWindow)
1903
+ return true;
1904
+ debugLog(`[reika:debug] round=${i} compaction-report skipped prompt=${promptTokens} window=${contextWindow}\n`);
1905
+ return false;
1906
+ };
1863
1907
  const autoReport = !manualRound &&
1864
1908
  reportEnabled &&
1865
1909
  !!window &&
@@ -1876,7 +1920,8 @@ export async function runTurn(opts) {
1876
1920
  ? foldAfterShed(opts.history, h => rawEstimate(h) * compactCalibration, window, compactCalibration, minGen(), !latchesFor(opts.config).reasoningRoundtrip,
1877
1921
  // The manual trigger's only question is "would the fold remove anything" (#481).
1878
1922
  !manualRound)
1879
- : wouldFold(opts.history, window, compactCalibration, minGen()))) {
1923
+ : wouldFold(opts.history, window, compactCalibration, minGen())) &&
1924
+ noteFitsWindow(window)) {
1880
1925
  const n = shrink.folds + 1;
1881
1926
  const directive = buildCompactionReportDirective(n);
1882
1927
  // Notice first, so the barred note block that follows reads as a deliberate side
@@ -1998,9 +2043,9 @@ export async function runTurn(opts) {
1998
2043
  return plain;
1999
2044
  }
2000
2045
  };
2046
+ const notePrompt = () => rawEstimate(opts.history, noteTools);
2001
2047
  const rep = await report(directive);
2002
- if (rep.usage)
2003
- opts.onUsage?.(rep.usage);
2048
+ reportUsage(rep, !!opts.signal?.aborted, notePrompt);
2004
2049
  // callModel returns what streamed before a ctrl-c rather than throwing, so an aborted note
2005
2050
  // is a cut-off fragment — never a note, and not a reason to fold.
2006
2051
  if (opts.signal?.aborted) {
@@ -2017,8 +2062,7 @@ export async function runTurn(opts) {
2017
2062
  debugLog(`[reika:debug] round=${i} compaction-report n=${n} no-note ${describe(rep)}; retrying\n`);
2018
2063
  opts.onReasoningReset?.();
2019
2064
  retry = await report(`${directive}\n\n${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
2020
- if (retry.usage)
2021
- opts.onUsage?.(retry.usage);
2065
+ reportUsage(retry, !!opts.signal?.aborted, notePrompt);
2022
2066
  if (opts.signal?.aborted) {
2023
2067
  commitNoteRoundAbort();
2024
2068
  return;
@@ -2050,10 +2094,11 @@ export async function runTurn(opts) {
2050
2094
  debugLog(`[reika:debug] round=${i} compaction-report failed err=${String(err)}\n`);
2051
2095
  }
2052
2096
  finally {
2053
- opts.onCompactionNote?.(false);
2054
2097
  // The live region held the note; if the reply was empty no assistant commit cleared it,
2055
- // so the UI is told explicitly before the round's real reply streams.
2098
+ // so the UI is told explicitly before the round's real reply streams. Ahead of the note
2099
+ // flag, so the UI still knows the stream it is ending was a note's.
2056
2100
  opts.onReasoningReset?.();
2101
+ opts.onCompactionNote?.(false);
2057
2102
  }
2058
2103
  }
2059
2104
  // Prefix-stable shrink event: payloads stay live (byte-frozen) across rounds, so shed them in
@@ -2319,8 +2364,7 @@ export async function runTurn(opts) {
2319
2364
  opts.onReasoningStatus?.(false);
2320
2365
  debugLog(`[reika:debug] reasoning-spin off round=${i} (block ended while flagged)\n`);
2321
2366
  }
2322
- if (response.usage)
2323
- opts.onUsage?.(response.usage);
2367
+ reportUsage(response, callAbort.signal.aborted, () => sentEstimate);
2324
2368
  // Recalibrate from what the provider actually counted vs. what we estimated for the
2325
2369
  // request we just sent. Clamped to a sane band to ignore one-off outliers.
2326
2370
  if (response.usage?.promptTokens && sentEstimate > 0) {
@@ -3254,6 +3298,7 @@ export async function runTurn(opts) {
3254
3298
  if (summary.startsWith('Edited ') || summary.startsWith('Wrote ')) {
3255
3299
  lastEditFailed = false;
3256
3300
  lastEditFailure = undefined;
3301
+ editRecoveryGroundingTried = false;
3257
3302
  // Read-first (#72): a successful edit/write grounds its path, but by different routes. An
3258
3303
  // edit grounds only through the post-edit echo it hands back (tools/edit.ts refreshedFile),
3259
3304
  // which is size-capped and absent on a large file — so it keys on the message index and
@@ -3435,6 +3480,17 @@ function commitAborted(opts, partial, partialReasoning, turnStart, fetchedUrls)
3435
3480
  opts.history.push(m);
3436
3481
  opts.onMessage(m);
3437
3482
  }
3483
+ // The files a stop message names, as inline code and project-relative: an edit's `path` arg is
3484
+ // often absolute, and a bare `/Users/…/src/a.ts, …` list read as prose and wrapped mid-path.
3485
+ function stopFileList(files, cwd, max) {
3486
+ return [...files]
3487
+ .slice(0, max)
3488
+ .map(f => {
3489
+ const rel = isAbsolute(f) ? relative(cwd, f) : f;
3490
+ return `\`${rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel : f}\``;
3491
+ })
3492
+ .join(', ');
3493
+ }
3438
3494
  // Honest terminal stop when reasoning keeps spiraling even through recovery (the force-write looped,
3439
3495
  // or the recovery budget is spent). Better than committing spiral garbage as a "plan" or running to
3440
3496
  // the token wall. Names the files examined so the user has a handle on what was done. Deliberately
@@ -3454,7 +3510,7 @@ reason = 'loop') {
3454
3510
  files.add(tc.args.path);
3455
3511
  }
3456
3512
  }
3457
- const examined = files.size > 0 ? ` Files I examined: ${[...files].slice(0, 12).join(', ')}.` : '';
3513
+ const examined = files.size > 0 ? ` Files I examined: ${stopFileList(files, opts.bundle.cwd, 12)}.` : '';
3458
3514
  const m = {
3459
3515
  role: 'assistant',
3460
3516
  content: reason === 'length'
@@ -3494,7 +3550,7 @@ function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited, typecheckAdde
3494
3550
  }
3495
3551
  }
3496
3552
  }
3497
- const fileList = files.size > 0 ? ` to ${[...files].slice(0, 8).join(', ')}` : '';
3553
+ const fileList = files.size > 0 ? ` to ${stopFileList(files, opts.bundle.cwd, 8)}` : '';
3498
3554
  const content = edited
3499
3555
  ? `I made changes${fileList} but then kept repeating the same checks without making progress, so ` +
3500
3556
  `I've stopped to avoid looping. The edits are saved — review them and ask me to continue if ` +
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { jsx as _jsx } from "react/jsx-runtime";
3
2
  import { sweepDebugLogs } from './debug.js';
4
3
  import { sweepStaleSpills } from './tools/_spill.js';
5
4
  import { USAGE, parseHeadlessArgs } from './headless/headlessargs.js';
5
+ import { loadWithProductionReact } from './ui/reactbuild.js';
6
6
  import { VERSION } from './version.js';
7
7
  // Lowercase like the command: ps/top/Activity Monitor otherwise list every session as `node`, and
8
8
  // pgrep/pkill match case-sensitively.
@@ -59,12 +59,6 @@ if (headless) {
59
59
  process.exit(code);
60
60
  }
61
61
  else {
62
- const [{ render }, { App }, { createSyncedStdout }] = await Promise.all([
63
- import('ink'),
64
- import('./ui/App.js'),
65
- import('./ui/syncframe.js'),
66
- ]);
67
- // Frames go out as one synchronized write each (#345) so a swapped-out process can't leave the
68
- // terminal painting a half-erased screen between Ink's writes.
69
- render(_jsx(App, {}), { exitOnCtrlC: false, stdout: createSyncedStdout(process.stdout) });
62
+ const { startTui } = await loadWithProductionReact(() => import('./ui/tui.js'));
63
+ startTui();
70
64
  }
@@ -292,7 +292,10 @@ export function createHeadlessStatus(messages) {
292
292
  const shrinkEvents = [];
293
293
  return {
294
294
  events: {
295
- onUsage: u => (lastUsage = u),
295
+ onUsage: u => {
296
+ if (!u.estimated)
297
+ lastUsage = u;
298
+ },
296
299
  onContextEstimate: t => (estimatedContext = t),
297
300
  onShrink: event => {
298
301
  lastUsage = null;
package/dist/session.js CHANGED
@@ -172,13 +172,16 @@ export async function createSession(opts) {
172
172
  emit(n);
173
173
  },
174
174
  onUsage: u => {
175
- lastUsage = u;
175
+ // An estimate says nothing about the last real request, which is what lastUsage is for.
176
+ if (!u.estimated)
177
+ lastUsage = u;
176
178
  totals = {
177
179
  promptTokens: totals.promptTokens + u.promptTokens,
178
180
  completionTokens: totals.completionTokens + u.completionTokens,
179
181
  ...(u.cachedTokens != null || totals.cachedTokens != null
180
182
  ? { cachedTokens: (totals.cachedTokens ?? 0) + (u.cachedTokens ?? 0) }
181
183
  : {}),
184
+ ...(u.estimated || totals.estimated ? { estimated: true } : {}),
182
185
  };
183
186
  events.onUsage?.(u);
184
187
  },
@@ -153,7 +153,7 @@ export function modelHistoryFromScrollback(messages) {
153
153
  case 'user':
154
154
  return !m.meta;
155
155
  case 'assistant':
156
- return !m.nested && !m.compactionNote;
156
+ return !m.nested && !m.compactionNote && !m.discarded;
157
157
  case 'tool':
158
158
  return !m.nested;
159
159
  default:
@@ -20,6 +20,7 @@ export function buildTranscriptMeta(opts) {
20
20
  promptTokens: totals.promptTokens,
21
21
  completionTokens: totals.completionTokens,
22
22
  ...(totals.cachedTokens != null ? { cachedTokens: totals.cachedTokens } : {}),
23
+ ...(totals.estimated ? { tokensEstimated: true } : {}),
23
24
  contextTokens: last?.promptTokens ?? status.estimatedContext,
24
25
  // No call has landed yet, so the context size above is the pre-send estimate.
25
26
  ...(last?.promptTokens == null ? { contextEstimated: true } : {}),
@@ -105,7 +106,8 @@ export function summarizeModes(messages) {
105
106
  export function formatUsageHeader(usage) {
106
107
  const lines = [`# turns: ${usage.turns}`];
107
108
  const cachedTotal = usage.cachedTokens != null ? `, ${kFormat(usage.cachedTokens)} from cache` : '';
108
- lines.push(`# tokens: ${kFormat(usage.promptTokens)}↑ ${kFormat(usage.completionTokens)}↓ (session total${cachedTotal})`);
109
+ const approx = usage.tokensEstimated ? '~' : '';
110
+ lines.push(`# tokens: ${approx}${kFormat(usage.promptTokens)}↑ ${approx}${kFormat(usage.completionTokens)}↓ (session total${cachedTotal})`);
109
111
  const ctx = usage.contextTokens;
110
112
  if (ctx != null && ctx > 0) {
111
113
  const fill = contextFill(ctx, usage.contextUsable ?? usage.contextWindow);
@@ -23,6 +23,7 @@ const POLICY_PATTERNS = [
23
23
  { re: /\bgit\s+commit\b/, label: 'Git commit (records to version history)' },
24
24
  // Bare push; force push is also flagged separately below as a destructive pattern.
25
25
  { re: /\bgit\s+push\b/, label: 'Git push (publishes commits to remote)' },
26
+ { re: /\bgit\s+send-email\b/, label: 'Git send-email (sends mail, outward-facing)' },
26
27
  // Outward-facing GitHub/HF actions. Scoped to the publishing subcommands here because they are
27
28
  // the ones whose label the user needs to see in these words — the rest of the coverage is the
28
29
  // read-verb allowlists (`GH_READ_VERBS`, `HF_READ_VERBS`), which flag every verb that is not a
@@ -220,8 +220,9 @@ const GIT_GLOBAL_VALUE_FLAGS = new Set([
220
220
  ]);
221
221
  // Subcommand options that run a program the model wrote. `--template` plants hooks that run at
222
222
  // checkout and clone's `--config` is `-c` again, so both belong here although neither is spelled
223
- // as a command. Long names apply to every subcommand: none has a harmless option abbreviated by
224
- // these, and `push --exec`/`archive --exec` mean the same as `rebase --exec`.
223
+ // as a command. Long names apply to every subcommand: `push --exec`/`archive --exec` mean the same
224
+ // as `rebase --exec`, and an abbreviation of one of these is refused on any subcommand — a false
225
+ // deny where that subcommand's own `--e`/`--t`/`--u` means something else, never a hole.
225
226
  const GIT_PROGRAM_LONG_FLAGS = [
226
227
  'upload-pack',
227
228
  'receive-pack',
@@ -240,8 +241,14 @@ const GIT_PROGRAM_SHORT_FLAGS = {
240
241
  rebase: { run: 'x', value: 'sXxC' },
241
242
  difftool: { run: 'x', value: 'tx' },
242
243
  };
243
- // Whole subcommands (or a subcommand's first operand) whose job is running a command.
244
- const GIT_PROGRAM_SUBCOMMANDS = new Set(['filter-branch', 'submodule foreach', 'bisect run']);
244
+ // Whole subcommands (or a subcommand's first operand) that name a program to run: `send-email`
245
+ // does so five ways (four `--*-cmd` options, and `--smtp-server=/path`), so it goes by subcommand.
246
+ const GIT_PROGRAM_SUBCOMMANDS = new Set([
247
+ 'filter-branch',
248
+ 'submodule foreach',
249
+ 'bisect run',
250
+ 'send-email',
251
+ ]);
245
252
  function gitSubcommandRunsProgram(sub, args) {
246
253
  if (GIT_PROGRAM_SUBCOMMANDS.has(sub))
247
254
  return true;
@@ -254,7 +261,8 @@ function gitSubcommandRunsProgram(sub, args) {
254
261
  return false;
255
262
  if (a.startsWith('--')) {
256
263
  const name = a.slice(2).split('=')[0];
257
- if (name.length >= 2 && GIT_PROGRAM_LONG_FLAGS.some(f => f.startsWith(name)))
264
+ // Any prefix, down to one letter (`--u=cmd` ran); `--=x` has an empty name, which is none.
265
+ if (name && GIT_PROGRAM_LONG_FLAGS.some(f => f.startsWith(name)))
258
266
  return true;
259
267
  }
260
268
  else if (short && a.startsWith('-')) {
package/dist/ui/App.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
3
- import { Box, Static, Text, useApp, useInput } from 'ink';
2
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, } from 'react';
3
+ import { Box, Static, Text, measureElement, useApp, useInput } from 'ink';
4
4
  import { basename, dirname, isAbsolute, resolve } from 'node:path';
5
5
  import { homedir } from 'node:os';
6
6
  import { Splash } from './Splash.js';
@@ -78,6 +78,17 @@ function promptPlaceholder() {
78
78
  return withHint.length + 6 <= (process.stdout.columns || 80) ? withHint : base;
79
79
  }
80
80
  const AUTOSAVE_INTERVAL_MS = 3000;
81
+ // A frozen stream's kept tail: well past what a viewport-tall live block can draw.
82
+ const FROZEN_STREAM_CHARS = 16000;
83
+ // An answered approval's rows: held this long for output to fill them, then whatever is still blank
84
+ // shrinks by this fraction a frame (at least a row), so the input slides up rather than snapping.
85
+ // Once the command has printed, the ease waits for it to go quiet this long instead: a command
86
+ // printing a line every half second fills the rows, where easing them out between lines slid the
87
+ // input up and then had each line push it back down.
88
+ const HOLD_GRACE_MS = 300;
89
+ const HOLD_QUIET_MS = 1500;
90
+ const HOLD_FRAME_MS = 32;
91
+ const HOLD_EASE = 0.35;
81
92
  // A resumed session reaches the scrollback a slice at a time (#854): a commit renders its messages'
82
93
  // markdown, highlighting and wrap synchronously, and one commit for the whole session held the
83
94
  // event loop — the resuming spinner's timer included — for as long as that took (~2s at 460
@@ -127,10 +138,24 @@ export function App() {
127
138
  // is the status bar's one-second tick (below) — a state of its own would repaint the live region
128
139
  // a second time every second for a value that changes on no other edge.
129
140
  const pendingToolAtRef = useRef(0);
141
+ // An answered approval or question keeps its rows for a moment: closing a 13-row dialog in one
142
+ // frame dropped the input 13 rows, and output arriving in the grace window fills that space
143
+ // instead. Whatever is still blank after it eases out (HOLD_*). An approval's hold is keyed to its
144
+ // call's start stamp (`forCall`), so the next call never inherits it; a question's lasts past its
145
+ // call, whose answer commits at once, into the model's next round.
146
+ const [dialogHold, setDialogHold] = useState(null);
147
+ const heldFrameRef = useRef(null);
148
+ const heldFrameRowsRef = useRef(0);
149
+ // The blank the hold is leaving right now, which is what the ease-out shrinks.
150
+ const holdSpacerRef = useRef(null);
151
+ const lastLiveOutputAtRef = useRef(0);
130
152
  // A subagent owns the live region right now (#342): its streamed blocks draw at the nested indent.
131
153
  const [subagentLive, setSubagentLive] = useState(false);
132
154
  // The model is writing a compaction note (#280): nested like a subagent, labelled as itself.
133
155
  const [noteLive, setNoteLive] = useState(false);
156
+ // Read by onReasoningReset, which runs inside the loop's callbacks rather than a render.
157
+ const subagentLiveRef = useRef(false);
158
+ const noteLiveRef = useRef(false);
134
159
  // The session owns the config, the active profile, the bundle and everything a turn threads to
135
160
  // the next (#403); App renders from its snapshot and never keeps a copy of its own.
136
161
  const [session, setSession] = useState(null);
@@ -282,6 +307,8 @@ export function App() {
282
307
  };
283
308
  const statusRef = useRef('loading');
284
309
  statusRef.current = status;
310
+ const pendingToolRef = useRef('');
311
+ pendingToolRef.current = pendingTool;
285
312
  const pendingRef = useRef(null);
286
313
  pendingRef.current = pending;
287
314
  const questionRef = useRef(null);
@@ -1237,6 +1264,16 @@ export function App() {
1237
1264
  setApprovalTyping(false);
1238
1265
  return new Promise(resolve => {
1239
1266
  const wrappedResolve = (answer) => {
1267
+ // Only for the call that is running: a subagent's approval names a nested call, and the
1268
+ // parent's row (`subagent`) would hold these rows for the whole delegated run.
1269
+ if (req.tool === pendingToolRef.current) {
1270
+ setDialogHold({
1271
+ rows: heldFrameRowsRef.current,
1272
+ at: pendingToolAtRef.current,
1273
+ forCall: true,
1274
+ command: answer === true && req.tool === 'bash' ? req.preview : undefined,
1275
+ });
1276
+ }
1240
1277
  setApprovals(a => answer === true ? { ...a, approved: a.approved + 1 } : { ...a, declined: a.declined + 1 });
1241
1278
  resolve(answer);
1242
1279
  };
@@ -1246,7 +1283,13 @@ export function App() {
1246
1283
  const requestQuestion = (req) => {
1247
1284
  setQuestionSelected(0);
1248
1285
  setQuestionTyping(null);
1249
- return new Promise(resolve => setQuestion({ request: req, resolve }));
1286
+ return new Promise(resolve => setQuestion({
1287
+ request: req,
1288
+ resolve: answer => {
1289
+ setDialogHold({ rows: heldFrameRowsRef.current, at: Date.now(), forCall: false });
1290
+ resolve(answer);
1291
+ },
1292
+ }));
1250
1293
  };
1251
1294
  // The mode change itself, shared by the slash commands and Shift+Tab cycling. `trailing`
1252
1295
  // lands after any restored history (the command echo + banner for /chat et al., nothing
@@ -1815,9 +1858,11 @@ export function App() {
1815
1858
  case 'cwd':
1816
1859
  response = bundle?.cwd ?? '(unknown)';
1817
1860
  break;
1818
- case 'tokens':
1819
- response = `prompt: ${totalUsage.promptTokens}\ncompletion: ${totalUsage.completionTokens}`;
1861
+ case 'tokens': {
1862
+ const approx = totalUsage.estimated ? '~' : '';
1863
+ response = `prompt: ${approx}${totalUsage.promptTokens}\ncompletion: ${approx}${totalUsage.completionTokens}`;
1820
1864
  break;
1865
+ }
1821
1866
  case 'skills': {
1822
1867
  const list = bundle?.skills ?? [];
1823
1868
  if (list.length === 0) {
@@ -2492,6 +2537,8 @@ export function App() {
2492
2537
  setStreamingReasoning('');
2493
2538
  setStreamingTool('');
2494
2539
  setPendingTool('');
2540
+ subagentLiveRef.current = false;
2541
+ noteLiveRef.current = false;
2495
2542
  setSubagentLive(false);
2496
2543
  setNoteLive(false);
2497
2544
  resetTypecheck();
@@ -2545,14 +2592,17 @@ export function App() {
2545
2592
  setMessages(prev => [...prev, msg]);
2546
2593
  },
2547
2594
  onContentDelta: delta => {
2595
+ lastLiveOutputAtRef.current = Date.now();
2548
2596
  streamingRef.current += delta;
2549
2597
  scheduleFlush();
2550
2598
  },
2551
2599
  onReasoningDelta: delta => {
2600
+ lastLiveOutputAtRef.current = Date.now();
2552
2601
  reasoningRef.current += delta;
2553
2602
  scheduleReasoningFlush();
2554
2603
  },
2555
2604
  onToolProgress: (chunk, tool) => {
2605
+ lastLiveOutputAtRef.current = Date.now();
2556
2606
  toolRef.current += chunk;
2557
2607
  toolNameRef.current = tool;
2558
2608
  scheduleToolFlush();
@@ -2561,6 +2611,7 @@ export function App() {
2561
2611
  // Stamped here, not in the loop: `onToolStart` fires immediately before `tool.run`, so
2562
2612
  // this is the call's own start — the same instant the row it ages appears (#585).
2563
2613
  pendingToolAtRef.current = Date.now();
2614
+ pendingToolRef.current = name;
2564
2615
  setPendingTool(name);
2565
2616
  },
2566
2617
  onPhase: p => {
@@ -2569,8 +2620,14 @@ export function App() {
2569
2620
  setReasoningSpin(false);
2570
2621
  setPhase(p);
2571
2622
  },
2572
- onSubagent: setSubagentLive,
2573
- onCompactionNote: setNoteLive,
2623
+ onSubagent: live => {
2624
+ subagentLiveRef.current = live;
2625
+ setSubagentLive(live);
2626
+ },
2627
+ onCompactionNote: live => {
2628
+ noteLiveRef.current = live;
2629
+ setNoteLive(live);
2630
+ },
2574
2631
  onTypecheck: onTypecheckChange,
2575
2632
  onRecovering: setRecovering,
2576
2633
  // Copy: the loop mutates its tracker array in place, so a same-reference set wouldn't
@@ -2578,9 +2635,24 @@ export function App() {
2578
2635
  onPlanProgress: steps => setPlanSteps(steps.map(st => ({ ...st }))),
2579
2636
  onReasoningStatus: setReasoningSpin,
2580
2637
  onReasoningReset: () => {
2581
- // Loop-break recovery: drop the degenerate looped reasoning's live preview so the
2638
+ // Loop-break recovery: end the degenerate looped reasoning's live preview so the
2582
2639
  // recovery notice is visible and the next round streams into a fresh Thinking block
2583
- // instead of appending onto the looped text (#55).
2640
+ // instead of appending onto the looped text (#55). Frozen into the scrollback where it
2641
+ // stood rather than erased: erased, the frame dropped by the block's height under a
2642
+ // one-line notice and the input jumped up. The tail is all that is kept, since a cut
2643
+ // spiral can run to tens of thousands of chars and the block only ever drew its end.
2644
+ const reasoning = reasoningRef.current.trim();
2645
+ const content = streamingRef.current.trim();
2646
+ if (reasoning || content) {
2647
+ const frozen = {
2648
+ role: 'assistant',
2649
+ content: content.slice(-FROZEN_STREAM_CHARS),
2650
+ ...(reasoning ? { reasoning: reasoning.slice(-FROZEN_STREAM_CHARS) } : {}),
2651
+ discarded: noteLiveRef.current ? 'note' : 'stream',
2652
+ ...(subagentLiveRef.current ? { nested: true } : {}),
2653
+ };
2654
+ setMessages(prev => [...prev, frozen]);
2655
+ }
2584
2656
  reasoningRef.current = '';
2585
2657
  setStreamingReasoning('');
2586
2658
  setReasoningSpin(false);
@@ -2591,7 +2663,9 @@ export function App() {
2591
2663
  setStreaming('');
2592
2664
  },
2593
2665
  onUsage: u => {
2594
- setLastUsage(u);
2666
+ // The gauge and cache chip read lastUsage, and an estimate has no real count for either.
2667
+ if (!u.estimated)
2668
+ setLastUsage(u);
2595
2669
  setTotalUsage(t => ({
2596
2670
  promptTokens: t.promptTokens + u.promptTokens,
2597
2671
  completionTokens: t.completionTokens + u.completionTokens,
@@ -2600,6 +2674,7 @@ export function App() {
2600
2674
  : t.cachedTokens != null
2601
2675
  ? { cachedTokens: t.cachedTokens }
2602
2676
  : {}),
2677
+ ...(u.estimated || t.estimated ? { estimated: true } : {}),
2603
2678
  }));
2604
2679
  },
2605
2680
  onContextEstimate: t => setEstimatedContext(t),
@@ -2659,6 +2734,55 @@ export function App() {
2659
2734
  const dialogReservedRows = statusExtraRows +
2660
2735
  (planSteps && (mode === 'agent' || mode === 'vibe') ? planProgressRows(planSteps) : 0) +
2661
2736
  (queue.length > 0 ? queue.length + 1 : 0);
2737
+ const holdActive = dialogHold !== null &&
2738
+ status === 'busy' &&
2739
+ pending === null &&
2740
+ question === null &&
2741
+ (!dialogHold.forCall || (pendingTool !== '' && pendingToolAtRef.current === dialogHold.at));
2742
+ const heldRows = holdActive && dialogHold.rows > 0 ? dialogHold.rows : undefined;
2743
+ const holdAt = holdActive ? dialogHold.at : undefined;
2744
+ // Measured after every frame the dialog is in, so the answer can hold exactly what it drew.
2745
+ useEffect(() => {
2746
+ if ((pending || question) && heldFrameRef.current) {
2747
+ heldFrameRowsRef.current = measureElement(heldFrameRef.current).height;
2748
+ }
2749
+ });
2750
+ useEffect(() => {
2751
+ if (dialogHold && !holdActive && pending === null && question === null)
2752
+ setDialogHold(null);
2753
+ }, [dialogHold, holdActive, pending, question]);
2754
+ // A row committed while the hold is up lands above the held frame and would push the input down
2755
+ // by its height (a question's answer row, the round's next message), so the hold gives those rows
2756
+ // back. Ink lays out only the rows being committed in this render under its static node; a layout
2757
+ // effect's update re-renders inside the same tick, so the two renders paint as one frame.
2758
+ useLayoutEffect(() => {
2759
+ if (heldRows === undefined)
2760
+ return;
2761
+ const root = heldFrameRef.current?.parentNode;
2762
+ const committed = root?.staticNode?.yogaNode?.getComputedHeight() ?? 0;
2763
+ if (committed > 0)
2764
+ setDialogHold(h => h && { ...h, rows: Math.max(0, h.rows - committed) });
2765
+ }, [messages, heldRows]);
2766
+ // A short timer of its own, unlike the rest of the live region: the ease is a few frames long,
2767
+ // and the status bar's one-second tick is far too coarse to animate it.
2768
+ useEffect(() => {
2769
+ if (holdAt === undefined)
2770
+ return;
2771
+ let timer = setTimeout(function step() {
2772
+ const sinceOutput = Date.now() - lastLiveOutputAtRef.current;
2773
+ if (lastLiveOutputAtRef.current >= holdAt && sinceOutput < HOLD_QUIET_MS) {
2774
+ timer = setTimeout(step, HOLD_QUIET_MS - sinceOutput);
2775
+ return;
2776
+ }
2777
+ const blank = holdSpacerRef.current ? measureElement(holdSpacerRef.current).height : 0;
2778
+ setDialogHold(h => h && h.at === holdAt
2779
+ ? { ...h, rows: blank > 0 ? h.rows - Math.max(1, Math.ceil(blank * HOLD_EASE)) : 0 }
2780
+ : h);
2781
+ if (blank > 0)
2782
+ timer = setTimeout(step, HOLD_FRAME_MS);
2783
+ }, HOLD_GRACE_MS);
2784
+ return () => clearTimeout(timer);
2785
+ }, [holdAt]);
2662
2786
  if (status === 'error') {
2663
2787
  return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { children: "Error" }), _jsx(Text, { children: error })] }));
2664
2788
  }
@@ -2682,9 +2806,9 @@ export function App() {
2682
2806
  noteFrameState(`${status === 'busy' ? phase : status} msgs=${messages.length} live=${live.join(',') || '-'}` +
2683
2807
  ` pending=${pendingTool || '-'} dialog=${dialog} queue=${queue.length}` +
2684
2808
  ` plan=${planSteps ? planSteps.length : 0} suggest=${suggestionState ? 1 : 0}` +
2685
- `${subagentLive ? ' subagent' : ''}`);
2809
+ `${subagentLive ? ' subagent' : ''}${heldRows ? ` held=${heldRows}` : ''}`);
2686
2810
  }
2687
- return (_jsxs(Box, { flexDirection: "column", paddingX: 1, children: [_jsx(Static, { items: headerItems, children: (h, i) => (_jsx(Splash, { model: h.model, cwd: h.cwd, version: h.version, subagent: h.subagent }, i)) }), status === 'loading' && loadingNote ? _jsx(Text, { color: theme.muted, children: loadingNote }) : null, status === 'loading' ? null : (_jsxs(_Fragment, { children: [_jsx(Scrollback, { messages: messages, streaming: status === 'busy' ? streaming : '', streamingReasoning: status === 'busy' ? streamingReasoning : '', streamingTool: status === 'busy' ? streamingTool : '', streamingNested: subagentLive, streamingCommand: streamingToolName === 'bash',
2811
+ return (_jsxs(Box, { ref: heldFrameRef, flexDirection: "column", paddingX: 1, minHeight: heldRows, children: [_jsx(Static, { items: headerItems, children: (h, i) => (_jsx(Splash, { model: h.model, cwd: h.cwd, version: h.version, subagent: h.subagent }, i)) }), status === 'loading' && loadingNote ? _jsx(Text, { color: theme.muted, children: loadingNote }) : null, status === 'loading' ? null : (_jsxs(_Fragment, { children: [_jsx(Scrollback, { messages: messages, streaming: status === 'busy' ? streaming : '', streamingReasoning: status === 'busy' ? streamingReasoning : '', streamingTool: status === 'busy' ? streamingTool : '', streamingNested: subagentLive, streamingCommand: streamingToolName === 'bash',
2688
2812
  // Hidden while a dialog is up: the approval a tool asks for happens *inside* the call
2689
2813
  // (after the loop announced it), so an "Editing…" row behind the prompt would name work
2690
2814
  // that has not been permitted yet. Same condition the spinner uses.
@@ -2692,11 +2816,11 @@ export function App() {
2692
2816
  // Its age (#585), read here rather than ticked in the Scrollback: the status bar's
2693
2817
  // one-second `elapsed` interval re-renders this component for the whole of a call, so
2694
2818
  // the row's timer advances off that instead of an interval of its own.
2695
- pendingToolMs: pendingTool ? Date.now() - pendingToolAtRef.current : 0, streamingNote: noteLive, showHeldWorked: status !== 'busy',
2819
+ pendingToolMs: pendingTool ? Date.now() - pendingToolAtRef.current : 0, pendingCommand: holdActive ? dialogHold.command : undefined, streamingNote: noteLive, showHeldWorked: status !== 'busy',
2696
2820
  // Everything the live frame draws besides the stream and the baseline chrome — the
2697
2821
  // suggestion list and queue grow it mid-turn, and unbudgeted they push it to viewport
2698
2822
  // height, where Ink repaints with a scrollback clear on every chunk (#470).
2699
- chromeRows: dialogReservedRows + suggestionRows(suggestionState) }), planSteps && (mode === 'agent' || mode === 'vibe') ? (_jsx(PlanProgress, { steps: planSteps })) : null, status === 'busy' && pending === null && question === null ? (_jsx(Working
2823
+ chromeRows: dialogReservedRows + suggestionRows(suggestionState) }), heldRows !== undefined ? _jsx(Box, { ref: holdSpacerRef, flexGrow: 1 }) : null, planSteps && (mode === 'agent' || mode === 'vibe') ? (_jsx(PlanProgress, { steps: planSteps })) : null, status === 'busy' && pending === null && question === null ? (_jsx(Working
2700
2824
  // Definite harness actions (typecheck, loop recovery) take priority over the soft spin
2701
2825
  // hint — they're things the harness is actively doing, not a maybe.
2702
2826
  , {
@@ -2,12 +2,11 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
2
2
  import { Box, Text } from 'ink';
3
3
  import { diffWordsWithSpace } from 'diff';
4
4
  import stringWidth from 'string-width';
5
- import wrapAnsi from 'wrap-ansi';
6
5
  import chalk from 'chalk';
7
6
  import { theme, themeChalk } from './theme.js';
8
7
  import { highlightCode } from './highlight.js';
9
8
  import { drawnWidth, sanitizeTerminalText } from './termtext.js';
10
- import { sliceStyled, wrapStyledRows } from './layout.js';
9
+ import { sliceStyled, wrapLines, wrapStyledRows } from './layout.js';
11
10
  import stripAnsi from 'strip-ansi';
12
11
  export function DiffView({ diff, path, maxWidth, startLine, oldStartLine, maxRows, hiddenNote = n => `… ${n} more lines`, }) {
13
12
  const lang = detectLanguage(path);
@@ -37,7 +36,7 @@ export function DiffView({ diff, path, maxWidth, startLine, oldStartLine, maxRow
37
36
  // Exported for unit tests.
38
37
  export function fitRowsToHeight(lines, maxRows, contentWidth) {
39
38
  const wrapWidth = Math.max(1, contentWidth - CONTINUATION.length);
40
- const heights = lines.map(row => wrapAnsi(row.text, wrapWidth, { trim: false, hard: true }).split('\n').length);
39
+ const heights = lines.map(row => wrapLines(row.text, wrapWidth).split('\n').length);
41
40
  const total = heights.reduce((a, b) => a + b, 0);
42
41
  if (total <= maxRows)
43
42
  return { lines, hidden: 0 };
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box, Text } from 'ink';
3
+ import { useMemo } from 'react';
3
4
  import { glyphs } from './glyphs.js';
4
5
  import { theme } from './theme.js';
5
6
  // A project can collect hundreds of sessions, and the picker lives in the dynamic frame, where a
@@ -14,13 +15,18 @@ export function ResumeSelect({ entries, selectedIndex, heading, }) {
14
15
  const start = windowStart(entries.length, selectedIndex, RESUME_VISIBLE_ROWS);
15
16
  const shown = entries.slice(start, start + RESUME_VISIBLE_ROWS);
16
17
  const below = entries.length - start - shown.length;
17
- const now = new Date();
18
18
  // Locale formats vary in width ("9:05 a.m." vs "11:28 p.m."); padding over every entry, not just
19
- // the visible ones, keeps the title column still while the window scrolls.
20
- const whenWidth = Math.max(0, ...entries.map(e => formatSavedAt(e.savedAt, now).length));
19
+ // the visible ones, keeps the title column still while the window scrolls. Formatted once per
20
+ // list: toLocaleString over hundreds of entries on every cursor move was the picker's whole cost.
21
+ const whens = useMemo(() => {
22
+ const now = new Date();
23
+ const formatted = entries.map(e => formatSavedAt(e.savedAt, now));
24
+ const width = Math.max(0, ...formatted.map(w => w.length));
25
+ return formatted.map(w => w.padEnd(width));
26
+ }, [entries]);
21
27
  return (_jsxs(Box, { borderStyle: glyphs.border, borderBottom: false, flexDirection: "column", paddingX: 1, marginX: -1, marginTop: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: theme.tool, children: '• Resume' }), _jsx(Text, { color: theme.secondary, children: ` ${heading} · ${entries.length}` })] }), _jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsx(Text, { color: theme.muted, children: start > 0 ? ` ↑ ${start} newer` : ' ' }), shown.map((e, i) => {
22
28
  const selected = start + i === selectedIndex;
23
- const when = formatSavedAt(e.savedAt, now).padEnd(whenWidth);
29
+ const when = whens[start + i];
24
30
  const label = e.title ?? '(untitled)';
25
31
  // The model is what tells apart two sessions opened with the same prompt; `chat` marks a
26
32
  // session holding a chat (#875), which otherwise reads like any other.
@@ -2,7 +2,6 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
2
2
  import { useMemo, useRef } from 'react';
3
3
  import { Box, Static, Text } from 'ink';
4
4
  import chalk from 'chalk';
5
- import wrapAnsi from 'wrap-ansi';
6
5
  import stringWidth from 'string-width';
7
6
  import { hideDanglingMarkers, renderMarkdown, renderReasoningMarkdown } from './markdown.js';
8
7
  import { glyphs } from './glyphs.js';
@@ -11,10 +10,10 @@ import { scrubGeneration } from './identity.js';
11
10
  import { scrubDisplay, scrubOutput } from './scrub.js';
12
11
  import { DiffView } from './DiffView.js';
13
12
  import { changeLabel, formatDurationMs, toolLabel, toolTimer, toolVerb } from './format.js';
14
- import { contentWidth, hangingWrap } from './layout.js';
13
+ import { contentWidth, hangingWrap, wrapLines } from './layout.js';
15
14
  import { foldedAssistantFields, foldedLiveFields } from './reasoningfold.js';
16
15
  import { OUTPUT_TAIL_LINES } from '../tools/bash.js';
17
- export function Scrollback({ messages, streaming, streamingReasoning, streamingTool, streamingNested = false, streamingNote = false, streamingCommand = false, pendingTool = '', pendingToolMs = 0, chromeRows = 0, showHeldWorked = true, }) {
16
+ export function Scrollback({ messages, streaming, streamingReasoning, streamingTool, streamingNested = false, streamingNote = false, streamingCommand = false, pendingTool = '', pendingToolMs = 0, pendingCommand = '', chromeRows = 0, showHeldWorked = true, }) {
18
17
  // The live (non-Static) region must never grow taller than the viewport: Ink can't
19
18
  // erase a frame taller than the screen, which is what produces the "duplicated
20
19
  // terminal" on long streamed output and breaks native scrollback. Each active stream
@@ -55,14 +54,25 @@ export function Scrollback({ messages, streaming, streamingReasoning, streamingT
55
54
  }
56
55
  const { log: scrollback, held } = useScrollbackLog(messages);
57
56
  const pendingGap = pendingTool ? pendingToolGap(pendingTool, scrollback.at(-1)) : 0;
58
- const pool = region - (pendingTool ? 1 + pendingGap : 0) - blocks.reduce((sum, b) => sum + b.fixed, 0);
57
+ const commandWidth = contentWidth(COMMAND_MARGIN + indent);
58
+ const commandLines = pendingTool && pendingCommand
59
+ ? hangingWrap(scrubOutput(pendingCommand), commandWidth, SHELL_MARKER.length).split('\n')
60
+ : [];
61
+ const poolBeforeCommand = region - (pendingTool ? 1 + pendingGap : 0) - blocks.reduce((sum, b) => sum + b.fixed, 0);
62
+ // The output tail keeps its room (the rows the chip will show), and a long command gives up
63
+ // its rows past that, ending in `…` — the chip draws all of it once it commits.
64
+ const commandRows = commandLines.length === 0
65
+ ? 0
66
+ : Math.min(commandLines.length, Math.max(1, poolBeforeCommand - 1 - OUTPUT_TAIL_LINES));
67
+ const commandCut = commandRows < commandLines.length;
68
+ const pool = poolBeforeCommand - (commandRows ? 1 + commandRows : 0);
59
69
  // A running command's tail is held to the rows its committed chip shows: grown to the pool, it
60
70
  // pushed the input to the bottom and then dropped it by the difference when the chip replaced it.
61
71
  const shares = allocateLiveRows(blocks.map(b => {
62
72
  const need = b.live.cut ? Infinity : b.live.rows.length;
63
73
  return b.kind === 'tool' && streamingCommand ? Math.min(need, OUTPUT_TAIL_LINES) : need;
64
74
  }), pool);
65
- const live = (_jsxs(_Fragment, { children: [pendingTool ? (_jsx(Box, { marginTop: pendingGap, children: _jsxs(Text, { color: theme.secondary, children: [_jsx(Text, { color: theme.tool, children: TOOL_MARKER }), `${toolVerb(pendingTool)}…`, _jsx(Text, { color: theme.muted, children: toolTimer(pendingTool, pendingToolMs) })] }) })) : null, blocks.map((b, i) => b.kind === 'reasoning' ? (_jsx(Box, { marginTop: 1, children: _jsx(ReasoningBlock, { lines: b.live.rows.slice(-shares[i]), barColor: streamingNote ? theme.info : undefined }) }, b.kind)) : b.kind === 'content' && streamingNote ? (_jsx(NoteBody, { tail: fitTail(b.live, shares[i]), joined: blocks[i - 1]?.kind === 'reasoning' }, b.kind)) : (_jsx(StreamingTail, { tail: fitTail(b.live, shares[i]), muted: b.kind === 'tool',
75
+ const live = (_jsxs(_Fragment, { children: [pendingTool ? (_jsx(Box, { marginTop: pendingGap, children: _jsxs(Text, { color: theme.secondary, children: [_jsx(Text, { color: theme.tool, children: TOOL_MARKER }), `${toolVerb(pendingTool)}…`, _jsx(Text, { color: theme.muted, children: toolTimer(pendingTool, pendingToolMs) })] }) })) : null, commandRows ? (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginLeft: COMMAND_MARGIN, children: [_jsxs(Text, { children: [_jsx(Text, { color: theme.success, children: SHELL_MARKER }), _jsx(Text, { children: commandLines.slice(0, commandCut ? commandRows - 1 : commandRows).join('\n') })] }), commandCut ? _jsx(Text, { color: theme.muted, children: "\u2026" }) : null] })) : null, blocks.map((b, i) => b.kind === 'reasoning' ? (_jsx(Box, { marginTop: 1, children: _jsx(ReasoningBlock, { lines: b.live.rows.slice(-shares[i]), barColor: streamingNote ? theme.info : undefined }) }, b.kind)) : b.kind === 'content' && streamingNote ? (_jsx(NoteBody, { tail: fitTail(b.live, shares[i]), joined: blocks[i - 1]?.kind === 'reasoning' }, b.kind)) : (_jsx(StreamingTail, { tail: fitTail(b.live, shares[i]), muted: b.kind === 'tool',
66
76
  // Relative to the live wrapper (which already pays `indent`), so a command's output
67
77
  // lands where the committed one will: inside the chip's margin, or flush left.
68
78
  offset: b.kind === 'tool' ? toolOffset : 0 }, b.kind)))] }));
@@ -126,7 +136,7 @@ function liveContentWidth(indent = 0) {
126
136
  // exceeds the viewport. Wrapped with the exact wrap-ansi options Ink uses (build/wrap-text.js), so
127
137
  // the count matches and Ink's own re-wrap of a row is a no-op (rows are already ≤ width).
128
138
  export function displayRows(text, width) {
129
- return wrapAnsi(text, width, { trim: false, hard: true }).split('\n');
139
+ return wrapLines(text, width).split('\n');
130
140
  }
131
141
  // The block's last rows that fit `allowance`, the "…" marker counted inside it.
132
142
  export function fitTail(block, allowance) {
@@ -285,6 +295,29 @@ const liveReasoningRows = lastCall(streamingReasoningRows, paintKey);
285
295
  const liveContentRows = lastCall(streamingContentRows, paintKey);
286
296
  const liveNoteRows = lastCall(streamingNoteRows, paintKey);
287
297
  const liveToolRows = lastCall(streamingToolRows, paintKey);
298
+ // A discarded stream, drawn as its live tail was: the same builders and row split, so the committed
299
+ // rows take the live rows' place one for one and the input stays where it was. At least as tall as
300
+ // what was on screen, since the live region it was split against also paid for any dialog chrome.
301
+ function FrozenStream({ reasoning, content, note, indent, }) {
302
+ const region = liveRegionRows();
303
+ const folded = note ? { reasoning, content } : foldedLiveFields(reasoning, content);
304
+ const blocks = [];
305
+ if (folded.reasoning) {
306
+ const columns = process.stdout.columns || 80;
307
+ const live = streamingReasoningRows(folded.reasoning, indent, region, columns);
308
+ blocks.push({ kind: 'reasoning', live, fixed: 2 });
309
+ }
310
+ if (folded.content.trim()) {
311
+ const width = liveContentWidth(indent);
312
+ const live = note
313
+ ? streamingNoteRows(folded.content, width, region)
314
+ : streamingContentRows(folded.content, width, region);
315
+ blocks.push({ kind: 'content', live, fixed: note ? 3 : 1 });
316
+ }
317
+ const pool = region - blocks.reduce((sum, b) => sum + b.fixed, 0);
318
+ const shares = allocateLiveRows(blocks.map(b => (b.live.cut ? Infinity : b.live.rows.length)), pool);
319
+ return (_jsx(Box, { flexDirection: "column", children: blocks.map((b, i) => b.kind === 'reasoning' ? (_jsx(Box, { marginTop: 1, children: _jsx(ReasoningBlock, { lines: b.live.rows.slice(-shares[i]), barColor: note ? theme.info : undefined }) }, b.kind)) : note ? (_jsx(NoteBody, { tail: fitTail(b.live, shares[i]), joined: i > 0 }, b.kind)) : (_jsx(StreamingTail, { tail: fitTail(b.live, shares[i]) }, b.kind))) }));
320
+ }
288
321
  // `offset` is how far inside the live wrapper the committed row will sit (the command chip's
289
322
  // margin), so the tail doesn't jump sideways when it commits (#461).
290
323
  function StreamingTail({ tail, muted = false, offset = 0, }) {
@@ -305,7 +338,7 @@ function NoteBody({ tail, joined }) {
305
338
  return (_jsxs(Box, { flexDirection: "column", marginTop: joined ? 0 : 1, children: [joined ? _jsx(NoteBarRow, {}) : null, _jsx(NoteBarRow, { children: _jsx(Text, { color: theme.info, bold: true, children: NOTE_LABEL }) }), _jsx(NoteBarRow, {}), tail.marker ? (_jsx(NoteBarRow, { children: _jsx(Text, { color: theme.muted, children: '…' }) })) : null, tail.text.split('\n').map((row, i) => (_jsx(NoteBarRow, { children: row }, i)))] }));
306
339
  }
307
340
  function CompactionNoteBlock({ note, reasoning, indent, }) {
308
- return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [reasoning ? (_jsx(ReasoningBlock, { lines: reasoningLines(reasoning, indent), barColor: theme.info })) : null, _jsx(NoteBody, { tail: { text: noteBodyRows(note, contentWidth(indent)).join('\n'), marker: false }, joined: !!reasoning })] }));
341
+ return (_jsxs(Box, { flexDirection: "column", marginTop: reasoning ? 1 : 0, children: [reasoning ? (_jsx(ReasoningBlock, { lines: reasoningLines(reasoning, indent), barColor: theme.info })) : null, _jsx(NoteBody, { tail: { text: noteBodyRows(note, contentWidth(indent)).join('\n'), marker: false }, joined: !!reasoning })] }));
309
342
  }
310
343
  function plural(n, word) {
311
344
  return `${n} ${word}${n === 1 ? '' : 's'}`;
@@ -515,6 +548,9 @@ function renderMessage(msg, indent = 0, ctx = {}) {
515
548
  // The transcript already redacts shell messages on save; this brings the UI in line with it.
516
549
  return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: theme.success, children: SHELL_MARKER }), _jsx(Text, { children: hangingWrap(scrubOutput(msg.command), contentWidth(indent), SHELL_MARKER.length) })] }), msg.output.trimEnd() ? (_jsx(Text, { color: theme.muted, children: hangingWrap(scrubOutput(msg.output.trimEnd()), contentWidth(indent), 0) })) : null] }));
517
550
  }
551
+ if (msg.role === 'assistant' && msg.discarded) {
552
+ return (_jsx(FrozenStream, { reasoning: msg.reasoning ?? '', content: msg.content, note: msg.discarded === 'note', indent: indent }));
553
+ }
518
554
  if (msg.role === 'assistant' && msg.compactionNote) {
519
555
  return (_jsx(CompactionNoteBlock, { note: msg.content ?? '', reasoning: msg.reasoning, indent: indent }));
520
556
  }
@@ -636,7 +672,7 @@ function UserBubble({ text, indent = 0, nested = false, }) {
636
672
  function wrapText(text, width) {
637
673
  const out = [];
638
674
  for (const raw of text.split('\n')) {
639
- const rows = wrapAnsi(raw, width, { trim: false, hard: true }).split('\n');
675
+ const rows = wrapLines(raw, width).split('\n');
640
676
  // The space a break landed on heads the next row; a leading space on a real line is content.
641
677
  rows.forEach((row, i) => out.push(i === 0 ? row : row.replace(/^ +/, '')));
642
678
  }
package/dist/ui/Status.js CHANGED
@@ -28,8 +28,9 @@ export function statusChips({ model, turns, status, elapsed, usage, contextToken
28
28
  const busy = elapsed !== null;
29
29
  const timer = busy ? ` · ${formatElapsed(elapsed)}` : '';
30
30
  const keys = busy ? 'ctrl-c to abort' : 'ctrl-c to exit';
31
+ const approx = usage.estimated ? '~' : '';
31
32
  const tokens = usage.promptTokens > 0 || usage.completionTokens > 0
32
- ? `${kFormat(usage.promptTokens)}↑ ${kFormat(usage.completionTokens)}↓`
33
+ ? `${approx}${kFormat(usage.promptTokens)}↑ ${approx}${kFormat(usage.completionTokens)}↓`
33
34
  : '';
34
35
  // Current context size and how full the window is. The fill % drives the color so a
35
36
  // long run that's approaching the limit is visible at a glance.
@@ -165,7 +166,9 @@ export function formatCache(cachedTokens, contextTokens) {
165
166
  const pct = Math.round((cachedTokens / contextTokens) * 100);
166
167
  return cachedTokens > 0 ? `${pct}% cached (${kFormat(cachedTokens)})` : `${pct}% cached`;
167
168
  }
168
- // `PR #12` when the branch has an open PR, empty when it doesn't (or we couldn't tell). The
169
+ // `PR #12` when the branch has an open PR, `PR #12 draft` or `PR #12 merged` when that changes
170
+ // what the branch is for, empty when there is none (or we couldn't tell). Merged gets a color of
171
+ // its own: it is the one state where the next commit on this branch goes nowhere. The
169
172
  // number is the click target, the `PR` label is not, so the chip comes in two segments — and the
170
173
  // separating space rides on the *label*, not the number: a segment's underline runs the whole
171
174
  // width of the segment it is on, so a leading space inside the number would draw a column of
@@ -184,11 +187,21 @@ export function prChip(pr, links = supportsHyperlink(process.stdout)) {
184
187
  const label = { text: 'PR ', color: theme.secondary };
185
188
  const shown = `#${number}`;
186
189
  const url = pr?.url;
190
+ // Outside the link, or the underline would run under the word and past the click target.
191
+ const suffix = pr?.state
192
+ ? [
193
+ {
194
+ text: ` ${pr.state}`,
195
+ color: pr.state === 'merged' ? theme.prMerged : theme.secondary,
196
+ },
197
+ ]
198
+ : [];
187
199
  if (url && links) {
188
200
  return [
189
201
  label,
190
202
  { text: `\x1b]8;;${url}\x07${shown}\x1b]8;;\x07`, color: theme.link, underline: true },
203
+ ...suffix,
191
204
  ];
192
205
  }
193
- return [label, { text: shown, color: url ? theme.link : theme.secondary }];
206
+ return [label, { text: shown, color: url ? theme.link : theme.secondary }, ...suffix];
194
207
  }
package/dist/ui/layout.js CHANGED
@@ -32,11 +32,38 @@ export function useContentWidth(indent = 0) {
32
32
  }, [indent]);
33
33
  return width;
34
34
  }
35
+ // wrap-ansi measures every word with string-width (a grapheme segmenter plus an emoji regex),
36
+ // which was ~45% of drawing a resumed 1.3MB session, mostly on rows that already fit. A line of
37
+ // printable ASCII under CSI codes that fits comes back from it byte-for-byte, so it is returned
38
+ // as is; anything else (wide or combining text, tabs, hyperlinks, a trim that would bite) goes
39
+ // to wrap-ansi. Same options as Ink's wrap, so the rows are the ones Ink would draw.
40
+ // The punctuation models write most (`→`, `—`, `✓`, `…`, `•`: a fifth of a measured session's
41
+ // rows held one) passes too: each is one code unit, one string-width cell and NFC-stable, which is
42
+ // all the shortcut assumes — `layout.test.ts` checks every one.
43
+ export const NARROW_PUNCTUATION = '→←↑↓—–…•·×✓≠≤≥‘’“”│─';
44
+ const STYLED_ASCII = new RegExp(`^[\\x20-\\x7e\\x1b${NARROW_PUNCTUATION}]*$`);
45
+ const CSI_SEQUENCE = /\x1b\[[0-9;]*[A-Za-z]/g;
46
+ function fitsUnwrapped(line, width, trim) {
47
+ if (!STYLED_ASCII.test(line))
48
+ return false;
49
+ const plain = line.includes('\x1b') ? line.replace(CSI_SEQUENCE, '') : line;
50
+ if (plain.length > width || plain.includes('\x1b'))
51
+ return false;
52
+ return !trim || !(plain.startsWith(' ') || plain.endsWith(' '));
53
+ }
54
+ export function wrapLines(text, width, trim = false) {
55
+ const lines = text.split('\n');
56
+ if (lines.every(line => fitsUnwrapped(line, width, trim)))
57
+ return text;
58
+ return lines
59
+ .map(line => fitsUnwrapped(line, width, trim) ? line : wrapAnsi(line, width, { trim, hard: true }))
60
+ .join('\n');
61
+ }
35
62
  // Display rows `text` takes at `width` columns — the unit Ink measures a frame in when it decides
36
63
  // the frame is as tall as the viewport. Wrapped with the exact options Ink wraps with
37
64
  // (build/wrap-text.js), so a row count measured here is the row count that gets drawn.
38
65
  export function wrappedRows(text, width) {
39
- return wrapAnsi(text, Math.max(1, width), { trim: false, hard: true }).split('\n').length;
66
+ return wrapLines(text, Math.max(1, width)).split('\n').length;
40
67
  }
41
68
  // Wrap styled text into rows that each carry every style active where they start (#852).
42
69
  //
@@ -45,9 +72,10 @@ export function wrappedRows(text, width) {
45
72
  // default foreground; a changed word in a diff is a background then a foreground, and lost its
46
73
  // highlight the same way. So the state at each row's end is replayed at the next row's start, and
47
74
  // closed at the row's end so a row never leaks a style into whatever Ink draws after it. Same
48
- // options as Ink's own wrap, so the break points and row count are unchanged.
49
- export function wrapStyledRows(text, width) {
50
- const rows = wrapAnsi(text, Math.max(1, width), { trim: false, hard: true }).split('\n');
75
+ // options as Ink's own wrap, so the break points and row count are unchanged. `trim` is for a caller
76
+ // that wraps prose itself (markdown), where wrap-ansi's default drops the space a break lands on.
77
+ export function wrapStyledRows(text, width, trim = false) {
78
+ const rows = wrapLines(text, Math.max(1, width), trim).split('\n');
51
79
  let open = new Map();
52
80
  return rows.map(row => {
53
81
  const lead = [...open.values()].join('');
@@ -172,12 +200,9 @@ export function hangingWrap(text, width, hang, first = hang) {
172
200
  const out = [];
173
201
  let atStart = true;
174
202
  for (const line of text.split('\n')) {
175
- const rows = wrapAnsi(atStart ? lead + line : line, wrapAt, {
176
- // Ink's own options (build/wrap-text.js), so the break points match what Ink would have
177
- // chosen and this stays a re-formatting of Ink's wrap rather than a second, different one.
178
- trim: false,
179
- hard: true,
180
- }).split('\n');
203
+ // Ink's own options (build/wrap-text.js), so the break points match what Ink would have
204
+ // chosen and this stays a re-formatting of Ink's wrap rather than a second, different one.
205
+ const rows = wrapLines(atStart ? lead + line : line, wrapAt).split('\n');
181
206
  rows.forEach((row, i) => {
182
207
  // trim:false leaves the whitespace wrap-ansi broke on at the head of the continuation row —
183
208
  // the whole run of it, so a line that breaks inside expanded tabs staggers further right on
@@ -3,11 +3,10 @@ import { Lexer } from 'marked';
3
3
  import stringWidth from 'string-width';
4
4
  import stripAnsi from 'strip-ansi';
5
5
  import { supportsHyperlink } from 'supports-hyperlinks';
6
- import wrapAnsi from 'wrap-ansi';
7
6
  import { theme, themeChalk } from './theme.js';
8
7
  import { highlightCode } from './highlight.js';
9
8
  import { drawnWidth, sanitizeTerminalText } from './termtext.js';
10
- import { contentWidth } from './layout.js';
9
+ import { contentWidth, wrapStyledRows } from './layout.js';
11
10
  // Left indent of a top-level list.
12
11
  const TAB_WIDTH = 2;
13
12
  // Narrowest a nested block wraps at, however deep it sits: below this a line holds a word or two.
@@ -15,9 +14,11 @@ const MIN_PROSE_WIDTH = 20;
15
14
  function proseWidth(ctx) {
16
15
  return Math.max(MIN_PROSE_WIDTH, ctx.width);
17
16
  }
18
- // `hard` splits a bare URL longer than the line instead of letting it overflow.
17
+ // `hard` splits a bare URL longer than the line instead of letting it overflow. Styled rows, not
18
+ // bare wrap-ansi: it re-opens a named color at a break but not a hex one, so an inline code span
19
+ // that wrapped lost its color from the second row on.
19
20
  function wrapProse(text, ctx) {
20
- return wrapAnsi(text, proseWidth(ctx), { hard: true });
21
+ return wrapStyledRows(text, proseWidth(ctx), true).join('\n');
21
22
  }
22
23
  function renderBlocks(tokens, ctx) {
23
24
  return tokens
@@ -115,7 +116,7 @@ function renderTable(table, ctx) {
115
116
  const border = themeChalk(theme.muted);
116
117
  const rule = (left, mid, right) => border(left + widths.map(w => '─'.repeat(w)).join(mid) + right);
117
118
  const drawRow = (row, paint) => {
118
- const wrapped = widths.map((w, col) => wrapAnsi(row[col] ?? '', Math.max(1, w - 2), { hard: true }).split('\n'));
119
+ const wrapped = widths.map((w, col) => wrapStyledRows(row[col] ?? '', Math.max(1, w - 2), true));
119
120
  const height = Math.max(...wrapped.map(lines => lines.length));
120
121
  const lines = [];
121
122
  for (let r = 0; r < height; r++) {
package/dist/ui/pr.js CHANGED
@@ -7,8 +7,8 @@ import { execFile } from 'node:child_process';
7
7
  // shows, the URL is what makes it click (ui/Status.tsx opens an OSC 8 hyperlink on it).
8
8
  const GIT_TIMEOUT_MS = 2_000;
9
9
  const GH_TIMEOUT_MS = 4_000;
10
- // A PR opened mid-session should appear without a restart; a merged one should stop
11
- // showing eventually. Neither is urgent, so both TTLs sit well above the poll interval.
10
+ // A PR opened mid-session should appear without a restart; a merge should reach the badge
11
+ // eventually. Neither is urgent, so both TTLs sit well above the poll interval.
12
12
  const MISS_TTL_MS = 60_000;
13
13
  const HIT_TTL_MS = 300_000;
14
14
  const cache = new Map();
@@ -36,13 +36,13 @@ export async function currentBranch(cwd) {
36
36
  return out?.trim() || null;
37
37
  }
38
38
  async function lookupPr(cwd, branch) {
39
- const out = await run('gh', ['pr', 'view', branch, '--json', 'number,state,url'], cwd, GH_TIMEOUT_MS);
39
+ const out = await run('gh', ['pr', 'view', branch, '--json', 'number,state,isDraft,url'], cwd, GH_TIMEOUT_MS);
40
40
  return out ? parsePrView(out) : null;
41
41
  }
42
- // `gh` reports the newest PR for the branch whatever its state; a closed or merged number
43
- // is stale the moment it lands, so only an open one earns the status-bar slot. Draft isn't
44
- // a state (drafts are OPEN + isDraft), so they show like any other open PR — deliberate:
45
- // the badge answers "which PR is this branch", not "is it ready".
42
+ // `gh` reports the newest PR for the branch whatever its state. Merged stays on the badge: people
43
+ // stay on a branch after it lands, a commit there goes nowhere, and a badge that just vanishes
44
+ // reads the same as `gh` failing. Closed does not, since it says nothing about what to do next.
45
+ // Draft isn't a state to `gh` (drafts are OPEN + isDraft).
46
46
  // The URL rides along only when `gh` gave us a usable one: it is the click target, never the
47
47
  // label, so its absence costs the hyperlink and nothing else.
48
48
  export function parsePrView(stdout) {
@@ -50,10 +50,16 @@ export function parsePrView(stdout) {
50
50
  const data = JSON.parse(stdout);
51
51
  if (typeof data.number !== 'number')
52
52
  return null;
53
- if (typeof data.state === 'string' && data.state.toUpperCase() !== 'OPEN')
53
+ const state = typeof data.state === 'string' ? data.state.toUpperCase() : 'OPEN';
54
+ if (state !== 'OPEN' && state !== 'MERGED')
54
55
  return null;
55
56
  const url = typeof data.url === 'string' && data.url ? data.url : undefined;
56
- return url ? { number: data.number, url } : { number: data.number };
57
+ const pr = url ? { number: data.number, url } : { number: data.number };
58
+ if (state === 'MERGED')
59
+ pr.state = 'merged';
60
+ else if (data.isDraft === true)
61
+ pr.state = 'draft';
62
+ return pr;
57
63
  }
58
64
  catch {
59
65
  return null;
@@ -0,0 +1,15 @@
1
+ // React, its JSX runtime and Ink's reconciler each pick a build from NODE_ENV when first loaded, so
2
+ // the TUI ran the development ones (~12% slower resume, ~10% more CPU). Scoped to the load because
3
+ // bash and every other child inherit process.env: `npm install` under production skips
4
+ // devDependencies. An explicit NODE_ENV is the user's and is left alone.
5
+ export async function loadWithProductionReact(load) {
6
+ if (process.env.NODE_ENV !== undefined)
7
+ return load();
8
+ process.env.NODE_ENV = 'production';
9
+ try {
10
+ return await load();
11
+ }
12
+ finally {
13
+ delete process.env.NODE_ENV;
14
+ }
15
+ }
@@ -3,7 +3,7 @@ import { formatElapsed } from './format.js';
3
3
  export function buildSummary(messages, usage, startedAt, approvals) {
4
4
  const elapsed = Math.floor((Date.now() - startedAt) / 1000);
5
5
  const userTurns = messages.filter(m => m.role === 'user' && !m.nested && !m.meta).length;
6
- const assistantTurns = messages.filter(m => m.role === 'assistant' && !m.nested && !m.compactionNote).length;
6
+ const assistantTurns = messages.filter(m => m.role === 'assistant' && !m.nested && !m.compactionNote && !m.discarded).length;
7
7
  const toolCounts = {};
8
8
  const files = new Set();
9
9
  for (const m of messages) {
@@ -36,6 +36,7 @@ export function buildSummary(messages, usage, startedAt, approvals) {
36
36
  .sort()
37
37
  .map(f => scrubPaths(f))
38
38
  .join(', ');
39
+ const approx = usage.estimated ? '~' : '';
39
40
  return [
40
41
  'Session summary',
41
42
  '─'.repeat(40),
@@ -43,7 +44,7 @@ export function buildSummary(messages, usage, startedAt, approvals) {
43
44
  `Turns: ${userTurns} user · ${assistantTurns} assistant`,
44
45
  `Tools: ${totalTools}${breakdown}`,
45
46
  `Subagents: ${subagentCount}`,
46
- `Tokens: ${usage.promptTokens.toLocaleString()} ↑ ${usage.completionTokens.toLocaleString()} ↓`,
47
+ `Tokens: ${approx}${usage.promptTokens.toLocaleString()} ↑ ${approx}${usage.completionTokens.toLocaleString()} ↓`,
47
48
  ...(usage.cachedTokens && usage.promptTokens > 0
48
49
  ? [
49
50
  `Cache hits: ${usage.cachedTokens.toLocaleString()} (${Math.round((usage.cachedTokens / usage.promptTokens) * 100)}% of prompt)`,
@@ -98,10 +98,14 @@ const ASKS_FOR_EMOJI = /\uFE0F/;
98
98
  const ASKS_FOR_TEXT = /\uFE0E/;
99
99
  const segmenter = new Intl.Segmenter();
100
100
  export function drawnWidth(text) {
101
+ const plain = stripAnsi(text);
102
+ // Printable ASCII is one cell a character on every path below; skip the segmenter for it.
103
+ if (/^[\x20-\x7e]*$/.test(plain))
104
+ return plain.length;
101
105
  let width = 0;
102
106
  // Grapheme by grapheme, the way string-width counts: a ZWJ sequence is one glyph on screen and
103
107
  // a combining mark spends no cell of its own.
104
- for (const { segment } of segmenter.segment(stripAnsi(text))) {
108
+ for (const { segment } of segmenter.segment(plain)) {
105
109
  const measured = stringWidth(segment);
106
110
  const textPresentation = measured === 2 &&
107
111
  PICTOGRAPHIC.test(segment) &&
package/dist/ui/theme.js CHANGED
@@ -58,6 +58,10 @@ const truecolor = {
58
58
  // that marks the Thinking bar. Underlined only on terminals that take OSC 8 hyperlinks
59
59
  // (markdown.ts): an underline promises a click, and elsewhere there is none to deliver.
60
60
  link: '#aac0f0',
61
+ // `merged` on the status line's PR chip. GitHub's merged purple, so it reads without a legend.
62
+ // Not `warning`, which the context gauge on the same line turns at 80% fill, and more saturated
63
+ // than the agent tag's soft magenta at the other end of that line.
64
+ prMerged: '#b48cf0',
61
65
  };
62
66
  // A 16-color terminal (the Linux console, TERM=vt100/ansi, an old ssh client) gets named colors in
63
67
  // place of the pastels. Chalk downsamples a hex to the nearest of 16, and nearly every pastel above
@@ -83,6 +87,7 @@ const ansi16 = {
83
87
  modeGrind: 'magenta',
84
88
  modeChat: 'cyan',
85
89
  modeShell: 'greenBright',
90
+ prMerged: 'magenta',
86
91
  link: 'blueBright',
87
92
  };
88
93
  export function themeForLevel(level) {
package/dist/ui/tui.js ADDED
@@ -0,0 +1,9 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { render } from 'ink';
3
+ import { App } from './App.js';
4
+ import { createSyncedStdout } from './syncframe.js';
5
+ export function startTui() {
6
+ // Frames go out as one synchronized write each (#345) so a swapped-out process can't leave the
7
+ // terminal painting a half-erased screen between Ink's writes.
8
+ render(_jsx(App, {}), { exitOnCtrlC: false, stdout: createSyncedStdout(process.stdout) });
9
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexwkleung/reika",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Coding agent CLI for local and hosted models, designed around small local models first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Alex Leung",