@alexwkleung/reika 0.7.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.
Files changed (43) hide show
  1. package/README.md +15 -0
  2. package/README.zh-CN.md +15 -0
  3. package/dist/agent/compaction.js +82 -27
  4. package/dist/agent/loop.js +84 -20
  5. package/dist/agent/prefillcost.js +16 -0
  6. package/dist/agent/prompt.js +5 -2
  7. package/dist/cli.js +5 -11
  8. package/dist/context/bootstrap.js +1 -1
  9. package/dist/debug.js +15 -0
  10. package/dist/{headless.js → headless/headless.js} +185 -48
  11. package/dist/{headlessargs.js → headless/headlessargs.js} +12 -2
  12. package/dist/headless/headlessprompt.js +132 -0
  13. package/dist/mcp/client.js +97 -5
  14. package/dist/mcp/manager.js +15 -2
  15. package/dist/provider/client.js +13 -0
  16. package/dist/session.js +12 -1
  17. package/dist/{skills.js → skills/skills.js} +93 -13
  18. package/dist/store/sessions.js +40 -3
  19. package/dist/store/transcript.js +38 -1
  20. package/dist/tools/_carriers.js +119 -0
  21. package/dist/tools/_danger.js +305 -82
  22. package/dist/tools/_readonly.js +13 -12
  23. package/dist/tools/_sandbox.js +13 -5
  24. package/dist/ui/App.js +288 -83
  25. package/dist/ui/Approval.js +80 -33
  26. package/dist/ui/Confirm.js +1 -27
  27. package/dist/ui/DiffView.js +24 -14
  28. package/dist/ui/Question.js +152 -19
  29. package/dist/ui/ResumeSelect.js +13 -6
  30. package/dist/ui/Scrollback.js +44 -8
  31. package/dist/ui/Status.js +35 -10
  32. package/dist/ui/commands.js +1 -1
  33. package/dist/ui/dialogspecs.js +38 -0
  34. package/dist/ui/layout.js +149 -6
  35. package/dist/ui/markdown.js +6 -5
  36. package/dist/ui/pr.js +15 -9
  37. package/dist/ui/reactbuild.js +15 -0
  38. package/dist/ui/summary.js +3 -2
  39. package/dist/ui/termtext.js +5 -1
  40. package/dist/ui/theme.js +5 -0
  41. package/dist/ui/tui.js +9 -0
  42. package/package.json +1 -1
  43. /package/dist/{skillmatch.js → skills/skillmatch.js} +0 -0
package/dist/ui/App.js CHANGED
@@ -1,7 +1,7 @@
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';
4
- import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
2
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, } from 'react';
3
+ import { Box, Static, Text, measureElement, useApp, useInput } from 'ink';
4
+ import { basename, dirname, isAbsolute, resolve } from 'node:path';
5
5
  import { homedir } from 'node:os';
6
6
  import { Splash } from './Splash.js';
7
7
  import { Scrollback } from './Scrollback.js';
@@ -9,13 +9,14 @@ import { VERSION } from '../version.js';
9
9
  import { Input } from './Input.js';
10
10
  import { Working, WORKING_WORDS } from './Working.js';
11
11
  import { PlanProgress, planProgressRows } from './PlanProgress.js';
12
- import { Status } from './Status.js';
12
+ import { Status, statusRows } from './Status.js';
13
13
  import { createSession } from '../session.js';
14
14
  import { resolvePr } from './pr.js';
15
15
  import { clearIdentity, enableAnon, isAnon } from './identity.js';
16
16
  import { theme } from './theme.js';
17
- import { APPROVAL_FEEDBACK_INDEX, APPROVAL_OPTIONS, Approval } from './Approval.js';
18
- import { CONFIRM_ACCEPT, CONFIRM_DECLINE, Confirm, TOGGLE_CANCEL, TOGGLE_OFF, TOGGLE_ON, implementModeConfirmSpec, pastedUrlConfirmSpec, skillConfirmSpec, toggleConfirmSpec, } from './Confirm.js';
17
+ import { Approval } from './Approval.js';
18
+ import { APPROVAL_FEEDBACK_INDEX, APPROVAL_OPTIONS, CONFIRM_ACCEPT, CONFIRM_DECLINE, pastedUrlConfirmSpec, skillConfirmSpec, } from './dialogspecs.js';
19
+ import { Confirm, TOGGLE_CANCEL, TOGGLE_OFF, TOGGLE_ON, implementModeConfirmSpec, toggleConfirmSpec, } from './Confirm.js';
19
20
  import { Question, questionDialogHeight } from './Question.js';
