@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
@@ -1,12 +1,13 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box, Text } from 'ink';
3
3
  import wrapAnsi from 'wrap-ansi';
4
+ import { APPROVAL_OPTIONS } from './dialogspecs.js';
4
5
  import { glyphs } from './glyphs.js';
5
6
  import { theme } from './theme.js';
6
7
  import { DiffView } from './DiffView.js';
7
8
  import { highlightCode } from './highlight.js';
8
9
  import { sanitizeTerminalText } from './termtext.js';
9
- import { contentWidth } from './layout.js';
10
+ import { hangingRows, hangingWrap, useContentWidth, wrappedRows, wrapStyledRows, } from './layout.js';
10
11
  import { toolLabel } from './format.js';
11
12
  // The dialog's own border (1 column each side) plus its paddingX={1}, on top of the App padding
12
13
  // contentWidth already accounts for. The diff has to wrap inside all of it or its rows push
@@ -19,46 +20,93 @@ export const DIALOG_MARKER = glyphs.dialogCall;
19
20
  // The dialog sits in Ink's live frame, and a frame as tall as the viewport makes Ink repaint the
20
21
  // whole terminal with `\x1b[3J` — iTerm2's "attempted to clear scrollback" — and leaves the rows
21
22
  // that scrolled off the top stranded in the scrollback after the dialog closes (#447). So the
22
- // preview gets whatever the viewport has left. Fixed rows: marginTop, top border, both paddingY
23
- // rows, the subject line, and the options and hint with their margins — then the input and status
24
- // bar underneath, plus slack.
25
- const DIALOG_FIXED_ROWS = 13;
26
- const BELOW_DIALOG_ROWS = 6;
23
+ // preview gets whatever the viewport has left: the frame, the subject, the warnings, the options
24
+ // and the hint are paid for first, and the input and status bar underneath get their reserve.
25
+ //
26
+ // Those chrome rows are MEASURED, not assumed (#842). On a narrow pane the subject, each warning,
27
+ // the option labels and the hint all wrap, and a constant that counted one row each undercounted
28
+ // the frame by the wraps — so the preview sized itself against a budget the dialog then overspent,
29
+ // and on a small pane the frame reached the viewport height and cleared the scrollback.
30
+ const FRAME_ROWS = 4; // marginTop, top border, and both paddingY rows
31
+ const GAP_ROWS = 1; // the margin above the preview, the warnings, the options and the hint
32
+ const OPTION_HANG = 2; // '› ' — the marker every option row hangs under
33
+ const BELOW_DIALOG_ROWS = 6; // the input box, the status bar, and slack
27
34
  const MIN_PREVIEW_ROWS = 3;