20
21
  import { inheritProfile, loadConfig, modeSwitchProfile, resolveDefaultMode, resolveProfile, } from '../config.js';
21
22
  import { loadLastState, persistableMode, saveLastState, startMode, startProfiles, } from '../laststate.js';
@@ -25,7 +26,7 @@ import { budgetWarning, formatBudget } from '../context/bundlesize.js';
25
26
  import { debugEnabled, debugLog, processSessionStem } from '../debug.js';
26
27
  import { noteFrameState } from './framedrops.js';
27
28
  import { addFileToIndex } from '../context/files.js';
28
- import { saveTranscript, TRANSCRIPT_VERSION, } from '../store/transcript.js';
29
+ import { saveTranscript, buildTranscriptMeta, } from '../store/transcript.js';
29
30
  import {} from '../agent/loop.js';
30
31
  import { compactThreshold } from '../agent/compaction.js';
31
32
  import { createPrefixWarmer } from '../agent/warm.js';
@@ -34,7 +35,7 @@ import { isOffline } from '../tools/_net.js';
34
35
  import { expandMentions } from '../agent/mentions.js';
35
36
  import { attachImageBlocks, NATIVE_IMAGE_NOTE, readNativeAttachments, nextImageMarker, } from '../agent/attachments.js';
36
37
  import { expandPastedUrls, planPastedUrls } from '../agent/pastedurls.js';
37
- import { matchSkill, shouldConfirmInject } from '../skillmatch.js';
38
+ import { matchSkill, shouldConfirmInject } from '../skills/skillmatch.js';
38
39
  import { imageReader, pasteIsNative } from '../ocr/select.js';
39
40
  import { systemOcr } from '../ocr/system.js';
40
41
  import { sniffImageMime } from '../ocr/vision.js';
@@ -43,8 +44,9 @@ import { isWarmEdge } from './warmtrigger.js';
43
44
  import { Suggestions, suggestionRows } from './Suggestions.js';
44
45
  import { ModelSelect } from './ModelSelect.js';
45
46
  import { mcpStartupLine } from './format.js';
47
+ import { useContentWidth } from './layout.js';
46
48
  import { ResumeSelect } from './ResumeSelect.js';
47
- import { countRealTurns, forAutosave, listSessions, loadSession, modelHistoryFromScrollback, newSessionPath, projectHistoryDir, ROOT_HISTORY_DIR, writeSession, } from '../store/sessions.js';
49
+ import { countRealTurns, forAutosave, listSessions, loadSession, modelHistoryFromScrollback, newSessionPath, projectHistoryDir, ROOT_HISTORY_DIR, saveHeader, writeSession, } from '../store/sessions.js';
48
50
  import { buildModelTargets } from './models.js';
49
51
  import { buildImplementPrompt, buildSearchPrompt, IMPLEMENT_MODES, isImplementCommand, isMinimalPrompt, isGrindPrompt, isSaveCommand, nextMode, searchModeRefusal, searchUnavailableNotice, turnMode, turnPromptMode, turnRefines, turnTools, } from './commands.js';
50
52
  import { acceptSuggestion, computeSuggestions } from './suggest.js';
@@ -76,6 +78,29 @@ function promptPlaceholder() {
76
78
  return withHint.length + 6 <= (process.stdout.columns || 80) ? withHint : base;
77
79
  }
78
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;
92
+ // A resumed session reaches the scrollback a slice at a time (#854): a commit renders its messages'
93
+ // markdown, highlighting and wrap synchronously, and one commit for the whole session held the
94
+ // event loop — the resuming spinner's timer included — for as long as that took (~2s at 460
95
+ // messages). Slices are sized to about this long each, so the spinner ticks between them.
96
+ const RESUME_SLICE_MS = 40;
97
+ const RESUME_FIRST_SLICE = 4;
98
+ // Scaled from how long the last slice took, so its cost does not depend on what the messages hold;
99
+ // growth is held to doubling, since a run of tiny messages says little about the next ones.
100
+ function nextResumeSliceSize(size, tookMs) {
101
+ const scaled = Math.round((size * RESUME_SLICE_MS) / Math.max(tookMs, 1));
102
+ return Math.min(Math.max(scaled, 1), size * 2);
103
+ }
79
104
  export function App() {
80
105
  const { exit } = useApp();
81
106
  const [messages, setMessages] = useState([]);
@@ -113,10 +138,24 @@ export function App() {
113
138
  // is the status bar's one-second tick (below) — a state of its own would repaint the live region
114
139
  // a second time every second for a value that changes on no other edge.
115
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);
116
152
  // A subagent owns the live region right now (#342): its streamed blocks draw at the nested indent.
117
153
  const [subagentLive, setSubagentLive] = useState(false);
118
154
  // The model is writing a compaction note (#280): nested like a subagent, labelled as itself.
119
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);
120
159
  // The session owns the config, the active profile, the bundle and everything a turn threads to