28
- export function approvalPreviewRows(warnings, reservedRows = 0, rows = process.stdout.rows || 24) {
29
- const warningRows = warnings > 0 ? warnings + 1 : 0;
30
- return Math.max(MIN_PREVIEW_ROWS, rows - DIALOG_FIXED_ROWS - BELOW_DIALOG_ROWS - warningRows - reservedRows);
35
+ export const APPROVAL_HINT = '↑↓ navigate · enter select · y/n shortcuts · ctrl-c abort';
36
+ export const APPROVAL_TYPING_HINT = 'enter send · ctrl-c back to the options';
37
+ const APPROVAL_TYPING_LINE = 'Declining — type what to do instead below';
38
+ // What the dialog costs vertically at `cols` columns and how much of `rows` the preview may take.
39
+ // `height` is what the dialog draws, so `height + BELOW_DIALOG_ROWS <= rows - 1` holds wherever the
40
+ // pane has room for the dialog at all.
41
+ //
42
+ // The budget is `rows - 1`: Ink's condition is `outputHeight >= stdout.rows` (build/ink.js), so a
43
+ // frame that lands exactly on the viewport height is already a full repaint. When the measured
44
+ // chrome leaves the preview under `MIN_PREVIEW_ROWS`, the HINT is what goes — the options and the
45
+ // warnings are what the user is deciding on, and the preview is where the evidence is.
46
+ const withGap = (rows) => rows + GAP_ROWS;
47
+ export function layoutApproval(request, typing, cols, rows = process.stdout.rows || 24, reservedRows = 0) {
48
+ const warnings = request.warnings ?? [];
49
+ // Pre-wrapped, so the rows counted here are the rows drawn whatever width Ink lays the frame
50
+ // out in, rather than only the width this measured at.
51
+ const hint = hangingWrap(typing ? APPROVAL_TYPING_HINT : APPROVAL_HINT, Math.max(1, cols), 0);
52
+ const hintRows = withGap(hint.split('\n').length);
53
+ const warningRows = warnings.length
54
+ ? withGap(warnings.reduce((n, w) => n + wrappedRows(`▲ ${w}`, cols), 0))
55
+ : 0;
56
+ const optionRows = typing
57
+ ? wrappedRows(APPROVAL_TYPING_LINE, cols)
58
+ : APPROVAL_OPTIONS.reduce((n, label) => n + hangingRows(label, cols, OPTION_HANG), 0);
59
+ const chrome = FRAME_ROWS +
60
+ wrappedRows(`${DIALOG_MARKER} ${toolLabel(request.tool)} ${request.subject}`, cols) +
61
+ GAP_ROWS +
62
+ warningRows +
63
+ GAP_ROWS +
64
+ optionRows;
65
+ // Whatever the chrome, the warnings and the reserve leave of the viewport.
66
+ const room = rows - 1 - BELOW_DIALOG_ROWS - reservedRows - chrome;
67
+ const withHint = room - hintRows;
68
+ if (withHint >= MIN_PREVIEW_ROWS) {
69
+ return { previewRows: withHint, showHint: true, hint, height: chrome + hintRows + withHint };
70
+ }
71
+ // The hint is the one block nothing else depends on, so it pays for the preview — even when the
72
+ // rows it frees still don't reach MIN_PREVIEW_ROWS: on a pane that narrow every row counts.
73
+ const previewRows = Math.max(1, room);
74
+ return { previewRows, showHint: false, hint, height: chrome + previewRows };
31
75
  }
32
- // The last row declines with a reason the user types into the input box below. Last, not beside
33
- // Decline, so the rows Approval-trained fingers already know keep their places.
34
- export const APPROVAL_OPTIONS = [
35
- 'Approve',
36
- 'Decline',
37
- 'Always (this session)',
38
- 'Decline, and say what to do instead',
39
- ];
40
- export const APPROVAL_FEEDBACK_INDEX = 3;
41
76
  // The popup renders as the top half of one continuous frame whose bottom half is
42
77
  // the input box (see Input's `attachedAbove`): `borderBottom={false}` + the input
43
78
  // dropping its top border merges them into a single outline, so the prompt reads
44
79
  // as part of the input region rather than a card floating above it. The frame
45
80
  // stays neutral (no borderColor) to match the input; caution is signalled inside
46
81
  // via themed `▲` warning lines, not a colored border.
47
- export function Approval({ request, selectedIndex, typing = false, reservedRows = 0, }) {
82
+ export function Approval({ request, selectedIndex, typing = false, width, rows = process.stdout.rows || 24, reservedRows = 0, }) {
48
83
  const isCommand = request.tool === 'bash';
49
84
  const warnings = request.warnings ?? [];
50
- const maxRows = approvalPreviewRows(warnings.length, reservedRows);
51
- return (_jsxs(Box, { borderStyle: glyphs.border, borderBottom: false, flexDirection: "column", paddingX: 1, paddingY: 1, marginX: -1, marginTop: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: theme.tool, children: `${DIALOG_MARKER} ${toolLabel(request.tool)}` }), _jsx(Text, { color: theme.secondary, children: ` ${request.subject}` })] }), _jsx(Box, { flexDirection: "column", marginTop: 1, children: isCommand ? (_jsx(CommandPreview, { command: request.preview, maxRows: maxRows })) : request.tool === 'fetch_url' ? (_jsx(Text, { children: request.preview })) : (_jsx(DiffView, { diff: request.preview, path: request.subject, maxWidth: contentWidth(DIALOG_CHROME), startLine: request.startLine, maxRows: maxRows, hiddenNote: n => `… ${n} more lines — the full diff prints once approved` })) }), warnings.length > 0 ? (_jsx(Box, { flexDirection: "column", marginTop: 1, children: warnings.map((w, i) => (_jsx(Text, { color: theme.warning, children: `▲ ${w}` }, i))) })) : null, _jsx(Box, { flexDirection: "column", marginTop: 1, children: typing ? (_jsx(Text, { color: theme.secondary, children: "Declining \u2014 type what to do instead below" })) : (APPROVAL_OPTIONS.map((label, i) => {
85
+ // `useContentWidth`, not a bare contentWidth(): the packing has to follow a resize, and this is
86
+ // the width the dialog's own rows cost against — the same number the rows are drawn at.
87
+ const liveWidth = useContentWidth(DIALOG_CHROME);
88
+ const layoutWidth = width ?? liveWidth;
89
+ const { previewRows, showHint, hint } = layoutApproval(request, typing, layoutWidth, rows, reservedRows);
90
+ return (_jsxs(Box, { borderStyle: glyphs.border, borderBottom: false, flexDirection: "column", paddingX: 1, paddingY: 1, marginX: -1, marginTop: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: theme.tool, children: `${DIALOG_MARKER} ${toolLabel(request.tool)}` }), _jsx(Text, { color: theme.secondary, children: ` ${request.subject}` })] }), _jsx(Box, { flexDirection: "column", marginTop: 1, children: isCommand ? (_jsx(CommandPreview, { command: request.preview, maxRows: previewRows, width: layoutWidth })) : request.tool === 'fetch_url' ? (_jsx(UrlPreview, { url: request.preview, maxRows: previewRows, width: layoutWidth })) : (_jsx(DiffView, { diff: request.preview, path: request.subject, maxWidth: layoutWidth, startLine: request.startLine, maxRows: previewRows, hiddenNote: n => `… ${n} more lines — the full diff prints once approved` })) }), warnings.length > 0 ? (_jsx(Box, { flexDirection: "column", marginTop: 1, children: warnings.map((w, i) => (_jsx(Text, { color: theme.warning, children: `▲ ${w}` }, i))) })) : null, _jsx(Box, { flexDirection: "column", marginTop: 1, children: typing ? (_jsx(Text, { color: theme.secondary, children: APPROVAL_TYPING_LINE })) : (APPROVAL_OPTIONS.map((label, i) => {
52
91
  const selected = i === selectedIndex;
53
- return (_jsxs(Text, { children: [_jsx(Text, { color: selected ? theme.accent : undefined, children: selected ? '› ' : ' ' }), _jsx(Text, { color: selected ? theme.accent : undefined, children: label })] }, i));
54
- })) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: theme.muted, children: typing
55
- ? 'enter send · ctrl-c back to the options'
56
- : '↑↓ navigate · enter select · y/n shortcuts · ctrl-c abort' }) })] }));
92
+ return (_jsxs(Text, { children: [_jsx(Text, { color: selected ? theme.accent : undefined, children: selected ? '› ' : ' ' }), _jsx(Text, { color: selected ? theme.accent : undefined, children: hangingWrap(label, layoutWidth, OPTION_HANG) })] }, i));
93
+ })) }), showHint ? (_jsx(Box, { marginTop: 1, children: _jsx(Text, { color: theme.muted, children: hint }) })) : null] }));
94
+ }
95
+ // A URL drawn as plain text, bounded to the rows the preview was given: it has no gutter and no
96
+ // line structure to fit, but it still wraps.
97
+ function UrlPreview({ url, maxRows, width }) {
98
+ const rows = wrapAnsi(url, Math.max(1, width), { trim: false, hard: true }).split('\n');
99
+ if (rows.length <= maxRows)
100
+ return _jsx(Text, { children: url });
101
+ // One row is the note's, as the diff and the command preview spend theirs, and what is left is
102
+ // what the URL may take: a one-row preview is the note alone.
103
+ const shown = rows.slice(0, Math.max(0, maxRows - 1));
104
+ return (_jsxs(_Fragment, { children: [shown.length > 0 ? _jsx(Text, { children: shown.join('\n') }) : null, _jsx(Text, { color: theme.muted, children: `… ${rows.length - shown.length} more lines` })] }));
57
105
  }