121
160
  // the next (#403); App renders from its snapshot and never keeps a copy of its own.
122
161
  const [session, setSession] = useState(null);
@@ -235,6 +274,9 @@ export function App() {
235
274
  // the note on the label below), and without this the picker just vanished and the app sat on a
236
275
  // stale frame until it landed.
237
276
  const [resuming, setResuming] = useState(null);
277
+ // Held for the whole resume, slices included: a submit or a mode switch between two slices would
278
+ // land its rows in the middle of the resumed scrollback, or swap it for the other side's.
279
+ const resumingRef = useRef(false);
238
280
  // `status` is still 'idle' during expansion (submitToModel flips it), so without this a second
239
281
  // Enter during a slow fetch starts a duplicate turn. Ref, not state: the handler closes over
240
282
  // its render's value, so a fast double-press would read a stale `false`.
@@ -265,6 +307,8 @@ export function App() {
265
307
  };
266
308
  const statusRef = useRef('loading');
267
309
  statusRef.current = status;
310
+ const pendingToolRef = useRef('');
311
+ pendingToolRef.current = pendingTool;
268
312
  const pendingRef = useRef(null);
269
313
  pendingRef.current = pending;
270
314
  const questionRef = useRef(null);
@@ -908,8 +952,9 @@ export function App() {
908
952
  // in-flight turn's tools and prompt, the same reason /plan et al. refuse while busy; a
909
953
  // keystroke shouldn't spam that refusal into scrollback, so it just no-ops.
910
954
  if (key.tab && key.shift) {
911
- if (statusRef.current === 'idle')
955
+ if (statusRef.current === 'idle' && !resumingRef.current) {
912
956
  transitionMode(nextMode(modeRef.current), []);
957
+ }
913
958
  return;
914
959
  }
915
960
  const sug = suggestionStateRef.current;
@@ -950,44 +995,26 @@ export function App() {
950
995
  // The header both /save and the auto-save write. `msgs` is what the file's body holds.
951
996
  const transcriptMeta = (msgs, cwd, midTurn) => {
952
997
  // Use the active profile's model/base so the saved meta reflects what was actually running,
953
- // not the default. Stamp savedAt here (the serializer is pure and takes no clock).
998
+ // not the default.
954
999
  const profile = config.profiles[activeProfileRef.current] ?? config.profiles.default;
955
- // Everything the status line shows, frozen at save time (#199). Computed exactly as the
956
- // status bar computes it — same turn count, same last-call-else-estimate context — so the
957
- // header and a screenshot of the footer can never disagree.
958
- const last = lastUsageRef.current;
959
- const totals = usageRef.current;
960
- const shrink = sessionRef.current?.shrink ?? { sheds: 0, folds: 0 };
961
- const window = profile.contextWindow ?? config.contextWindow;
962
- // The session's reserve is the learned one (#551), the number the next round compacts at.
963
- const minGen = sessionRef.current?.config.minGenTokens ?? profile.minGenTokens;
964
- const usable = window ? Math.round(compactThreshold(window, minGen)) : undefined;
965
- const usage = {
966
- turns: msgs.filter(m => m.role === 'assistant').length,
967
- promptTokens: totals.promptTokens,
968
- completionTokens: totals.completionTokens,
969
- ...(totals.cachedTokens != null ? { cachedTokens: totals.cachedTokens } : {}),
970
- contextTokens: last?.promptTokens ?? estimatedContextRef.current,
971
- // No call has landed yet, so the context size above is the pre-send estimate.
972
- ...(last?.promptTokens == null ? { contextEstimated: true } : {}),
973
- ...(window ? { contextWindow: window } : {}),
974
- ...(usable ? { contextUsable: usable } : {}),
975
- ...(last?.cachedTokens != null ? { lastCachedTokens: last.cachedTokens } : {}),
976
- ...(shrink.sheds > 0 || shrink.folds > 0
977
- ? { ...shrink, shrinkEvents: shrinkEventsRef.current }
978
- : {}),
979
- };
980
- return {
981
- version: TRANSCRIPT_VERSION,
982
- savedAt: new Date().toISOString(),
1000
+ return buildTranscriptMeta({
1001
+ msgs,
983
1002
  model: profile.model,
984
1003
  baseURL: profile.baseURL,
985
1004
  cwd,
986
- messageCount: msgs.length,
987
1005
  mode: modeRef.current,
988
- usage,
989
- ...(midTurn ? { midTurn: true } : {}),
990
- };
1006
+ midTurn,
1007
+ status: {
1008
+ totals: usageRef.current,
1009
+ lastUsage: lastUsageRef.current,
1010
+ estimatedContext: estimatedContextRef.current,
1011
+ shrink: sessionRef.current?.shrink ?? { sheds: 0, folds: 0 },
1012
+ shrinkEvents: shrinkEventsRef.current,
1013
+ contextWindow: profile.contextWindow ?? config.contextWindow,
1014
+ // The session's reserve is the learned one (#551), the number the next round compacts at.
1015
+ minGenTokens: sessionRef.current?.config.minGenTokens ?? profile.minGenTokens,
1016
+ },
1017
+ });
991
1018
  };
992
1019
  // Both sides of the chat boundary, wherever each currently lives.
993
1020
  const sessionSides = () => {
@@ -1081,9 +1108,16 @@ export function App() {
1081
1108
  autosaveHoldRef.current = null;
1082
1109
  };
1083
1110
  const resumeSession = async (entry, projectDir) => {
1084
- // Set before the first await, so the frame lands while the file is still being read: the
1085
- // commit below runs every message's markdown, syntax highlighting and wrap in one synchronous
1086
- // pass, and nothing the UI does after that point can paint until it finishes.
1111
+ resumingRef.current = true;
1112
+ try {
1113
+ await loadResumedSession(entry, projectDir);
1114
+ }
1115
+ finally {
1116
+ resumingRef.current = false;
1117
+ }
1118
+ };
1119
+ const loadResumedSession = async (entry, projectDir) => {
1120
+ // Set before the first await, so the frame lands while the file is still being read.
1087
1121
  setResuming(`Resuming "${entry.title ?? 'untitled'}"`);
1088
1122
  let sides;
1089
1123
  try {
@@ -1107,6 +1141,23 @@ export function App() {
1107
1141
  logSessionFile(entry.path);
1108
1142
  }
1109
1143
  autosaveHoldRef.current = countRealTurns(sides.agent) + countRealTurns(sides.chat);
1144
+ // A session with only one side opens on that side (#875): resumed from the other, it would
1145
+ // land on an empty screen, its messages one /chat or /agent away. A session with both stays
1146
+ // put. Leaving chat goes to agent rather than the session's last mode, which could be plan or
1147
+ // shell. The conversation was just reset, so there is no screen to stash — only the session's
1148
+ // side and the mode move.
1149
+ const agentTurns = countRealTurns(sides.agent);
1150
+ const chatTurns = countRealTurns(sides.chat);
1151
+ const switchedTo = modeRef.current !== 'chat' && agentTurns === 0 && chatTurns > 0
1152
+ ? 'chat'
1153
+ : modeRef.current === 'chat' && chatTurns === 0 && agentTurns > 0
1154
+ ? 'agent'
1155
+ : null;
1156
+ if (switchedTo) {
1157
+ sessionRef.current?.switchSide(switchedTo === 'chat' ? 'chat' : 'agent');
1158
+ modeRef.current = switchedTo;
1159
+ setMode(switchedTo);
1160
+ }
1110
1161
  const inChat = modeRef.current === 'chat';
1111
1162
  const active = inChat ? sides.chat : sides.agent;
1112
1163
  const other = inChat ? sides.agent : sides.chat;
@@ -1114,15 +1165,27 @@ export function App() {
1114
1165
  sessionRef.current?.loadHistory(modelHistoryFromScrollback(active), modelHistoryFromScrollback(other));
1115
1166
  const where = inChat ? 'chat' : 'agent';
1116
1167
  const otherNote = other.length > 0 ? ` (+ ${other.length} on the ${inChat ? 'agent' : 'chat'} side)` : '';
1117
- setMessages([
1168
+ const resumed = [
1118
1169
  ...active,
1119
1170
  {
1120
1171
  role: 'system',
1121
- content: `Resumed "${entry.title ?? 'untitled'}" — ${active.length} ${where} messages${otherNote} from ${entry.path}`,
1172
+ content: `Resumed "${entry.title ?? 'untitled'}" — ${active.length} ${where} messages${otherNote}${switchedTo ? `, switched to ${switchedTo} mode,` : ''} from ${entry.path}`,
1122
1173
  },
1123
- ]);
1124
- // Same commit as the messages, not a frame later: the spinner's rows are the ones the first
1125
- // resumed frame takes, so clearing it in a separate update would flash the live frame twice.
1174
+ ];
1175
+ let size = RESUME_FIRST_SLICE;
1176
+ for (let at = 0; at < resumed.length;) {
1177
+ const slice = resumed.slice(at, at + size);
1178
+ const started = performance.now();
1179
+ // The first slice replaces the old conversation; the rest extend it.
1180
+ setMessages(at === 0 ? slice : prev => [...prev, ...slice]);
1181
+ at += slice.length;
1182
+ if (at >= resumed.length)
1183
+ break;
1184
+ // A timer, not a microtask: the spinner ticks on an interval, which only a yield to the timer
1185
+ // phase lets fire. Measured past the yield, so the commit counts whenever React flushes it.
1186
+ await new Promise(resolve => setTimeout(resolve, 0));
1187
+ size = nextResumeSliceSize(size, performance.now() - started);
1188
+ }
1126
1189
  setResuming(null);
1127
1190
  };
1128
1191
  const requestExit = () => {
@@ -1201,6 +1264,16 @@ export function App() {
1201
1264
  setApprovalTyping(false);
1202
1265
  return new Promise(resolve => {
1203
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
+ }
1204
1277
  setApprovals(a => answer === true ? { ...a, approved: a.approved + 1 } : { ...a, declined: a.declined + 1 });
1205
1278
  resolve(answer);
1206
1279
  };
@@ -1210,7 +1283,13 @@ export function App() {
1210
1283
  const requestQuestion = (req) => {
1211
1284
  setQuestionSelected(0);
1212
1285
  setQuestionTyping(null);
1213
- 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
+ }));
1214
1293
  };
1215
1294
  // The mode change itself, shared by the slash commands and Shift+Tab cycling. `trailing`
1216
1295
  // lands after any restored history (the command echo + banner for /chat et al., nothing
@@ -1478,24 +1557,39 @@ export function App() {
1478
1557
  return;
1479
1558
  }
1480
1559
  const target = args.trim().toLowerCase();
1481
- if (target !== '' && target !== 'root') {
1482
- say('Usage: /resume (this project) or /resume root (manual /save files).');
1560
+ if (target !== '' && target !== 'all' && target !== 'root') {
1561
+ say('Usage: /resume (this project; chats only in chat mode), /resume all, or /resume root (manual /save files).');
1483
1562
  return;
1484
1563
  }
1485
1564
  const projectDir = projectHistoryDir(bundle.cwd);
1486
1565
  // The session in progress is not something to resume into.
1487
1566
  const notCurrent = (e) => e.path !== sessionPathRef.current;
1567
+ // Chat history is kept apart from every other mode's, so chat mode lists chats (#875). A
1568
+ // project file saved before the header counted chat turns is not listed here; /resume all
1569
+ // still has it.
1570
+ const chatsOnly = target === '' && modeRef.current === 'chat';
1488
1571
  let entries = [];
1489
1572
  let heading = 'saved with /save';
1490
- if (target === '') {
1573
+ if (target !== 'root') {
1491
1574
  entries = (await listSessions(projectDir)).filter(notCurrent);
1492
- heading = 'this project';
1575
+ if (chatsOnly)
1576
+ entries = entries.filter(e => e.chat);
1577
+ heading = chatsOnly ? 'chats in this project' : 'this project';
1493
1578
  }
1494
- // A project with no sessions yet falls back to the manual saves.
1579
+ // A project with nothing to list falls back to the manual saves — in chat mode, the ones that
1580
+ // hold a chat (#882).
1495
1581
  if (entries.length === 0) {
1496
- entries = await listSessions(ROOT_HISTORY_DIR);
1582
+ entries = await listSessions(ROOT_HISTORY_DIR, true);
1583
+ if (chatsOnly)
1584
+ entries = entries.filter(e => e.chat);
1497
1585
  if (target === '' && entries.length > 0)
1498
- heading = 'none for this project — saved with /save';
1586
+ heading = chatsOnly
1587
+ ? 'no chats for this project — saved with /save'
1588
+ : 'none for this project — saved with /save';
1589
+ }
1590
+ if (entries.length === 0 && chatsOnly) {
1591
+ say('No saved chats for this project. /resume all lists every session.');
1592
+ return;
1499
1593
  }
1500
1594
  if (entries.length === 0) {
1501
1595
  say(target === 'root'
@@ -1529,7 +1623,7 @@ export function App() {
1529
1623
  return;
1530
1624
  }
1531
1625
  try {
1532
- const { jsonlPath, txtPath } = await saveTranscript(join(homedir(), '.config', 'reika', 'history'), msgs, transcriptMeta(msgs, bundle.cwd, midTurn), { redact: !raw });
1626
+ const { jsonlPath, txtPath } = await saveTranscript(ROOT_HISTORY_DIR, msgs, saveHeader(transcriptMeta(msgs, bundle.cwd, midTurn), msgs), { redact: !raw });
1533
1627
  setMessages(prev => [
1534
1628
  ...prev,
1535
1629
  echo,
@@ -1573,7 +1667,7 @@ export function App() {
1573
1667
  ' /tokens show token usage this session',
1574
1668
  ' /stats show full session summary',
1575
1669
  ' /save save the full conversation to history, even mid-turn (--raw skips redaction)',
1576
- ' /resume [root] resume a saved session of this project (root: the /save files)',
1670
+ ' /resume [all|root] resume a saved session of this project (chat mode: chats only; all: every session; root: the /save files)',
1577
1671
  ' /skills list available skills (loaded from your skill directories)',
1578
1672
  ' /mcp list MCP servers and their tools (REIKA_MCP_SERVERS)',
1579
1673
  ' /<server>:<tool> call an MCP tool directly (JSON args, or the bare string for a one-arg tool)',
@@ -1764,19 +1858,21 @@ export function App() {
1764
1858
  case 'cwd':
1765
1859
  response = bundle?.cwd ?? '(unknown)';
1766
1860
  break;
1767
- case 'tokens':
1768
- 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}`;
1769
1864
  break;
1865
+ }
1770
1866
  case 'skills': {
1771
1867
  const list = bundle?.skills ?? [];
1772
1868
  if (list.length === 0) {
1773
1869
  response =
1774
- 'No skills loaded. Drop *.md files in ~/.config/reika/skills/ or <cwd>/.reika/skills/.';
1870
+ 'No skills loaded. Drop *.md files or SKILL.md folders in ~/.config/reika/skills/, <cwd>/.reika/skills/, ~/.agents/skills/ or <cwd>/.agents/skills/.';
1775
1871
  }
1776
1872
  else {
1777
1873
  response = [
1778
1874
  'Available skills (invoke as /<name>):',
1779
- ...list.map(s => ` /${s.name.padEnd(16)} ${s.description} ${s.source === 'project' ? '(project)' : ''}`),
1875
+ ...list.map(s => ` /${s.name.padEnd(16)} ${s.description} ${s.from ? `(${s.from})` : s.source === 'project' ? '(project)' : ''}`),
1780
1876
  ].join('\n');
1781
1877
  }
1782
1878
  break;
@@ -2122,6 +2218,10 @@ export function App() {
2122
2218
  // eslint-disable-next-line react-hooks/exhaustive-deps
2123
2219
  }, [status, pending, confirm, queue]);
2124
2220
  const onSubmit = async (input) => {
2221
+ // Left in the box rather than queued: the resume replaces the conversation the prompt was
2222
+ // typed against, and the user sees it land before deciding to send.
2223
+ if (resumingRef.current)
2224
+ return;
2125
2225
  // An answer being typed for `ask_user` — not a message for the model. Intercepted ahead of the
2126
2226
  // busy-queue branch below: a question only exists mid-turn, so every such submit would otherwise
2127
2227
  // be queued as the user's next prompt.
@@ -2437,6 +2537,8 @@ export function App() {
2437
2537
  setStreamingReasoning('');
2438
2538
  setStreamingTool('');
2439
2539
  setPendingTool('');
2540
+ subagentLiveRef.current = false;
2541
+ noteLiveRef.current = false;
2440
2542
  setSubagentLive(false);
2441
2543
  setNoteLive(false);
2442
2544
  resetTypecheck();
@@ -2490,14 +2592,17 @@ export function App() {
2490
2592
  setMessages(prev => [...prev, msg]);
2491
2593
  },
2492
2594
  onContentDelta: delta => {
2595
+ lastLiveOutputAtRef.current = Date.now();
2493
2596
  streamingRef.current += delta;
2494
2597
  scheduleFlush();
2495
2598
  },
2496
2599
  onReasoningDelta: delta => {
2600
+ lastLiveOutputAtRef.current = Date.now();
2497
2601
  reasoningRef.current += delta;
2498
2602
  scheduleReasoningFlush();
2499
2603
  },
2500
2604
  onToolProgress: (chunk, tool) => {
2605
+ lastLiveOutputAtRef.current = Date.now();
2501
2606
  toolRef.current += chunk;
2502
2607
  toolNameRef.current = tool;
2503
2608
  scheduleToolFlush();
@@ -2506,6 +2611,7 @@ export function App() {
2506
2611
  // Stamped here, not in the loop: `onToolStart` fires immediately before `tool.run`, so
2507
2612
  // this is the call's own start — the same instant the row it ages appears (#585).
2508
2613
  pendingToolAtRef.current = Date.now();
2614
+ pendingToolRef.current = name;
2509
2615
  setPendingTool(name);
2510
2616
  },
2511
2617
  onPhase: p => {
@@ -2514,8 +2620,14 @@ export function App() {
2514
2620
  setReasoningSpin(false);
2515
2621
  setPhase(p);
2516
2622
  },
2517
- onSubagent: setSubagentLive,
2518
- onCompactionNote: setNoteLive,
2623
+ onSubagent: live => {
2624
+ subagentLiveRef.current = live;
2625
+ setSubagentLive(live);
2626
+ },
2627
+ onCompactionNote: live => {
2628
+ noteLiveRef.current = live;
2629
+ setNoteLive(live);
2630
+ },
2519
2631
  onTypecheck: onTypecheckChange,
2520
2632
  onRecovering: setRecovering,
2521
2633
  // Copy: the loop mutates its tracker array in place, so a same-reference set wouldn't
@@ -2523,9 +2635,24 @@ export function App() {
2523
2635
  onPlanProgress: steps => setPlanSteps(steps.map(st => ({ ...st }))),
2524
2636
  onReasoningStatus: setReasoningSpin,
2525
2637
  onReasoningReset: () => {
2526
- // 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
2527
2639
  // recovery notice is visible and the next round streams into a fresh Thinking block
2528
- // 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
+ }
2529
2656
  reasoningRef.current = '';
2530
2657
  setStreamingReasoning('');
2531
2658
  setReasoningSpin(false);
@@ -2536,7 +2663,9 @@ export function App() {
2536
2663
  setStreaming('');
2537
2664
  },
2538
2665
  onUsage: u => {
2539
- 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);
2540
2669
  setTotalUsage(t => ({
2541
2670
  promptTokens: t.promptTokens + u.promptTokens,
2542
2671
  completionTokens: t.completionTokens + u.completionTokens,
@@ -2545,6 +2674,7 @@ export function App() {
2545
2674
  : t.cachedTokens != null
2546
2675
  ? { cachedTokens: t.cachedTokens }
2547
2676
  : {}),
2677
+ ...(u.estimated || t.estimated ? { estimated: true } : {}),
2548
2678
  }));
2549
2679
  },
2550
2680
  onContextEstimate: t => setEstimatedContext(t),
@@ -2571,9 +2701,88 @@ export function App() {
2571
2701
  statusProfile?.minGenTokens ??
2572
2702
  config.minGenTokens))
2573
2703
  : undefined;
2574
- // Live rows above a dialog (plan checklist, queued messages) it has to leave viewport room for.
2575
- const dialogReservedRows = (planSteps && (mode === 'agent' || mode === 'vibe') ? planProgressRows(planSteps) : 0) +
2704
+ const statusWidth = useContentWidth();
2705
+ const statusProps = {
2706
+ model: config?.profiles[activeProfile]?.model ?? config?.model ?? '',
2707
+ turns: messages.filter(m => m.role === 'assistant').length,
2708
+ status: status === 'busy' ? phase : status,
2709
+ elapsed: status === 'busy' ? elapsed : null,
2710
+ usage: totalUsage,
2711
+ contextTokens: lastUsage?.promptTokens ?? estimatedContext,
2712
+ contextWindow: statusWindow,
2713
+ contextUsable: statusUsable,
2714
+ sheds: shrink.sheds,
2715
+ folds: shrink.folds,
2716
+ cachedTokens: lastUsage?.cachedTokens,
2717
+ decodeRate: decodeRate,
2718
+ pr: pr,
2719
+ autoApprove: config?.autoApprove === 'bypass'
2720
+ ? 'bypass'
2721
+ : effectiveAutoApprove(config, sessionAutoApprove) === 'safe'
2722
+ ? 'safe'
2723
+ : undefined,
2724
+ unattended: unattended,
2725
+ modeTag: mode,
2726
+ exitArmed: exitArmed && status === 'idle' && pending === null && inputValue === '',
2727
+ };
2728
+ // Status rows past the one the baseline chrome assumes: a narrow pane (three iTerm2 panes) wraps
2729
+ // the bar onto several, and unbudgeted they push the live frame to viewport height, where Ink
2730
+ // repaints with a scrollback clear on every chunk.
2731
+ const statusExtraRows = Math.max(0, statusRows(statusProps, statusWidth) - 1);
2732
+ // Live rows above a dialog (plan checklist, queued messages, a wrapped status bar) it has to
2733
+ // leave viewport room for.
2734
+ const dialogReservedRows = statusExtraRows +
2735
+ (planSteps && (mode === 'agent' || mode === 'vibe') ? planProgressRows(planSteps) : 0) +
2576
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]);
2577
2786
  if (status === 'error') {
2578
2787
  return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { children: "Error" }), _jsx(Text, { children: error })] }));
2579
2788
  }
@@ -2597,9 +2806,9 @@ export function App() {
2597
2806
  noteFrameState(`${status === 'busy' ? phase : status} msgs=${messages.length} live=${live.join(',') || '-'}` +
2598
2807
  ` pending=${pendingTool || '-'} dialog=${dialog} queue=${queue.length}` +
2599
2808
  ` plan=${planSteps ? planSteps.length : 0} suggest=${suggestionState ? 1 : 0}` +
2600
- `${subagentLive ? ' subagent' : ''}`);
2809
+ `${subagentLive ? ' subagent' : ''}${heldRows ? ` held=${heldRows}` : ''}`);
2601
2810
  }
2602
- 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',
2603
2812
  // Hidden while a dialog is up: the approval a tool asks for happens *inside* the call
2604
2813
  // (after the loop announced it), so an "Editing…" row behind the prompt would name work
2605
2814
  // that has not been permitted yet. Same condition the spinner uses.
@@ -2607,11 +2816,11 @@ export function App() {
2607
2816
  // Its age (#585), read here rather than ticked in the Scrollback: the status bar's
2608
2817
  // one-second `elapsed` interval re-renders this component for the whole of a call, so
2609
2818
  // the row's timer advances off that instead of an interval of its own.
2610
- 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',
2611
2820
  // Everything the live frame draws besides the stream and the baseline chrome — the
2612
2821
  // suggestion list and queue grow it mid-turn, and unbudgeted they push it to viewport
2613
2822
  // height, where Ink repaints with a scrollback clear on every chunk (#470).
2614
- 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
2615
2824
  // Definite harness actions (typecheck, loop recovery) take priority over the soft spin
2616
2825
  // hint — they're things the harness is actively doing, not a maybe.
2617
2826
  , {
@@ -2651,8 +2860,8 @@ export function App() {
2651
2860
  modelSelect !== null ||
2652
2861
  resumeSelect !== null ||
2653
2862
  confirm !== null, attachedBelow: suggestionState !== null, reservedRows: question
2654
- ? questionDialogHeight(question.request, questionTyping, dialogReservedRows)
2655
- : 0, suggesting: !!suggestionState && suggestionState.items.length > 0, history: inputHistory, mode: mode, value: inputValue, onChange: onInputChange, onSubmit: onSubmit, onPasteImage: onPasteImageSafely, onPasteText: onPasteText, placeholder:
2863
+ ? questionDialogHeight(question.request, questionTyping, dialogReservedRows, questionSelected)
2864
+ : statusExtraRows, suggesting: !!suggestionState && suggestionState.items.length > 0, history: inputHistory, mode: mode, value: inputValue, onChange: onInputChange, onSubmit: onSubmit, onPasteImage: onPasteImageSafely, onPasteText: onPasteText, placeholder:
2656
2865
  // A reason that should stop the model has to say so: "tell me the script" read as
2657
2866
  // run-then-tell and drew retries, "don't run anything" did not (decline-terse/-ask).
2658
2867
  approvalTyping
@@ -2661,9 +2870,5 @@ export function App() {
2661
2870
  ? 'Run a shell command'
2662
2871
  : mode === 'vibe'
2663
2872
  ? 'Describe a change — it plans first, then implements'
2664
- : promptPlaceholder() }), suggestionState ? (_jsx(Suggestions, { state: suggestionState, selectedIndex: suggestionSelected })) : null, _jsx(Status, { model: config?.profiles[activeProfile]?.model ?? config?.model ?? '', turns: messages.filter(m => m.role === 'assistant').length, status: status === 'busy' ? phase : status, elapsed: status === 'busy' ? elapsed : null, usage: totalUsage, contextTokens: lastUsage?.promptTokens ?? estimatedContext, contextWindow: statusWindow, contextUsable: statusUsable, sheds: shrink.sheds, folds: shrink.folds, cachedTokens: lastUsage?.cachedTokens, decodeRate: decodeRate, pr: pr, autoApprove: config?.autoApprove === 'bypass'
2665
- ? 'bypass'
2666
- : effectiveAutoApprove(config, sessionAutoApprove) === 'safe'
2667
- ? 'safe'
2668
- : undefined, unattended: unattended, modeTag: mode, exitArmed: exitArmed && status === 'idle' && pending === null && inputValue === '' })] }))] }));
2873
+ : promptPlaceholder() }), suggestionState ? (_jsx(Suggestions, { state: suggestionState, selectedIndex: suggestionSelected })) : null, _jsx(Status, { ...statusProps })] }))] }));
2669
2874
  }