58
106
  // The marker on a command's first row; every wrapped/extra line hangs under it by this width.
59
107
  const MARKER = '$ ';
60
108
  const MARKER_WIDTH = 2;
61
- function CommandPreview({ command, maxRows }) {
109
+ function CommandPreview({ command, maxRows, width, }) {
62
110
  // Sanitized like the scrollback chip (issue #154), but NOT scrubbed: this is the dialog where
63
111
  // the user decides whether to run the thing, so it must show the command as written, secrets
64
112
  // and all. Tabs and cursor motions still go — inside a bordered box they wrap past the border
@@ -66,8 +114,8 @@ function CommandPreview({ command, maxRows }) {
66
114
  const all = sanitizeTerminalText(command).split('\n');
67
115
  // Same width the rows are rendered at below, so the row counts fitted here are the row counts
68
116
  // the dialog actually draws.
69
- const width = Math.max(1, contentWidth(DIALOG_CHROME) - MARKER_WIDTH);
70
- const { lines, hidden } = fitCommandLines(all, maxRows, width);
117
+ const textWidth = Math.max(1, width - MARKER_WIDTH);
118
+ const { lines, hidden } = fitCommandLines(all, maxRows, textWidth);
71
119
  // Each logical line is pre-wrapped to the dialog width the way DiffView's WrappedRow does it
72
120
  // (#489): the `$`/` ` marker and the text are adjacent siblings in a row Box, and when the row
73
121
  // is long enough to wrap, Ink drops the character at that sibling boundary — the space of `$ `,
@@ -75,10 +123,7 @@ function CommandPreview({ command, maxRows }) {
75
123
  // Wrapping ourselves keeps each row inside the width, so Ink never wraps one and the marker's
76
124
  // space survives; short commands were the only ones that kept their space before this.
77
125
  return (_jsxs(_Fragment, { children: [lines.flatMap((line, i) => {
78
- const rows = wrapAnsi(highlightCode(line, 'bash'), width, {
79
- trim: false,
80
- hard: true,
81
- }).split('\n');
126
+ const rows = wrapStyledRows(highlightCode(line, 'bash'), textWidth);
82
127
  return rows.map((row, j) => (_jsxs(Box, { children: [_jsx(Text, { color: theme.success, children: j === 0 && i === 0 ? MARKER : ' '.repeat(MARKER_WIDTH) }), _jsx(Text, { children: j === 0 ? row : dropWrapWhitespace(row) })] }, `${i}:${j}`)));
83
128
  }), hidden > 0 ? _jsx(Text, { color: theme.muted, children: `… ${hidden} more lines` }) : null] }));
84
129
  }
@@ -92,7 +137,9 @@ export function fitCommandLines(lines, maxRows, width) {
92
137
  const heights = lines.map(l => wrapAnsi(l, Math.max(1, width), { trim: false, hard: true }).split('\n').length);
93
138
  if (heights.reduce((a, b) => a + b, 0) <= maxRows)
94
139
  return { lines, hidden: 0 };
95
- const budget = Math.max(1, maxRows - 1);
140
+ // One row is the footer's when anything is cut, and the rows kept must stay INSIDE `maxRows`:
141
+ // a preview budgeted one row draws the footer alone rather than a line plus a footer.
142
+ const budget = Math.max(0, maxRows - 1);
96
143
  let used = 0;
97
144
  let kept = 0;
98
145
  while (kept < lines.length && used + heights[kept] <= budget)
@@ -1,35 +1,9 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box, Text } from 'ink';
3
+ import {} from './dialogspecs.js';
3
4
  import { IMPLEMENT_MODES } from './commands.js';
4
5
  import { glyphs } from './glyphs.js';
5
6
  import { theme } from './theme.js';
6
- // Row 0 is "send as typed" and starts selected — the inverse of Approval, where Approve is row 0.
7
- // There the model has already committed to an action; here nothing has happened yet and the
8
- // literal prompt is what was asked for. A wrong default that acts costs a turn (or a request
9
- // nobody meant); a wrong default that doesn't costs a keystroke.
10
- export const CONFIRM_DECLINE = 0;
11
- export const CONFIRM_ACCEPT = 1;
12
- export function skillConfirmSpec(match) {
13
- return {
14
- title: 'Skill',
15
- subtitle: `/${match.skill.name} — ${match.skill.description}`,
16
- details: [`matched: ${match.matched.join(', ')}`],
17
- options: ['Send as typed', `Apply /${match.skill.name}`],
18
- accept: 'apply',
19
- };
20
- }
21
- // A long URL wraps the frame; the user just typed it, so the head is enough to recognize it.
22
- const URL_DISPLAY_CHARS = 90;
23
- export function pastedUrlConfirmSpec(urls) {
24
- const n = urls.length;
25
- return {
26
- title: n > 1 ? 'Pasted links' : 'Pasted link',
27
- subtitle: `the prompt doesn't read as a request to open ${n > 1 ? 'them' : 'it'} — fetch before the turn?`,
28
- details: urls.map(u => u.length > URL_DISPLAY_CHARS ? `${u.slice(0, URL_DISPLAY_CHARS)}…` : u),
29
- options: ['Send as typed', `Fetch ${n > 1 ? `${n} links` : 'the link'}`],
30
- accept: 'fetch',
31
- };
32
- }
33
7
  const IMPLEMENT_MODE_LABELS = {
34
8
  agent: 'Agent — full tool set',
35
9
  minimal: 'Minimal — shell only, no repo map or AGENTS.md',
@@ -2,11 +2,12 @@ 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';
9
+ import { sliceStyled, wrapLines, wrapStyledRows } from './layout.js';
10
+ import stripAnsi from 'strip-ansi';
10
11
  export function DiffView({ diff, path, maxWidth, startLine, oldStartLine, maxRows, hiddenNote = n => `… ${n} more lines`, }) {
11
12
  const lang = detectLanguage(path);
12
13
  const blocks = parseDiffBlocks(sanitizeDiffLines(diff));
@@ -35,11 +36,13 @@ export function DiffView({ diff, path, maxWidth, startLine, oldStartLine, maxRow
35
36
  // Exported for unit tests.
36
37
  export function fitRowsToHeight(lines, maxRows, contentWidth) {
37
38
  const wrapWidth = Math.max(1, contentWidth - CONTINUATION.length);
38
- 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);
39
40
  const total = heights.reduce((a, b) => a + b, 0);
40
41
  if (total <= maxRows)
41
42
  return { lines, hidden: 0 };
42
- const budget = Math.max(1, maxRows - 1);
43
+ // As in the command preview: the footer costs a row, and the rows kept must stay inside
44
+ // `maxRows` — a one-row budget draws the footer alone.
45
+ const budget = Math.max(0, maxRows - 1);
43
46
  let used = 0;
44
47
  let kept = 0;
45
48
  while (kept < lines.length && used + heights[kept] <= budget)
@@ -192,15 +195,13 @@ const CONTINUATION = ' ';
192
195
  // Ink counts as one row while the screen spends two (the undercount the live-frame budget can't
193
196
  // afford). So wrap here, where the widths are known.
194
197
  //
195
- // wrap-ansi does the breaking because the content is already syntax-highlighted: it re-opens the
196
- // active SGR codes on each row instead of leaving the tail unstyled. `hard` breaks tokens with no
197
- // space in them — a long path or a base64 blob — which is the common case in code.
198
+ // wrap-ansi does the breaking because the content is already syntax-highlighted, and
199
+ // `wrapStyledRows` re-opens every active style on each row — wrap-ansi alone re-opens only the
200
+ // innermost, which dropped a wrapped comment's gray (#852). `hard` breaks tokens with no space in
201
+ // them — a long path or a base64 blob — which is the common case in code.
198
202
  function WrappedRow({ content, prefix, gutter, maxWidth, side, }) {
199
203
  const bg = side ? rowBg(side) : undefined;
200
- const rows = wrapAnsi(content, Math.max(1, maxWidth - prefix.length), {
201
- trim: false,
202
- hard: true,
203
- }).split('\n');
204
+ const rows = wrapStyledRows(content, maxWidth - prefix.length);
204
205
  // Columns the gutter holds: its digits plus the space between it and the code.
205
206
  const gutterCells = gutter ? gutter.length + 1 : 0;
206
207
  return (_jsx(_Fragment, { children: rows.map((row, i) => {
@@ -290,6 +291,12 @@ function PairedLine({ line, other, side, language, maxWidth, gutter, }) {
290
291
  // Painted into one string rather than nested <Text> elements: wrapping needs a single run of
291
292
  // text to break, and chalk re-opens the outer style after each nested close, so the line's base
292
293
  // background survives every highlighted span the same way Ink's own nesting would.
294
+ //
295
+ // The line is highlighted whole and the unchanged parts cut out of it: highlighted alone, a part
296
+ // from the middle of a comment has no `//` and came out in the default color (#852).
297
+ const highlighted = highlightCode(line, language);
298
+ const sliceable = stripAnsi(highlighted) === line;
299
+ let offset = 0;
293
300
  const painted = parts
294
301
  .map(p => {
295
302
  // Skip segments that belong only to the other side.
@@ -297,13 +304,16 @@ function PairedLine({ line, other, side, language, maxWidth, gutter, }) {
297
304
  return '';
298
305
  if (side === 'added' && p.removed)
299
306
  return '';
307
+ const start = offset;
308
+ offset += p.value.length;
300
309
  const isChange = side === 'removed' ? p.removed : p.added;
301
310
  // Brighter background for the changed portion — stands out against the line's own.
302
- return isChange
303
- ? chalk.level === 1
311
+ if (isChange) {
312
+ return chalk.level === 1
304
313
  ? chalk[side === 'added' ? 'bgGreen' : 'bgRed'].whiteBright(p.value)
305
- : chalk.bgHex(highlightBg).hex(HIGHLIGHT_FG)(p.value)
306
- : highlightCode(p.value, language);
314
+ : chalk.bgHex(highlightBg).hex(HIGHLIGHT_FG)(p.value);
315
+ }
316
+ return sliceable ? sliceStyled(highlighted, start, offset) : highlightCode(p.value, language);
307
317
  })
308
318
  .join('');
309
319
  return (_jsx(WrappedRow, { content: painted, prefix: prefix, gutter: gutter, maxWidth: maxWidth, side: side }));
@@ -15,17 +15,26 @@ export const OWN_ANSWER_LABEL = 'Something else — type your own answer';
15
15
  // The dialog sits in Ink's live frame, and every word in it is model-written: a frame as tall as
16
16
  // the viewport makes Ink repaint with `\x1b[3J` and strands the dialog in the scrollback (#456,
17
17
  // the #447 shape). Fixed rows: marginTop, top border, both paddingY rows, the header, the margins
18
- // above the question, the options and the hint, and the hint — then the input and status bar
19
- // underneath, plus slack.
20
- const DIALOG_FIXED_ROWS = 9;
18
+ // above the question, the options and the hint — then the input and status bar underneath, plus
19
+ // slack. The hint rides ON TOP of that, measured at the live width (#842): it is one row on a wide
20
+ // terminal and three on a narrow pane, and counting it as one is how the frame outgrew the budget
21
+ // that sized the question and cleared the scrollback.
22
+ const FRAME_ROWS = 4; // marginTop, top border, and both paddingY rows
23
+ const LABEL_ROWS = 1; // the `⏺ Question` header
24
+ const GAP_ROWS = 2; // the margins above the question and above the options
25
+ const HINT_GAP_ROWS = 1; // … and the one above the hint, which goes with it
21
26
  const BELOW_DIALOG_ROWS = 6;
22
27
  // While the user types, the input under the dialog is live and scrolls its own window once the
23
28
  // answer outgrows the room the dialog leaves it (App passes `questionDialogHeight` to Input). That
24
29
  // window never goes below three lines plus its two "… lines above/below" markers, so the question
25
30
  // holds those rows back — the input can't be squeezed into overflowing the frame.
26
31
  const TYPING_INPUT_ROWS = 4;
27
- // What fits, in the order things are given up: the options are what the user acts on, so every
28
- // option row and the own-answer row always show; descriptions go first, then the question's tail.
32
+ // The two hint lines, and what the dialog says while the reason field is open on the question.
33
+ const QUESTION_HINT = '↑↓ or 1-9 navigate · enter select · tab add a note · ctrl-c abort';
34
+ const QUESTION_TYPING_HINT = 'enter submit · ctrl-c back to the options';
35
+ // What fits, in the order things are given up: the options are what the user acts on, so the
36
+ // own-answer row always shows and an option row is the last thing to go; descriptions go first,
37
+ // then the hint (see below), then the question's tail.
29
38
  // Exported for unit tests.
30
39
  export function fitQuestionToHeight(questionRows, labelRows, descriptionRows, budget) {
31
40
  if (questionRows + labelRows + descriptionRows <= budget) {
@@ -36,15 +45,77 @@ export function fitQuestionToHeight(questionRows, labelRows, descriptionRows, bu
36
45
  // One row goes to the "more lines" note, and the question keeps at least its first row.
37
46
  return { showDescriptions: false, questionRows: Math.max(1, budget - labelRows - 1) };
38
47
  }
48
+ // For the typing state, where the option list is not drawn: nothing visible, nothing hidden.
49
+ const EMPTY_WINDOW = { start: 0, end: 0, moreAbove: 0, moreBelow: 0, rows: 0 };
50
+ // Which options show when the option rows alone outgrow the pane (#856). Every option row can no
51
+ // longer always show — a dialog whose labels overflow is a frame as tall as the viewport, which is
52
+ // the scrollback wipe — but truncating a label to one row is worse than hiding options: these are
53
+ // full sentences, and the words that tell two of them apart sit past the first row. So the list is
54
+ // windowed around the selection, and the markers say how many are out of sight. Exported for unit
55
+ // tests.
56
+ export function fitOptionsToHeight(rowCosts, budget, selectedIndex) {
57
+ const n = rowCosts.length;
58
+ const whole = {
59
+ start: 0,
60
+ end: n,
61
+ moreAbove: 0,
62
+ moreBelow: 0,
63
+ rows: rowCosts.reduce((a, c) => a + c, 0),
64
+ };
65
+ if (n === 0 || whole.rows <= budget)
66
+ return whole;
67
+ // The markers are paid for out of the same budget they will be sized against, so each possible
68
+ // reservation is tried and the widest run whose markers fit inside it wins. Settling one
69
+ // reservation into the next does not converge: a freed row can let the run grow past an option
70
+ // that then keeps it off the end, and the loop stopped on the run that overran (#857). Reserving
71
+ // both rows always fits its own markers, so there is always a candidate.
72
+ let run = grow(rowCosts, Math.max(0, budget - 2), selectedIndex);
73
+ for (const reserved of [0, 1]) {
74
+ const candidate = grow(rowCosts, Math.max(0, budget - reserved), selectedIndex);
75
+ const markers = (candidate.start > 0 ? 1 : 0) + (candidate.end < n ? 1 : 0);
76
+ if (markers > reserved)
77
+ continue;
78
+ if (candidate.end - candidate.start > run.end - run.start)
79
+ run = candidate;
80
+ }
81
+ const moreAbove = run.start;
82
+ const moreBelow = n - run.end;
83
+ return {
84
+ start: run.start,
85
+ end: run.end,
86
+ moreAbove,
87
+ moreBelow,
88
+ rows: run.rows + (moreAbove > 0 ? 1 : 0) + (moreBelow > 0 ? 1 : 0),
89
+ };
90
+ }
91
+ // The longest run of options containing the selection that fits in `avail` rows: downward first,
92
+ // so the list reads in order from the row the cursor is on, then upward to fill what is left. A
93
+ // run always holds its selection, even when that row alone overruns: there is nothing smaller to
94
+ // draw, and the window is derived from the cursor's index every render — the 1-9 keys land wherever
95
+ // they name — so it never has to scroll a stale run into view.
96
+ function grow(rowCosts, avail, selectedIndex) {
97
+ const n = rowCosts.length;
98
+ let start = Math.min(Math.max(selectedIndex, 0), n - 1);
99
+ let end = start + 1;
100
+ let rows = rowCosts[start];
101
+ while (end < n && rows + rowCosts[end] <= avail)
102
+ rows += rowCosts[end++];
103
+ while (start > 0 && rows + rowCosts[start - 1] <= avail)
104
+ rows += rowCosts[--start];
105
+ return { start, end, rows };
106
+ }
39
107
  // Renders as the top half of one continuous frame whose bottom half is the input box (see
40
108
  // Approval/ModelSelect for the same `borderBottom={false}` + `attachedAbove` merge). Unlike those
41
109
  // two, the input stays LIVE underneath while typing — the question is a prompt for text, and
42
110
  // reusing Input gets editing, history and paste for free rather than rebuilding a field in here.
43
111
  export function Question({ request, selectedIndex, typing, width, rows = process.stdout.rows || 24, reservedRows = 0, }) {
44
112
  const liveWidth = useContentWidth(DIALOG_CHROME);
45
- const { labels, descriptions, ownAnswer, questionLines, typingLine, fit, hiddenQuestionRows } = layoutQuestion(request, typing ?? null, width ?? liveWidth, rows, reservedRows);
113
+ const { labels, descriptions, ownAnswer, questionLines, typingLine, fit, hiddenQuestionRows, hint, showHint, options, padRows, } = layoutQuestion(request, typing ?? null, width ?? liveWidth, rows, reservedRows, selectedIndex);
114
+ // Null only while typing, where the list is not drawn at all.
115
+ const shown = options ?? EMPTY_WINDOW;
46
116
  const hang = HANG;
47
- return (_jsxs(Box, { borderStyle: glyphs.border, borderBottom: false, flexDirection: "column", paddingX: 1, paddingY: 1, marginX: -1, marginTop: 1, children: [_jsx(Text, { color: theme.tool, children: `${DIALOG_MARKER} Question` }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { children: questionLines.slice(0, fit.questionRows).join('\n') }), hiddenQuestionRows > 0 ? (_jsx(Text, { color: theme.muted, children: `… ${hiddenQuestionRows} more lines` })) : null] }), typing ? (_jsx(Box, { flexDirection: "column", marginTop: 1, children: _jsx(Text, { color: theme.secondary, children: typingLine }) })) : (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [request.options.map((o, i) => {
117
+ return (_jsxs(Box, { borderStyle: glyphs.border, borderBottom: false, flexDirection: "column", paddingX: 1, paddingY: 1, marginX: -1, marginTop: 1, children: [_jsx(Text, { color: theme.tool, children: `${DIALOG_MARKER} Question` }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { children: questionLines.slice(0, fit.questionRows).join('\n') }), hiddenQuestionRows > 0 ? (_jsx(Text, { color: theme.muted, children: `… ${hiddenQuestionRows} more lines` })) : null] }), typing ? (_jsx(Box, { flexDirection: "column", marginTop: 1, children: _jsx(Text, { color: theme.secondary, children: typingLine }) })) : (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [shown.moreAbove > 0 ? (_jsx(Text, { color: theme.muted, children: ` ↑ ${shown.moreAbove} more` })) : null, request.options.slice(shown.start, shown.end).map((o, at) => {
118
+ const i = shown.start + at;
48
119
  const selected = i === selectedIndex;
49
120
  const num = `${i + 1}. `;
50
121
  // Wrapped as one string so the tag can't be pushed onto its own flush-left row, then
@@ -53,9 +124,7 @@ export function Question({ request, selectedIndex, typing, width, rows = process
53
124
  const tagAt = tag ? wrapped.lastIndexOf(tag.trimStart()) : -1;
54
125
  const label = tagAt >= 0 ? wrapped.slice(0, tagAt) : wrapped;
55
126
  return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: selected ? theme.accent : undefined, children: selected ? '› ' : ' ' }), _jsx(Text, { color: selected ? theme.accent : theme.secondary, children: num }), _jsx(Text, { color: selected ? theme.accent : undefined, children: label }), tagAt >= 0 ? _jsx(Text, { color: theme.info, children: wrapped.slice(tagAt) }) : null] }), fit.showDescriptions && descriptions[i] ? (_jsx(Text, { color: theme.muted, children: ' '.repeat(hang) + descriptions[i] })) : null] }, i));
56
- }), _jsxs(Text, { children: [_jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : undefined, children: selectedIndex === request.options.length ? '› ' : ' ' }), _jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : theme.secondary, children: `${request.options.length + 1}. ` }), _jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : theme.secondary, children: ownAnswer })] })] })), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: theme.muted, children: typing
57
- ? 'enter submit · ctrl-c back to the options'
58
- : '↑↓ or 1-9 navigate · enter select · tab add a note · ctrl-c abort' }) })] }));
127
+ }), shown.moreBelow > 0 ? (_jsx(Text, { color: theme.muted, children: ` ↓ ${shown.moreBelow} more` })) : null, _jsxs(Text, { children: [_jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : undefined, children: selectedIndex === request.options.length ? '› ' : ' ' }), _jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : theme.secondary, children: `${request.options.length + 1}. ` }), _jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : theme.secondary, children: ownAnswer })] }), padRows > 0 ? _jsx(Box, { height: padRows }) : null] })), showHint ? (_jsx(Box, { marginTop: 1, children: _jsx(Text, { color: theme.muted, children: hint }) })) : null] }));
59
128
  }
60
129
  // Labels are full sentences and wrap on any ordinary terminal. Ink has no hanging indent, so a
61
130
  // continuation row would land flush left under the marker, detached from its number
@@ -63,7 +132,10 @@ export function Question({ request, selectedIndex, typing, width, rows = process
63
132
  const HANG = '› 1. '.length;
64
133
  // Everything the dialog draws, pre-wrapped and fitted to the viewport, plus the height it comes to.
65
134
  // App calls it too, so the input underneath knows how much room the dialog leaves it.
66
- export function layoutQuestion(request, typing, cols, rows, reservedRows) {
135
+ export function layoutQuestion(request, typing, cols, rows, reservedRows,
136
+ // Which row the cursor is on, so the option window on a short pane follows it. The own-answer row
137
+ // is index `options.length`.
138
+ selectedIndex = 0) {
67
139
  const hang = HANG;
68
140
  const noting = typing && typing.forIndex !== undefined ? request.options[typing.forIndex] : null;
69
141
  const labels = request.options.map(o => {
@@ -81,13 +153,70 @@ export function layoutQuestion(request, typing, cols, rows, reservedRows) {
81
153
  : labels.reduce((n, l) => n + rowsOf(l.wrapped), 0) + rowsOf(ownAnswer);
82
154
  const descriptionRows = typing ? 0 : descriptions.reduce((n, d) => n + (d ? rowsOf(d) : 0), 0);
83
155
  const below = BELOW_DIALOG_ROWS + (typing ? TYPING_INPUT_ROWS : 0);
84
- const fit = fitQuestionToHeight(questionLines.length, labelRows, descriptionRows, rows - DIALOG_FIXED_ROWS - below - reservedRows);
85
- const hiddenQuestionRows = questionLines.length - fit.questionRows;
86
- const height = DIALOG_FIXED_ROWS +
87
- fit.questionRows +
88
- (hiddenQuestionRows > 0 ? 1 : 0) +
156
+ // Pre-wrapped, like the labels: the rows counted here are then the rows drawn at any width the
157
+ // frame is laid out in, not just the one this happened to measure at.
158
+ const hint = hangingWrap(typing ? QUESTION_TYPING_HINT : QUESTION_HINT, Math.max(1, cols), 0);
159
+ const hintRows = HINT_GAP_ROWS + hint.split('\n').length;
160
+ // Everything that does not depend on the question: the frame, the header and the margins.
161
+ const chrome = FRAME_ROWS + LABEL_ROWS + GAP_ROWS;
162
+ const fixed = chrome + hintRows;
163
+ // `rows - 1`: Ink repaints the whole terminal once the frame is AT LEAST as tall as the viewport
164
+ // (build/ink.js), so a budget that lands exactly on `rows` still clears the scrollback.
165
+ const budget = (fixedRows) => rows - 1 - fixedRows - below - reservedRows;
166
+ const fitAt = (fixedRows) => fitQuestionToHeight(questionLines.length, labelRows, descriptionRows, budget(fixedRows));
167
+ let fit = fitAt(fixed);
168
+ let showHint = true;
169
+ // On a pane too short for the whole dialog, the HINT is what goes before the question is cut:
170
+ // the options are what the user acts on and the question is what they are answering, while the
171
+ // hint is keyboard help they learn once. It goes when dropping it shows the question whole, and
172
+ // also when the frame overflows with it: `fitQuestionToHeight` keeps a question row and its note
173
+ // past the budget, and keeping the hint there spends the scrollback on keyboard help.
174
+ const cut = (f) => f.questionRows < questionLines.length || (!f.showDescriptions && descriptionRows > 0);
175
+ const heightOf = (f, fixedRows) => fixedRows +
176
+ f.questionRows +
177
+ (f.questionRows < questionLines.length ? 1 : 0) +
89
178
  labelRows +
90
- (fit.showDescriptions ? descriptionRows : 0);
179
+ (f.showDescriptions ? descriptionRows : 0);
180
+ if (cut(fit)) {
181
+ const without = fitAt(chrome);
182
+ if (!cut(without) || heightOf(fit, fixed) > budget(0)) {
183
+ showHint = false;
184
+ fit = without;
185
+ }
186
+ }
187
+ const hiddenQuestionRows = questionLines.length - fit.questionRows;
188
+ const fixedRows = showHint ? fixed : chrome;
189
+ // What is left for the options once the fixed rows, the question and its note have taken theirs.
190
+ // The own-answer row is always drawn, so it comes off the budget before the window is picked —
191
+ // what is left is the option rows (descriptions included) plus their markers.
192
+ const optionBudget = rows -
193
+ 1 -
194
+ fixedRows -
195
+ below -
196
+ reservedRows -
197
+ fit.questionRows -
198
+ (hiddenQuestionRows > 0 ? 1 : 0) -
199
+ rowsOf(ownAnswer);
200
+ const optionCosts = labels.map((l, i) => {
201
+ const d = fit.showDescriptions ? descriptions[i] : null;
202
+ return rowsOf(l.wrapped) + (d ? rowsOf(d) : 0);
203
+ });
204
+ const options = typing ? null : fitOptionsToHeight(optionCosts, optionBudget, selectedIndex);
205
+ // A windowed list is padded to the tallest window any cursor position gives (capped at the
206
+ // budget), or the dialog — and the input App sizes under it — grew and shrank by a row as the
207
+ // user arrowed past labels that wrap to different heights. A whole list never moves.
208
+ let padRows = 0;
209
+ if (options && options.moreAbove + options.moreBelow > 0) {
210
+ let steady = 0;
211
+ for (let i = 0; i <= request.options.length; i++) {
212
+ steady = Math.max(steady, fitOptionsToHeight(optionCosts, optionBudget, i).rows);
213
+ }
214
+ padRows = Math.max(0, Math.min(steady, optionBudget) - options.rows);
215
+ }
216
+ // `options.rows` already carries the descriptions of the options on show, and while typing the
217
+ // list is replaced by the prompt line, so neither term is added again here.
218
+ const optionRows = typing || !options ? labelRows : options.rows + padRows + rowsOf(ownAnswer);
219
+ const height = fixedRows + fit.questionRows + (hiddenQuestionRows > 0 ? 1 : 0) + optionRows;
91
220
  return {
92
221
  labels,
93
222
  descriptions,
@@ -97,9 +226,13 @@ export function layoutQuestion(request, typing, cols, rows, reservedRows) {
97
226
  fit,
98
227
  hiddenQuestionRows,
99
228
  height,
229
+ hint,
230
+ showHint,
231
+ options,
232
+ padRows,
100
233
  };
101
234
  }
102
235
  // The dialog's height at the live terminal size, for the input underneath it.
103
- export function questionDialogHeight(request, typing, reservedRows) {
104
- return layoutQuestion(request, typing, contentWidth(DIALOG_CHROME), process.stdout.rows || 24, reservedRows).height;
236
+ export function questionDialogHeight(request, typing, reservedRows, selectedIndex = 0) {
237
+ return layoutQuestion(request, typing, contentWidth(DIALOG_CHROME), process.stdout.rows || 24, reservedRows, selectedIndex).height;
105
238
  }
@@ -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,16 +15,22 @@ 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
- // The model is what tells apart two sessions opened with the same prompt.
26
- const tail = ` ${e.messageCount} msgs${e.model ? ` · ${e.model}` : ''}`;
31
+ // The model is what tells apart two sessions opened with the same prompt; `chat` marks a
32
+ // session holding a chat (#875), which otherwise reads like any other.
33
+ const tail = ` ${e.messageCount} msgs${e.chat ? ' · chat' : ''}${e.model ? ` · ${e.model}` : ''}`;
27
34
  const budget = Math.max(10, maxDisplay - when.length - tail.length - 2);
28
35
  // One Text with nested runs: on wrap Ink drops the char at a sibling boundary.
29
36
  return (_jsxs(Text, { children: [_jsx(Text, { color: selected ? theme.accent : undefined, children: selected ? '› ' : ' ' }), _jsx(Text, { color: theme.muted, children: `${when} ` }), _jsx(Text, { color: selected ? theme.accent : undefined, children: truncate(label, budget) }), _jsx(Text, { color: theme.muted, children: tail })] }, e.path));