Compare commits

...
134 Commits
Author SHA1 Message Date
esengine ee3f8c676c chore(release): 0.26.0 2026-05-04 22:38:51 -07:00
YHH cebe2c3ba8 fix(renderer): avoid \x1b[2J on resize so input bar stops duplicating on conhost (#249) (#255)
\x1b[2J on Windows PowerShell 5.1's legacy conhost scrolls the visible
viewport into scrollback rather than truly erasing it. Each terminal
resize was pushing the current input/toolbar into scrollback, and a
later grow-resize pulled those rows back into the viewport — visible
to the user as duplicated input bars.

Use the same rewind-and-clear pattern (\r\x1b[<N>A\x1b[J) already
used by commitScrollback / emitStatic. \x1b[J fills with spaces in
place, no scrollback push. Platform-neutral, no Windows branch.
2026-05-04 22:34:41 -07:00
YHH d24a6b5b38 refactor(cli): move /prune-sessions to reasonix prune-sessions CLI (#254)
The slash form didn't need any chat state — it just deleted idle session
files from disk. Belongs as a CLI subcommand. Adds --days and --dry-run
flags (the slash form had neither).

  reasonix prune-sessions               # default 90d, deletes
  reasonix prune-sessions --days 30
  reasonix prune-sessions --dry-run     # preview, no delete

Removed:
  - /prune-sessions slash handler + registry entry
  - pruneUsage / pruneNone / pruneInfo i18n strings (EN + zh-CN)
  - slash schema entries for "prune-sessions"
  - tests covering the slash form

Updated:
  - /doctor's stale-session warning now points at `reasonix prune-sessions`
  - i18n schema gains cli.pruneSessions, ui.pruneDaysHint, ui.pruneDryRunHint

Part of #243. /init stays slash (it leverages the live edit-gate;
not actually a CLI shape on closer look). /dashboard stays dual.
/clear rename pending RFC.

Tests: 2254 pass.
2026-05-04 22:09:43 -07:00
YHH 8c49b38732 refactor(slash): drop /setup — handler did nothing useful (#253)
/setup just printed a static "exit and run reasonix setup" reminder.
The actual `reasonix setup` CLI subcommand is unchanged; we just
removed the slash command that pointed at it.

Part of the #243 inventory cleanup. Net -5 LOC across handlers,
commands, i18n (EN + zh-CN), and tests.

Tests: 2254 pass.
2026-05-04 20:55:57 -07:00
Wesley Viana 32a4818d76 chore: test coverage and mutation test (#247)
* chore: test coverage and mutation test

* Increase mutation scope
2026-05-04 20:46:48 -07:00
Wesley Viana fe074942f4 fix: Model was still doing things while pending to approve (#237)
* fix: Model was still doing things while user was being prompt to accept tool call.

* Checkpoint feedback, remove dead code
2026-05-04 20:43:07 -07:00
YHH eb6291843a feat(loop): aggressive fold tier between 70% and 80% of ctxMax (#252)
PR-D from #244. Closes the gap between the normal-fold threshold (50%)
and the force-summary cliff (80%): when a turn lands in 70-85%, the
recent K turns alone are already big enough that a normal fold (tail =
20% of ctxMax) wouldn't buy meaningful headroom. The aggressive tier
shrinks the tail to 10% of ctxMax — sacrifices some recent context
for a real reset.

Decision matrix now:

  ratio > 0.8  → exit-with-summary
  ratio > 0.7  → fold (tail = 10% ctxMax)  [aggressive]
  ratio > 0.5  → fold (tail = 20% ctxMax)  [normal]
  else         → none

The status line and warning text both surface "aggressive" when that
tier fires, so users know why recent turns were trimmed harder than
usual.

Implementation:

  - PostUsageDecision now carries `tailBudget` and `aggressive` fields
    when kind === "fold". loop.ts passes tailBudget through to
    compactHistory (which already accepted keepRecentTokens).
  - decideAfterUsage hoists the alreadyFolded short-circuit above the
    fold-band checks so neither tier re-fires within a turn.

Tests: 2243 pass (was 2242; +1 covering the aggressive band yields a
warning matching `aggressively folded` and a status with `aggressive`).
2026-05-04 20:36:55 -07:00
ctharveyandCharles H 305bc641a2 refactor(mcp): extract server summary matching + replacement helpers (#250)
- Add sameMcpServerSummary(a, b) for logical identity (ref or label+spec).
- Add replaceMcpServerSummary(servers, target, updated) for immutable list update.
- Replace inline prev.map(...) in App.tsx with the helper call.

Co-authored-by: Charles H <[email protected]>
2026-05-04 20:19:20 -07:00
YHH 557cfc12c7 refactor(loop): /compact now folds (cache-safe), drop in-place mutation (#251)
PR-B from #244: closes the foot-gun left over from #238 / #241.

Before this PR, /compact called loop.compact() → ContextManager.inPlaceCompact(),
which mutated mid-history tool result bodies. Cache-aware analysis (#238) showed
that path costs more than it saves: shrinking 50% of prompt size while
invalidating 100% of cache from the mutation point on. The 95% preflight valve
was the second caller of the same path.

What changed:
  - /compact handler now calls loop.compactHistory() (the cache-safe fold from
    #241) via the existing async-via-postInfo pattern (mirrors /dashboard).
    Sync return is "folding…"; result lands as a follow-up info line.
  - 95% preflight: tries fold first (one summary call, append-only) instead of
    in-place compact. If fold can't shrink anything, surfaces the warning and
    lets the request go (the user can /clear).
  - loop.compact() public method removed. ContextManager.inPlaceCompact()
    removed. shrinkOversizedTool* helpers stay (still used by session
    heal-on-load and tests).
  - 80% force-summary warning text updated: now mentions /compact since the
    name is safe to recommend.

User-visible:
  - /compact name kept (muscle memory + short to type), behavior is now
    cache-safe fold. Old behavior is gone.
  - /help text updated to reflect the new semantics.
  - tests/preflight.test.ts: warnings now report fold result instead of
    pre-compacted tool count; the "nothing to fold" path replaces the old
    "nothing to auto-compact".

Tests: 2233 pass. Typecheck clean.

Closes #243's foot-gun deletion concerns.
2026-05-04 20:18:20 -07:00
ctharveyandCharles H 10f1866c02 refactor: make applyMcpAppend immutable — returns new McpServerSummary instead of mutating input (#248)
- applyMcpAppend() now returns a new McpServerSummary with updated
  report.tools.items and toolCount, built via object/array spreads.
- Original target object is never mutated.
- ApplyAppend type returns McpServerSummary instead of void.
- kickOffMcpReconnect captures the return value and updates its local target.
- App.tsx stores MCP servers in local state and immutably replaces the
  matching summary after append-drift.
- Both biome-ignore/noExplicitAny suppressions removed.

Co-authored-by: Charles H <[email protected]>
2026-05-04 19:45:32 -07:00
YHH d632755f43 refactor(loop): extract ContextManager — zero behavior change (#245)
Pulls the four ad-hoc compaction mechanisms behind one component
(see #244 for the full architectural rationale):

  - decideAfterUsage(usage, model, alreadyFoldedThisTurn) returns
    "fold" / "exit-with-summary" / "none" — the policy that used to
    live as inline if-blocks in step()
  - decidePreflight(messages, toolSpecs, model) is the local outgoing
    estimate gate (>95% of ctxMax)
  - fold(model, opts) replaces compactHistory's body
  - inPlaceCompact(maxTokens) replaces compact's body and is also
    what the 95% preflight calls — the one remaining cache-breaking
    path, marked for removal in PR-B
  - trimTrailingToolCalls() factors out the in-flight tool_calls tail
    drop used before forced-summary

loop.ts methods become thin delegators: compact / compactHistory keep
their public signatures (slash handlers and tests untouched);
forceSummaryAfterIterLimit stays in loop.ts because it's tightly
coupled to LoopEvent yielding.

All thresholds and the summary-marker constant moved to
context-manager.ts. No values changed.

Tests: 2235 pass (no test changes). Typecheck clean.
2026-05-04 19:38:29 -07:00
YHH ea37106e03 ci: add CodeQL security scanning workflow (#246)
Runs on push to main, every PR, and weekly cron. Uses the
javascript-typescript analyzer with security-extended queries.
2026-05-04 19:33:57 -07:00
ctharveyandCharles H eb7c9b5425 fix(mcp): prevent unhandled rejection during hung send timeout (#240)
Co-authored-by: Charles H <[email protected]>
2026-05-04 19:15:56 -07:00
YHH 8681d158aa feat(loop): append-only history fold at 50% of ctxMax (#241)
When a turn's response shows promptTokens > 50% of the model's context
window, replace the older portion of the log with a single synthesized
assistant summary and keep the trailing turns whose token weight fits
in 20% of ctxMax. One cache break per fold; cache rebuilds in ~1 turn,
then the conversation continues under the cap until the next fold.

Without this, append-only sessions grow unbounded — by the time
prompt > 80% of ctxMax, the existing force-summary path fires every
turn ($0.07/turn purgatory until /clear or /compact). Fold prevents
ever reaching that cliff.

Sized so:
  - tail budget = 0.2 * ctxMax → ~30% headroom before next fold
  - min savings fraction = 0.3 → no fold if head wouldn't shrink the
    log meaningfully (avoids re-fold thrash on stable post-fold logs)
  - summary call uses deepseek-v4-flash + high effort, ~$0.07 each

Validated on a real 20-turn DeepSeek session with ctxMax pinned at 50k
(scripts/probe-long-session.mts):
  turn 10: 52% trips → fold fires → 42 msgs → 19, prompt 25k → 13k
  turn 11: cache rebuilds to 84% within one turn
  turn 16: 51% trips again, fold fires
  total cost across 20 turns: $0.0381 (vs $0.0493 without fold)
  total mutations: 2 (= the 2 folds, nothing else)

Closes #236.
2026-05-04 19:03:32 -07:00
YHH a621f17294 perf(loop): drop in-place auto-compaction — was destroying prompt cache (#238)
* perf(loop): drop in-place auto-compaction — was destroying prompt cache

DeepSeek prompt cache is prefix-exact: mutating any byte of an old
message invalidates every cached token after that point. We were
calling compactInPlace() in five places (turn-end, post-tool-args,
40-80% proactive, 80% reactive, plus the slash command), which meant
long sessions repeatedly traded "smaller prompt" for "0% cache hit
on the rest" — net negative against DeepSeek's 4× cache discount.

Probed empirically (scripts/probe-cache.mjs):
  append-only:    98.6% cache hit
  one mutation:    0.0% cache hit, lost 4480 cached tokens
  long session:   ~91% sustained across turns after warmup

Removed the auto-trigger paths entirely. The 80% reactive block now
goes straight to forced-summary instead of trying to mutate-then-bail
(it was already falling through to summary in the common case). The
95% preflight emergency valve and the manual /compact slash command
are kept — they're explicit/last-resort and expected to break cache.

Refs #236

* test(loop): add end-to-end cache-hit probe driving real CacheFirstLoop

Complements scripts/probe-cache.mjs (which probes the API primitive).
This drives the actual loop through 6 real turns and asserts:
  - log.compactInPlace() is never called (append-only invariant)
  - warm-turn cache hit % stays above 80%

Measured against the live API after the auto-compaction removal:
  turn 0:  0.0% (cold cache, expected)
  turns 1-5: 99.0, 98.5, 98.0, 97.6, 97.1 — ~98% sustained
  total mutations: 0
2026-05-04 18:35:08 -07:00
esengine 4b446e8640 release: 0.25.1 — chain operators + file redirects in run_command
`run_command` learns the four common shell chain operators (`|`, `||`,
`&&`, `;`) and the seven file redirect operators (`>`, `>>`, `<`, `2>`,
`2>>`, `2>&1`, `&>`). Parsed and spawned natively — no shell is invoked,
so semantics are identical on Windows / macOS / Linux; PowerShell 5.1's
`&&` parse error and the object-vs-bytes pipe gap are sidestepped.

Each chain segment is allowlist-checked independently: `git status |
grep main` now auto-runs when both halves are individually allowed, the
granular-approval behaviour wviana asked for in discussion #231.

The chain parser stays consistent with the project's long-standing
lenient tokenizer — `cargo run -- --flag=1&2` and similar embedded-
operator args stay literal instead of getting POSIX-strict-rejected.
shell-quote is no longer a dependency; `splitOnChainOps` is whitespace-
bounded like the existing `detectShellOperator`.

Mid-pipe `2>&1` correctly merges stderr into the next segment's stdin
without truncating on stdout-end (counter-based close-when-both-ended).

Targets resolve relative to the project root. Heredoc `<<` and
background `&` remain explicitly rejected with clear errors. `\$VAR`
and `\$(...)` pass through as literal characters — no shell expansion.

Closes #232. Driven by discussion #231. PRs: #233 (chain ops), #234
(lenient-tokenizer regression fix), #235 (redirects + mid-pipe `2>&1`).
2026-05-04 17:56:30 -07:00
YHH 9443f50955 feat(shell): support file redirects in run_command (#235)
* feat(shell): support file redirects in run_command (`>`, `>>`, `<`, `2>`, `2>>`, `2>&1`, `&>`)

Phase 2 of the chain-aware run_command rewrite. Each segment now parses
trailing redirects via a single-pass walker (no shell), opens files with
fs.openSync, and hands the resulting fds to spawn's stdio array. Pipe
wiring still applies — `<` overrides pipe-stdin only when explicitly
present; `>`/`>>`/`&>` override the pipe-out / capture-buffer wiring.

Supported per segment (max one per fd):

- `>`   stdout truncate
- `>>`  stdout append
- `<`   stdin from file
- `2>`  stderr truncate
- `2>>` stderr append
- `2>&1` merge stderr → stdout (file fd, pipe, or our buffer, whatever stdout points to)
- `&>`  both → file (truncate)

Targets resolve relative to the chain's cwd. Multiple redirects to the
same fd are rejected with a clear conflict message.

ChainSegment now carries `redirects: Redirect[]` alongside `argv`. The
old `tokenizeCommand + detectShellOperator` per-segment combo is
replaced with `parseSegment`, a quote-aware single-pass walker that
emits both argv tokens and redirects at the same level — keeps the
lenient embedded-`&`/`|` handling intact (the `cmd1 ; cmd2 -flag=1&2`
regression fix from #234 still passes).

Heredoc `<<` is rejected explicitly. Background `&` is rejected
explicitly (use run_background, not run_command). `$VAR` and `$(…)`
pass through as literal characters — no shell expansion, matching the
existing single-command tokenizer.

Adds 30 new tests in tests/shell-redirects.test.ts covering parser
output and execution; updates the obsolete redirect-rejection tests
in tests/shell-tools.test.ts to cover the new rejection set
(background `&`, heredoc `<<`, missing target, multi-redirect-per-fd).

* fix(shell): hold child.stdin open until both prev streams end on mid-pipe `2>&1`

`cmd1 2>&1 | cmd2` was wiring prev.stdout into child.stdin with default
end-on-source-end, then piping prev.stderr in with `end: false`. When
stdout finished first, child.stdin closed and any subsequent stderr
writes hit a closed stream — output got truncated.

Both branches now pipe with `end: false` and a 2-counter closes stdin
only after both source streams emit `end`. Adds a test that pipes
stderr through to a downstream cat-like process and asserts both
streams reach the destination.
2026-05-04 17:29:08 -07:00
YHH 56b94d0677 fix(shell): drop shell-quote, hand-roll chain splitter to keep lenient tokenization (#234)
Phase 1 (#233) used shell-quote for chain segmentation, but its strict
POSIX tokenization split `--flag=1&2` into three tokens with `&` as a
background operator — a regression vs. pre-Phase-1 behavior, where the
existing lenient `tokenizeCommand` left embedded `&`/`|`/`;` chars as
literal bytes inside larger tokens.

Replace with a small whitespace-bounded chain splitter that matches the
existing `detectShellOperator` convention: chain ops only count when
they begin a whitespace-separated token. Each segment then runs through
the existing `tokenizeCommand` (lenient) and `detectShellOperator`
(rejects `>`, `<`, `&`, `2>&1`, `&>`).

Recovers:
- `cargo run -- --flag=1&2`           — runs (was rejected post-#233)
- `git status ; cargo run -- --flag=1&2` — chain runs, second segment keeps `&`

Drops:
- `git status|grep main` (no spaces) — never worked pre-Phase-1, was a
  shell-quote-only side effect; align with the project's
  whitespace-bounded operator convention.

Also drops `$VAR` / `$(...)` rejection — these now pass through as
literal arguments, matching the existing single-command tokenizer's
behavior. Models see the literal `$HOME` in echo's output and learn.
2026-05-04 17:10:13 -07:00
YHH 5ea5f76de6 feat(shell): support |, &&, ||, ; in run_command via split-and-spawn (#233)
Parse chain operators ourselves with shell-quote and spawn each segment
as a separate process — never invoke a system shell. Sidesteps PowerShell
5.1's `&&` parse error and the object-vs-bytes pipe semantics gap on
Windows. Each segment is allowlist-checked independently, so
`git status | grep main` runs when both halves are individually allowed.

Redirects (`>`, `<`, `2>&1`), background `&`, env-var expansion `$VAR`,
command substitution `$(…)`, and subshells `(…)` remain rejected up-front
with clear errors.

Tracks #232, addresses #231.
2026-05-04 16:56:38 -07:00
esengine 7526167d32 fix(setup): replace ink-text-input with MaskedInput, strip leaked paste markers
Two bugs in the Setup screen on Windows / cell-diff renderer:

1. ink-text-input bakes chalk-styled output into the text it returns.
   Our renderer strips the ESC byte but keeps the rest, so users saw
   literal `[7ms[27m[90mk-...[39m` in the input field. MaskedInput uses
   the renderer's <Text inverse> / <Text dimColor> primitives instead.

2. Windows ConPTY splits bracketed-paste wrappers across stdin chunks,
   so Ink's parser sees `\x1b[200~` / `\x1b[201~` as printable `[`,
   `2`, `0`, `0`, `~` and they leak into the buffer. Strip them at
   the input boundary and again at submit.

Also fixes a stale-closure bug where rapid keystrokes from a paste
burst all read the initial empty value, so only the last char survived.
A ref synced on every render lets each keystroke append onto the
latest accumulated value.
2026-05-04 09:55:43 -07:00
esengine 32126dece4 release: 0.25.0 — plan auto-execution, kill flicker root cause, prune demos
Plan execution is continuous after approval — `mark_step_complete` no
longer throws PlanCheckpointError; the model runs all steps in one turn.
Plan card commits to scrollback as the approved snapshot AND renders as
a fixed-height live strip (PlanLiveRow) docked above prompt input via
the windowed-5 step view.

Flicker root cause was orphan unsettled cards (aborted streams that
never fired their .end event) trapping every subsequent card in the
live region — Yoga re-measured the whole live tree on every chunk.
CardStream now allows only the LAST card to be live; earlier orphans
are force-committed to scrollback.

Streaming cards switch to a left ▎ stripe (Card.tsx). Round borders'
top/bottom rows orphaned under the cell-diff renderer's row-promotion
logic when content height changed mid-stream. Stripe rows always carry
both ▎ and content, so promotion is always atomic.

Active-tone color set (TONE_ACTIVE) lifts streaming/running cards one
shade brighter; settled tones unchanged. DiffCard tone bug fixed
(was warn, registry says ok). PlanCard wraps any plan length to a
fixed 5-step window with `✓ ⋯ N done` / `⋯ N upcoming` elision.

API surface: PlanCheckpointError + PlanCheckpointConfirm removed.
mark_step_complete returns the step_completed payload directly.
/stop slash command added (typed alternative to Esc abort).

Cleanup: removed all 7 demo CLI commands (banner / card / flicker /
preview / renderer / select / stress) and their 5 test files. They
duplicated production card components and drifted out of sync.
2026-05-04 09:29:48 -07:00
ctharvey 73000ce388 refactor(mcp): hide host client reads from browse UI (#227)
Refs #196.
2026-05-04 08:55:46 -07:00
ctharvey c86279a493 refactor(mcp): extract healthBadge to mcp-health.ts (#226)
Refs #196.
2026-05-04 08:54:14 -07:00
ctharvey fbcd82096c refactor(mcp): extract healthBadge to mcp-health.ts (#226)
Refs #196.
2026-05-04 08:51:37 -07:00
esengine 37b4cca4f6 refactor(ui): SubagentRow uses Card+CardHeader; drop CardRenderer's marginTop
Two related fixes:

1. SubagentRow was a hand-rolled 9-row block with ▎ left bar drawn on
   every row. User reported it didn't match the rest of the card pass —
   because it predates the Card primitive entirely. Rewritten on top of
   <Card> with round border + violet tone + CardHeader (titleBg pill +
   model pill + spinner in `right`). Body collapses from the 9-row
   stack into 3 lines (task / last / phase) inside the card. Row count
   is still fixed (no per-event growth) so flicker behavior is preserved.

2. CardRenderer had marginTop=1 on its outer wrapper, doubling the
   marginTop=1 the Card primitive already adds. Every static-emitted
   card carried 2 leading blank rows, accumulating noticeable gaps in
   scrollback between cards. Drop CardRenderer's mt; Card primitive
   alone owns inter-card spacing.
2026-05-04 07:11:02 -07:00
esengine 3d692ead01 feat(cards): tinted reasoning title + model pill on reasoning/streaming + subagent demo-style children
Three card-header upgrades the user asked for:

1. CardHeader gains an optional `titleBg` that paints the title as a
   colored chip — used by ReasoningCard so `reasoning` reads as a
   muted-purple block instead of plain bold text. (Borrowed from
   PILL_SECTION.reason — already in the theme.)

2. ReasoningCard + StreamingCard surface the snapshotted `card.model`
   as a Pill in the header `right` slot. v4-flash / v4-pro / r1 each
   get their own color via PILL_MODEL.

3. SubAgentCard children now match card-demo's row format:
   ▎ [status spinner|✓|✖] [kind glyph] [summary]

   Previously the row only had the kind glyph + content; now per-child
   running cards spin a tone-colored circle while done ones get a green
   ✓. Header switches the meta from a static status text to "N running"
   when active, mirroring the demo's runningCount.
2026-05-04 06:57:43 -07:00
esengine a9024a8d31 refactor(ui): soften ThinkingRow — italic + dim instead of bold blue block
Original was bold brand-blue spinner + bold brand-blue text + faint
duration with hardcoded `· ` separators. All three fields competed for
attention even though the row is just a "model is busy" hint.

Restraint: drop bold from spinner + label, switch label color to FG.sub
italic (semantic "thinking" via type, not color), accent-purple spinner
for a slower visual pulse, gap={1} for spacing instead of inline `· `
chunks. Reads as one sentence instead of three competing pills.
2026-05-04 06:52:39 -07:00
esengine a8e7ebeb47 fix(renderer): keep promotedRows across resize so scrollback isn't duplicated
mount.ts resize() reset promotedRows=0, which made the next commit's
commitScrollback see split.skipped > promotedRows and serialize every
already-scrolled-out row a second time. Each terminal resize stacked
another full copy of the overflowed history into scrollback — visible
as duplicate chrome bars / mode bars climbing up the scroll buffer.

Promoted rows live in the terminal's own scrollback, which the renderer
can't access — so resetting our counter is structurally wrong. Keep
promotedRows; with pendingClear handling the visible repaint, the new
layout's skipped count drives an honest newPromote (often 0 on resize,
since the layout's overflow boundary moves by 1-2 rows max under width
change, not by the entire history).

Also dedup same-dimension resize events — terminals fire 2-3× per
drag and each fires a full commit otherwise.
2026-05-04 06:43:16 -07:00
esengine 88e5becf06 Revert "fix(cards): pin flexShrink=0 on Card so settled bodies aren't squashed"
This reverts commit 8685215e23.
2026-05-04 06:27:42 -07:00
esengine 8685215e23 fix(cards): pin flexShrink=0 on Card so settled bodies aren't squashed
In `npm run dev` real ink (not the cell-diff renderer) drives layout,
and yoga defaults flex-shrink to 1. When a settled card lands inside
real ink's <Static> column, the box can be shrunk to fit even though no
explicit height is bound — UserCard's Markdown body and ReasoningCard's
SettledPreview both collapsed to 0 rows while the headers survived.

flexShrink=0 on both active and settled wrappers anchors each card to
its content height. The streaming reply was unaffected because its body
alone is already taller than terminal/2 so shrink wouldn't fire.
2026-05-04 06:25:11 -07:00
esengine 7b108cc2c0 fix(cards): drop paddingLeft from settled Card so bodies render
Adding paddingLeft={2} to the settled-mode wrapper collapsed the layout
so card bodies (UserCard's Markdown, ReasoningCard's BodyLines, etc.)
rendered as 0 rows — only the headers were visible. Card-demo's
StaticRow doesn't apply outer padding either; it pads body sub-Boxes
individually, which is the pattern the live cards used pre-refactor.

Settled mode now mirrors the original outer wrapper shape exactly:
`<Box flexDirection="column" marginTop={1}>`. Bodies render. Active
mode keeps the round border + paddingX=1 + width="100%".
2026-05-04 06:11:01 -07:00
esengine 948f361849 fix(cards): propagate ActiveCardContext into Static's off-tree render
CardStream previously wrapped <Static> in an ActiveCardContext.Provider,
but Static emits its items via bridge.emitStatic which renders them in
an off-tree reconciler — context from the live tree doesn't travel.
Settled cards still rendered with active=true (default) and kept their
borders.

Move the Provider inside the Static children function so it captures
into the per-item subtree that emitStatic actually serializes. Live
path drops its (now redundant) Provider since Card primitive defaults
to active=true.
2026-05-04 06:01:09 -07:00
esengine d65eeddac6 fix(cards): drop border on settled cards + stretch active borders to full width
Two visual bugs after the e78112b border roll-out:

1. Settled cards (in scrollback) carried borders too, but card-demo only
   borders the live/active cards — settled rows in demo are flat history
   text. Live chat now mirrors that: ActiveCardContext threads
   active=false through CardStream's <Static> path, and Card primitive
   renders a paddingLeft=2 flat block when not active.

2. Active card width was content-fit, so a narrow reasoning card and a
   wide reply card had different border widths in the same column. Adds
   width="100%" so every active card stretches to the full available
   width and the column reads as a uniform stack.

Also resolves the "reply bottom border missing" symptom — settled reply
cards no longer have a border at all, so the question doesn't arise.
2026-05-04 05:53:40 -07:00
esengine e78112bf4f feat(cards): wrap 16 cards in round-border Card primitive — port the demo look to live chat
card-demo had a polished round-border + paddingX=1 wrapper around each
card, but the live chat path (src/cli/ui/cards/*.tsx) never adopted it,
so the demo and the actual chat looked completely different. New
primitive `Card({tone, children})` ports that wrapper to the real cards.

Refactored cards now flow through `<Card tone={...}>` with their content
flush left inside the border (paddingX=1 on the wrapper provides the gap;
removed the per-body `paddingLeft={2}` that would have stacked).

Border tone tracks status:
- ok / running / settled — TONE.ok / brand / accent
- error / warn / abort  — TONE.err / warn
- meta-info             — FG.meta (usage / memory)

LiveCard skipped — it's a one-line transient toast and a 3-row border
would defeat the point. CompactUsageRow path also stays flat.

DEC 2026 sync from 0.24.1 means the border resizing for streaming
content (reasoning/tool/streaming card body growing) lands atomically
per frame; no flicker layered on top of what we already had.
2026-05-04 05:44:00 -07:00
esengine 51a5f9dd8e refactor(cards): unify card header via CardHeader primitive — drop CardBox
Every card had been hand-rolling its first row with the same
Box/Text/gap=1 incantation, so spacing and color hierarchy drifted
between cards. New CardHeader primitive accepts (glyph, tone, title,
optional titleColor / subtitle / meta / right) and gives 12 cards a
single source of truth:

- glyph + bold title in tone color (titleColor overrides for demoted
  cards like usage/memory/user where the bold reads as muted FG.sub)
- subtitle in FG.body (e.g. tool args summary, search query, task
  title, subagent name)
- meta items prefixed with `·` separator, joined by ` · `, faint by
  default; colored MetaItem variant carries diff +/- counts and
  retry/rejected badges without inline JSX clutter
- right slot for ad-hoc inline elements (streaming/reasoning/tool
  spinners)

Drops CardBox — it had a ▎ left-bar API but no card actually wrapped in
it (grep returned zero call sites); the inline ▎ each card showed was
hardcoded, and the redesign has no leading bar at all.

Cards converted: User, Streaming, Reasoning, Tool, Task, Plan, Diff,
Usage, Memory, Search, Branch, SubAgent. 12 files, net -55 lines.

Zero flicker risk — pure single-row replacement, same column width per
field. No row count changes.
2026-05-04 05:30:34 -07:00
esengine b5fd33700e feat(cards): visual audit pass — disambiguate streaming/task, demote usage, branch+ctx+doctor enter token table
The CARD constant was the source of truth on paper but most cards
hardcoded glyphs in JSX, so the table drifted from what's rendered.
This pass aligns intent and fixes the worst clashes:

- streaming and task were both `▶` brand-blue and visually
  indistinguishable when both surfaced in the same turn. Streaming now
  paints `◈` (paired with reasoning's `◆` for the thinking→speaking
  arc); task keeps `▶` but moves to TONE.warn so "doing work" reads
  separately from "model replying".
- usage is a turn-end summary, not active output — header demoted to
  FG.meta; bars + balance keep brand for information density.
- doctor's fail glyph `✗` aligned to error's `✖` for consistency.
- branch in-progress was reusing CARD.streaming.color (brand-blue);
  branching is orchestration, paired with subagent under TONE.violet.
- ctx, doctor, branch were absent from CARD; added so future cards have
  a token to anchor against. (Existing cards still hardcode glyphs;
  consolidation is a follow-up.)

Zero row-count or column-width changes — every replacement is a
single-cell glyph. No flicker risk on top of 0.24.1's sync wrap.
2026-05-04 05:14:47 -07:00
esengine b24d2350ed release: 0.24.1 — DEC 2026 sync to suppress flicker + marked v15 2026-05-04 04:55:46 -07:00
esengine 9f8df4da6b fix(deps): bump marked to v15 — v12 pre-escapes inline text to HTML entities
Marked v12's tokenizer ran inline text through HTML escape (& → &amp;,
< → &lt;, " → &quot;), which is correct for HTML output but wrong for a
TUI — both the user-input echo and assistant markdown rendered the raw
entities. v15 keeps token.text literal and only escapes at the HTML
renderer layer, which matches our actual rendering path. Also avoids the
miswidth where a 1-cell `<` was measured as 4 cells (`&lt;`) and clipped
content past the wrap edge.
2026-05-04 04:49:47 -07:00
esengine 6e2e869aaa fix(renderer): wrap commit writes in DEC 2026 sync to suppress flicker
Commit/static/resize paths buffered bytes into one write but the terminal
could still paint the cleared-then-repainted intermediate state. Wrapping
each frame in BSU/ESU (\x1b[?2026h…l) lets supporting terminals (Windows
Terminal ≥1.18, iTerm2, Kitty, Wezterm, alacritty, foot) swap the frame
atomically; others ignore the unknown CSI. Also folds resize's screen
clear into the next commit so clear+repaint is one sync block.
2026-05-04 04:49:32 -07:00
esengine ff6edff2f6 0.24.0 2026-05-04 04:04:48 -07:00
YHH 213b4ec198 Merge pull request #224 from esengine/fix/inkcompat-stdout-flicker
feat(renderer): yoga + 17/17 card migration + UX overhaul (#160)
2026-05-04 03:41:49 -07:00
esengine 5b5ff09088 feat: WelcomeBanner redesign + plan reject reason + prompt cursor + App cleanup (#160)
Five small, related UX improvements riding the yoga + card-migration train:

WelcomeBanner — REASONIX × 🐋 DeepSeek brand row (cyan brand + violet accent
+ whale emoji), tagline, slash-command hints. Drops the hand-painted box-
drawing borders that broke under CJK fonts; uses borderStyle="round" with
yoga's alignItems="center" so layout is correct in any font.

PlanRefineInput — new "reject" mode (red ✗ tone, error palette). The plan-
confirm picker's cancel branch now opens this input so users can attach a
reason like approve / refine already do. Empty Enter = same cancel synthetic
as before; with text = synthetic includes the user's reason. Symmetric with
the "Tab to add reason" pattern on tool-deny.

PromptInput — call useCursor({visible:false}) so the renderer hides the OS
cursor. PromptInput paints its own ▌ block; without this, the OS cursor
showed at screen-bottom too, doubling up.

App.tsx cleanup — dropped 8 unused imports / destructured fields (ApplyResult,
archivePlanState, ReasoningEffort, saveReasoningEffort, writeClipboard,
renderFrame, COLOR, updateAvailable). Flattened currentRootDir to a state
without setter (no caller).

flicker-demo.tsx — committed the previously-untracked debug demo command
(referenced from src/cli/index.ts).
2026-05-04 03:38:17 -07:00
esengine a92b3c042a feat(cards): migrate remaining 9 cards to flat card-demo style (#160)
Finishes the card-stream migration (now 17/17 = 100%). Each card replaces
CardHeader + BarRow with a flat layout: a row Box for the header glyph +
title + faint metadata, and paddingLeft={2} child rows for the body.

Cards in this commit:
- DiffCard, SubAgentCard, UsageCard, MemoryCard
- SearchCard, LiveCard, CtxCard, BranchCard, DoctorCard

Visual: tighter, no left bar gutter, headers read like one line of status.
Behavior: identical — just different layout primitive.
2026-05-04 03:37:42 -07:00
esengine a5abd9ef94 chore: drop v2 prompt path + Ink-era card primitives (#160)
The chat-v2 / SimplePromptInput stack was the migration test bed for the
cell-diff renderer. With yoga + isPrimaryRenderer in place, the production
chat path on the v1 PromptInput is the only supported entry point, so v2
is now dead weight.

Card primitives (BarRow / CardHeader / Card.tsx / glyphs.ts) became
unreferenced once every card finished migrating to the flat card-demo
style — yoga handles the alignment they were emulating.

Removed:
- src/cli/commands/chat-v2.tsx, input-demo.tsx
- src/cli/ui/chat-v2-slash.ts, loop-bridge.ts, prompt-input-v2.tsx, use-prompt-history.ts
- src/cli/ui/cards/{Card.tsx,CardHeader.tsx,glyphs.ts}
- src/cli/ui/primitives/BarRow.tsx
- tests/renderer/{chat-v2,chat-v2-slash,loop-bridge,prompt-input-v2,use-prompt-history}.test.tsx
- chat-v2 / input-demo command registrations from src/cli/index.ts

Added: src/cli/ui/primitives/CursorBlock.tsx (the only piece of BarRow.tsx
still needed by ReasoningCard, lifted to its own file).
2026-05-04 03:37:15 -07:00
esengine 38867e5c92 feat(renderer): integrate yoga-layout as the flexbox engine (#160)
Replaces our hand-written column/row flex math with Meta's yoga-layout
(WASM, used by real Ink and most React-based TUIs). Layout is now full-spec
flexbox with alignItems/Self/Content, flexShrink/Basis, flexWrap, margin,
min/max, columnGap/rowGap, percent widths.

Why now: the old engine had no cross-axis alignment, so every "center this"
required a nested row+justifyContent hack. With yoga, components describe
intent directly; banner / modal / input layouts collapse to a fraction of
the markup.

Scope:
- Add yoga-layout 3.2.1 dep
- New src/renderer/layout/yoga-layout.ts adapter (LayoutNode -> YogaNode + measure func)
- Rewrite layout.ts: drop layoutBox/Column/Row/intrinsicWidth, walk yoga's
  computed positions to populate LayoutRows
- Extend BoxNode + RsxBox + inkCompat.Box prop surface with the new flex props
- BoxSizing.BorderBox; default flex-shrink=1 (CSS, not yoga's 0); root margins
  reflected in total render bounds
- isPrimaryRenderer=true: only React renderer in this process, so context-stack
  collisions on re-entrant updateContainer go away
- emitStatic via queueMicrotask + reset reservedRows after static bytes -
  fixes resume-path layout collision
- Pin Block Elements (U+2580..U+259F) to width=1 alongside Box Drawing
- Per-edge borderColor props now forwarded through inkCompat
- render-to-bytes header trimmed to satisfy comment-policy

Tests: 2187/2187 pass. Two existing border/padding tests updated for yoga's
content-row reservation behavior (more correct than the old engine).
2026-05-04 03:36:44 -07:00
ctharveyandCharles H 99754672af fix(mcp): close client on handshake failure; swallow kill() errors on Windows (#216)
When mcp.initialize() rejects (timeout, bad spec, etc.), the catch
blocks in chat.tsx and run.ts never called mcp.close() — the child
process leaked, readLoop kept running, and on Node 24 the orphaned
rejection fired as an unhandled rejection.

- Lift mcp declaration before try so it's accessible in catch
- Call mcp?.close().catch(() => undefined) in both catch blocks
  (guard prevents cleanup masking the original bootstrap failure)
- StdioTransport.close(): child.kill("SIGTERM") throws EINVAL on
  Windows; use platform-conditional signal and try/catch to swallow
  both EINVAL and failed-spawn errors

Co-authored-by: Charles H <[email protected]>
2026-05-03 23:34:41 -07:00
esengine d5c02bfae2 fix(renderer): atomic frame writes in mount commit paths (#160)
commitScrollback / commitVirtual / emitStatic all made up to four
sequential opts.write() calls per frame: clear-promote header, promoted
bytes, reserve-grow prelude, and the actual diff patches. Between
writes the terminal could flush, briefly showing blank rows where
content was about to be painted — visible as flicker when ChoiceConfirm
mounts on top of an actively-streaming card (each chunk + the modal
mount each emitting their own multi-write commit).

Now each commit buffers everything into one string and issues a single
opts.write at the end. One terminal flush per frame, no in-between
blank state.

This stacks on top of the previous useStdout fix; the two together
should land the modal-mount flicker.
2026-05-03 22:24:31 -07:00
esengine b140d1c1fb fix(renderer): inkCompat.useStdout returns stable proxy — eliminates modal-mount flicker (#160)
Root cause of the flicker user reported when ChoiceConfirm (and other
modals) appears while a streaming card is still writing:

`inkCompat.useStdout` was returning `{ stdout: { columns, rows } }`,
a fresh object literal on every render with no `.on/.off/.isTTY/.write`.
viewport-budget.tsx (the row allocator the modal claims rows from)
runs `useEffect([stdout])` to register a "resize" listener — every
render produced a new stdout reference, so the effect re-fired every
render. Inside the effect, `stdout.on("resize", ...)` threw because
`.on` was undefined; throw skipped cleanup; cleanup never landed; the
listener that should have detached on next render never did. The
re-fire + throw + dispatch dance manifested as the flicker.

Fix:

1. New `StdoutContext` carries the real NodeJS.WriteStream (passed in
   via mount({stdout})).
2. `useStdout()` now `useMemo`-s the returned wrapper on
   (viewport.columns, viewport.rows, real stdout). Stable identity →
   downstream `useEffect([stdout])` doesn't re-fire on benign renders.
3. The wrapper exposes viewport-driven `columns`/`rows` (so layout
   still reflects the renderer's mounted size, not the host terminal),
   plus `.on/.off/.write/.isTTY` proxied to the real WriteStream.
4. `inkCompat.render` threads `opts.stdout` through to mount() so the
   chain is wired end to end.

All existing tests still pass (the live-banner-via-shim narrow-viewport
test, useStdout viewport tests, etc.).
2026-05-03 22:16:24 -07:00
YHH 3b070dce9c feat(cards): migrate PlanCard + TaskCard (#160) (#220)
PlanCard:
- Header: ⊞ {title} · 3/7 done
- Step rows: glyph + numbered title; running step bold + ← in progress

TaskCard:
- Header: glyph + step N/M + title · elapsed · status
- Step rows: glyph + bold tool name + step title + detail + elapsed

Drops CardHeader / BarRow chrome; both adopt the same flat layout
established for the other cards.
2026-05-03 21:42:07 -07:00
YHH 08e5ddd1f0 feat(cards): migrate ToolCard to card-demo style (#160) (#219)
Drops CardHeader / BarRow / CardBox chrome. Header is one row:
status-glyph + bold tool name + faint args + retry / rejected badges +
faint meta trail (size · elapsed · exit-code).

Status glyphs:
- ▢ running (alongside ⠋ braille spinner)
- ✓ ok
- ✗ rejected
- ✖ error (exit ≠ 0)
- ⊘ aborted

Output preview indented 2; long output keeps the `⋮ N earlier lines`
elision. Exit-code-non-zero output stays in error red, OK output dims.
2026-05-03 21:42:03 -07:00
YHH c3ab3fcb52 feat(cards): migrate ReasoningCard + StreamingCard (#160) (#218)
* feat(cards): migrate ErrorCard + WarnCard to card-demo style (#160)

Drops CardHeader + BarRow primitives. Both cards collapse to the same
flat header-row + indented body pattern that UserCard adopted in #214.

Error retains its retry meta + truncated stack-trace block (unchanged
behavior, lighter visual chrome). Warn keeps the optional detail meta
on the header line.

* feat(cards): migrate ReasoningCard + StreamingCard (#160)

The two most-visible cards in every chat turn drop CardBox + Pill
chrome and adopt the card-demo glyph + bold-title pattern.

ReasoningCard:
- Streaming: ◇ reasoning… · 234 tok ⠋ + italic preview tail (4 lines)
- Settled:   ◆ reasoning · 234 tok · 3¶ · 2.1s + tail (2 lines) + elision
- Aborted:   ◇ reasoning (aborted) in red

StreamingCard:
- Streaming: ▸ writing… ⠋ + clipped preview tail (4 lines)
- Done:      ‹ reply + full markdown body
- Aborted:   ‹ aborted (red) + clipped tail + [truncated by esc]

Spinner stays — liveness signal during streaming is real UX value.
Pills + CardBox left-bar removed.
2026-05-03 21:41:59 -07:00
YHH 4556fb0f09 feat(cards): migrate ErrorCard + WarnCard to card-demo style (#160) (#217)
Drops CardHeader + BarRow primitives. Both cards collapse to the same
flat header-row + indented body pattern that UserCard adopted in #214.

Error retains its retry meta + truncated stack-trace block (unchanged
behavior, lighter visual chrome). Warn keeps the optional detail meta
on the header line.
2026-05-03 21:41:55 -07:00
YHH c80be26517 feat(cards): migrate UserCard to card-demo style (#160) (#214)
* chore(deps): drop ink from runtime dependencies (#160)

The CLI bundle now inlines ink + ink-text-input via tsup's noExternal +
alias chain, so neither package needs to ship at runtime. ink and
ink-text-input move to devDependencies (kept for source resolution
during build / test), and ink-spinner is dropped outright (only ever
referenced in a comment).

vitest gets the same ink → inkCompat alias as tsup so the test suite
runs through the same renderer shim production ships, removing the
last divergence between the two paths.

bundle-smoke already asserts no `from "ink"` literal survives in
dist/cli/; the noExternal extension to ink-text-input means the
bundle has zero `from "ink-text-input"` references too, so a future
regression that breaks either alias fails CI.

* feat(cards): migrate UserCard to card-demo style (#160)

Drops the CardBox left-bar wrapper. The new layout matches card-demo's
flat row aesthetic — accent ›, bold "you", faint relative-time meta,
followed by the user's markdown body indented under it. No more border
or marginLeft offset; cards align to the page's left margin.

This is the first card in the visual migration sweep. Pattern is:
* drop CardBox
* marginTop={1} between cards (was implicit via CardBox)
* header row: glyph + bold word + faint meta
* body indented paddingLeft={2}

Each remaining card (reasoning / streaming / tool / plan / ...) lands
in its own follow-up so before/after diffs stay reviewable.
2026-05-03 20:55:35 -07:00
YHH 252e1258bd chore(deps): drop ink from runtime dependencies (#160) (#213)
The CLI bundle now inlines ink + ink-text-input via tsup's noExternal +
alias chain, so neither package needs to ship at runtime. ink and
ink-text-input move to devDependencies (kept for source resolution
during build / test), and ink-spinner is dropped outright (only ever
referenced in a comment).

vitest gets the same ink → inkCompat alias as tsup so the test suite
runs through the same renderer shim production ships, removing the
last divergence between the two paths.

bundle-smoke already asserts no `from "ink"` literal survives in
dist/cli/; the noExternal extension to ink-text-input means the
bundle has zero `from "ink-text-input"` references too, so a future
regression that breaks either alias fails CI.
2026-05-03 20:55:31 -07:00
YHH 5bd2678d51 feat(build): tsup alias 'ink' → inkCompat — chat now runs on cell-diff (#160) (#212)
Adds an esbuild alias on the CLI bundle that resolves every `import …
from "ink"` to src/renderer/ink-compat. Combined with noExternal:
["ink"] this forces the bundle to inline the shim instead of leaving
"ink" as a runtime external. The 3496-line App.tsx and every UI file
that imports Box / Text / Static / useApp / useInput / useStdout /
render now flow through the cell-diff renderer with zero source
changes.

Library + dashboard bundles are unchanged — only the CLI alias.

bundle-smoke gains an assertion that no `from "ink"` literal survives
in dist/cli/, so a future regression that breaks the alias fails the
build pipeline. Doctor command runs end-to-end through the aliased
path; help / version / non-interactive subcommands work.

Tests still resolve the real "ink" package (vitest doesn't go through
tsup), so unit tests stay on the existing path; the bundle test is the
production-correctness check.
2026-05-03 19:32:09 -07:00
YHH f01f12d0ae feat(renderer): inkCompat.render — Ink-shaped runtime over the cell-diff renderer (#160) (#211)
New render(element, opts) → { rerender, unmount, waitUntilExit, cleanup,
clear } that mirrors Ink's render API while mounting through the
cell-diff renderer's mount(). Wires resize, Ctrl+C handling
(default-on, opt-out via exitOnCtrlC: false), and useApp().exit()
integration so existing Ink-shaped apps drop in cleanly.

Foundation for the next step: a tsup alias 'ink' → inkCompat that lets
the existing reasonix chat (and its full 3496-line App.tsx) render
through cell-diff without any source changes — replacing the parallel
chat-v2 rebuild track.

7 new tests cover initial mount, waitUntilExit gating, rerender,
Ctrl+C exit, exitOnCtrlC: false, useApp().exit(), and useInput wiring.
2026-05-03 19:20:55 -07:00
YHH b4b196ea3a feat(renderer): chat-v2 — slash commands (/help /clear /cost /new /exit) (#160) (#210)
handleSubmit detects a leading / and routes to a pure handler map in
src/cli/ui/chat-v2-slash.ts instead of running a turn. Each handler
returns events to dispatch (synthetic user + canned reply, or a
session.reset, or a live.show error) plus an optional exit flag.

/help renders the command list as a regular streaming card so the
markdown view picks up the formatting; /cost reads from agentStore
state and shows current usage; /clear and /new both fire session.reset
which the existing reducer already handles. Unknown commands surface
as an err live card with the offending name.

10 new tests (7 unit + 3 integration through the chat-v2 shell).
2026-05-03 19:16:13 -07:00
YHH ada301ffce feat(renderer): chat-v2 — session persistence + resume (#160) (#209)
runChatV2 accepts session / forceNew / forceResume options; resolveSession
picks the actual name (timestamp suffix on --new, latest prefix on
--resume); CacheFirstLoop({session}) handles persistence so the running
transcript carries across launches.

Resumed sessions replay user-side history as user cards on mount via
AgentStoreProvider's initialCards seed. Assistant content isn't replayed
(no event log on disk yet); fresh turns stream into place.

CLI: `reasonix chat-v2 --session foo` resumes; `--new` forks a fresh
suffix; `--resume` walks to the latest matching prefix. Header shows
the resolved session name when one is active.
2026-05-03 18:54:00 -07:00
YHH 8f6a12767c feat(renderer): chat-v2 — wire web / memory / ask_choice tools (#160) (#208)
The real-loop runTurn now builds a ToolRegistry mirroring chatCommand:
web search/fetch (when searchEnabled()), memory tools (remember /
recall / forget), and ask_choice. The loop is constructed once per
chat session and reused across turns so cache state and the running
transcript carry over.

Tool events flow through the existing makeLoopBridge into tool.start /
tool.end card pairs, so the chat-v2 surface now shows real tool
activity inline (when DEEPSEEK_API_KEY is set). MCP / sessions /
slash commands are still deferred to 5d-23c-e.
2026-05-03 18:43:56 -07:00
YHH fb80b9cb38 feat(renderer): chat-v2 — real DeepSeek loop when API key is set (#160) (#207)
New makeLoopBridge() translates LoopEvents into the AgentStore event
shape: assistant_delta opens reasoning / streaming cards and emits
chunks; tool_start + tool produce paired cards with elapsedMs;
assistant_final and done close everything and stamp turn.end with
usage; error closes any open card with aborted=true and fires
turn.abort.

ChatV2Shell takes an injectable runTurn callback. runChatV2 builds the
real one (DeepSeekClient + ImmutablePrefix + CacheFirstLoop) when
DEEPSEEK_API_KEY is set; otherwise the canned demo path still runs so
the UI is explorable without an account.

11 new bridge unit tests; existing chat-v2 tests rewired to the new
runTurn injection point.
2026-05-03 18:36:55 -07:00
YHH ce01092f9c feat(renderer): chat-v2 — settled cards flow through Static (#160) (#206)
chat-v2 splits its card list into settled (user, finished reasoning,
finished tool, completed streaming) and in-flight at every render.
Settled cards go through inkCompat.Static so they emit to scrollback
once and never re-render; only the actively-streaming card stays in
the live region. The viewport's live region is now bounded by the size
of the in-flight card, not by the whole conversation.

MarkdownView drops its useMemo: Static's renderToBytes path uses a
one-shot tree walker without a React dispatcher, so any hook call
inside a Static-promoted subtree throws. Recomputing markdown lines
each render is allocation-light enough that the cache wasn't load-bearing.
2026-05-03 18:25:52 -07:00
YHH 0bd11e1e63 feat(renderer): bracketed paste + sentinels in SimplePromptInput (#160) (#205)
The keystroke parser now recognises ESC[200~...ESC[201~ wrappers and
emits the entire payload as a single keystroke, so multi-line pastes
hit processMultilineKey's pasteRequest branch. SimplePromptInput keeps
a per-instance paste registry; each burst gets one PUA sentinel in the
buffer + an inline `[paste #N · Ml · Nb]` placeholder. Submit expands
sentinels back to original content via expandPasteSentinels.

chat-v2 + input-demo enable bracketed-paste mode (ESC[?2004h) on entry
and disable on exit so the wrapper actually arrives.
2026-05-03 18:06:30 -07:00
YHH 42dba23bf7 feat(renderer): chat-v2 — submit history with ↑/↓ recall (#160) (#204)
usePromptHistory hook holds a FIFO of submitted entries. Up arrow on a
boundary saves the current draft, then walks back; down arrow walks
forward and restores the saved draft past the newest entry.
Duplicate-of-latest submissions are coalesced; entries past the cap
(default 100) drop from the front.

chat-v2 wires it into SimplePromptInput's onHistoryPrev / onHistoryNext.
2026-05-03 17:51:07 -07:00
YHH ea3bdbed4d feat(renderer): SimplePromptInput goes multi-line (#160) (#203)
Reuses processMultilineKey from src/cli/ui/multiline-keys.ts so chat-v2's
prompt input shares behavior with the live chat input: backslash line
continuation, ↑/↓ between logical lines, Ctrl+W word delete, Meta+B/F
word jump, Alt+Enter for newline, Enter to submit, history hooks at
buffer boundaries.

Renders each logical line as its own row; cursor lands on the right
(line, col) via useCursor's rowFromBottom. The keystroke parser also
learns Alt+Enter (\x1b\r → meta+return) so the multi-line reducer can
distinguish it from a bare Enter.
2026-05-03 17:41:56 -07:00
YHH 7cd9456440 feat(renderer): chat-v2 — live input replaces canned playback (#160) (#202)
chat-v2 now opens an empty conversation with SimplePromptInput at the
bottom. Each Enter dispatches user.submit and plays a stock canned reply
turn (reasoning + streaming + turn.end) — no real model is wired up yet,
but the seam from keystroke → reducer → cards → cell-diff renderer is
fully exercised end-to-end.

Esc on an empty prompt exits; Esc on a non-empty prompt clears (handled
by SimplePromptInput's onCancel semantics).
2026-05-03 17:27:00 -07:00
ctharveyandCharles H 9bf23b49ca refactor(mcp): move McpServerSummary out of UI slash types into src/mcp/summary.ts (#201)
- New src/mcp/summary.ts: canonical McpServerSummary interface + buildMcpServerSummary() builder
- slash/types.ts: import+re-export McpServerSummary from MCP layer, remove inline interface and unused inspect/registry imports
- chat.tsx: use buildMcpServerSummary() instead of inline object literal

Addresses issue #196 first boundary: relocation + builder, zero behavior change.

Co-authored-by: Charles H <[email protected]>
2026-05-03 17:23:31 -07:00
YHH e931db397e feat(renderer): SimplePromptInput — single-line input on cell-diff renderer (#160) (#200)
New SimplePromptInput component built on useCursor + useKeystroke. Handles
printable chars, backspace, delete, enter, ←→, home/end, ctrl+a/e/u/k,
escape (clear when non-empty, cancel when empty). Caret position published
through useCursor so the terminal cursor sits where the user expects.

`reasonix input-demo` exercises the component standalone — submitted
entries land in a Static history list above the prompt.
2026-05-03 17:17:16 -07:00
YHH 184a4a0366 feat(renderer): useCursor hook — React-driven terminal cursor positioning (#160) (#199)
Adds CursorContext + useCursor() in the renderer. Components register a
target { col, rowFromBottom?, visible? }; mount() reads the latest target
on every frame commit and feeds it into next.cursor.

Also adds a "cursorVisible" patch type so visibility transitions emit
ESC[?25h / ESC[?25l on the diff stream. Foundation for the chat-v2
PromptInput migration — single-line input lands next.
2026-05-03 17:04:26 -07:00
YHH 4d58eef324 feat(renderer): markdown pipeline — marked → MdLine[] → inkCompat (#160) (#198)
Splits markdown rendering into a pure parser (markdown-lines.ts) and a
cell-diff-renderer view (markdown-view.tsx). chat-v2's reasoning and
streaming card bodies now render proper headings, lists, code blocks,
blockquotes, and inline bold/italic/code instead of a single flat line.

`markdownToLines` is streaming-safe — partial input parses gracefully,
so the same call on every chunk yields a stable line tree.
2026-05-03 16:55:10 -07:00
YHH c2603a897e feat(renderer): chat-v2 — stripped-down App tree on cell-diff renderer (#160) (#197)
Mounts AgentStoreProvider through `mount()` instead of Ink's `render()`.
A canned event script drives the real reducer; CardRows read state via
`useAgentState`. No PromptInput yet — Esc / Ctrl+C exits.

Lays the seam for the chat App migration: events → reducer → useState
→ inkCompat tree → cell-diff renderer all proven end-to-end.
2026-05-03 16:42:21 -07:00
ctharveyandCharles H d9684bbff5 fix(tui): bound Markdown table rendering to card width with fallback key/value layout (#195)
- MarkdownWidthCtx + useWidth() propagate available column width into
  nested block renderers; width prop is body-width (no double subtraction)
- tableLayout() pure function decides columnar vs fallback layout
- FallbackTable wraps long values under their label; labelPad clamped to
  availableWidth-1 so label+value never exceeds card width
- ColumnarTable for tables that fit; HorizontalRule width-bounded
- plainText() exported for test access
- 18 tests: smoke (11), tableLayout fallback decision (2),
  FallbackTable width invariants (5 including narrow-width sweep)

Co-authored-by: Charles H <[email protected]>
2026-05-03 16:25:53 -07:00
YHH 02ce601ef2 feat(renderer): card-demo — full chat lifecycle reference (#160) (#191)
* feat(renderer): card-demo — full chat lifecycle reference

Demonstrates the design pattern for streaming-TUI cards: every card
type (user, reasoning, tool, plan, response, diff, error) has an
active form that lives in the live region, animating, and a settled
form (typically 1 line) that commits to terminal scrollback once
the underlying work completes.

Auto-replays a fake chat session: user message → reasoning →
shell tool with rolling output → plan with stepwise spinner →
diff → streaming response → error notice. Each card animates
in the live region, then collapses to a single-line summary in
the Static history above. The live region is bounded — at most
ONE active card plus status + prompt — so it never overflows
the viewport, native mouse scroll/select keep working.

This is the pattern Reasonix's actual chat App.tsx should adopt
when migrating to the cell-diff renderer: track in-flight work
in live state, commit completed work to Static. Mirrors how
Claude Code structures its CLI streaming.

Refs #160.

* feat(card-demo): full Reasonix card vocabulary + variants

After surveying src/cli/ui's actual card stream, expanded card-demo
from 7 stages to 13 covering every real card type and lifecycle
variant we ship today:

  user  → reasoning (R1) → read_file → bash → bash retry/error
       → plan (4 steps with embedded tool ops)
       → write_file rejected → diff → subagent (nested children)
       → streaming response → usage → warn → error

Card behavior matches the live App's CardStream conventions:

- reasoning: active spinner + last 4 token-streamed lines; settled
  keeps last 2 lines + "⋯ N ¶ · M tok · /reasoning last"
- tool: tone-colored glyph (▤ read, ▥ write, ▶ bash, ⊙ search,
  ⌬ fetch, ⊕ mcp); active rolling 5-line tail + elapsed; settled
  shows "⋮ N earlier lines" + tail (2-5 lines per tool tone);
  rejected = badge replaces body; retry/error = red + ↻ retry X/Y
- plan: ◯/▶/✓/✗/!/s glyphs + "← in progress" marker; settled
  keeps full step list (per #160 Plan never collapses to 1 line)
- response: active "writing…" spinner + last 4 lines; settled
  keeps full markdown body (or "(truncated by esc)" if aborted)
- diff: file header + first-N hunk preview; +/- coloring
- subagent: ⌬ + nested children with ▎ indent; child cards are
  single-line summaries with their own tone/glyph
- usage / warn / error: single-row badges

Wrap helper added so streaming text wraps at ~70 cols and the tail
is computed against actual visual rows.

Refs #160.

* fix(renderer): wide-char width compensation for Ambiguous glyphs

User repro: card-demo in Windows Terminal showed residue chars next to
glyphs like ↻ ▶ ⊞ ◆. East Asian Ambiguous width disagreement —
stringWidth reports 1, the terminal renders 2 (or vice versa on
Western terminals), so the diff cursor model gets out of sync with
where the terminal actually advanced. Subsequent cells land in the
wrong column → leftover chars from the previous frame appear next to
the new content.

Two-part fix:

1. Layout (string-width call site): treat ambiguous chars as wide
   (width 2) by default, so the layout reserves enough cells either
   way. Box-drawing block U+2500..U+257F is pinned to width 1
   explicitly because terminals never render those wide and our
   borders depend on it.

2. writeCell, when emitting a Wide cell, runs a leading-space + CHA
   compensation:
     CHA col+1     ← jump to the right-neighbor cell
     stdout ' '    ← pre-write a blank there (covered by wide
                     glyph if the terminal renders 2-wide; visible
                     as a clean space if the terminal renders 1-wide)
     CHA col       ← jump back to the original column
     stdout char   ← write the actual glyph
     cursor.x += 2 ← model advances 2 cells regardless
     CHA col+2     ← force the terminal cursor to col+2 so the next
                     cell write lands in the right spot

   ~4 extra escape sequences + 1 leading space per Wide cell, only
   fires when cell.width === Wide. Empty / narrow cells unaffected.

This is what was making \`↻ retry 1/3\` and \`0.4s\` run together
with stray chars between them, and what made the Plan card render
\`││\` on the right edge.

Refs #160.

* feat(card-demo): real-world plan execution + concurrent active cards

Restructure to match how a real session actually drives cards:

- active state is now an array. Multiple cards can be live at once
  (plan stays live while a tool runs below it; subagent stays live
  while children animate inline).

- Plan no longer appears all-done in one shot. Steps progress one
  at a time: each step starts running, a tool card appears below the
  plan card, the tool animates, settles to history, plan step flips
  to done, next step starts. Plan card itself never leaves live area
  until every step is in a terminal state.

- The fix-failing-test scene now exercises:
  * search step (grep) — short tool with rolling output
  * write_file rejected mid-plan → step gets blocked → plan retries
    via patch tool
  * bash test with retry chain (1/3 fails, 2/3 succeeds)
  * bash deploy (npm publish)
  * full plan settles, diff card pushed, markdown response
    streams (header + code block + bullet list)

- Subagent scene: ⌬ card stays live while 4 child rows animate
  in sequence (reasoning, grep, read, diff). Each child flips
  from running spinner to ✓ in place. CJK streaming response
  follows.

- Edge cases scene: aborted reasoning (settles with red glyph +
  "(aborted)" badge), MCP tool, web_fetch, compaction warn, rate
  limit error, final usage card.

Tools now have per-tone tail length (read/search/fetch = 2 lines,
bash/mcp = 5 lines) matching the real CardStream conventions.
ToolActive carries a `retry` field rendered as `R 1/3` next to the
elapsed timer.

Refs #160.
2026-05-03 16:23:14 -07:00
YHH 4ee324b02e feat(renderer): virtual viewport — full layout stays live, PgUp/PgDn scrolls (#160) (#190)
* feat(renderer): virtual viewport — full layout stays live, PgUp/PgDn scrolls

Adds a scroll: "virtual" mode to mount(). Rather than promoting overflow
rows to scrollback (where they freeze), the entire layout lives in
memory and the visible viewport-1 window slides over it. All animations
keep running for the full layout, even when the user has scrolled away
from the bottom.

mount opts.scroll defaults to "scrollback" — the existing behavior is
unchanged for chat / preview / banner-demo et al. Apps that want
dashboard-style live regions opt in.

Implementation:
  - renderVirtual returns the full layout with a windowAt(offset, h)
    slicer.
  - mount tracks scrollOffset + stickyBottom + lastTotalRows.
  - Each commit picks a window: stickyBottom or shrink → snap to
    bottom; otherwise hold the user's offset (clamped).
  - PgUp / PgDown scroll by viewport-1 rows. Home / End jump to
    extremes. After any scroll, stickyBottom re-evaluates against
    the new offset so resuming at the bottom auto-follows growth.

stress-demo opts into "virtual" — its 4 concurrent regions can now
exceed the viewport without freezing anything; user scrolls the
viewport over a still-live layout.

Tests: tests/renderer/virtual-viewport.test.tsx (6) — initial bottom
pin, PgUp older rows visible, Home/End jumps, growth-while-sticky
follows latest, growth-after-user-scroll holds position. Uses an
inline virtual-terminal byte parser to read final screen state past
cell-diff fragmentation.

Refs #160.

* feat(renderer): mouse wheel scrolls the virtual viewport

Mouse wheel was being consumed by the terminal's own scrollback and
landed on empty pre-mount terminal output instead of scrolling our
virtual layout.

Fix: enable SGR mouse mode (\x1b[?1000h\x1b[?1006h) on mount when
scroll: "virtual", disable on destroy. Keystroke parser recognizes
button 64 → wheelUp, button 65 → wheelDown. mount's scroll handler
maps wheel events to scrollBy(±3 rows).

Mouse capture is only enabled in virtual mode; scrollback mode
leaves text selection / native scrollback alone for chat-style
apps where the user expects normal terminal behavior.

Tests: keystroke parser cases for SGR `<64;X;YM`, `<65;X;Ym`. Two
virtual-viewport tests cover wheel scrolling and the enable/disable
escape sequences at mount/destroy.

Refs #160.

* fix(renderer): disable mouse mode on any exit path

The bug: enabling SGR mouse mode (\x1b[?1000h\x1b[?1006h) at mount
without disabling it on every exit path leaves the terminal stuck —
mouse clicks and selection get swallowed by escape sequences for
the now-dead process. User has to close the terminal window or
manually emit the disable bytes.

Fix: register `process.on("exit", ...)` to write DISABLE_MOUSE on
ANY process exit (normal, crash, parent-killed). Also intercept
SIGINT/SIGTERM with `process.exit(130)` so Ctrl+C funnels through
the same exit handler. destroy() unregisters these handlers when
mount tears down cleanly.

Idempotent disable: writing DISABLE_MOUSE twice (once from
destroy, once from exit handler) is safe — the disable sequence
just sets a flag in the terminal.

Refs #160.

* feat(renderer): virtual mode enters alt-screen — like the live chat

Aligned mount's virtual mode with src/cli/ui/alt-screen.ts: enter the
terminal's alternate buffer (1049h) so the renderer owns its own
viewport without polluting the user's main shell history. Use button-
event mouse mode (1002, not 1000) for press/drag/release tracking;
SGR coords (1006). Shift+drag still bypasses for native selection.

The escape sequence on enter is now:
  \x1b[?1049h\x1b[2J\x1b[H\x1b[?1002h\x1b[?1006h

On any exit (destroy, process.exit, SIGINT/SIGTERM):
  \x1b[?1006l\x1b[?1002l\x1b[?1000l\x1b[?1049l

The alt-screen toggle (1049l) automatically restores the user's
pre-mount terminal contents — npm wrapper output, prior shell prompts,
all visible again. No more polluted scrollback after stress-demo
exits, no more stuck mouse mode if the process crashes.

This is what the user meant by "fullscreen": the chat command and
stress-demo now both behave like vim/htop/less — own the viewport,
restore on exit. The scrollback mode (default for chat preview etc.)
keeps the inline behavior where output streams to the user's main
terminal buffer.

Refs #160.

* fix(stress-demo): inline mode + rolling Shell — like Claude Code

After studying claude-code-sourcemap: their CLI runs **inline** for
streaming output (no alt-screen, no mouse capture). Native mouse
selection and terminal scrollback work the user's whole life.
AlternateScreen wrapping is opt-in for explicit modal UIs (plan
mode, etc.) — not the default.

Reasonix stress-demo was wrong to opt into virtual mode. Reverting:

  - scroll: "virtual" removed → uses default "scrollback"
  - SHELL_WINDOW=5 rolling window restored so the layout fits a
    typical viewport (~22 rows)
  - alt-screen takeover gone → user keeps native mouse selection
    and terminal scrollback

Now matches Claude Code's pattern: streaming dashboards stay inline,
trade-off is older content goes to terminal scrollback frozen (which
is fine, that's how every TUI streaming app works).

Virtual mode stays in the renderer for genuine modal/fullscreen UIs
that explicitly opt in. Not the default.

Refs #160.
2026-05-03 08:45:27 -07:00
YHH fd64c2f8e5 feat(renderer): stress-demo — 4 concurrent live regions (#160) (#189)
* feat(renderer): stress-demo — 4 concurrent live regions

The simple-streaming preview wasn't a real test of the renderer's
value. Plain text streaming on its own is something Ink doesn't
struggle with too much. The actual jitter that #155 reports comes
from STACKED dynamic regions all updating concurrently — Plan card
on top with a spinner, shell command appending output rows below,
streaming response card on top of that, status header ticking, etc.

This subcommand mounts that exact scene:

  - status row (ticks every 100ms — elapsed time + cost)
  - Plan card (4 steps, step 2 has a spinner ticking every 80ms)
  - Shell card (npm test, output rows append every 250ms)
  - Response card (text reveals 4 chars every 33ms, wraps mid-phrase)
  - hint bar at bottom

All five regions update at independent rates. On Ink, every state
change in any of them re-emits the entire 20-row tree. On the new
renderer, each tick produces patches only for the cells that
actually changed — typically 1-3 cells per tick.

Three tests cover initial paint, ticked state after 1s
(verifying multiple regions are advancing), and ESC-to-exit.

Refs #160. Run `reasonix stress-demo` to see whether the original
jitter problem is actually fixed in the live terminal.

* fix(renderer): re-reserve vertical space when layout grows mid-session

stress-demo exposed a hard correctness bug: live repro showed
spinner glyphs scattered down the left margin overwriting npm dev
output, multiple stacked top borders, scrambled text everywhere.

Root cause: reservation only ran on the first paint. stress-demo's
layout grows over time (Shell card appends rows every 250ms,
Response card text wraps onto new rows as it streams). When the
new layout height exceeded the originally-reserved rows, each
overflowing row triggered a terminal scroll. The diff cursor model
didn't track scrolls, so subsequent relative cursor moves landed
in completely wrong positions — overwriting whatever was at those
real terminal coordinates, including pre-mount scrollback content.

Fix: track reservedRows. On every commit, if the new layout's
height exceeds reservedRows, emit `\n * delta + CSI <delta> A` to
reserve more rows (scrolling once if needed) and bring cursor
back to its model position. Subsequent diffs then use relative
moves within the now-larger reserved region — never past it,
never into pre-mount territory.

Also corrects the off-by-one math from 5d-13: each commit can
extend the reserved area incrementally as content grows.

Refs #160.

* fix(renderer): clip layout to viewport-1 + ink-compat Box default = row

Two fixes from running stress-demo to actual chaos in PowerShell.

1. Layout taller than viewport caused overflow rows to write past
   the reserved area, triggering scrolls the diff cursor model
   didn't track. Subsequent relative cursor moves landed in
   pre-mount terminal territory — Plan spinner cells overwrote
   npm dev output, top borders got clobbered by glyphs from
   later commits.

   Fix: renderToScreen takes an optional maxHeight. mount passes
   viewportHeight - 1. When the layout produces more rows than
   that, the SKIP rows come off the TOP — so the most recent
   streaming content stays visible while the older static chrome
   scrolls off the top of the live region.

2. inkCompat.Box defaulted flexDirection to undefined (which our
   native Box treats as column). Ink defaults to row. Real
   components like the live WelcomeBanner used <Box> for hint
   lines expecting row flow; the shim was stacking each Text
   on its own line, blowing the layout up to 19 rows.

   Fix: ink-compat Box defaults flexDirection to "row" when
   not explicitly set.

Refs #160.

* feat(renderer): promote overflow rows to scrollback when layout > viewport

Last fix clipped layout to viewport-1 to stop the diff from corrupting
pre-mount terminal content, but it also meant scrolled-off rows were
never preserved — user couldn't scroll up to see the older state.

Now when layout exceeds viewport-1, the top rows that get clipped are
EMITTED to scrollback explicitly:

  1. Track promotedRows — how many top rows have been committed.
  2. Each commit, if the new clip count exceeds promotedRows, emit
     bytes for those new rows via serializePromoted: clear the live
     area, write the promoted rows (cursor advances, they go into
     scrollback), reset frame, then repaint the live region below.
  3. promotedRows monotonically increases — once a row is promoted,
     it stays in scrollback at the state it had when promoted (its
     last-known content before scrolling off).

renderViewport replaces the renderToScreen call inside mount: it
returns the visible Screen + a serializer for the promoted slice
of the same layout pass (no double-layouting).

For status / spinner rows whose content keeps changing: when they
overflow, the snapshot at the moment of overflow is what scrollback
keeps. Subsequent commits stop touching those rows. UX-wise this is
similar to how a real terminal scroll preserves output history.

Refs #160.

* fix(stress-demo): rolling Shell window — keep all 4 regions in viewport

Reframing: terminal scrollback is write-once. Once a row scrolls off
the live region, terminals can't update it anymore — animations on
that row are necessarily frozen. The promote-to-scrollback path
preserves the row so users can scroll back, but it'll never re-animate.

The fix isn't more renderer plumbing — it's keeping the demo's layout
inside the viewport so nothing has to scroll off in the first place.

Shell card now shows the last 5 output rows; older rows roll out with
a "(+N earlier)" indicator next to the title. The card stays a
constant ~7 rows tall regardless of how many test lines have arrived.
Status + Plan + Shell + Response + hint now total ~22 rows — fits in
a typical 24-row terminal with all four regions live and animating.

Real chat use cases will use Static for committed messages (which
DOES belong in scrollback) and live region for the in-flight reply
(which fits the viewport). The promote path stays for those cases.

* fix(renderer): full reset on resize — no double-paint

Live repro: shrink the terminal while stress-demo is running. The Plan
card appears stacked twice — one frozen copy above, one live below.

Cause: resize re-rendered through the normal onCommit path, which
saw layout > new viewport-1 and ran promote-to-scrollback. The old
live frame's height (from the bigger viewport) was used to compute
how far up to clear with CSI nA — but CSI A clamps at viewport top,
so the clear missed pre-resize content. Then promoted bytes wrote
visibly into the cleared area, and the diff repainted the live
region below. Net effect: duplicate cards.

Fix: resize is a special event, not a normal commit. Reset frame,
reservedRows, promotedRows; emit `\x1b[2J\x1b[H` to wipe the
visible viewport (scrollback above is preserved by terminals);
then re-render through the normal first-paint path. Pre-resize
content stays in scrollback; current frame paints fresh in the
new viewport size.

Refs #160.
2026-05-03 07:47:48 -07:00
YHH a9df67102b feat(renderer): preview — incremental text reveal on the streaming row (#188)
Builds on the spinner state machine: instead of just spinning then
echoing, the response now reveals 3 chars per 33ms, growing in place
in the live area. Spinner glyph keeps ticking (80ms) while text grows.
When fully revealed, a 200ms pause, then the user line + complete
echo land in Static and the prompt comes back.

This is the workload that breaks Ink (#155): a streaming card whose
content grows mid-frame. Each reveal here is ~3 cell writes; the diff
layer doesn't repaint anything else (spinner cell, user line, hint
bar all stay frozen across the reveal). Real LLM streaming, when we
wire it in, slots into the same state — just replace the setInterval
that advances `revealed` with the token-arrival callback.

Response wraps at 60-col viewport — exercises the reveal-across-wrap
case where adding chars at end of one row spills onto the next.

Refs #160.
2026-05-03 07:07:43 -07:00
YHH a3b346848f feat(renderer): preview — streaming spinner state machine (#187)
Enter on a non-slash submission no longer echoes immediately. Shell
enters a "streaming" state: the user line and a Braille spinner row
('thinking…') render in the live area below the Static history,
ticking 80ms/frame. After 1500ms the streaming row commits both the
user line and the echo to Static and the prompt becomes available
again.

This is the core value-prop test for the cell-diff renderer: the
spinner ticks 18-ish times during the stream, each tick is a single
cell change, and the diff emits ~1 patch per frame instead of
re-painting the whole live region the way Ink does. No row-count
churn during the stream → no jitter.

Input is paused while inflight (keystrokes are dropped). The slash
fast-path (/help, /clear, /exit, /unknown) still works because slash
commands return synchronously without entering streaming.

Two new e2e tests in preview.test.tsx assert the spinner appears,
the echo lands after the timeout, and keystrokes during streaming
are dropped. The /clear test was rewritten to use /help submissions
(slash-only) to avoid streaming interference.

Refs #160.
2026-05-03 06:56:35 -07:00
YHH 966ddeac3b fix(renderer): reserve vertical space + slash commands in preview (#160) (#186)
* fix(renderer): anchor cursor to col 0 before the first paint

Bug surfaced live: typing into the preview shell wrote characters at
the wrong screen position because the very first frame's diff started
emitting cells from wherever the terminal cursor happened to sit at
mount time (often mid-line, after the npm dev wrapper output). The
moveTo no-op for (0,0)→(0,0) meant no \r got emitted, so the first
row landed in the column the shell had left the cursor at.

Fix: emit \r CSI J before the first reconciler commit. \r anchors the
cursor at column 0 of the current row; CSI J clears below so any
straggler text isn't visible underneath the live area. Subsequent
diffs already use \r on every row transition, so only row 0 of the
initial paint was vulnerable.

Adds reasonix preview slash commands (/help / /clear / /exit) on top
of 5d-12 since the user was testing them and surfaced the cursor bug.
Also fixes Static so that shrinking items[] resets lastIndex (without
this, a /clear followed by new items wouldn't emit the new ones).

Refs #160.

* fix(renderer): treat OOB cells as EMPTY_CELL in diffEach

Live repro from running reasonix preview:

  > 123 ▏         1 dev    <-- our prompt landed on the npm wrapper line
  > tsx src/cli/index.ts preview
  Enter submit · / for commands · Esc exit

Initial paint mounted on a 24-tall emptyFrame against a 6-row layout.
diffEach iterates the union (24 rows). For y=6..23 prev had EMPTY_CELL
(allocated by emptyFrame), next.cellAt returned undefined (OOB on the
shorter screen). The early-skip required BOTH non-undefined for
cellsEqual, so the OOB case fell through and emitted clear-patches —
~18 rows × viewportWidth cells of cursor moves + spaces. On a 24-row
terminal that ran the cursor past the bottom, scrolling the npm
output up; the header scrolled out of view and the prompt landed
where "> [email protected].1 dev" used to sit.

Fix: coalesce undefined to EMPTY_CELL on both sides before the equality
check. OOB-vs-EMPTY is now a no-op; populated-vs-OOB still emits a
clear (which is correct — the row really shrank).

Two regression tests in tests/renderer/diff.test.ts pin both legs.

* fix(renderer): reserve vertical rows + revert OOB coalesce

User-visible repro: reasonix renderer-demo (and preview) only showed
the bottom row of the layout in PowerShell. Header / prompt rows
appeared to be missing.

Two interacting bugs:

1. mount painted rows top-down using CSI nB cursor moves. When the
   shell left the cursor near the bottom of the viewport, every row
   transition past the visible region scrolled the terminal up,
   pushing earlier-painted rows off-screen. Only the LAST row written
   ended up still visible.

   Fix: before the first paint, emit `\r \n*(N-1) CSI <N-1>A` to
   pre-reserve N rows below the cursor (scrolling up once if needed)
   and return to the start. Subsequent moves stay within the reserved
   block — no more scrolls.

2. The earlier OOB-coalesce attempt in diffEach treated
   prev=undefined / next=EMPTY_CELL as equal, which silently dropped
   patches for spaces inside text content (since space cells share
   charId/style with EMPTY_CELL). "(none yet)" rendered with cursor
   gaps where its space should have been.

   Reverted to the original diff predicate. Initial paint now emits
   patches for every cell in the new screen (verbose, but correct);
   subsequent diffs still coalesce identical cells.

Reservation regression test in mount.test.tsx asserts the
\r\n*8\x1b[8A prelude for a 9-row layout.

Refs #160.

* fix(renderer): reserve N+1 rows so the final cursor park doesn't scroll

Off-by-one in the reservation prelude caused values to drift one row
up after the first paint when the live region used the bottom of the
viewport. Trace: 9-row content + final cursor parks at frame y=9
(one past the last content row). Old reservation only covered 9 rows
(R..R+8); the cursor's final move to R+9 hit the viewport bottom and
scrolled, shifting all painted content up by 1. Subsequent diffs
targeted the now-shifted rows correctly in their own model, but the
already-rendered content had drifted, so visually new values landed
one row above the row where the label sat.

Bump reserve to screen.height (was screen.height - 1) so the parking
row is also pre-allocated. seven-key-trace test confirms the byte
stream produces the right cells; mount.test.tsx regression updated
to assert the new prelude shape.

Refs #160.
2026-05-03 06:48:08 -07:00
YHH 9e206a14ad feat(renderer): reasonix preview — minimal chat shell on the cell-diff renderer (#185)
First user-facing surface that runs entirely on the new pipeline. Echo
mode for now: header, Static-emitted history, single-line input,
Enter to submit, Esc to exit. Composes everything 5d-2..5d-11 added
(useKeystroke, useApp.exit, Static scrollback, gap, hex colors,
marginTop, useState-driven draft).

State held in refs so a single push("abc\r") that fires four
keystrokes synchronously commits the right text — closure-captured
state would otherwise read pre-update values.

Subsequent PRs grow this shell toward feature parity with the live
chat: model badge, streaming card, tool result rows, slash-commands.
Once it catches up, the existing Ink-based App becomes the legacy
backend.

Refs #160.
2026-05-03 05:46:21 -07:00
YHH c557b9726b test(renderer): the live WelcomeBanner renders end-to-end via the shim (#184)
Mounts the actual src/cli/ui/WelcomeBanner.tsx — the component the
running app uses today — through our cell-diff renderer with **zero
source changes**. vi.mock substitutes "ink" with the ink-compat shim
at test time, so the production import paths stay intact.

Asserts the frame glyphs, REASONIX brand line, slash hints, in-code
mode tagline swap, dashboardUrl link line, and a narrow viewport
(cols=40). This is the first time a real production component renders
under the new pipeline without being copied or rewritten.

Refs #160. The path forward for full migration: add a runtime
"ink" → ink-compat alias when the new renderer is selected, and
existing components keep working.
2026-05-03 05:29:22 -07:00
YHH 5e040ad2e5 feat(renderer): wire useApp().exit() to a mount-level onExit hook (#183)
Previously useApp() returned a default {exit: noop}. Components inside
a mount tree could call exit() but nothing happened — the host had to
read the user's intent some other way (a Promise resolved from a
keystroke handler, etc.).

mount() now provides AppContext.Provider with a real exit fn. The fn
defers via queueMicrotask so it never fires synchronously inside a
render or effect — that would unmount the tree mid-commit. After
destroy, exit() becomes a no-op, so a stale ref can't fire onExit
later.

mount opt: onExit?: (error?: Error) => void. The host owns the actual
teardown; onExit is just the signal.

Refs #160. Smaller surface than full lifecycle plumbing — covers the
Ink useApp() pattern that DiffApp/ReplayApp/Setup/Wizard rely on.
2026-05-03 05:22:24 -07:00
YHH 0e893e1c0a feat(renderer): select-demo — arrow-nav SingleSelect via ink-compat (#182)
Reasonix select-demo subcommand mounts a faithful single-select list
through the cell-diff renderer: arrow nav, Enter to submit, Esc to
cancel, disabled rows skip + dim. Real-world pattern that combines
useKeystroke, useState-driven highlight, hex/named-color theming, and
nested column Boxes.

Five end-to-end tests cover initial paint, ArrowDown skipping a
disabled row, Enter on the initial active row, Esc cancel, and
ArrowUp wrap-around.

Refs #160. Together with banner-demo, this proves both static-shaped
content (banner) and interactive-shaped content (select) ride the new
pipeline cleanly.
2026-05-03 05:15:21 -07:00
Matt Van HornandMatt Van Horn d6fde1786d test(gitignore): add unit tests for src/gitignore.ts (#139) (#180)
Adds tests/gitignore.test.ts covering ignoredByLayers (empty layers,
literal dir match, intra-file negation, isDir toggle, out-of-scope
layer skip, fall-through, no-match) and loadGitignoreAt /
loadGitignoreAtSync (missing-file null path, working Ignore from a
real .gitignore in a tmpdir).

11 tests; vitest, lint, typecheck, and full suite (2064 tests) pass
locally. No source changes; no new dependencies.

Closes #139

Co-authored-by: Matt Van Horn <[email protected]>
2026-05-03 05:07:23 -07:00
YHH ac3e4f1d56 test(renderer): wide-char + emoji end-to-end through mount (#181)
Locks in the diff pipeline's behavior with CJK and emoji content:
both glyphs of a 4-cell CJK string land, replacing wide content with
narrow leaves no ghost half-cells, narrow→wide growth writes the new
wide char, multiple emoji in a row each appear, a styled CJK char
wraps in the right SGR open/close pair, and wrapping at the viewport
edge keeps the wide glyph intact on the next row.

Refs #160. The renderer's main correctness risk in real Reasonix usage
is wide chars across diffs (Chinese UI strings change between frames
constantly). These tests catch the SpacerTail-not-cleared regression
class up front.
2026-05-03 05:02:21 -07:00
YHH e250afc007 feat(renderer): gap on Box — column rows + row columns (#179)
Adds gap to BoxNode with the obvious semantics: in column flow it
inserts N empty rows between siblings; in row flow it reserves N cells
between siblings before flexGrow distribution.

Plumbed through native BoxProps + ink-compat Box. intrinsicWidth now
counts gap*N-1 for row-flow boxes so flex distribution is correct.
gap composes with justifyContent — extra slack from space-between is
added on top of the configured gap.

Refs #160. Used by markdown.tsx, etc.
2026-05-03 04:54:39 -07:00
YHH f28c67fddd feat(renderer): Static — emit settled rows to scrollback (#178)
Implements the "rendered once and never updated" semantic for
inkCompat.Static. Previously the shim just wrapped items in a column
Box, which left them subject to re-diff every frame.

Pipeline: when Static's items array grows, the new items are rendered
offline via renderToBytes and handed to the mount Handle's emitStatic.
emitStatic clears the previous live area, writes the static bytes
(advancing scrollback), and resets the prev frame so the next paint
starts fresh below.

renderToBytes is exposed publicly so apps can stage scrollback content
without React (e.g., a one-shot welcome banner emitted before the live
loop starts).

Refs #160.
2026-05-03 04:48:19 -07:00
YHH 3f15d000e8 feat(renderer): banner-demo — first real-app component via ink-compat (#177)
Reasonix banner-demo subcommand mounts a structurally faithful version
of the welcome banner — nested Box + marginY + marginTop +
justifyContent="center" + hex colors, useStdout for centering, useKeystroke
for ESC — entirely through the ink-compat shim onto the cell-diff
renderer.

Three end-to-end tests assert frame glyphs, brand line, hint row, ESC
exit, and resize re-paint. The Ink-flavored banner used by the live App
is left untouched on this branch; this is the first concrete proof that
a non-trivial component renders end-to-end through the new pipeline.

Refs #160.
2026-05-03 04:39:21 -07:00
YHH 19c33d1a9a feat(renderer): fixed width / height on Box (#176)
Adds width and height props to BoxNode + BoxProps + ink-compat. Width
overrides intrinsic size for row-flow allocation and clamps to the
parent's available width. Height pads with empty rows when content is
shorter and truncates when content is taller.

Unblocks the height={1} spacer-row pattern (4 components in src/cli/ui
use it) and width-constrained columns (sidebar, picker lists) that
need to land before the main App can migrate off Ink.

Refs #160.
2026-05-03 04:33:18 -07:00
YHH 25240984cb feat(renderer): justifyContent in row flow — flex-end / center / space-between (#175)
Wires Yoga-style row distribution into the layout engine. Default
(flex-start) preserves current behavior. flex-end pushes children to
the right edge, center splits slack evenly, space-between distributes
the gap between siblings. flexGrow children consume slack first, so
justifyContent silently degrades to flex-start when grow is present —
which matches CSS flexbox.

Plumbed through BoxNode → BoxProps → ink-compat Box so existing Ink
code reading `<Box justifyContent="space-between">` migrates with no
source changes. Three of four uses in the codebase already match this
shape.

Refs #160.
2026-05-03 04:24:19 -07:00
YHH e8594a973f feat(renderer): ink-compat shim — Box / Text / Spacer / Static / hooks (#174)
Lets components written against Ink's API render under the cell-diff
renderer with no source changes for the props we cover.

Box: padding{X,Y,Top,Bottom,Left,Right} pass through; margin{X,Y,Top,
Bottom,Left,Right,} translate to a wrapper Box's padding so empty rows
sit above/around the inner box (works in both column and row flow,
since the wrapper carries flexGrow on row participation). borderStyle
takes the string presets, borderColor takes color names + hex.

Text: color, backgroundColor, bold, dimColor, italic, underline,
strikethrough, inverse all stack into the StylePool entry.

Spacer is just <Box flexGrow={1}/>. Static is a flexDirection=column
wrapper — it doesn't yet implement Ink's "settled content stays in
place" semantic; that needs row-level commit isolation, deferred.

Hooks: useStdout reads {columns,rows} from a ViewportContext that
mount() now provides and re-publishes on resize(). useApp returns
{exit} from AppContext (host wires its own exit). useInput translates
each Keystroke to Ink's (input, key) callback shape, with isActive
gating.

Out of scope: width/height (need fixed-size layout), justifyContent,
alignItems, gap, useFocus, Transform, measureElement.

Refs #160.
2026-05-03 04:16:19 -07:00
YHH 35637b15aa feat(renderer): reasonix renderer-demo subcommand — end-to-end on real TTY (#173)
Lets us exercise the cell-diff renderer against real stdin/stdout
without touching the main Ink-based App. Counter + last-key display,
ESC to exit. Component-level tests cover initial paint, key handling,
and ESC-to-exit through a fake stdin and the test writer.

Refs #160.
2026-05-03 04:01:43 -07:00
YHH d0ab2cbd42 feat(renderer): stdin keystroke parser + useKeystroke hook (#172)
Adds the input side of the renderer pipeline so React components can
react to user keystrokes through the same provider/hook idiom they
already use for state.

Architecture:

- parseKeystrokes(chunk) is a pure ANSI escape-sequence parser. Plain
  ASCII passes through; \x01..\x1a become ctrl+letter; \r / \n
  return; \x7f / \x08 backspace; \t tab; \x1b alone escape; ESC +
  printable is meta+char; CSI A/B/C/D arrows; CSI 1;modifier <X>
  surfaces shift/meta/ctrl modifiers; CSI 3~ delete, 5~ pageUp,
  6~ pageDown, 1~/H home, 4~/F end.
- KeystrokeReader wraps a stdin-like stream (anything with on/off
  'data') and emits parsed Keystroke events to subscribers. Sets raw
  mode on construction, drops it on destroy.
- useKeystroke(handler) hook subscribes the calling component to the
  reader provided via KeystrokeContext.
- mount({ stdin }) constructs the reader, wraps the React tree in
  KeystrokeContext.Provider, and tears the reader down on destroy.

Tracking issue: #160.
2026-05-03 03:43:35 -07:00
YHH ed1ad08615 feat(renderer): react-reconciler integration — useState drives paints (#171)
useState / useEffect / re-render-on-state now drive paints without
the caller manually calling update(). React's reconciler maintains
the host node tree; on every commit we walk it to a LayoutNode tree,
hand it to the diff layer, and write only the changed bytes.

Surface:

  const handle = mount(<App />, { viewportWidth, viewportHeight, pools, write });
  // setState in App triggers a paint automatically.
  handle.update(<NewApp />);   // explicit replace also works
  handle.resize(cols, rows);
  handle.destroy();

Box and Text are now thin wrappers that emit string-typed JSX
intrinsics ('rsx-box' / 'rsx-text'). The reconciler matches the
strings in createInstance and instantiates host nodes; the existing
no-reconciler walker in react/render.ts matches the same strings.
Both code paths converge.

Adds react-reconciler + @types/react-reconciler as direct deps.

Tracking issue: #160.
2026-05-03 03:34:29 -07:00
YHH 40fe1dc546 feat(renderer): Renderer runtime — frame state + diff + write to a sink (#170)
Closes the offline pipeline of #160. Caller pushes a React tree at
the Renderer; it lays out, diffs against the previous frame, writes
only the changed bytes to the configured sink, and stashes the new
frame for the next call.

  const r = new Renderer({ viewportWidth, viewportHeight, pools, write });
  r.update(<App />);              // first paint — full screen
  r.update(<App />);              // identical tree — zero bytes
  r.update(<AppMutated />);       // only the diff
  r.resize(cols, rows);           // next update full-resets via clearTerminal
  r.destroy();                    // SGR reset + OSC 8 close

Sink is injected (write: (bytes: string) => void), so tests run
purely in memory via makeTestWriter() — no real stdout, no real
terminal. The same shape will plug into process.stdout.write in
the runtime integration step.

Doesn't yet:
- Drive re-renders from React state (the caller still has to call
  update; Phase 5b adds reconciler-driven re-renders).
- Read keystrokes (Phase 5c).
- Replace Ink in Reasonix's CLI (Phase 5d, behind a feature flag).

Tracking issue: #160.
2026-05-03 03:02:29 -07:00
YHH 266a4d509e feat(renderer): serialize Patch[] to ANSI byte stream (#169)
Closes the second-to-last layer of #160. Takes the Patch[] that
diffFrames returns and produces the actual bytes a terminal
understands.

  cursorMove → CSI A/B/C/D (vertical first, then horizontal)
  cursorTo   → CSI <col+1> G (CHA is 1-based)
  hyperlink  → OSC 8;;<uri> ST  (empty uri = close)
  clear      → \r + CSI <count> A + CSI J  (move up N rows, erase to end)
  clearTerminal → CSI 2J + CSI H

stdout / styleStr / carriageReturn pass through verbatim — they are
already terminal bytes by the time the diff layer puts them in the
patch list.

dx=0 and dy=0 cursor moves serialize to the empty string (no wasted
escapes), and an empty Patch[] serializes to '' so emitting a frame
with no diff is a no-op.

Tracking issue: #160.
2026-05-03 02:57:24 -07:00
YHH aa87a6d88b feat(renderer): cell-level diff between two Frames → Patch[] (#168)
Core of #160 — the algorithm that takes two Screen snapshots and
emits the minimal set of (cursorMove + styleStr + stdout + hyperlink)
patches needed to bring the terminal from the old state to the new.
This is what replaces Ink's bulk eraseLines: unchanged cells produce
zero bytes.

diffFrames(prev, next, pools) → Patch[]:

- viewport size differs → emit clearTerminal + write the full new
  screen. Resize is rare; predicting wrap on a different width is
  not worth the layout machinery.
- otherwise walk every (x, y) where the cells differ:
  - move the cursor there (\r if pending-wrap, then \r + dy + dx)
  - transition style if changed (StylePool.transition cached)
  - transition hyperlink if changed (OSC 8 open / close)
  - skip SpacerTail (the wide glyph already advanced the cursor)
  - write the char
- after all changes, restore cursor to next.cursor and reset style /
  hyperlink to none so anything we don't own renders cleanly.

Adjacent same-style writes ride on the terminal's natural cursor
advance — no inter-cell cursor moves, no inter-cell style emits.

Tracking issue: #160.
2026-05-03 02:39:13 -07:00
kabaka a6fd807b49 feat(i18n): Implement front-end and back-end language setting synchronization feature (#167)
Add back-end language setting support, including initializing language settings from the server and bidirectional synchronization functionality
Expand the language registry to support more languages, and improve language storage and error handling
Fix issue of returning to the chat page after refreshing
2026-05-03 02:38:21 -07:00
YHH 3634bdeca5 feat(renderer): Box borders — preset styles + custom glyph object + per-side colors (#166)
Closes the layout side of the renderer feature surface for #160.

Borders compose with padding by sitting outside it:

  border-top
    padding-top
      content (width = inner - borders - padding)
    padding-bottom
  border-bottom

Five preset styles ('single', 'double', 'round', 'bold', 'ascii')
or a fully custom { topLeft, top, topRight, ... } glyph object —
the latter is what Reasonix's CardBox uses today (whitespace
corners + a single glyph on the left for the accent bar).

Each side toggles independently via borderTop / Bottom / Left /
Right; default-on when borderStyle is set, default-off otherwise.
borderColor sets all four; per-side overrides (borderLeftColor
etc.) win.

intrinsicWidth now accounts for border + padding so flexDirection
row in a parent allocates the correct slot width to bordered
children.

Tracking issue: #160.
2026-05-03 02:29:06 -07:00
YHH 933d01060f feat(renderer): flexDirection row + flexGrow (#165)
Refactors layout from a linear TextRow stream to a 2D structure
where each visual row holds a list of x-positioned fragments.
Necessary for row direction — sibling children need to share rows
at different x offsets, which the previous one-fragment-per-row
shape couldn't express.

flexDirection='row' lays children left-to-right. Each child gets
min(intrinsicWidth, remaining) of the available width. When the
sum of intrinsics exceeds the container, allocations scale
proportionally and children's text wraps inside its narrower slot.
Children with different heights align at the top.

flexGrow distributes leftover width after intrinsics are honored.
The common case — Box flexGrow=1 as a flex spacer between fixed
content — yields '<L> <pad> <R>' style headers without manual
column math.

Default direction stays column.

Tracking issue: #160.
2026-05-03 02:20:57 -07:00
YHH 4026baa28c feat(renderer): Box padding (top / bottom / left / right + X/Y/all shorthands) (#164)
Padding shifts content inward without changing the Box's own width.
paddingTop / Bottom emit blank rows above / below children;
paddingLeft / Right reduce the inner width children lay out into,
and every emitted row carries a leftPad offset that the blit step
honours so writes start at the correct x.

paddingX / paddingY / padding shorthands compose with the side-
specific props — explicit side wins (paddingLeft beats paddingX
beats padding).

Tracking issue: #160.
2026-05-03 02:14:07 -07:00
YHH af4e9e33ef feat(renderer): React JSX entry — Box / Text / function components → LayoutNode (#163)
Lets callers write the renderer surface in JSX instead of building
LayoutNode trees by hand. Box and Text are exported as host markers
(throw if invoked directly); the render() entry walks the React
element tree, recognizes those markers, calls stateless function
components inline, and unwraps Fragments. Output is a Screen.

No reconciler yet — stateful components / hooks / re-render-on-state
don't drive output. The walker is enough for static JSX rendering
and for tests to use familiar JSX syntax. The reconciler comes when
we wire the renderer to actually drive a live UI.

Tracking issue: #160.
2026-05-03 02:06:54 -07:00
YHH eacb4e56d3 feat(renderer): vertical-stack layout from Box / Text nodes (#162)
Walks a tree of Box and Text nodes and lays them out into a Screen
of the given width. Children stack vertically; nested boxes flatten
in source order. Long text lines wrap at the cell boundary using
grapheme-aware width via Intl.Segmenter + string-width, so CJK and
emoji ZWJ count as one rendered glyph occupying the right number
of cells.

Style and hyperlink on a Text node are interned through the pools
and propagated to every cell the node produces — sets up the diff
layer to compare cells purely by integer ids.

Tracking issue: #160.
2026-05-03 01:59:57 -07:00
YHH c222808985 feat(renderer): cell-buffer foundation — Screen, Cell, intern pools (#161)
Lays down the data structures the cell-diff renderer will read from.
Pure values, no terminal IO; the diff layer (next) reads two Screen
snapshots and emits patches per cell that actually differs.

Three pools collapse high-cardinality runtime values to integer ids
so cell comparison stays in int-vs-int and per-frame allocation
stops being a GC problem at 5K+ cells.

Tracking issue: #160.
2026-05-03 01:51:44 -07:00
YHH 0b0e19fc7a feat: remove plan sidebar / docking entirely (#159)
Plan card now lives only as a regular inline card in the stream.
No right-side panel, no above-input pinning, no Ctrl+\ toggle.
Layout stayed in 'either-or' / 'both' / 'sometimes-pinned' uncertainty
across PR #127 → #156, and the docking machinery itself was a steady
source of layout instability that no amount of width-conditional
gating fully closed.

Removes:
- src/cli/ui/layout/SidebarPanel.tsx (file)
- tests/sidebar-panel.test.ts (file)
- App.tsx: activePlanCard / rawActivePlanCard / sidebarVisible
  derivation, the sidebarOpen state + Ctrl+\ keybind, the
  <SidebarPanel> mount, the modal-active gating that only mattered
  to suppress the sidebar
- viewport-budget.tsx: 'plan-card' ZoneId entry (no claimers left),
  useIsModalActive() hook (only consumer was sidebar)
- CardStream.tsx: excludeId prop (no callers left)
- config.ts: sidebarOpen field + load/save helpers

The plan card itself is unchanged — it's already a settled card
once all steps complete and renders as a regular inline card via
CardStream's existing plan->Static path. Inline plan card has
stable height (no windowing), so it doesn't suffer the live-region
height-flutter issue the sidebar's windowed PlanSection had.
2026-05-03 01:27:51 -07:00
YHH 0da4c78ca0 fix(sidebar): stabilize windowed plan-section height across step transitions (#158)
Root-cause fix for the up-down screen jitter dududarochadev reported
in #155 (and the same class of bug we previously masked with
cols-based sidebar gating).

When a plan has more steps than fit in the window (>11), the windowed
plan-section conditionally rendered '(N earlier hidden)' / '(N more)'
hint rows only when N>0. As the running step crossed the window
boundaries those flipped on/off, changing the live region's row count
and triggering Ink's erase-then-reprint to leak the previous frame.

Always render both indicator rows in windowed mode; show the count
when N>0, an empty 1-row placeholder otherwise. Total rendered height
of the windowed plan-section is now stable regardless of how the
running step moves through the plan.

Fix lives on the plan card itself, not behind a width gate, so the
narrow-screen inline-plan path benefits the same way once the same
windowing pattern lands there (currently inline PlanCard doesn't
window, so it's already stable for now).

This is the start of the broader 'live-region row stability' work I'll
track in a follow-up issue — streaming/reasoning preview cards have
the same shape of bug during their initial output ramp.
2026-05-03 01:04:31 -07:00
YHH 161e36a461 fix(layout): plan card lives in EITHER sidebar OR card stream, never both (#156)
Per RFC #20 thread, lamyc's ask was "task list collapsed INTO a
sidebar" on portrait/narrow setups. PR #127 shipped a sidebar but
also kept a pinned PlanCard above the input — so on wide screens the
plan rendered twice (sidebar + pinned), and on narrow screens (where
the sidebar refuses to render below 88 cols) the plan was pulled out
of the card stream and pinned above input alone, leaving no inline
plan card at all.

Single rule now:

  sidebarVisible = !PLAIN_UI && sidebarOpen && cols ≥ 88 && activePlanCard

  - sidebarVisible       → CardStream excludes plan; sidebar renders it
  - !sidebarVisible      → CardStream keeps plan inline; nothing pinned

Drop the pinned PlanCard above input entirely. Drop the unconditional
`excludeId` on CardStream. `PlanCard` is no longer imported in App.

This implements interpretation B+C from the layout discussion:
B) plan fully in sidebar when room exists, no duplicate
C) narrow / portrait → plan stays inline in stream, no sidebar
2026-05-03 00:37:02 -07:00
YHH 559e684784 fix(plan): gate sidebar + pinned plan card on modal-active, not step transition (#153)
#147 used "at least one step has left queued" as the proxy for
"plan has been approved". That breaks the post-accept window: once
the user accepts, plan steps may sit in `queued` for several seconds
before the model issues its first tool call — during which the sidebar
should be visible but isn't.

Right discriminator is the approval modal itself. `useIsModalActive()`
is true exactly while PlanConfirm (or any other modal-priority claim)
is up. Drop the "non-queued" check from findActivePlan and gate at
the call site:

  - SidebarPanel: `isModalActive ? null : findActivePlan(cards)`
  - App.tsx activePlanCard: same shape

findActivePlan stays pure (no hook usage) so it remains unit-testable.
The test that previously locked in "all-queued returns null" now
locks in "all-queued returns plan" — modal-gating is the caller's
contract.
2026-05-02 23:57:13 -07:00
YHH ea66fb4bf1 feat(cards): tool card 'rejected' state + input-size meta (#154)
Closes #150 (the user-facing half — bounce wording itself stays as-is).

The plan-mode bounce error and silent write_file are both fundamentally
visual problems: the gate runs before fs writes, but the spinner-then-
JSON-error sequence reads as 'wrote, then failed'; large write_file
content gives no progress signal because formatArgsSummary picks the
short path field.

A. Plan-mode rejection visual

ToolRegistry now adds rejectedReason: 'plan-mode' to the bounce JSON.
The reducer parses tool.end output, sets card.rejected on the marker.
ToolCard swaps the spinner for a red ✗ rejected badge in the trailing
slot and hides the verbose error body — one quick visual cue replaces
a faux-write spinner followed by a wall of JSON.

B. Input size in meta

ToolCard.formatMeta gains a leading '1.2 KB in' fragment when any
string field on args is at or above 1 KB. Generic — no per-tool
special case — so write_file (content), edit_file (long replace),
run_command (long stdin) all benefit. Below 1 KB, nothing shows;
small writes don't get noisy meta.

Tests:
- ui-reducer: tool.end with plan-mode marker flips rejected=true,
  regular errors don't trigger.
- tool-card-meta: largestStringInputBytes thresholding + multi-field
  selection.
2026-05-02 23:45:22 -07:00
YHH edf4233a60 feat(i18n): default to system locale when no explicit config (#151)
First-run users with a Chinese OS locale saw English by default —
the only signal was config.lang, which doesn't exist on first launch.
Add a third tier between config and the EN fallback: detectSystemLanguage()
reads Intl.DateTimeFormat().resolvedOptions().locale (cross-platform,
no env-var spelunking) and prefix-maps zh* → zh-CN, en* → EN, anything
else → null (falls through).

Priority: user-set config > system locale > EN.

The detection function takes the locale string as a parameter (defaulting
to Intl) so it stays unit-testable without mocking globals.
2026-05-02 21:21:47 -07:00
kabaka 4b4d125987 feat(i18n): add multi-language support (#149)
Add internationalization support for the dashboard, including English and Simplified Chinese.
- Create i18n module to manage language switching and translations
- Replace hardcoded text with translation keys in all panels
- Add language switching functionality to the settings panel
- Implement dynamic loading of translation content
- Update all UI components to use translation functions
2026-05-02 21:07:33 -07:00
kabaka 5631dafdde feat(i18n): add multi-language support (#144)
Implement runtime language switching, including:
- Add /language command for language switching
- Add Chinese/English translation framework
- Modify state management to support language change events
- Update tests to ensure correct functionality
- Adjust UI components to support internationalized text
2026-05-02 21:07:29 -07:00
YHH e11fd6c848 fix(plan): only treat plan as 'active' once execution has started (#147)
User reported the right-side plan sidebar appears during the
PlanConfirm approval modal, before the user has accepted. Same bug
also pinned the plan card above the input prematurely.

Both selectors (App.tsx:297 + SidebarPanel.tsx:39) used the same
predicate: variant === "active" + at-least-one-step-not-done. But
fresh plans have every step in `queued` — the predicate matched
immediately on creation, before approval triggered any state
transition.

Tighten the predicate: "active" now means execution has actually
started — at least one step has left `queued` AND not all steps
are done/skipped. Approval-pending plans (every step queued) and
finished plans (every step done/skipped) both correctly return null.

Exported findActivePlan and added 5 tests covering the regression
plus the surrounding boundaries (variant guards, latest-of-many).
2026-05-02 20:59:31 -07:00
YHH 11c7150ed1 fix(cards): drop fake key hints + CtxCard CardHeader + TaskCard meta tidy (#145)
Plan + Error cards advertised inline keybinds in their footers
(`[r] revise` / `[r] retry` etc.) but no handler was ever wired
to scrollback cards — the actual revise/retry flow runs through
PlanConfirm modals via arrow + Enter. Pressing the advertised key
did nothing. Removed the misleading footers; the modal flows are
unchanged.

CtxCard hand-rolled its own header instead of using CardHeader,
breaking the visual contract every other card follows. Routed it
through CardHeader with the same tone/glyph/meta shape.

TaskCard's `meta` ended in a trailing space (`X.Xs · `) and
CardHeader inserts its own space before the trailing badge, so the
rendered output had a double space before the status word.

Also collapsed a dead ternary branch in PlanCard step-color logic
where two arms produced the same value.
2026-05-02 20:31:41 -07:00
YHH 4a3f5f035b feat(cards): UserCard gets CardBox accent + drop dead approval-card type (#143)
UserCard was the only Markdown-rendering card without a CardBox bar —
long pasted prompts wrapped without a continuing accent, breaking the
visual rhythm against the now-accented streaming/reasoning cards.

Audit also turned up the `approval` card kind in cards.ts: declared
in the Card union but with zero producers in src/ or tests/. The
CardRenderer case for it just routed to FallbackCard ("not yet
migrated"). Removed the interface, the union member, and the orphan
case — default branch already catches anything unexpected.
2026-05-02 19:45:11 -07:00
ctharveyandCharles H 2ed06d4213 fix(code): adapt LF model output to target file line endings for SEARCH/REPLACE matching (#142)
applyEditBlock and edit_file both detect the target file's line ending
(CRLF vs LF) and adapt the model's search/replace text before matching.
Duplicate-match checks, replacement, and diff rendering use the adapted
text. CRLF files are preserved as CRLF; LF files stay LF.

Adds tests for both paths: SEARCH/REPLACE blocks (edit-blocks) and the
native edit_file tool (filesystem-tools), covering LF→CRLF matching,
LF preservation, multi-line CRLF matching, and duplicate-match refusal.

Co-authored-by: Charles H <[email protected]>
2026-05-02 19:26:07 -07:00
YHH e625e01e2e fix(cards): restore brand accent on done-state assistant reply (#140)
PR #126 (0.23.0) gave done assistant Markdown a brand-toned
borderLeft per lamyc's RFC #20 readability ask. The #136 card
redesign extracted CardBox but flipped the done-state color to
FG.faint, defeating the contrast that lets long replies stand
out in scrollback. Now matches the streaming-state color so the
bar reads continuously across the streaming → done flip.
Aborted state stays on FG.faint (correctly de-emphasized).
2026-05-02 19:22:45 -07:00
YHH b2c9d416d2 test(slash): silence MCP reconnect spawn stderr leak (#138)
The /mcp reconnect <name> test fired kickOffMcpReconnect with spec
"node nope", spawning Node against a missing 'nope' module. The
test passed (lifecycle line is returned synchronously) but Node's
MODULE_NOT_FOUND error leaked to stderr in the test runner output.

"node -e 0" exits 0 silently and is cross-platform.
2026-05-02 09:23:17 -07:00
YHH 7da04c615a release: 0.23.1 — reasoning/streaming card redesign + loop storm self-correct (#137) 2026-05-02 09:15:32 -07:00
YHH dfaee68b2d fix(tui): redesign reasoning + streaming cards (closes #133) (#136)
The Reasoning card had three rendering bugs that compounded into a
"feels broken" UX: only one preview line was visible, that line was
the head not the tail of the actual reasoning, and once content
overflowed the viewport the screen jittered on every chunk.

Root causes were three independent issues:

  1. The line-budget constant in StreamingCard / ToolCard was off by
     two cells, so rendered lines exceeded the terminal width by one
     and the terminal wrap-extended each row. Ink's eraseLines(N)
     then miscounted against the visible row count and left ghost
     rows behind on every render — the visible "jitter."

  2. The streaming live region grew row-by-row as text arrived.
     Each new line pushed everything below down by one row before
     the eraseLines miscount kicked in to make it worse.

  3. The settled body sliced last N lines, but reasoning is
     typically a single long paragraph — slice(-2) returned the
     whole one-line string, then clipToCells truncated from the
     head, so the user saw the first cells of the line instead of
     the last.

Fixes:

  - Wrap card content in `<Box borderLeft borderStyle={{left:"▎"}}>`
    via a new CardBox primitive — Ink renders the bar on every
    visual row including markdown wrap continuations.
  - Streaming preview is fixed at 4 visual rows (live region small
    enough that eraseLines miscount can't pile up). Settled
    reasoning collapses to last 2 visual rows.
  - Pre-wrap content via wrapToCells before slicing, so `slice(-N)`
    returns the true visual tail.
  - Drop the CardRenderer "yield to content" branch that hid
    reasoning entirely while output streamed.

Visual:

  - Section + model pills replace the `◆` glyph + emoji prefix.
    Model pill color signals model class (flash blue, pro purple,
    r1 violet).
  - Bar color dims to FG.faint once a card settles — running cards
    are accent-bright, done cards are grey.
  - Streaming header carries a braille spinner + "thinking…" /
    "writing…" status text.
  - Settled reasoning header shows duration on the right.
  - Settled cards above the tail-2 lines get a single elision row
    (`⋯ N ¶ · K tok above · /reasoning last`) instead of a full
    head+tail layout.
2026-05-02 08:50:24 -07:00
YHH c72fca8c6f fix(loop): self-correct on first repeat-loop storm before stopping (#134)
Closes #132.

Bad-args bugs (e.g. read_file({path:""})) and genuine stuck loops
both used to land in the same place: storm-breaker suppressed the
calls, the loop force-summarized, the turn ended with a loud yellow
"recent-repeat window" warning. Bad-args is the common case and would
self-correct if the model just saw the prior tool error — terminating
the turn forces a /retry that didn't need to happen.

Now the first all-suppressed storm in a turn rewrites the just-
persisted assistant message to preserve the original tool_calls,
stubs role:"tool" responses to honor DeepSeek's "every tool_call
needs a tool message" contract, yields a plain-language warning,
and continues the iter — model gets one shot at a different approach.
Only the second storm in the same turn falls through to the
forced-summary path.

Also softens user-facing copy: "storm-broken" / "recent-repeat
window" / "call-storm suppressed" jargon → "repeat-loop guard" /
"repeated tool call" / "stuck retry loop". Auto-escalation toast
now reads "4× repeat-loop" instead of "4× storm-broken".

Adds REASONIX_STORM_THRESHOLD / REASONIX_STORM_WINDOW env vars for
manual testing of the guard at lower thresholds.
2026-05-02 07:09:58 -07:00
YHH 58732cacf2 release: 0.23.0 — TUI quality-of-life pass (#130) 2026-05-02 06:32:17 -07:00
YHH fee58f13da fix(at-mention): nested .gitignore via shared util (#129)
@paulo70015 reported every @ query returning "no files match" on
Flutter projects. Diagnosis: the picker walker did not honor
.gitignore, so the 500-result cap filled with ios/Pods/ before the
alphabetical walk reached lib/.

Rather than grow the hardcoded ignore list per framework (Pods,
DerivedData, target, vendor, …), trust the project's own
.gitignore — same source of truth fzf, ripgrep, and the rest of
the ecosystem use.

  - new `src/gitignore.ts` lifts loadGitignoreAt + ignoredByLayers
    out of the semantic chunker, so the @ picker walker and the
    indexer share one nested-gitignore implementation
  - `listFilesWithStats(Sync|Async)` push a layer per directory's
    .gitignore as it descends; statBatch checks the merged layer
    set before stat'ing
  - default maxResults bumped 500 → 2000
  - opt-out via `respectGitignore: false` on ListFilesOptions
  - `chunker.ts` switches to the shared util — no behavior change

Tests cover root + nested .gitignore, negation (`!keep.log`),
opt-out, and the existing skip / cap / DFS-order contracts.
2026-05-02 06:26:38 -07:00
will 16024bbd15 test: add preset resolution and canonicalization coverage (#125) 2026-05-02 05:55:12 -07:00
YHH b6d4d9beab feat(tui): right-side context panel with Ctrl+\ toggle (#127)
* feat(tui): right-side context panel with Ctrl+\ toggle (#122)

Sidebar shows current plan steps, running tools, and last-turn
usage as a read-only HUD. Defaults open on cols ≥ 120, off below;
persisted in ~/.reasonix/config.json.sidebarOpen. Below 88 cols
total the panel hides regardless of preference.

Carries the StreamingCard hook-order fix from #126.

* fix(sidebar): hide entirely when no active plan

Empty sidebar default-on was visual noise — 28 cols of blank panel
on every fresh session. Now the panel returns null unless an active
plan exists. Drop the Usage section: same data already lives in the
inline UsageCard.

* fix(sidebar): hide on rejected plans (require actual progress)

submit_plan creates the plan card with all steps "queued" before
PlanConfirm even pops; cancelling the modal leaves the card behind
unchanged. Sidebar was treating "variant=active" as enough and
stayed mounted after rejection. Now also require at least one step
to have started — distinguishes pending-approval / cancelled
("all queued, forever") from running / partially-done plans.

* refactor(sidebar): divider uses borderTop instead of hardcoded char repeat

The divider rendered "─".repeat(SIDEBAR_WIDTH - 2), which would break
the moment the panel width or padding changed. An empty box with
borderTop lets Yoga compute the line width from the parent — adapts
automatically.

* fix(plan): drop the active plan card on PlanConfirm cancel

submit_plan creates the plan card up-front (variant=active, all
steps queued) before the user picks approve / cancel. On cancel
nothing was clearing the card, so the existing activePlanCard
selector + the new sidebar both kept it visible as if the plan was
running.

New plan.drop reducer action flips the latest active plan's variant
to "replay" (already-existing archive variant). Sidebar + bottom
PlanCard now honor cancel correctly. Approved-but-not-yet-started
plans render as before — variant is still "active", just with all
steps queued.
2026-05-02 05:38:18 -07:00
YHH 4f6e99e772 feat(cards): left accent bar on done assistant replies (#126)
* feat(cards): left accent bar on done assistant replies (#122)

Add a brand-toned borderLeft to the done-state Markdown so long
replies are visually distinguishable from tool/reasoning cards in
scrollback. Ink's <Box> doesn't accept backgroundColor; a left bar
is the terminal-native equivalent and works on light + dark themes.

* chore(tui): trim comment essays from layout migration

Comments added in the #120 migration violated CLAUDE.md: multi-paragraph
module headers, defensive justification, incident narrative ("lamyc-video
trigger"). Reduced to single lines where the why is genuinely non-obvious.
2026-05-02 05:35:36 -07:00
YHH 1ff2c7c7b9 fix(tui): single layout authority for viewport rows (#124)
* fix(tui): single layout authority for viewport rows (#120)

Streaming cards and approval modals each read stdout.rows and
computed their own row budget independently — the bottom-anchor
modal could claim rows the streaming card had already counted on
and vice versa, producing visible jitter when both rendered the
same frame (lamyc's video).

Replaces the scattered RESERVED_CHROME_ROWS / MODAL_OVERHEAD_ROWS
constants with a priority-greedy allocator. Each component declares
{ min, max } rows for its zone via useReserveRows; the provider
runs allocation and feeds back actual budgets so consumers stay
within the viewport.

Migrated zones, in priority order:
  modal       (EditConfirm, ShellConfirm, PlanConfirm,
               PlanCheckpointConfirm, ChoiceConfirm)
  status      — left for follow-up; already conditionally hidden
  input       (PromptInput multi-line)
  stream      (StreamingCard)
  safety      — reserved margin

Skipped this pass: PlanCard anchor, plan-card zone, status rows.
Those don't trigger the lamyc bug and can plug into the same API
when their behavior is reviewed.

* fix(viewport-budget): break infinite useEffect loop in useReserveRows

The hook had `ctx` in its effect deps, but the provider's context value
identity changes after every dispatch (the memo depends on `allocations`
which recomputes whenever `claims` changes). So claim → state update →
new ctx identity → effect re-fires (release + claim) → infinite loop.

Depend on `dispatch` (stable from useReducer) and the spec primitives
instead. Effect now fires once on mount, again only when min/max
actually change, and once on unmount.
2026-05-02 04:35:31 -07:00
YHH 08c14ad828 feat(prompt): Home/End/Ctrl+K/Alt-word shortcuts (#123)
Long-time CLI users reach for Home/End and Ctrl+K muscle-memory keys
that were never bound. Reuses the existing startOfLine/endOfLine
helpers and the previousWordStart helper used by Ctrl+W.

Ctrl+U keeps its non-standard "clear all" behavior — see comment.
2026-05-02 04:35:16 -07:00
YHH 82a7fd8b1e release: 0.22.0 — live MCP reconnect (identity + append) + d keybind (#119) 2026-05-02 03:10:03 -07:00
YHH ae6021ea29 feat(mcp): activate d-keybind in /mcp browser; share disable helper (#118)
Final stage of #105: wire McpBrowser modal's labelled-but-stub `d`
keybind to the same `mcpDisabled` config persistence the slash
already does. Removes the "(TBD)" label from the modal footer.

- New `src/cli/ui/mcp-disable.ts` exporting `toggleMcpDisabled`,
  the readConfig+writeConfig logic that was previously inlined in
  the slash handler.
- `src/cli/ui/slash/handlers/mcp.ts` — replaces the inline
  read/write block with a single call to `toggleMcpDisabled`.
  Unknown-name validation stays in the slash since it has access
  to mcpServers + mcpSpecs to build the "Known: …" hint.
- `src/cli/ui/McpBrowser.tsx` — `d` key handler persists
  `mcpDisabled` for the selected server and closes the modal.
  No need for the unknown-name check in the modal — the user
  picked from a live list, the name is always valid.
- Footer label updated.

Refs #105.
2026-05-02 03:03:34 -07:00
YHH c7298fec4e feat(mcp): append-drift mid-session reconnect (refs #110) (#117)
Stage E2 of the C2b follow-ups: when /mcp reconnect finds the server
added new tools at the END of its tool list, register them
mid-session and addTool the prefix instead of refusing.

Drift kinds the reconnect now accepts:

- identity → free swap, ~95% cache hit (was already shipped in #115)
- append → register new tools, ~95% cache hit (the new chunks land
  in cache too, per benchmarks/spike-mcp-reconnect data)
- edit / reorder / remove → still refused with "restart Reasonix"

Touch:

- src/mcp/registry.ts — extract `registerSingleMcpTool(mcpTool, env)`
  + new `BridgeEnv` type (resolved bridge environment captured at
  first-bridge time). bridgeMcpTools' return shape gains `env` so
  reconnect can re-use the same options.
- src/cli/ui/slash/types.ts — McpServerSummary gains `bridgeEnv:
  BridgeEnv` so the append handler has everything it needs to
  register a new tool without redoing the whole bridge.
- src/cli/commands/chat.tsx — captures bridge.env onto the summary.
- src/mcp/reconnect.ts — accepts identity (always) plus append (if
  caller passes accept: ["identity", "append"]). On append, returns
  addedTools so the caller can register them. Identity is forced-
  accepted regardless of `accept` because it's free.
- src/cli/ui/mcp-append.ts (new) — `applyMcpAppend(loop, target,
  addedTools)` calls registerSingleMcpTool + prefix.addTool +
  refreshes target.report. Accepted-tools-only counting handles the
  unnamed-tool defensive case.
- src/cli/ui/mcp-reconnect-kickoff.ts — gains optional `applyAppend`
  callback. When set, opts the reconnect into ["identity",
  "append"]; when missing, behaviour is unchanged from #115.
- src/cli/ui/slash/handlers/mcp.ts + src/cli/ui/McpBrowser.tsx +
  src/cli/ui/App.tsx — both surfaces wire applyMcpAppend through.
- tests/mcp-append.test.ts (new) — 4 cases: registry registration,
  fingerprint invalidation, summary refresh, defensive skip on
  unnamed tools.

Closes most of #110. Edit / reorder / remove mid-session remain as
follow-up issues — each requires new ImmutablePrefix API
(replaceTool / removeTool) + cache-reset announcement.
2026-05-02 02:48:56 -07:00
YHH d5d6032f83 feat(mcp): activate r-keybind in /mcp browser; share kickoff helper (#116)
Refs #110.

Stage E1 of the C2b follow-ups: wire the `/mcp` browser modal's
labelled-but-stub `r` keybind to the same reconnect flow the
`/mcp reconnect <name>` slash already uses.

- New `src/cli/ui/mcp-reconnect-kickoff.ts` exporting
  `kickOffMcpReconnect(target, postInfo) → string`. Returns the
  start-line, schedules the result line via postInfo. Both the
  slash handler and the modal now route through it.
- `src/cli/ui/McpBrowser.tsx` adds an `r` key handler that calls
  the kickoff against the currently-selected server, pushes the
  start-line via `postInfo`, then closes the modal so the line is
  visible immediately.
- `src/cli/ui/App.tsx` passes `log.pushInfo` into the modal.
- Footer label updated: `[r] reconnect (Stage C)` → `[r] reconnect`
  (the `[d] disable` slot stays labelled "(TBD)" — that ties to
  the registry-mutation work still pending).
- `src/cli/ui/slash/handlers/mcp.ts` reduces to a one-line call to
  the kickoff helper, dropping the inline async block.

No behaviour change for the slash; it produces the same lifecycle
lines via the shared helper. Modal is the new surface.
2026-05-02 02:34:16 -07:00
YHH 05d1efb4c9 feat(mcp): /mcp reconnect <name> for identity drift only (#115)
C2b implementation per RFC #110. Identity-drift only — append / edit /
reorder / remove drift cases surface a clear "restart Reasonix to apply"
message instead of mutating the registry or prefix mid-session. The
graduated permissive policy from the empirical spike (#113) needs API
work on `ImmutablePrefix` (replaceTool / removeTool) before the other
drift kinds can take effect mid-session; that's a follow-up PR.

Touch:

- `src/mcp/registry.ts`: new `McpClientHost = { client: McpClient }`
  indirection on BridgeOptions. Tool closures resolve the live client
  via `host.client` at call time, so reconnect can swap the underlying
  socket without re-bridging tools.
- `src/mcp/reconnect.ts` (new): `reconnectMcpServer({ host, spec,
  beforeTools })` re-handshakes a fresh transport, classifies drift,
  swaps `host.client` only on identity, closes the new client cleanly
  on refusal so the old one stays untouched.
- `src/cli/ui/slash/handlers/mcp.ts`: third subcommand `reconnect <name>`,
  fires async, reports via `ctx.postInfo` with the lifecycle
  `↻ reconnect…` / `✓ connected` / `✖ failed` formatter.
- `src/cli/ui/mcp-lifecycle.ts`: `reconnect` state added to the union.
- `src/cli/ui/slash/types.ts`: `McpServerSummary.client?` replaced by
  `host: McpClientHost`. `McpClient` import dropped (now via host).
- `src/cli/ui/mcp-browse.ts`: `/resource` and `/prompt` read through
  `server.host.client`. Disconnected-server warnings dropped — host
  always carries a client now.
- `src/cli/commands/chat.tsx`: builds the host at bridge time, stores
  it on the summary.

Tests:

- `tests/mcp-reconnect.test.ts`: 2 cases for spec_parse early returns.
- `tests/mcp-integration.test.ts`: live test that bridge + host
  indirection routes a swapped client correctly through registry.dispatch.
- `tests/slash.test.ts`: 3 cases for the slash dispatch (lifecycle line
  emission, unknown-name rejection with hint, no-arg usage).
- `tests/mcp-browse.test.ts`: server() helper updated to accept `client`
  and wrap in host shape.

Closes part of #110 (identity case only). Append/edit/reorder/remove
mid-session handling deferred — needs ImmutablePrefix surgery.
2026-05-02 02:22:26 -07:00
YHH 1920d90717 feat(mcp): tool-list drift classifier (groundwork for #110 C2b) (#114)
Pure function `classifyToolListDrift(before, after) → DriftReport`
encoding the cache-cost taxonomy validated by the live spike (#113):

- `identity`  — same names, same order, same content → free
- `append`    — every before-tool unchanged, new tools at the end → trivially cheap (94.8% hit observed)
- `edit`      — same names + positions, content of ≥1 tool changed → bounded loss past the divergence point
- `reorder`   — same set, different order, OR additions not at the end → catastrophic
- `remove`    — any before-tool missing from after → catastrophic; dominates even when other tools were added

Report carries `added` / `removed` / `edited` arrays so the policy
layer (next PR) can populate the warn line precisely.

Pure function, no I/O. 12 unit tests cover the matrix including
edge cases (empty before/after, remove-with-also-added).

Refs #110.
2026-05-02 02:03:02 -07:00
YHH d811f2d545 chore(spike): live DeepSeek run for RFC #110 cache-prefix question (#113)
Two-file spike under benchmarks/spike-mcp-reconnect/:

- runner.ts — 5 chat calls against live deepseek-chat with
  controlled tool-list drifts (identity, append, mid-stream edit)
- results.md — captured run + empirical findings

The headline result overturns the RFC body's "any drift = full
cache miss" claim. DeepSeek's prefix cache works at chunk
granularity (≈128 tokens), so the cost depends on WHERE the drift
falls:

- append a tool at the end → trivial cost (94.8% hit, even better
  than the no-drift 85% baseline because the new chunk gets cached)
- edit a tool's description in the middle → loses chunks past the
  edit (84.1% hit observed)
- replacing or reordering the tool list → effectively full miss

This nudges the C2b design call away from blanket "strict default"
toward graduated permissive: silent on appends, warn on mid-stream
edits, refuse on reorders / removals. `--strict` remains as an
explicit flag.

Refs #110.
2026-05-02 01:53:41 -07:00
YHH b9a97bb4b1 test(mcp): pin RFC #110's cache-prefix claims with 6 unit tests (#112)
The reconnect RFC's central claim — "re-bridging tools mid-session
breaks the prompt prefix when the new tool surface differs from the
old" — was so far an architecture-derived assertion, not an empirical
result. Cheap to lock down at the prefix-fingerprint layer.

`tests/mcp-reconnect-prefix-invariant.test.ts` covers six cases the
RFC directly references:

- identical tool list → fingerprint unchanged (the safe-reconnect case)
- one tool added → fingerprint changes
- one tool removed → fingerprint changes
- description-only edit on an existing tool → fingerprint changes
- parameter-schema edit → fingerprint changes
- same tools reordered → fingerprint changes (array order is part of
  the prefix bytes via JSON.stringify)

This gives RFC #110 a concrete reference to point at when weighing the
strict / permissive / `--force` approaches: any drift past the
"identical bytes" line is a guaranteed cache miss, full stop.

Refs #110.
2026-05-02 01:41:35 -07:00
259 changed files with 23948 additions and 4089 deletions

No files matched your search

+6 -2
View File
@@ -32,8 +32,12 @@ jobs:
- name: Typecheck
run: npm run typecheck
- name: Test (vitest)
run: npm test
- name: Test (vitest + coverage)
run: npm run test:coverage
- name: Coverage job summary
if: always()
run: node scripts/coverage-summary.mjs
- name: Build (tsup)
run: npm run build
+38
View File
@@ -0,0 +1,38 @@
name: CodeQL
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: "0 6 * * 1"
jobs:
analyze:
name: analyze (${{ matrix.language }})
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [javascript-typescript]
steps:
- uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
queries: security-extended
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Analyze
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{ matrix.language }}"
+1
View File
@@ -1,6 +1,7 @@
node_modules/
dist/
coverage/
.stryker-tmp/
.env
.env.local
*.log
+227
View File
@@ -3,6 +3,233 @@
All notable changes to Reasonix. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.25.1] — 2026-05-05
**Headline:** `run_command` learns the four common shell chain
operators (`|`, `||`, `&&`, `;`) and the seven file redirect
operators (`>`, `>>`, `<`, `2>`, `2>>`, `2>&1`, `&>`). Parsed and
spawned natively — no shell is invoked, so semantics are identical
on Windows / macOS / Linux; PowerShell 5.1's `&&` parse error and
the object-vs-bytes pipe gap are sidestepped. Each chain segment is
allowlist-checked independently, so `git status | grep main` now
auto-runs when both halves are individually allowed. Driven by
discussion #231.
**Shell:**
- feat(shell): support `|`, `||`, `&&`, `;` chain operators in
`run_command` via split-and-spawn. The chain is segmented at
whitespace-bounded operators (preserves embedded `&` / `|` inside
arg values like `--flag=1&2`), each segment runs through the
existing lenient tokenizer, and segments are executed with proper
short-circuit semantics for `&&` / `||`. Each segment hits the
allowlist independently — `git status | grep main` runs when both
halves are allowed individually. (#233, #234)
- feat(shell): support file redirects in `run_command` — `>` (truncate),
`>>` (append), `<` (stdin from file), `2>` (stderr truncate), `2>>`
(stderr append), `2>&1` (merge stderr into wherever stdout points),
`&>` (both → file). Targets resolve relative to the project root.
Mid-pipe `2>&1` correctly merges stderr into the next segment's
stdin without truncating on stdout-end. (#235)
- fix(shell): chain parser stays consistent with the project's
long-standing lenient tokenizer — `cargo run -- --flag=1&2` and
similar embedded-operator args stay literal instead of getting
POSIX-strict-rejected. shell-quote dependency dropped;
`splitOnChainOps` is whitespace-bounded like the existing
`detectShellOperator`. (#234)
## [0.24.1] — 2026-05-04
**Headline:** Two TUI fixes on top of the 0.24.0 cell-diff renderer.
Frame writes are now wrapped in DEC 2026 synchronized-output markers so
supporting terminals can't paint a half-cleared intermediate state, and
`marked` is bumped to v15 to stop pre-escaping inline text into HTML
entities — which both displayed wrong and miscalculated wrap widths.
**Renderer:**
- fix(renderer): wrap commit writes in DEC 2026 sync to suppress
flicker. The commit / static / resize paths buffered bytes into a
single write but the terminal could still paint the cleared-then-
repainted intermediate state. Each frame now goes out wrapped in
`\x1b[?2026h…l`; supporting terminals (Windows Terminal ≥1.18,
iTerm2, Kitty, Wezterm, alacritty, foot) swap frames atomically,
others ignore the unknown CSI. Resize's screen clear is also folded
into the next commit so clear+repaint is one sync block. Closes #225.
**Markdown:**
- fix(deps): bump `marked` to v15 — v12 pre-escaped inline text to HTML
entities (`<` → `&lt;`, `"` → `&quot;`), which displayed wrong in the
TUI and miscalculated cell widths so content past the wrap edge could
be clipped. v15 keeps `token.text` literal and only escapes at the
HTML renderer layer, which matches our actual rendering path.
## [0.23.1] — 2026-05-02
**Headline:** Two follow-up fixes to 0.23.0 — the `ReasoningCard` and
`StreamingCard` get a card-aligned redesign so they share the
`CardBox` + `Pill` primitives the rest of the run cards already use,
and the repair-storm detector now grants the loop one self-correction
attempt on the first storm before bailing the turn.
**TUI:**
- fix(tui): redesign reasoning + streaming cards. Both cards now sit
inside the shared `CardBox` with a tier-aware accent and a `Pill`
header, replacing the ad-hoc layout that didn't line up with
`ToolCard` / done-assistant rendering. New `primitives/CardBox.tsx`
and `primitives/Pill.tsx` are reused by the broader card family.
Closes #133. (#136)
**Loop:**
- fix(loop): repair-storm detector now self-corrects once before
stopping. A single short repeat-loop sequence (e.g. one retry of
the same tool call) used to abort an otherwise recoverable turn;
the loop now gets one self-correction attempt and only bails on
the second storm. (#134)
## [0.23.0] — 2026-05-02
**Headline:** TUI quality-of-life pass driven by RFC discussion #20.
A read-only **context sidebar** on the right surfaces the active plan
+ running tools (`Ctrl+\` toggle, plan-only auto-show), assistant
replies get a left **accent bar** so long answers are scannable in
scrollback, the viewport gains a single **row-budget allocator** that
ends the jitter when an approval modal mounts mid-stream, the prompt
input grows a full **readline vocabulary** (`Home` / `End` / `Ctrl+K`
/ `Alt+B/F` / `Alt+Backspace`), and the `@`-picker honors **nested
`.gitignore`** instead of dropping files past a 500-result cap on
Flutter / iOS projects.
**TUI:**
- feat(tui): right-side context panel showing the active plan
(windowed ±5 around the running step) and any running tool /
subagent. Auto-shows when a plan starts running, hides on cancel
via a new `plan.drop` reducer action; manual `Ctrl+\` toggle
persists in `~/.reasonix/config.json.sidebarOpen`. Refuses below 88
cols total; sidebar divider uses `borderTop` so the line auto-fills
the panel width. (#127)
- feat(cards): done assistant Markdown gets a brand-toned `borderLeft`
accent. Picked over `backgroundColor` because Ink's `<Box>` doesn't
accept it — a left bar works on light + dark themes equally per
lamyc's RFC #20 callout. (#126)
- fix(tui): `StreamingCard`, `EditConfirm`, `ShellConfirm`,
`PlanCheckpointConfirm`, `PlanConfirm`, `ChoiceConfirm`,
`PromptInput` now declare their height to a single
`ViewportBudgetProvider` instead of each reading `stdout.rows` and
guessing. Modal-vs-streaming row race that produced visible
vertical jitter mid-turn (lamyc's video) is gone. Pure allocator in
`src/cli/ui/layout/viewport-budget.tsx` is priority-greedy
(`modal > plan-card > status > input > stream`). (#124)
- feat(prompt): full readline shortcut set wired into the prompt
input — `Home` / `End` (line jumps, joins existing `Ctrl+A` /
`Ctrl+E`), `Ctrl+K` (kill to end of line), `Alt+B` / `Alt+F` (word
back / forward), `Alt+Backspace` (alias for the existing `Ctrl+W`).
`Ctrl+U` keeps Reasonix's "clear whole buffer" behaviour, not
readline's "kill to start" — clearing a large paste needs a single
ergonomic key. (#123)
**Bug fixes:**
- fix(at-mention): @-picker walker now honors **nested** `.gitignore`
(root + every subdirectory, layered like git itself) and bumps the
default result cap from 500 → 2000. On Flutter / iOS projects with
a built `ios/Pods/` directory the alphabetical walk used to burn
the cap before reaching `lib/` and every `@` query returned "no
files match". The new `src/gitignore.ts` util is shared with the
semantic chunker — single source of truth for "walk a dir
respecting `.gitignore`". Supports negation (`!keep.log`) and
`respectGitignore: false` opt-out. (#129)
**Internal:**
- test: focused unit coverage for `resolvePreset` /
`canonicalPresetName` + invariant check that every preset keeps
`harvest: false` and `branch: 1` (the rule that branch and harvest
are never silently auto-enabled). (#125)
## [0.22.0] — 2026-05-02
**Headline:** Live MCP-server reconnect — `/mcp reconnect <name>` (and the
`r` keybind in the `/mcp` browser modal) tear down a stuck client, hand-
shake a fresh one, and accept either identity or append-drift mid-session
without breaking the prompt prefix cache. The `d` keybind in the same
modal persists `mcpDisabled` for the selected server.
The reconnect work was driven by an empirical DeepSeek cache spike
(`benchmarks/spike-mcp-reconnect/`) that overturned the original RFC's
"any drift = full miss" framing — the cache is chunk-keyed, so an
appended tool costs only the new chunks (~95% hit retained). The full
graduated-permissive design lives in #110.
**MCP UX:**
- feat(mcp): new `/mcp reconnect <name>` slash subcommand. Re-handshakes
the named server's transport and swaps the underlying `McpClient`
through a new `McpClientHost` indirection so existing tool closures
keep working without re-bridging. Identity-drift is always accepted;
append-drift (server added new tools at the end of its tool list) is
accepted mid-session via `applyMcpAppend`, which calls
`prefix.addTool` + `registry.register` for each new tool. Edit /
reorder / remove drift is refused with a clear "restart Reasonix to
apply" message — those are catastrophic for the cache and would need
new `ImmutablePrefix` API surface (`replaceTool` / `removeTool`).
(#115, #117)
- feat(mcp): activate `r` (reconnect) and `d` (disable) keybinds in the
`/mcp` browser modal. Both surfaces now route through one shared
helper (`kickOffMcpReconnect` / `toggleMcpDisabled`) so the slash
command and the modal stay byte-identical in behaviour. (#116, #118)
- feat(mcp): new `reconnect` lifecycle state added to the formatter —
`⌘ MCP · <name> ↻ reconnect… tearing down · re-handshake
· listing tools` per design §37.
**Internal architecture:**
- `src/mcp/registry.ts` — extracted `registerSingleMcpTool(mcpTool, env)`
+ new `BridgeEnv` type. `bridgeMcpTools` now exposes a `host`
parameter (mutable client holder) and returns the resolved env so
reconnect can register newly-added tools with the same options. (#115)
- `src/mcp/reconnect.ts` (new) — opens a fresh transport, classifies
drift via `classifyToolListDrift`, swaps `host.client` only on
accepted drift kinds, closes the new client cleanly on refusal so
the old one stays untouched.
- `src/mcp/drift.ts` (new) — `classifyToolListDrift(before, after)`
returns `{ kind, added, removed, edited }` over the five drift
taxonomy buckets (identity / append / edit / reorder / remove).
Pure function. (#114)
- `McpServerSummary.client?: McpClient` replaced by `host:
McpClientHost` + `bridgeEnv: BridgeEnv`. Internal-only (the type
isn't in the public package surface).
**Tests / spikes:**
- `tests/mcp-reconnect-prefix-invariant.test.ts` (new) — six structural
cases pinning `ImmutablePrefix.fingerprint` behaviour under every
drift the reconnect path can produce. Locks the bytes-equal claim
the design rests on. (#112)
- `benchmarks/spike-mcp-reconnect/` (new) — live `deepseek-chat` spike
+ captured results: confirms DeepSeek's cache is chunk-keyed (~128
tokens), so appended-tool drift retains 94.8% hit and a
description edit on the first tool retains 84.1% hit. Drives the
graduated-permissive policy. (#113)
- `tests/mcp-drift.test.ts`, `tests/mcp-reconnect.test.ts`,
`tests/mcp-append.test.ts` (new) — unit coverage for the
classifier, reconnect early-returns, and the append handler.
**Deferred (filed as catastrophic-cache-cost cases):**
- Edit-drift mid-session (needs `ImmutablePrefix.replaceTool`)
- Reorder-drift mid-session (needs `removeTool` + cache-reset card)
- Remove-drift mid-session (same)
- `--strict` flag to refuse even append-drift
Each is structurally a guaranteed cache miss and refused-with-restart
is the right default; the follow-up issues will land if real demand
surfaces.
## [0.21.0] — 2026-05-02
**Headline:** MCP CLI surfaces realigned with `docs/design/agent-tui-terminal.html`
+63
View File
@@ -0,0 +1,63 @@
# MCP reconnect — empirical cache-prefix spike
Live `deepseek-chat` (DeepSeek prefix cache enabled by default).
System prompt: 1546 chars (~390 tokens). 5 turns each with a small
user message; tool-set varies between turns to simulate the drift
shapes a `/mcp reconnect <name>` would emit.
## Run
```
turn prompt hit miss hit% ms
--------------------------------------------------------------------------------
1 · cold start (toolset A) 758 640 118 84.4% 1092
2 · same prefix (toolset A) 753 640 113 85.0% 1535
3 · drift: ADDED tool (toolset A+) 810 768 42 94.8% 1048
4 · same prefix again (toolset A+) 807 768 39 95.2% 1480
5 · drift: EDITED desc (toolset A') 761 640 121 84.1% 791
```
(Turn 1's "cold" is misleading — the prefix had been seen by the
remote cache from an earlier run within the cache TTL.)
## Findings
DeepSeek's prefix cache works at chunk granularity (consistent with
publicly documented ~128-token chunks). Three concrete lessons:
1. **Append-only drift is nearly free.** Turn 3 adds one tool *at the
end* of the tool list — every cache chunk before the new tool
stays valid, only the appended bytes miss. Net: 94.8% hit, even
higher than the no-drift baseline (because the system prompt +
whole toolset-A is still cached, and the appended chunk is now
cached too).
2. **Mid-stream drift loses everything past the divergence.** Turn 5
edits a description on the *first* tool, so divergence falls
inside the tools block early. Hit drops to 84.1% — still high
here only because the system prompt occupies enough chunks before
the divergence point.
3. **Position of the drift dominates the cost.** A trailing addition
is essentially zero. An edit near the start of tools is more
expensive. An edit in the system prompt itself (not tested) would
wipe the cache to zero — expected, but irrelevant for reconnect
since we don't change the system prompt on reconnect.
## Implication for RFC #110
The "any drift = full cache miss" framing in the RFC body is too
pessimistic. The real cost of accepting a drifted reconnect depends
on *where* the drift lands:
- Server adds a new tool (most common reconnect drift) → trivial
cost, accept silently.
- Server changes an existing tool's schema or description → bounded
cost depending on position, surface a one-line warning.
- Server completely reorders or replaces the tool list → effectively
full miss, refuse or require `--force`.
This nudges the design call away from blanket "strict default"
toward a **graduated permissive** policy: accept appends silently,
warn on mid-stream edits, refuse on whole-list reorders or removals.
The strict approach can still be the explicit `--strict` flag for
users who need every byte of cache (e.g. high-volume scripted runs).
+182
View File
@@ -0,0 +1,182 @@
/** Empirically confirms RFC #110: tool-list drift mid-session breaks DeepSeek's prefix cache. */
import { DeepSeekClient, loadDotenv } from "../../src/index.js";
import type { ChatMessage, ToolSpec } from "../../src/types.js";
loadDotenv();
const MODEL = "deepseek-chat";
// DeepSeek's prefix cache only kicks in past ~1024 tokens of repeated
// prefix, so the system prompt has to be substantial. Padded with
// realistic-shape filler so the test exercises the same code path a
// real Reasonix session would.
const SYSTEM = [
"You are a precise senior software engineer assisting with TypeScript codebases.",
"Style: terse, concrete, no filler. Don't restate the question. Don't apologise.",
"When you reference a file, use the file:line shape so the user can click through.",
"When you list options, use a bulleted list, not prose.",
"When you reason, do so internally — final reply is the answer, not the deliberation.",
"If the user asks a yes/no question, lead with the answer, then one sentence of why.",
"If the user asks for code, output a minimal patch — not the whole file.",
"When a tool result is a long stack trace, surface the root frame and one stack item up.",
"Refuse to fabricate API surface; if you don't know a function exists, ask first.",
"Prefer existing libraries over hand-rolled implementations; flag the dependency cost.",
"When suggesting a refactor, point at the existing call sites that motivate it.",
"Don't add error handling that catches errors you have no recovery for.",
"Don't add comments that restate the code; only document the WHY.",
"Keep diffs reviewable: 1 change per commit, related changes per PR.",
"Treat user messages as authoritative on intent; ask only when truly ambiguous.",
"Response length is a function of complexity — short answers when short suffices.",
"Default to UTF-8, LF line endings, two-space indent unless the surrounding code differs.",
"When a request is impossible as stated, propose the nearest tractable alternative.",
"Cite specific paths and line numbers; never paraphrase a file you can read.",
"Optimise for the user's next action, not your own throughness.",
].join(" ");
const baseTool: ToolSpec = {
type: "function",
function: {
name: "read_file",
description: "Read the contents of a file at the given absolute or workspace-relative path.",
parameters: {
type: "object",
properties: {
path: { type: "string", description: "File path to read." },
},
required: ["path"],
},
},
};
const writeTool: ToolSpec = {
type: "function",
function: {
name: "write_file",
description: "Write text content to a file at the given path. Creates parents if missing.",
parameters: {
type: "object",
properties: {
path: { type: "string" },
content: { type: "string" },
},
required: ["path", "content"],
},
},
};
const searchTool: ToolSpec = {
type: "function",
function: {
name: "search_files",
description: "Find files whose path matches a glob pattern under the workspace root.",
parameters: {
type: "object",
properties: { pattern: { type: "string" } },
required: ["pattern"],
},
},
};
const TOOLSET_A: ToolSpec[] = [baseTool, writeTool, searchTool];
// Same shape as TOOLSET_A but adds one extra tool — emulates an MCP
// server reconnect that exposed an additional capability.
const newTool: ToolSpec = {
type: "function",
function: {
name: "delete_file",
description: "Remove a file at the given path. Refuses on directories.",
parameters: {
type: "object",
properties: { path: { type: "string" } },
required: ["path"],
},
},
};
const TOOLSET_A_PLUS: ToolSpec[] = [...TOOLSET_A, newTool];
// Same set as A, only the description on read_file edited.
const TOOLSET_A_EDITED: ToolSpec[] = [
{
...baseTool,
function: {
...baseTool.function,
description: "Read the contents of a file at the given path. Returns text or binary base64.",
},
},
writeTool,
searchTool,
];
interface Turn {
label: string;
tools: ToolSpec[];
user: string;
}
const TURNS: Turn[] = [
{ label: "1 · cold start (toolset A) ", tools: TOOLSET_A, user: "What does Reasonix optimise for, in one sentence?" },
{ label: "2 · same prefix (toolset A) ", tools: TOOLSET_A, user: "And why DeepSeek-only?" },
{ label: "3 · drift: ADDED tool (toolset A+) ", tools: TOOLSET_A_PLUS, user: "What's a flaky test, in one sentence?" },
{ label: "4 · same prefix again (toolset A+) ", tools: TOOLSET_A_PLUS, user: "And how do you stabilise one?" },
{ label: "5 · drift: EDITED desc (toolset A')", tools: TOOLSET_A_EDITED, user: "What's an idempotent operation, in one sentence?" },
];
async function main(): Promise<void> {
if (!process.env.DEEPSEEK_API_KEY) {
console.error("DEEPSEEK_API_KEY not set in env. Add it to .env and re-run.");
process.exit(1);
}
const client = new DeepSeekClient();
const systemMsg: ChatMessage = { role: "system", content: SYSTEM };
console.log(`RFC #110 cache spike — DeepSeek prompt-cache behaviour under tool-list drift`);
console.log(`model: ${MODEL}`);
console.log(`system prompt: ${SYSTEM.length} chars`);
console.log();
const head =
"turn".padEnd(40) +
"prompt".padStart(8) +
"hit".padStart(8) +
"miss".padStart(8) +
"hit%".padStart(8) +
"ms".padStart(8);
console.log(head);
console.log("-".repeat(head.length));
for (const turn of TURNS) {
const messages: ChatMessage[] = [systemMsg, { role: "user", content: turn.user }];
const t0 = Date.now();
const resp = await client.chat({
model: MODEL,
messages,
tools: turn.tools,
maxTokens: 64,
});
const ms = Date.now() - t0;
const u = resp.usage;
const hitRatio = u.promptTokens > 0 ? (u.promptCacheHitTokens / u.promptTokens) * 100 : 0;
console.log(
turn.label.padEnd(40) +
String(u.promptTokens).padStart(8) +
String(u.promptCacheHitTokens).padStart(8) +
String(u.promptCacheMissTokens).padStart(8) +
`${hitRatio.toFixed(1)}%`.padStart(8) +
String(ms).padStart(8),
);
}
console.log();
console.log("Expectations:");
console.log(" Turn 1 — cold, hit ≈ 0");
console.log(" Turn 2 — same prefix as 1, hit ≈ system-prompt-token-count");
console.log(" Turn 3 — DRIFTED (added tool), hit drops to ~0 again");
console.log(" Turn 4 — same prefix as 3, hit climbs back");
console.log(" Turn 5 — DRIFTED (edited description), hit drops to ~0 again");
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+56 -35
View File
@@ -6,6 +6,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { MODE } from "./src/lib/api";
import { ToastStack, appBus } from "./src/lib/bus";
import { ErrorBoundary, ErrorOverlay } from "./src/lib/error-boundary";
import { initLangFromServer, t, useLang } from "./src/i18n";
import { ChatPanel } from "./src/panels/chat";
import { HooksPanel } from "./src/panels/hooks";
import { McpPanel } from "./src/panels/mcp";
@@ -23,42 +24,50 @@ import { UsagePanel } from "./src/panels/usage";
const html = htm.bind(h);
const TAB_SECTIONS = [
{
label: "workspace",
tabs: [
{ id: "chat", name: "Chat", glyph: "◆", panel: () => html`<${ChatPanel} />` },
{ id: "plans", name: "Plans", glyph: "⊞", panel: () => html`<${PlansPanel} />` },
{ id: "sessions", name: "Sessions", glyph: "›", panel: () => html`<${SessionsPanel} />` },
],
},
{
label: "observe",
tabs: [
{ id: "overview", name: "Overview", glyph: "◈", panel: () => html`<${OverviewPanel} />` },
{ id: "usage", name: "Usage", glyph: "$", panel: () => html`<${UsagePanel} />` },
{ id: "health", name: "System", glyph: "+", panel: () => html`<${SystemPanel} />` },
{ id: "semantic", name: "Semantic", glyph: "≈", panel: () => html`<${SemanticPanel} />` },
],
},
{
label: "configure",
tabs: [
{ id: "tools", name: "Tools", glyph: "▣", panel: () => html`<${ToolsPanel} />` },
{ id: "permissions", name: "Permissions", glyph: "▎", panel: () => html`<${PermissionsPanel} />` },
{ id: "mcp", name: "MCP", glyph: "M", panel: () => html`<${McpPanel} />` },
{ id: "skills", name: "Skills", glyph: "S", panel: () => html`<${SkillsPanel} />` },
{ id: "memory", name: "Memory", glyph: "·", panel: () => html`<${MemoryPanel} />` },
{ id: "hooks", name: "Hooks", glyph: "H", panel: () => html`<${HooksPanel} />` },
{ id: "settings", name: "Settings", glyph: "⌘", panel: () => html`<${SettingsPanel} />` },
],
},
];
const ALL_TABS = TAB_SECTIONS.flatMap((s) => s.tabs);
function tabSections() {
return [
{
label: t("app.sectionWorkspace"),
tabs: [
{ id: "chat", name: t("app.tabChat"), glyph: "◆", panel: () => html`<${ChatPanel} />` },
{ id: "plans", name: t("app.tabPlans"), glyph: "⊞", panel: () => html`<${PlansPanel} />` },
{ id: "sessions", name: t("app.tabSessions"), glyph: "›", panel: () => html`<${SessionsPanel} />` },
],
},
{
label: t("app.sectionObserve"),
tabs: [
{ id: "overview", name: t("app.tabOverview"), glyph: "◈", panel: () => html`<${OverviewPanel} />` },
{ id: "usage", name: t("app.tabUsage"), glyph: "$", panel: () => html`<${UsagePanel} />` },
{ id: "health", name: t("app.tabSystem"), glyph: "+", panel: () => html`<${SystemPanel} />` },
{ id: "semantic", name: t("app.tabSemantic"), glyph: "≈", panel: () => html`<${SemanticPanel} />` },
],
},
{
label: t("app.sectionConfigure"),
tabs: [
{ id: "tools", name: t("app.tabTools"), glyph: "▣", panel: () => html`<${ToolsPanel} />` },
{ id: "permissions", name: t("app.tabPermissions"), glyph: "▎", panel: () => html`<${PermissionsPanel} />` },
{ id: "mcp", name: t("app.tabMcp"), glyph: "M", panel: () => html`<${McpPanel} />` },
{ id: "skills", name: t("app.tabSkills"), glyph: "S", panel: () => html`<${SkillsPanel} />` },
{ id: "memory", name: t("app.tabMemory"), glyph: "·", panel: () => html`<${MemoryPanel} />` },
{ id: "hooks", name: t("app.tabHooks"), glyph: "H", panel: () => html`<${HooksPanel} />` },
{ id: "settings", name: t("app.tabSettings"), glyph: "⌘", panel: () => html`<${SettingsPanel} />` },
],
},
];
}
function App() {
const [activeId, setActiveId] = useState("chat");
useLang();
useEffect(() => { initLangFromServer(); }, []);
const [activeId, setActiveId] = useState(() => {
try {
return localStorage.getItem("rx.activeTab") ?? "chat";
} catch {
return "chat";
}
});
const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
try {
return localStorage.getItem("rx.sidebarCollapsed") === "1";
@@ -73,7 +82,19 @@ function App() {
/* private mode / disabled storage — ignore */
}
}, [sidebarCollapsed]);
useEffect(() => {
try {
localStorage.setItem("rx.activeTab", activeId);
} catch {
/* private mode / disabled storage — ignore */
}
}, [activeId]);
const TAB_SECTIONS = tabSections();
const ALL_TABS = TAB_SECTIONS.flatMap((s) => s.tabs);
const active = ALL_TABS.find((t) => t.id === activeId) ?? ALL_TABS[0];
useEffect(() => {
if (active.id !== activeId) setActiveId(active.id);
}, [active.id, activeId]);
useEffect(() => {
const onNav = (ev) => {
@@ -135,7 +156,7 @@ function App() {
</div>
<footer class="app-status">
<span class="grow"></span>
<span class="item">127.0.0.1 only · token-gated</span>
<span class="item">${t("app.footer")}</span>
</footer>
</div>
<${ToastStack} />
+53 -44
View File
@@ -1,6 +1,7 @@
import { marked } from "marked";
import { useState } from "preact/hooks";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
import {
escapeHtml,
hlLine,
@@ -129,6 +130,7 @@ export function parseToolArgs(raw: string | null | undefined): Record<string, un
}
export function ToolCard({ msg }: ToolCardProps) {
useLang();
const args = parseToolArgs(msg.toolArgs);
const name = msg.toolName ?? "tool";
// Reasonix's filesystem tools emit the path in args.path; MCP-bridged
@@ -247,7 +249,7 @@ export function ToolCard({ msg }: ToolCardProps) {
</div>
${
args
? html`<details class="tool-card-args"><summary>arguments</summary><pre>${escapeHtml(JSON.stringify(args, null, 2))}</pre></details>`
? html`<details class="tool-card-args"><summary>${t("modal.arguments")}</summary><pre>${escapeHtml(JSON.stringify(args, null, 2))}</pre></details>`
: null
}
<pre class="tool-card-output">${msg.text}</pre>
@@ -301,31 +303,33 @@ export function ModalCard({ accent, icon, title, subtitle, children }: ModalCard
}
export function ShellModal({ modal, onResolve }: { modal: ShellModalSpec; onResolve: OnResolve }) {
useLang();
const isBg = modal.shellKind === "run_background";
return html`
<${ModalCard}
accent="#f87171"
icon=${isBg ? "⏱" : "⚡"}
title=${isBg ? "background process" : "shell command"}
title=${isBg ? t("modal.shellBgTitle") : t("modal.shellTitle")}
subtitle=${
isBg ? "long-running — keeps running after approval" : "model wants to run a shell command"
isBg ? t("modal.shellBgSubtitle") : t("modal.shellSubtitle")
}
>
<div class="modal-cmd"><span class="modal-cmd-prompt">$</span> <code>${modal.command}</code></div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("shell", "run_once")}>Run once</button>
<button onClick=${() => onResolve("shell", "always_allow")}>Always allow "${modal.allowPrefix}"</button>
<button class="danger" onClick=${() => onResolve("shell", "deny")}>Deny</button>
<button class="primary" onClick=${() => onResolve("shell", "run_once")}>${t("modal.runOnce")}</button>
<button onClick=${() => onResolve("shell", "always_allow")}>${t("modal.alwaysAllow", { prefix: modal.allowPrefix ?? "" })}</button>
<button class="danger" onClick=${() => onResolve("shell", "deny")}>${t("modal.deny")}</button>
</div>
<//>
`;
}
export function ChoiceModal({ modal, onResolve }: { modal: ChoiceModalSpec; onResolve: OnResolve }) {
useLang();
const [custom, setCustom] = useState("");
const [showCustom, setShowCustom] = useState(false);
return html`
<${ModalCard} accent="#f0abfc" icon="🔀" title="model wants you to pick" subtitle=${modal.question}>
<${ModalCard} accent="#f0abfc" icon="🔀" title=${t("modal.choiceTitle")} subtitle=${modal.question}>
${modal.options.map(
(opt: ChoiceOption) => html`
<button
@@ -345,44 +349,45 @@ export function ChoiceModal({ modal, onResolve }: { modal: ChoiceModalSpec; onRe
? html`
<div class="modal-custom">
<textarea
placeholder="Type a free-form answer…"
placeholder=${t("modal.typePlaceholder")}
rows="2"
value=${custom}
onInput=${(e: Event) => setCustom((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("choice", { kind: "custom", text: custom })} disabled=${!custom.trim()}>Send</button>
<button class="primary" onClick=${() => onResolve("choice", { kind: "custom", text: custom })} disabled=${!custom.trim()}>${t("modal.send")}</button>
<button onClick=${() => {
setShowCustom(false);
setCustom("");
}}>Back</button>
}}>${t("common.back")}</button>
</div>
</div>
`
: html`
<button class="modal-choice-row" onClick=${() => setShowCustom(true)}>
<span class="modal-choice-id">·</span>
<span class="modal-choice-title">Type my own answer</span>
<span class="modal-choice-summary">None of the above fits — write a free-form reply.</span>
<span class="modal-choice-title">${t("modal.typeOwn")}</span>
<span class="modal-choice-summary">${t("modal.typeOwnSummary")}</span>
</button>
`
: null
}
<button class="modal-choice-row modal-choice-cancel" onClick=${() => onResolve("choice", { kind: "cancel" })}>
<span class="modal-choice-id">×</span>
<span class="modal-choice-title">Cancel</span>
<span class="modal-choice-summary">Drop the question. Model will ask what you actually want.</span>
<span class="modal-choice-title">${t("modal.cancel")}</span>
<span class="modal-choice-summary">${t("modal.cancelSummary")}</span>
</button>
<//>
`;
}
export function PlanModal({ modal, onResolve }: { modal: PlanModalSpec; onResolve: OnResolve }) {
useLang();
const [feedback, setFeedback] = useState("");
const [stage, setStage] = useState<"approve" | "refine" | null>(null);
const send = () => onResolve("plan", stage, feedback);
return html`
<${ModalCard} accent="#67e8f9" icon="◆" title="plan submitted" subtitle="model proposed a plan; review then pick">
<${ModalCard} accent="#67e8f9" icon="◆" title=${t("modal.planTitle")} subtitle=${t("modal.planSubtitle")}>
<div class="md modal-plan-body" dangerouslySetInnerHTML=${{ __html: marked.parse(modal.body || "") }}></div>
${
stage
@@ -390,26 +395,26 @@ export function PlanModal({ modal, onResolve }: { modal: PlanModalSpec; onResolv
<textarea
placeholder=${
stage === "approve"
? "Optional last instructions / answers to open questions (Enter to send blank)"
: "What needs to change? Be specific."
? t("modal.approveInstructions")
: t("modal.refinePlaceholder")
}
rows="3"
value=${feedback}
onInput=${(e: Event) => setFeedback((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${send}>${stage === "approve" ? "Approve" : "Send refinement"}</button>
<button class="primary" onClick=${send}>${stage === "approve" ? t("modal.approve") : t("modal.sendRefinement")}</button>
<button onClick=${() => {
setStage(null);
setFeedback("");
}}>Back</button>
}}>${t("common.back")}</button>
</div>
`
: html`
<div class="modal-actions">
<button class="primary" onClick=${() => setStage("approve")}>Approve</button>
<button onClick=${() => setStage("refine")}>Refine</button>
<button class="danger" onClick=${() => onResolve("plan", "cancel")}>Cancel</button>
<button class="primary" onClick=${() => setStage("approve")}>${t("modal.approve")}</button>
<button onClick=${() => setStage("refine")}>${t("modal.refine")}</button>
<button class="danger" onClick=${() => onResolve("plan", "cancel")}>${t("modal.cancel")}</button>
</div>
`
}
@@ -489,6 +494,7 @@ function pairDiffRows(diff: DiffEntry[]): DiffPair[] {
}
export function EditReviewModal({ modal, onResolve }: { modal: EditReviewSpec; onResolve: OnResolve }) {
useLang();
const search = modal.search ?? "";
const replace = modal.replace ?? "";
const lang = langFromPath(modal.path);
@@ -500,16 +506,16 @@ export function EditReviewModal({ modal, onResolve }: { modal: EditReviewSpec; o
<${ModalCard}
accent="#86efac"
icon="◆"
title="edit pending review"
subtitle=${`${modal.path} · ${modal.remaining} of ${modal.total} blocks remaining`}
title=${t("modal.editTitle")}
subtitle=${t("modal.editSubtitle", { path: modal.path ?? "", remaining: modal.remaining, total: modal.total })}
>
<div class="edit-diff-wrap">
<div class="edit-diff-head">
<div class="edit-diff-side edit-diff-side-old">
<span class="edit-diff-marker">−</span> before
<span class="edit-diff-marker">−</span> ${t("modal.before")}
</div>
<div class="edit-diff-side edit-diff-side-new">
<span class="edit-diff-marker">+</span> after
<span class="edit-diff-marker">+</span> ${t("modal.after")}
</div>
</div>
<div class="edit-diff-body">
@@ -542,33 +548,35 @@ export function EditReviewModal({ modal, onResolve }: { modal: EditReviewSpec; o
</div>
</div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("edit-review", "apply")}>Apply (y)</button>
<button onClick=${() => onResolve("edit-review", "reject")}>Reject (n)</button>
<button onClick=${() => onResolve("edit-review", "apply-rest-of-turn")}>Apply rest (a)</button>
<button onClick=${() => onResolve("edit-review", "flip-to-auto")}>Flip to AUTO (A)</button>
<button class="primary" onClick=${() => onResolve("edit-review", "apply")}>${t("chat.confirmBtn")}</button>
<button onClick=${() => onResolve("edit-review", "reject")}>${t("chat.rejectBtn")}</button>
<button onClick=${() => onResolve("edit-review", "apply-rest-of-turn")}>${t("chat.applyRestBtn")}</button>
<button onClick=${() => onResolve("edit-review", "flip-to-auto")}>${t("chat.flipAutoBtn")}</button>
</div>
<//>
`;
}
export function WorkspaceModal({ modal, onResolve }: { modal: WorkspaceSpec; onResolve: OnResolve }) {
useLang();
return html`
<${ModalCard}
accent="#fbbf24"
icon="◇"
title="model wants to switch workspace"
subtitle="every subsequent file / shell / memory tool resolves against the new root"
title=${t("modal.workspaceTitle")}
subtitle=${t("modal.workspaceSubtitle")}
>
<div class="modal-cmd"><span class="modal-cmd-prompt">→</span> <code>${modal.path}</code></div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("workspace", "switch")}>Switch (Enter)</button>
<button class="danger" onClick=${() => onResolve("workspace", "deny")}>Deny (Esc)</button>
<button class="primary" onClick=${() => onResolve("workspace", "switch")}>${t("modal.switchBtn")}</button>
<button class="danger" onClick=${() => onResolve("workspace", "deny")}>${t("modal.denyBtn")}</button>
</div>
<//>
`;
}
export function CheckpointModal({ modal, onResolve }: { modal: CheckpointSpec; onResolve: OnResolve }) {
useLang();
const [reviseText, setReviseText] = useState("");
const [staged, setStaged] = useState(false);
const label = modal.title ? `${modal.stepId} · ${modal.title}` : modal.stepId;
@@ -577,31 +585,31 @@ export function CheckpointModal({ modal, onResolve }: { modal: CheckpointSpec; o
<${ModalCard}
accent="#a5f3fc"
icon="✓"
title=${`step complete${counter}`}
title=${t("modal.stepComplete", { counter })}
subtitle=${label}
>
${
staged
? html`
<textarea
placeholder="What needs to change before the next step? Leave blank to just continue."
placeholder=${t("modal.revisePlaceholder")}
rows="3"
value=${reviseText}
onInput=${(e: Event) => setReviseText((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("checkpoint", "revise", reviseText)}>Send revision</button>
<button class="primary" onClick=${() => onResolve("checkpoint", "revise", reviseText)}>${t("modal.sendRevision")}</button>
<button onClick=${() => {
setStaged(false);
setReviseText("");
}}>Back</button>
}}>${t("common.back")}</button>
</div>
`
: html`
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("checkpoint", "continue")}>Continue</button>
<button onClick=${() => setStaged(true)}>Revise…</button>
<button class="danger" onClick=${() => onResolve("checkpoint", "stop")}>Stop</button>
<button class="primary" onClick=${() => onResolve("checkpoint", "continue")}>${t("modal.continueBtn")}</button>
<button onClick=${() => setStaged(true)}>${t("modal.reviseBtn")}</button>
<button class="danger" onClick=${() => onResolve("checkpoint", "stop")}>${t("modal.stopBtn")}</button>
</div>
`
}
@@ -610,13 +618,14 @@ export function CheckpointModal({ modal, onResolve }: { modal: CheckpointSpec; o
}
export function RevisionModal({ modal, onResolve }: { modal: RevisionSpec; onResolve: OnResolve }) {
useLang();
const riskColor = (r: string | undefined) =>
r === "high" ? "#f87171" : r === "med" ? "#fbbf24" : r === "low" ? "#86efac" : "#9ca3af";
return html`
<${ModalCard}
accent="#c4b5fd"
icon="✎"
title="model proposed a plan revision"
title=${t("modal.revisionTitle")}
subtitle=${modal.summary || modal.reason}
>
<div class="modal-revise-reason">${modal.reason}</div>
@@ -633,8 +642,8 @@ export function RevisionModal({ modal, onResolve }: { modal: RevisionSpec; onRes
)}
</ol>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("revision", "accept")}>Accept</button>
<button class="danger" onClick=${() => onResolve("revision", "reject")}>Reject</button>
<button class="primary" onClick=${() => onResolve("revision", "accept")}>${t("modal.accept")}</button>
<button class="danger" onClick=${() => onResolve("revision", "reject")}>${t("modal.reject")}</button>
</div>
<//>
`;
+485
View File
@@ -0,0 +1,485 @@
export const en = {
app: {
sectionWorkspace: "workspace",
sectionObserve: "observe",
sectionConfigure: "configure",
tabChat: "Chat",
tabPlans: "Plans",
tabSessions: "Sessions",
tabOverview: "Overview",
tabUsage: "Usage",
tabSystem: "System",
tabSemantic: "Semantic",
tabTools: "Tools",
tabPermissions: "Permissions",
tabMcp: "MCP",
tabSkills: "Skills",
tabMemory: "Memory",
tabHooks: "Hooks",
tabSettings: "Settings",
footer: "127.0.0.1 only · token-gated",
},
common: {
loading: "loading…",
loadingFailed: "{name} failed: {error}",
back: "← back",
save: "Save",
remove: "remove",
cancel: "Cancel",
delete: "Delete",
add: "Add",
confirm: "Confirm",
noData: "No {name} yet.",
all: "all",
yes: "yes",
no: "no",
on: "ON",
off: "off",
enabled: "enabled",
disabled: "disabled",
},
settings: {
title: "Settings",
loading: "loading settings…",
saved: "saved: {fields}",
sectionApi: "DeepSeek API",
apiKey: "API key",
notSet: "(not set)",
replace: "replace",
pasteKey: "paste a fresh sk-… token",
saveKey: "Save key",
baseUrl: "base url",
baseUrlPlaceholder: "https://api.deepseek.com (default)",
sectionDefaults: "Defaults",
preset: "preset",
presetAuto: "auto — flash → pro on hard turns",
presetFlash: "flash — always flash, no auto-escalate",
presetPro: "pro — always pro",
appliesNextTurn: "applies next turn",
effort: "effort",
effortMax: "max (default — best)",
effortHigh: "high (cheaper / faster)",
webSearch: "web search",
webSearchNote: "web_fetch + web_search tools",
sectionRuntime: "Runtime",
activeModel: "active model",
editMode: "edit mode",
editModeNote: "switch from the Chat tab header",
sectionLanguage: "Language",
language: "language",
langEn: "English",
langZhCn: "简体中文",
},
chat: {
modeMirror: "TUI mirror",
modeView: "session view",
placeholder: "Type a prompt — Enter sends, Shift+Enter for a newline · / @ for pickers",
placeholderBusy: "wait for the current turn to finish…",
send: "Send",
new: "New",
clear: "Clear",
newTitle: "/new — wipe conversation context (loop log + scrollback)",
clearTitle: "/clear — wipe just visible scrollback (context kept)",
noConversation: "No conversation yet. Send a prompt below to begin.",
newConfirmBusy: "A turn is in flight. Abort and start a new conversation?",
newConfirm: "Clear current conversation and start fresh?",
newToast: "new conversation",
clearToast: "scrollback cleared",
newFailed: "/new failed: {error}",
clearFailed: "/clear failed: {error}",
eventStreamError: "event stream interrupted — reconnecting…",
semanticBanner: "Semantic search isn't enabled for this project.",
semanticBannerDesc: "Build the index once and the model can find code by meaning (\"where do we handle auth failures?\") instead of grep on exact strings.",
semanticBannerBtn: "Build it →",
semanticBannerDismiss: "dismiss (don't show again)",
slashCommands: "slash commands",
projectFiles: "project files",
effortTitle: "reasoning_effort — applies next turn",
effortMaxTitle: "max (default — best quality)",
effortHighTitle: "high (cheaper / faster)",
presetTitle: "preset — model commitment",
presetAutoTitle: "auto — flash baseline; auto-escalates to pro on hard turns (NEEDS_PRO / failure threshold)",
presetFlashTitle: "flash — always flash; no auto-escalate. /pro still works for one-shot manual",
presetProTitle: "pro — always pro; ~3× flash cost (5/31 discount). Locks in on hard architecture work.",
editGateTitle: "edit gate — Shift+Tab cycles in TUI",
editReviewTitle: "review — both edits and non-allowlisted shell ask first",
editAutoTitle: "auto — edits auto-apply, shell still asks",
editYoloTitle: "yolo — edits AND shell auto-run, allowlist bypassed",
railSession: "Session",
railTurns: "turns",
railPromptTok: "prompt tok",
railCost: "cost",
railCacheHit: "cache hit",
railToolBudget: "Tool budget",
railSpend: "spend",
railActivePlan: "Active plan",
railProgress: "progress",
statusModel: "model",
statusCtx: "ctx",
statusCache: "cache",
statusTurn: "turn",
statusSession: "session",
statusBalance: "balance",
statusTurns: "{count} turn{s}",
waitingStats: "· · · waiting for live stats",
inflightPhase: "{phase}",
inflightRunning: "running",
inflightThinking: "thinking",
inflightStreaming: "streaming",
inflightWaiting: "waiting",
inflightReasoning: "reasoning {count} ch",
inflightOut: "out {count} ch",
abortBtn: "Abort (Esc)",
confirmBtn: "Apply (y)",
rejectBtn: "Reject (n)",
applyRestBtn: "Apply rest (a)",
flipAutoBtn: "Flip to AUTO (A)",
},
overview: {
loading: "loading overview…",
failed: "overview failed: {error}",
standaloneTitle: "Standalone mode",
standaloneDesc: "Read-only disk view. Start /dashboard from inside reasonix code for live session state, MCP, and tools.",
cockpit: "Cockpit",
balance: "balance",
tokens7d: "tokens · 7d",
cacheHit: "cache hit",
toolCalls24h: "tool calls · 24h",
currentSession: "current session",
noSession: "No live session — /dashboard from inside reasonix code to attach.",
promptTok: "prompt tok",
completionTok: "completion tok",
cost: "cost",
costTrend: "cost · 14 day",
noUsageYet: "no usage yet",
dayAvg: "/day avg",
recentPlans: "recent plans",
noPlans: "No plans yet — submit one with submit_plan.",
toolActivity: "tool activity",
noToolCalls: "No tool calls yet.",
toolsLoaded: "tools loaded",
mcpServers: "mcp servers",
editMode: "edit mode",
version: "Reasonix",
workingDir: "Working directory",
projectRoot: "project root",
noPriorData: "no prior data",
stable: "— stable",
vsPrior: "{arrow} {pct}% vs prior",
active: "active",
allUp: "all up",
yoloWarning: "all prompts bypassed",
checking: "checking",
latest: "latest",
},
usage: {
loading: "loading usage…",
failed: "usage failed: {error}",
records: "{count} records",
dailyUsage: "Daily usage",
dailyMeta: "cost · cache saved · turns",
noData: "No usage data yet — run a turn in reasonix chat / code / run and refresh.",
windows: "Rolling windows",
colTurns: "turns",
colCacheHit: "cache hit",
colCost: "cost (USD)",
colCacheSaved: "cache saved",
colVsClaude: "vs Claude",
colSaved: "saved",
mostUsed: "Most used models",
colModel: "model",
},
sessions: {
loading: "loading sessions…",
failed: "sessions failed: {error}",
noSessions: "No saved sessions yet.",
filterPlaceholder: "filter sessions",
msgs: "msgs",
pickHint: "Pick a session on the left to read its transcript.",
resumeTitle: "Resume in TUI",
resumeDesc: "Mid-session swap requires a restart so the message log can rewind cleanly. Quit your current session, then run:",
loadingTranscript: "loading transcript…",
emptyTranscript: "empty transcript.",
messages: "{count} message{s}",
},
tools: {
loading: "loading tools…",
failed: "tools failed: {error}",
noTools: "No tools registered.",
planMode: "plan mode — writes gated",
colTool: "tool",
colFlags: "flags",
colDesc: "description",
readOnly: "read-only",
write: "write",
flat: "flat",
},
permissions: {
loading: "loading permissions…",
failed: "permissions failed: {error}",
yoloTitle: "YOLO mode",
yoloDesc: "Every shell command auto-runs, allowlist bypassed. Switch back with /mode review in the TUI.",
project: "project",
builtin: "builtin",
addPrefix: "add a prefix",
addPlaceholder: "e.g. \"npm run build\" or \"deploy.sh\"",
clearAll: "Clear all",
alreadyIn: "{prefix} already in list",
added: "added: {prefix}",
removed: "removed: {prefix}",
cleared: "cleared {count} entr{y}",
removeConfirm: "Remove \"{prefix}\" from this project's allowlist?",
clearConfirm: "Wipe every project allowlist entry? Builtin entries are unaffected.",
projectAllowlist: "Project allowlist · {count}",
nothingStored: "Nothing stored yet for this project.",
colNum: "#",
colPrefix: "prefix",
builtinTitle: "Builtin · {count} · read-only",
standaloneWarning: "Mutations require /dashboard from inside an active reasonix code session — standalone reasonix dashboard can't tell which project's allowlist to edit.",
},
mcp: {
loading: "loading MCP…",
servers: "MCP servers · {count} bridged",
all: "all",
live: "live",
unbridged: "unbridged",
specPlaceholder: "spec — e.g. fs=npx -y @modelcontextprotocol/...",
saved: "saved",
savedRestart: "saved — restart reasonix code to bridge this server",
removed: "removed — restart to drop the live bridge",
removeConfirm: "Remove MCP spec from config?\n\n{spec}",
noServers: "No MCP servers in this session.",
tools: "tools",
inConfig: "in config · not loaded",
unbridgedTitle: "unbridged · in config",
removeBtn: "Remove",
spec: "spec",
whyUnbridged: "Why unbridged?",
whyUnbridgedDesc: "This spec lives in your config.json but isn't bridged into the live session. MCP servers attach when reasonix code starts; the dashboard alone can't spawn the child process.",
whyUnbridgedHint: "To activate: restart reasonix code, then refresh this dashboard.",
pickHint: "Pick an MCP server on the left to inspect tools / resources / prompts.",
toolsTitle: "Tools · {count}",
resourcesTitle: "Resources · {count}",
promptsTitle: "Prompts · {count}",
colName: "name",
colDesc: "description",
colUri: "uri",
},
memory: {
loading: "loading memory…",
files: "memory · {count} files",
exists: "exists",
create: "create",
noFiles: "No memory files yet.",
pickHint: "Pick a memory file on the left.",
pickDesc: "Project REASONIX.md is committable; global notes live in ~/.reasonix/memory/.",
chars: "{count} chars",
saved: "saved {scope}",
reloadHint: "re-applied on next /new or session restart",
},
hooks: {
loading: "loading hooks…",
resolved: "resolved",
eventMatrix: "Event matrix",
matrixSub: "{scripts} script{s} × {events} event{s}",
noHooks: "No hooks configured. Edit the JSON below to add some.",
colScript: "script",
noProject: "No active project — open /dashboard from reasonix code to edit project hooks.",
saveReload: "Save + Reload",
discard: "Discard changes",
savedReloaded: "saved + reloaded {scope}",
recentRuns: "Recent runs",
noRuns: "No hook runs in the recent session log.",
colWhen: "when",
colPhase: "phase",
colHook: "hook",
colOutcome: "outcome",
},
skills: {
loading: "loading skills…",
filterPlaceholder: "filter skills",
project: "project",
global: "global",
builtin: "builtin",
newSkill: "new skill",
noDescription: "(no description)",
runs7d: "runs · 7d",
pickHint: "Pick a skill on the left, or create a new one above.",
readOnlyBuiltin: "read-only · builtin",
builtinDesc: "Built-in skills ship with Reasonix; the model picks them up automatically. To customize, create a project- or global-scoped skill with the same name.",
saved: "saved {scope}/{name}",
deleteConfirm: "Delete skill {scope}/{name}?",
reloadHint: "re-loaded on next /new or session restart",
},
system: {
loading: "loading health…",
failed: "health failed: {error}",
healthChecks: "Health checks",
version: "version",
checking: "checking",
latest: "● latest",
outOfDate: "● out of date",
versionPending: "version check pending",
upToDate: "up to date",
latestVer: "latest: {version}",
sessions: "sessions",
ok: "● ok",
memory: "memory",
semanticIndex: "semantic index",
built: "● built",
none: "— none",
runIndex: "run reasonix index to build",
usageLog: "usage log",
backgroundJobs: "background jobs",
noSession: "— no session",
running: "{count} running",
attachHint: "attach a session to see jobs",
shellSpawn: "shell + spawn",
paths: "paths",
home: "home",
sessionsPath: "sessions",
memoryPath: "memory",
semanticPath: "semantic",
usagePath: "usage",
},
plans: {
loading: "loading plans…",
failed: "plans failed: {error}",
noPlans: "No archived plans yet — run a turn that calls submit_plan and mark_step_complete.",
filterPlaceholder: "filter plans",
active: "active",
done: "done",
steps: "steps",
pickHint: "Pick a plan on the left.",
noTitle: "(no title)",
stepTimeline: "Step timeline · {done} / {total}",
step: "step {n}",
},
semantic: {
codeRequired: "Semantic — code-mode required",
indexBuilt: "index built",
noIndex: "no index yet",
ready: "ready",
setupNeeded: "setup needed",
installOllama: "Install Ollama",
installOllamaDesc: "Reasonix doesn't run package managers for you. Install Ollama first, then come back:",
macWindows: "macOS / Windows:",
download: "download from ollama.com/download",
linux: "Linux:",
refreshHint: "Refresh after install — this panel will offer to start the daemon and pull {model}.",
daemon: "Daemon",
daemonDesc: "ollama is on your PATH but the HTTP daemon isn't reachable.",
startDaemon: "Start daemon",
runsOllama: "runs ollama serve detached",
model: "Model",
modelMissing: "{model} isn't installed yet.",
modelSize: "~270 MB on first pull.",
pulling: "pulling…",
pullModel: "Pull {model}",
indexStatus: "index status",
builtStatus: "● built",
chunks: "chunks",
files: "files",
dim: "dim",
size: "size",
lastBuild: "last build",
runIndexHint: "Run an index to enable semantic_search.",
reIndex: "Re-index",
build: "Build",
rebuild: "Rebuild",
stop: "Stop",
ollama: "ollama",
binary: "binary",
found: "found",
missing: "missing",
daemonStatus: "daemon",
up: "up",
down: "down",
pulled: "pulled",
indexConfig: "index config",
reset: "reset",
excludeDirs: "exclude dirs",
excludeFiles: "exclude files",
excludeExts: "exclude exts",
excludePatterns: "exclude patterns",
glob: "glob",
respectGitignore: "respect .gitignore",
maxFileBytes: "max file bytes",
skipLarger: "skip files larger than ~{size} MiB",
preview: "Preview",
searchPlaceholder: "describe what to find — 'where do we handle abort signals'",
searching: "searching…",
results: "{count} result{s} · {ms}ms · {model}",
noMatches: "No matches above the score threshold.",
previewSummary: "Preview — would index {included} file(s), skip {skipped}",
nothingSkipped: "nothing skipped — all walked files would be indexed.",
firstIncluded: "first {count} included file(s)",
job: "Job",
phaseScan: "scanning files",
phaseEmbed: "embedding chunks",
phaseWrite: "writing index",
phaseDone: "done",
phaseError: "error",
stopping: "stopping",
scanned: "scanned {count}",
changed: "changed {count}",
skipped: "skipped {count}",
chunksProgress: "{done} / {total} ({pct}%)",
result: "result",
added: "added {count}",
removed: "removed {count}",
failed: "failed {count}",
skippedFiles: "{total} files ({details})",
rebuildStarted: "rebuild started",
incrementalStarted: "incremental index started",
stopRequested: "stopping requested — current chunk batch will finish first",
startingDaemon: "starting ollama daemon (15s timeout)…",
daemonUp: "daemon is up",
daemonTimeout: "daemon didn't come up in time — check ollama serve manually",
pullingModel: "pulling {model} — this may take a few minutes on first install",
savedConfig: "saved · {count} fields updated · re-run index to apply",
runningPreview: "running dry walk against project root…",
exclude: "exclude",
},
modal: {
shellTitle: "shell command",
shellBgTitle: "background process",
shellSubtitle: "model wants to run a shell command",
shellBgSubtitle: "long-running — keeps running after approval",
runOnce: "Run once",
alwaysAllow: "Always allow \"{prefix}\"",
deny: "Deny",
choiceTitle: "model wants you to pick",
typeOwn: "Type my own answer",
typeOwnSummary: "None of the above fits — write a free-form reply.",
typePlaceholder: "Type a free-form answer…",
send: "Send",
cancel: "Cancel",
cancelSummary: "Drop the question. Model will ask what you actually want.",
planTitle: "plan submitted",
planSubtitle: "model proposed a plan; review then pick",
approveInstructions: "Optional last instructions / answers to open questions (Enter to send blank)",
refinePlaceholder: "What needs to change? Be specific.",
approve: "Approve",
refine: "Refine",
sendRefinement: "Send refinement",
editTitle: "edit pending review",
editSubtitle: "{path} · {remaining} of {total} blocks remaining",
before: "before",
after: "after",
workspaceTitle: "model wants to switch workspace",
workspaceSubtitle: "every subsequent file / shell / memory tool resolves against the new root",
switchBtn: "Switch (Enter)",
denyBtn: "Deny (Esc)",
stepComplete: "step complete{counter}",
continueBtn: "Continue",
reviseBtn: "Revise…",
stopBtn: "Stop",
revisionTitle: "model proposed a plan revision",
sendRevision: "Send revision",
accept: "Accept",
reject: "Reject",
arguments: "arguments",
revisePlaceholder: "What needs to change before the next step? Leave blank to just continue.",
},
};
+8
View File
@@ -0,0 +1,8 @@
import { createT } from "../lib/i18n.js";
import { en } from "./en.js";
import { zhCN } from "./zh-CN.js";
export { getLang, initLangFromServer, setLang, useLang, onLangChange } from "../lib/i18n.js";
export type { DashboardLang } from "../lib/i18n.js";
export const t = createT({ en, "zh-CN": zhCN });
+485
View File
@@ -0,0 +1,485 @@
export const zhCN = {
app: {
sectionWorkspace: "工作区",
sectionObserve: "监控",
sectionConfigure: "配置",
tabChat: "对话",
tabPlans: "计划",
tabSessions: "会话",
tabOverview: "概览",
tabUsage: "用量",
tabSystem: "系统",
tabSemantic: "语义",
tabTools: "工具",
tabPermissions: "权限",
tabMcp: "MCP",
tabSkills: "技能",
tabMemory: "记忆",
tabHooks: "钩子",
tabSettings: "设置",
footer: "仅 127.0.0.1 · Token 保护",
},
common: {
loading: "加载中…",
loadingFailed: "{name}失败:{error}",
back: "← 返回",
save: "保存",
remove: "移除",
cancel: "取消",
delete: "删除",
add: "添加",
confirm: "确认",
noData: "暂无{name}。",
all: "全部",
yes: "是",
no: "否",
on: "开启",
off: "关闭",
enabled: "已启用",
disabled: "已禁用",
},
settings: {
title: "设置",
loading: "加载设置…",
saved: "已保存:{fields}",
sectionApi: "DeepSeek API",
apiKey: "API 密钥",
notSet: "(未设置)",
replace: "替换",
pasteKey: "粘贴新的 sk-… 令牌",
saveKey: "保存密钥",
baseUrl: "基础 URL",
baseUrlPlaceholder: "https://api.deepseek.com(默认)",
sectionDefaults: "默认设置",
preset: "预设",
presetAuto: "auto — flash 基线,困难时自动升级为 pro",
presetFlash: "flash — 始终使用 flash,不自动升级",
presetPro: "pro — 始终使用 pro",
appliesNextTurn: "下一轮生效",
effort: "推理强度",
effortMax: "max(默认 — 最佳质量)",
effortHigh: "high(更便宜 / 更快)",
webSearch: "网页搜索",
webSearchNote: "web_fetch + web_search 工具",
sectionRuntime: "运行时",
activeModel: "当前模型",
editMode: "编辑模式",
editModeNote: "在对话标签页头部切换",
sectionLanguage: "语言",
language: "语言",
langEn: "English",
langZhCn: "简体中文",
},
chat: {
modeMirror: "TUI 镜像",
modeView: "会话视图",
placeholder: "输入提示词 — Enter 发送,Shift+Enter 换行 · / @ 打开选择器",
placeholderBusy: "请等待当前轮次完成…",
send: "发送",
new: "新建",
clear: "清除",
newTitle: "/new — 清除对话上下文(循环日志 + 滚动回放)",
clearTitle: "/clear — 仅清除可见的滚动回放(上下文保留)",
noConversation: "暂无对话。在下方发送提示词开始。",
newConfirmBusy: "有轮次正在执行。中止并开始新对话?",
newConfirm: "清除当前对话并重新开始?",
newToast: "新对话",
clearToast: "滚动回放已清除",
newFailed: "/new 失败:{error}",
clearFailed: "/clear 失败:{error}",
eventStreamError: "事件流中断 — 正在重连…",
semanticBanner: "此项目未启用语义搜索。",
semanticBannerDesc: "构建一次索引,模型即可按含义查找代码(“哪里处理认证失败?”),而不仅依赖精确字符串的 grep。",
semanticBannerBtn: "构建 →",
semanticBannerDismiss: "关闭(不再显示)",
slashCommands: "斜杠命令",
projectFiles: "项目文件",
effortTitle: "reasoning_effort — 下一轮生效",
effortMaxTitle: "max(默认 — 最佳质量)",
effortHighTitle: "high(更便宜 / 更快)",
presetTitle: "预设 — 模型承诺",
presetAutoTitle: "auto — flash 基线;困难轮次自动升级为 pro(NEEDS_PRO / 失败阈值)",
presetFlashTitle: "flash — 始终 flash;不自动升级。/pro 仍可用于一次性手动提升",
presetProTitle: "pro — 始终 pro;约 3 倍 flash 成本(5/31 折扣)。锁定困难的架构工作。",
editGateTitle: "编辑门控 — Shift+Tab 在 TUI 中循环",
editReviewTitle: "review — 编辑和非允许列表的 shell 命令都会先询问",
editAutoTitle: "auto — 编辑自动应用,shell 仍会询问",
editYoloTitle: "yolo — 编辑和 shell 都自动运行,绕过允许列表",
railSession: "会话",
railTurns: "轮次",
railPromptTok: "提示 tokens",
railCost: "费用",
railCacheHit: "缓存命中",
railToolBudget: "工具预算",
railSpend: "已用",
railActivePlan: "活跃计划",
railProgress: "进度",
statusModel: "模型",
statusCtx: "上下文",
statusCache: "缓存",
statusTurn: "轮次",
statusSession: "会话",
statusBalance: "余额",
statusTurns: "{count} 轮",
waitingStats: "· · · 等待实时统计",
inflightPhase: "{phase}",
inflightRunning: "运行中",
inflightThinking: "思考中",
inflightStreaming: "输出中",
inflightWaiting: "等待中",
inflightReasoning: "推理 {count} 字符",
inflightOut: "输出 {count} 字符",
abortBtn: "中止 (Esc)",
confirmBtn: "应用 (y)",
rejectBtn: "拒绝 (n)",
applyRestBtn: "应用剩余 (a)",
flipAutoBtn: "切换为 AUTO (A)",
},
overview: {
loading: "加载概览…",
failed: "概览失败:{error}",
standaloneTitle: "独立模式",
standaloneDesc: "只读磁盘视图。在 reasonix code 内启动 /dashboard 以获取实时会话状态、MCP 和工具。",
cockpit: "驾驶舱",
balance: "余额",
tokens7d: "tokens · 7 天",
cacheHit: "缓存命中",
toolCalls24h: "工具调用 · 24 小时",
currentSession: "当前会话",
noSession: "无活跃会话 — 在 reasonix code 内执行 /dashboard 进行连接。",
promptTok: "提示 tokens",
completionTok: "补全 tokens",
cost: "费用",
costTrend: "费用 · 14 天",
noUsageYet: "暂无用量",
dayAvg: "/天 均值",
recentPlans: "近期计划",
noPlans: "暂无计划 — 使用 submit_plan 提交一个。",
toolActivity: "工具活动",
noToolCalls: "暂无工具调用。",
toolsLoaded: "已加载工具",
mcpServers: "MCP 服务器",
editMode: "编辑模式",
version: "Reasonix",
workingDir: "工作目录",
projectRoot: "项目根目录",
noPriorData: "无历史数据",
stable: "— 稳定",
vsPrior: "{arrow} {pct}% 较上期",
active: "活跃",
allUp: "全部在线",
yoloWarning: "所有提示被绕过",
checking: "检查中",
latest: "最新",
},
usage: {
loading: "加载用量…",
failed: "用量失败:{error}",
records: "{count} 条记录",
dailyUsage: "每日用量",
dailyMeta: "费用 · 缓存节省 · 轮次",
noData: "暂无用量数据 — 在 reasonix chat / code / run 中执行一轮,然后刷新。",
windows: "滚动窗口",
colTurns: "轮次",
colCacheHit: "缓存命中",
colCost: "费用 (USD)",
colCacheSaved: "缓存节省",
colVsClaude: "对比 Claude",
colSaved: "节省",
mostUsed: "最常用模型",
colModel: "模型",
},
sessions: {
loading: "加载会话…",
failed: "会话失败:{error}",
noSessions: "暂无已保存的会话。",
filterPlaceholder: "筛选会话",
msgs: "条消息",
pickHint: "选择左侧的会话以查看其转录稿。",
resumeTitle: "在 TUI 中恢复",
resumeDesc: "会话中途切换需要重启,以便消息日志可以干净地回退。请退出当前会话,然后运行:",
loadingTranscript: "加载转录稿…",
emptyTranscript: "空的转录稿。",
messages: "{count} 条消息",
},
tools: {
loading: "加载工具…",
failed: "工具失败:{error}",
noTools: "未注册任何工具。",
planMode: "计划模式 — 写入受限",
colTool: "工具",
colFlags: "标志",
colDesc: "描述",
readOnly: "只读",
write: "写入",
flat: "扁平",
},
permissions: {
loading: "加载权限…",
failed: "权限失败:{error}",
yoloTitle: "YOLO 模式",
yoloDesc: "所有 shell 命令自动运行,允许列表被绕过。在 TUI 中使用 /mode review 切换回来。",
project: "项目",
builtin: "内置",
addPrefix: "添加前缀",
addPlaceholder: "例如 \"npm run build\" 或 \"deploy.sh\"",
clearAll: "清除全部",
alreadyIn: "{prefix} 已在列表中",
added: "已添加:{prefix}",
removed: "已移除:{prefix}",
cleared: "已清除 {count} 条",
removeConfirm: "从此项目的允许列表中移除 \"{prefix}\"?",
clearConfirm: "清除所有项目允许列表条目?内置条目不受影响。",
projectAllowlist: "项目允许列表 · {count}",
nothingStored: "此项目暂无存储的条目。",
colNum: "#",
colPrefix: "前缀",
builtinTitle: "内置 · {count} · 只读",
standaloneWarning: "修改操作需要在活跃的 reasonix code 会话内执行 /dashboard — 独立模式的 reasonix dashboard 无法确定要编辑哪个项目的允许列表。",
},
mcp: {
loading: "加载 MCP…",
servers: "MCP 服务器 · {count} 个已桥接",
all: "全部",
live: "在线",
unbridged: "未桥接",
specPlaceholder: "规格 — 例如 fs=npx -y @modelcontextprotocol/...",
saved: "已保存",
savedRestart: "已保存 — 重启 reasonix code 以桥接此服务器",
removed: "已移除 — 重启以断开实时桥接",
removeConfirm: "从配置中移除 MCP 规格?\n\n{spec}",
noServers: "此会话中无 MCP 服务器。",
tools: "个工具",
inConfig: "在配置中 · 未加载",
unbridgedTitle: "未桥接 · 在配置中",
removeBtn: "移除",
spec: "规格",
whyUnbridged: "为什么未桥接?",
whyUnbridgedDesc: "此规格存在于您的 config.json 中,但未桥接到实时会话。MCP 服务器在 reasonix code 启动时连接;仪表盘本身无法生成子进程。",
whyUnbridgedHint: "激活方法:重启 reasonix code,然后刷新此仪表盘。",
pickHint: "选择左侧的 MCP 服务器以检查工具 / 资源 / 提示。",
toolsTitle: "工具 · {count}",
resourcesTitle: "资源 · {count}",
promptsTitle: "提示 · {count}",
colName: "名称",
colDesc: "描述",
colUri: "URI",
},
memory: {
loading: "加载记忆…",
files: "记忆 · {count} 个文件",
exists: "已存在",
create: "创建",
noFiles: "暂无记忆文件。",
pickHint: "选择左侧的记忆文件。",
pickDesc: "项目 REASONIX.md 可提交;全局笔记存储在 ~/.reasonix/memory/。",
chars: "{count} 个字符",
saved: "已保存 {scope}",
reloadHint: "在下次 /new 或会话重启时重新加载",
},
hooks: {
loading: "加载钩子…",
resolved: "已解析",
eventMatrix: "事件矩阵",
matrixSub: "{scripts} 个脚本 × {events} 个事件",
noHooks: "未配置钩子。编辑下方的 JSON 以添加。",
colScript: "脚本",
noProject: "无活跃项目 — 在 reasonix code 中打开 /dashboard 以编辑项目钩子。",
saveReload: "保存并重载",
discard: "放弃更改",
savedReloaded: "已保存并重载 {scope}",
recentRuns: "近期运行",
noRuns: "近期会话日志中无钩子运行记录。",
colWhen: "时间",
colPhase: "阶段",
colHook: "钩子",
colOutcome: "结果",
},
skills: {
loading: "加载技能…",
filterPlaceholder: "筛选技能",
project: "项目",
global: "全局",
builtin: "内置",
newSkill: "新技能",
noDescription: "(无描述)",
runs7d: "次运行 · 7 天",
pickHint: "选择左侧的技能,或在上方创建新技能。",
readOnlyBuiltin: "只读 · 内置",
builtinDesc: "内置技能随 Reasonix 一起发布;模型会自动识别。如需自定义,请创建同名的项目或全局技能。",
saved: "已保存 {scope}/{name}",
deleteConfirm: "删除技能 {scope}/{name}?",
reloadHint: "在下次 /new 或会话重启时重新加载",
},
system: {
loading: "加载健康状态…",
failed: "健康检查失败:{error}",
healthChecks: "健康检查",
version: "版本",
checking: "检查中",
latest: "● 最新",
outOfDate: "● 需要更新",
versionPending: "版本检查中",
upToDate: "已是最新",
latestVer: "最新:{version}",
sessions: "会话",
ok: "● 正常",
memory: "记忆",
semanticIndex: "语义索引",
built: "● 已构建",
none: "— 无",
runIndex: "运行 reasonix index 以构建",
usageLog: "用量日志",
backgroundJobs: "后台任务",
noSession: "— 无会话",
running: "{count} 个运行中",
attachHint: "连接会话以查看任务",
shellSpawn: "Shell + 生成",
paths: "路径",
home: "主目录",
sessionsPath: "会话",
memoryPath: "记忆",
semanticPath: "语义",
usagePath: "用量",
},
plans: {
loading: "加载计划…",
failed: "计划失败:{error}",
noPlans: "暂无归档计划 — 运行调用 submit_plan 和 mark_step_complete 的轮次。",
filterPlaceholder: "筛选计划",
active: "进行中",
done: "已完成",
steps: "步骤",
pickHint: "选择左侧的计划。",
noTitle: "(无标题)",
stepTimeline: "步骤时间线 · {done} / {total}",
step: "步骤 {n}",
},
semantic: {
codeRequired: "语义 — 需要代码模式",
indexBuilt: "索引已构建",
noIndex: "尚无索引",
ready: "就绪",
setupNeeded: "需要设置",
installOllama: "安装 Ollama",
installOllamaDesc: "Reasonix 不会为您运行包管理器。请先安装 Ollama,然后返回:",
macWindows: "macOS / Windows:",
download: "从 ollama.com/download 下载",
linux: "Linux:",
refreshHint: "安装后刷新 — 此面板将提供启动守护进程和拉取 {model} 的选项。",
daemon: "守护进程",
daemonDesc: "ollama 在您的 PATH 中,但 HTTP 守护进程不可达。",
startDaemon: "启动守护进程",
runsOllama: "以分离模式运行 ollama serve",
model: "模型",
modelMissing: "{model} 尚未安装。",
modelSize: "首次拉取约 270 MB。",
pulling: "拉取中…",
pullModel: "拉取 {model}",
indexStatus: "索引状态",
builtStatus: "● 已构建",
chunks: "分块",
files: "文件",
dim: "维度",
size: "大小",
lastBuild: "上次构建",
runIndexHint: "运行索引以启用 semantic_search。",
reIndex: "重建索引",
build: "构建",
rebuild: "完全重建",
stop: "停止",
ollama: "Ollama",
binary: "二进制",
found: "已找到",
missing: "缺失",
daemonStatus: "守护进程",
up: "运行中",
down: "已停止",
pulled: "已拉取",
indexConfig: "索引配置",
reset: "重置",
excludeDirs: "排除目录",
excludeFiles: "排除文件",
excludeExts: "排除扩展名",
excludePatterns: "排除模式",
glob: "glob",
respectGitignore: "遵循 .gitignore",
maxFileBytes: "最大文件字节数",
skipLarger: "跳过大于 ~{size} MiB 的文件",
preview: "预览",
searchPlaceholder: "描述要查找的内容 — '哪里处理中止信号'",
searching: "搜索中…",
results: "{count} 个结果 · {ms}ms · {model}",
noMatches: "没有超过分数阈值的匹配。",
previewSummary: "预览 — 将索引 {included} 个文件,跳过 {skipped} 个",
nothingSkipped: "无跳过 — 所有遍历的文件都将被索引。",
firstIncluded: "前 {count} 个包含的文件",
job: "任务",
phaseScan: "扫描文件",
phaseEmbed: "嵌入分块",
phaseWrite: "写入索引",
phaseDone: "完成",
phaseError: "错误",
stopping: "停止中",
scanned: "已扫描 {count}",
changed: "已变更 {count}",
skipped: "已跳过 {count}",
chunksProgress: "{done} / {total}({pct}%)",
result: "结果",
added: "已添加 {count}",
removed: "已移除 {count}",
failed: "失败 {count}",
skippedFiles: "{total} 个文件({details})",
rebuildStarted: "已启动完全重建",
incrementalStarted: "已启动增量索引",
stopRequested: "已请求停止 — 当前分块批次将首先完成",
startingDaemon: "正在启动 ollama 守护进程(15 秒超时)…",
daemonUp: "守护进程已启动",
daemonTimeout: "守护进程未在规定时间内启动 — 请手动检查 ollama serve",
pullingModel: "正在拉取 {model} — 首次安装可能需要几分钟",
savedConfig: "已保存 · {count} 个字段已更新 · 重新运行索引以应用",
runningPreview: "正在对项目根目录执行干运行…",
exclude: "排除",
},
modal: {
shellTitle: "Shell 命令",
shellBgTitle: "后台进程",
shellSubtitle: "模型想要运行一条 Shell 命令",
shellBgSubtitle: "长时间运行 — 批准后继续运行",
runOnce: "运行一次",
alwaysAllow: "始终允许 \"{prefix}\"",
deny: "拒绝",
choiceTitle: "模型需要您选择",
typeOwn: "输入自定义回答",
typeOwnSummary: "以上选项都不合适 — 写一个自由格式的回复。",
typePlaceholder: "输入自由格式的回答…",
send: "发送",
cancel: "取消",
cancelSummary: "放弃此问题。模型将询问您实际想要什么。",
planTitle: "计划已提交",
planSubtitle: "模型提出了一项计划;请审阅后选择",
approveInstructions: "可选的最后指示 / 对开放问题的回答(Enter 发送空白)",
refinePlaceholder: "需要更改什么?请具体说明。",
approve: "批准",
refine: "优化",
sendRefinement: "发送优化",
editTitle: "编辑待审阅",
editSubtitle: "{path} · {remaining} / {total} 个块剩余",
before: "修改前",
after: "修改后",
workspaceTitle: "模型想要切换工作区",
workspaceSubtitle: "后续所有文件 / Shell / 记忆工具将针对新根目录解析",
switchBtn: "切换 (Enter)",
denyBtn: "拒绝 (Esc)",
stepComplete: "步骤完成{counter}",
continueBtn: "继续",
reviseBtn: "修订…",
stopBtn: "停止",
revisionTitle: "模型提出了计划修订",
sendRevision: "发送修订",
accept: "接受",
reject: "拒绝",
arguments: "参数",
revisePlaceholder: "下一步之前需要更改什么?留空则直接继续。",
},
};
+146
View File
@@ -0,0 +1,146 @@
import { useEffect, useState } from "preact/hooks";
import { TOKEN, api } from "./api.js";
type Listener = () => void;
export type DashboardLang = "en" | "zh-CN";
// [dashboardCode, backendCode] — add new languages here.
const LANG_REGISTRY: [DashboardLang, string][] = [
["en", "EN"],
["zh-CN", "zh-CN"],
];
const SUPPORTED = new Set(LANG_REGISTRY.map(([d]) => d));
const TO_BACKEND = new Map(LANG_REGISTRY);
const FROM_BACKEND = new Map(LANG_REGISTRY.map(([d, b]) => [b, d]));
const STORAGE_KEY = "rx.lang";
const EXPLICIT_KEY = "rx.langExplicit";
const listeners: Listener[] = [];
let currentLang: DashboardLang = loadFromStorage() ?? "en";
function loadFromStorage(): DashboardLang | null {
try {
const v = localStorage.getItem(STORAGE_KEY);
if (v !== null && SUPPORTED.has(v as DashboardLang)) return v as DashboardLang;
} catch {
/* private mode */
}
return null;
}
function isExplicit(): boolean {
try {
return localStorage.getItem(EXPLICIT_KEY) === "1";
} catch {
return false;
}
}
function markExplicit(): void {
try {
localStorage.setItem(EXPLICIT_KEY, "1");
} catch {
/* ignore */
}
}
function toBackendLang(lang: DashboardLang): string {
return TO_BACKEND.get(lang) ?? lang;
}
function fromBackendLang(raw: string): DashboardLang {
return (FROM_BACKEND.get(raw) as DashboardLang) ?? "en";
}
/** Fetch lang from backend on startup. */
export async function initLangFromServer(): Promise<void> {
try {
const stored = loadFromStorage();
const res = await api<{ lang?: string }>("/settings");
const serverLang = res.lang ? fromBackendLang(res.lang) : null;
if (!serverLang || stored === serverLang) return;
if (isExplicit() && stored) {
// User explicitly chose a language — push to server.
api("/settings", { method: "POST", body: { lang: toBackendLang(stored) } })
.catch((err) => console.error("[reasonix dashboard] lang sync:", err));
return;
}
// No explicit choice yet (first visit or cleared storage) — adopt server value.
currentLang = serverLang;
try {
localStorage.setItem(STORAGE_KEY, serverLang);
} catch {
/* ignore */
}
for (const cb of listeners) cb();
} catch {
/* offline — keep localStorage value */
}
}
export function getLang(): DashboardLang {
return currentLang;
}
export function setLang(lang: DashboardLang): void {
if (!SUPPORTED.has(lang)) return;
currentLang = lang;
markExplicit();
try {
localStorage.setItem(STORAGE_KEY, lang);
} catch {
/* ignore */
}
for (const cb of listeners) cb();
// keepalive ensures the request completes even during page unload (refresh).
fetch(`/api/settings?token=${TOKEN}`, {
method: "POST",
headers: { "Content-Type": "application/json", "X-Reasonix-Token": TOKEN },
body: JSON.stringify({ lang: toBackendLang(lang) }),
keepalive: true,
}).catch((err) => console.error("[reasonix dashboard] lang persist:", err));
}
export function onLangChange(cb: Listener): () => void {
listeners.push(cb);
return () => {
const i = listeners.indexOf(cb);
if (i >= 0) listeners.splice(i, 1);
};
}
export function useLang(): DashboardLang {
const [lang, setLangState] = useState<DashboardLang>(currentLang);
useEffect(() => onLangChange(() => setLangState(currentLang)), []);
return lang;
}
type Nested = { [k: string]: string | Nested };
function get(translations: Nested | undefined, path: string): string | undefined {
let val: string | Nested | undefined = translations;
for (const part of path.split(".")) {
if (val === undefined || typeof val === "string") return undefined;
val = val[part];
}
return typeof val === "string" ? val : undefined;
}
export function createT(translations: Record<string, Nested>) {
return function t(path: string, params?: Record<string, string | number>): string {
let val = get(translations[currentLang] ?? translations.en, path);
if (val === undefined) val = get(translations.en, path);
if (val === undefined) return path;
if (!params) return val;
let result = val;
for (const [k, v] of Object.entries(params)) {
result = result.replaceAll(`{${k}}`, String(v));
}
return result;
};
}
+59 -53
View File
@@ -16,6 +16,7 @@ import { MODE, TOKEN, api } from "../lib/api.js";
import { appBus, showToast } from "../lib/bus.js";
import { fmtUsd } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface StreamingState {
id: string;
@@ -100,6 +101,7 @@ interface SettingsPatch {
}
export function ChatPanel() {
useLang();
const [messages, setMessages] = useState<ChatMsg[]>([]);
const [streaming, setStreaming] = useState<StreamingState | null>(null);
const [activeTool, setActiveTool] = useState<ActiveToolState | null>(null);
@@ -263,7 +265,7 @@ export function ChatPanel() {
es.onerror = () => {
// Auto-reconnect by default; surface a brief banner on persistent
// failure but don't tear down — EventSource retries in the background.
setError("event stream interrupted — reconnecting…");
setError(t("chat.eventStreamError"));
setTimeout(() => setError(null), 3000);
};
return () => es.close();
@@ -298,8 +300,8 @@ export function ChatPanel() {
const newConversation = useCallback(async () => {
if (busy) {
if (!confirm("A turn is in flight. Abort and start a new conversation?")) return;
} else if (messages.length > 0 && !confirm("Clear current conversation and start fresh?")) {
if (!confirm(t("chat.newConfirmBusy"))) return;
} else if (messages.length > 0 && !confirm(t("chat.newConfirm"))) {
return;
}
try {
@@ -307,7 +309,7 @@ export function ChatPanel() {
setMessages([]);
setStreaming(null);
setActiveTool(null);
showToast("new conversation", "info");
showToast(t("chat.newToast"), "info");
setTimeout(async () => {
try {
const r = await api<MessagesResponse>("/messages");
@@ -317,7 +319,7 @@ export function ChatPanel() {
}
}, 200);
} catch (err) {
setError(`/new failed: ${(err as Error).message}`);
setError(t("chat.newFailed", { error: (err as Error).message }));
}
}, [busy, messages.length]);
@@ -327,7 +329,7 @@ export function ChatPanel() {
setMessages([]);
setStreaming(null);
setActiveTool(null);
showToast("scrollback cleared", "info");
showToast(t("chat.clearToast"), "info");
setTimeout(async () => {
try {
const r = await api<MessagesResponse>("/messages");
@@ -337,7 +339,7 @@ export function ChatPanel() {
}
}, 200);
} catch (err) {
setError(`/clear failed: ${(err as Error).message}`);
setError(t("chat.clearFailed", { error: (err as Error).message }));
}
}, []);
@@ -443,7 +445,7 @@ export function ChatPanel() {
);
if (bootError) {
return html`<div class="notice err">chat unavailable: ${bootError}</div>`;
return html`<div class="notice err">${t("common.loadingFailed", { name: "chat", error: bootError })}</div>`;
}
/** Suppresses scroll listener during programmatic auto-snap so it doesn't re-arm shouldAutoScroll. */
@@ -557,20 +559,20 @@ export function ChatPanel() {
<div class="chat-shell">
<div style="display:flex;align-items:center;gap:12px;margin-bottom:10px">
<div class="chips" style="padding:0">
<span class="chip-f active">${MODE === "attached" ? "TUI mirror" : "session view"}</span>
<span class="chip-f active">${MODE === "attached" ? t("chat.modeMirror") : t("chat.modeView")}</span>
</div>
<div class="header-pickers" style="margin-left:auto">
${
effort
? html`
<div class="mode-picker" title="reasoning_effort — applies next turn">
<div class="mode-picker" title=${t("chat.effortTitle")}>
${["high", "max"].map(
(e) => html`
<button
key=${e}
class="mode-btn ${effort === e ? "active accent" : ""}"
onClick=${() => setSetting("reasoningEffort", e)}
title=${e === "max" ? "max (default — best quality)" : "high (cheaper / faster)"}
title=${e === "max" ? t("chat.effortMaxTitle") : t("chat.effortHighTitle")}
>${e}</button>
`,
)}
@@ -581,7 +583,7 @@ export function ChatPanel() {
${
preset
? html`
<div class="mode-picker" title="preset — model commitment">
<div class="mode-picker" title=${t("chat.presetTitle")}>
${(() => {
// Anything that isn't one of the three new presets
// (including legacy fast/smart/max from old configs)
@@ -597,10 +599,10 @@ export function ChatPanel() {
onClick=${() => setSetting("preset", p)}
title=${
p === "auto"
? "auto — flash baseline; auto-escalates to pro on hard turns (NEEDS_PRO / failure threshold)"
? t("chat.presetAutoTitle")
: p === "flash"
? "flash — always flash; no auto-escalate. /pro still works for one-shot manual"
: "pro — always pro; ~3× flash cost (5/31 discount). Locks in on hard architecture work."
? t("chat.presetFlashTitle")
: t("chat.presetProTitle")
}
>${p}</button>
`,
@@ -613,7 +615,7 @@ export function ChatPanel() {
${
editMode
? html`
<div class="mode-picker" title="edit gate — Shift+Tab cycles in TUI">
<div class="mode-picker" title=${t("chat.editGateTitle")}>
${["review", "auto", "yolo"].map(
(m) => html`
<button
@@ -622,10 +624,10 @@ export function ChatPanel() {
onClick=${() => setEditMode(m)}
title=${
m === "review"
? "review — both edits and non-allowlisted shell ask first"
? t("chat.editReviewTitle")
: m === "auto"
? "auto — edits auto-apply, shell still asks"
: "yolo — edits AND shell auto-run, allowlist bypassed"
? t("chat.editAutoTitle")
: t("chat.editYoloTitle")
}
>${m}</button>
`,
@@ -647,19 +649,19 @@ export function ChatPanel() {
? html`<div class="chat-banner">
<span class="chat-banner-icon">≈</span>
<span class="chat-banner-text">
<strong>Semantic search isn't enabled for this project.</strong>
<strong>${t("chat.semanticBanner")}</strong>
<span class="muted">
Build the index once and the model can find code by meaning ("where do we handle auth failures?") instead of grep on exact strings.
${t("chat.semanticBannerDesc")}
</span>
</span>
<button
class="primary"
onClick=${() => appBus.dispatchEvent(new CustomEvent("navigate-tab", { detail: { tabId: "semantic" } }))}
>Build it →</button>
>${t("chat.semanticBannerBtn")}</button>
<button
class="chat-banner-close"
onClick=${() => setSemanticBannerDismissed(true)}
title="dismiss (don't show again)"
title=${t("chat.semanticBannerDismiss")}
>×</button>
</div>`
: null
@@ -692,7 +694,7 @@ export function ChatPanel() {
${
allMessages.length === 0
? html`<div class="chat-empty">
No conversation yet. Send a prompt below to begin.
${t("chat.noConversation")}
</div>`
: allMessages.map(
(m) => html`
@@ -711,7 +713,7 @@ export function ChatPanel() {
popoverKind && popoverItems.length > 0
? html`
<div class="popover" style="position:absolute;bottom:calc(100% + 6px);left:0;width:380px;max-height:280px;overflow-y:auto;z-index:10">
<div class="popover-h">${popoverKind === "slash" ? "slash commands" : "project files"}</div>
<div class="popover-h">${popoverKind === "slash" ? t("chat.slashCommands") : t("chat.projectFiles")}</div>
${popoverItems.map(
(it, i) => html`
<div
@@ -733,7 +735,7 @@ export function ChatPanel() {
: null
}
<textarea
placeholder=${busy ? "wait for the current turn to finish…" : "Type a prompt — Enter sends, Shift+Enter for a newline · / @ for pickers"}
placeholder=${busy ? t("chat.placeholderBusy") : t("chat.placeholder")}
value=${input}
onInput=${onInput}
onKeyDown=${onKeyDown}
@@ -746,10 +748,10 @@ export function ChatPanel() {
class="primary"
onClick=${send}
disabled=${busy || !input.trim()}
>Send</button>
>${t("chat.send")}</button>
<div style="display: flex; gap: 6px;">
<button onClick=${newConversation} title="/new — wipe conversation context (loop log + scrollback)">New</button>
<button onClick=${clearScrollback} title="/clear — wipe just visible scrollback (context kept)">Clear</button>
<button onClick=${newConversation} title=${t("chat.newTitle")}>${t("chat.new")}</button>
<button onClick=${clearScrollback} title=${t("chat.clearTitle")}>${t("chat.clear")}</button>
</div>
</div>
</div>
@@ -782,6 +784,7 @@ interface SideRailProps {
}
function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
useLang();
if (!stats && !activePlan) return html`<aside class="chat-rail"></aside>`;
const cachePct = stats ? Math.round(stats.cacheHitRatio * 100) : 0;
const cacheTone = cachePct >= 80 ? "ok" : cachePct >= 50 ? "" : "warn";
@@ -795,12 +798,12 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
stats
? html`
<div class="rail-card">
<div class="rh">Session</div>
<div class="rail-kv"><span class="k">turns</span><span class="v">${stats.turns.toLocaleString()}</span></div>
<div class="rail-kv"><span class="k">prompt tok</span><span class="v">${stats.lastPromptTokens.toLocaleString()}</span></div>
<div class="rail-kv"><span class="k">cost</span><span class="v">${fmtUsd(stats.totalCostUsd)}</span></div>
<div class="rh">${t("chat.railSession")}</div>
<div class="rail-kv"><span class="k">${t("chat.railTurns")}</span><span class="v">${stats.turns.toLocaleString()}</span></div>
<div class="rail-kv"><span class="k">${t("chat.railPromptTok")}</span><span class="v">${stats.lastPromptTokens.toLocaleString()}</span></div>
<div class="rail-kv"><span class="k">${t("chat.railCost")}</span><span class="v">${fmtUsd(stats.totalCostUsd)}</span></div>
<div class="progress-row" style="margin-top:8px">
<span class="lbl">cache hit</span>
<span class="lbl">${t("chat.railCacheHit")}</span>
<div class=${`progress ${cacheTone}`}><div class="progress-fill" style=${`width:${cachePct}%`}></div></div>
<span class="v">${cachePct}%</span>
</div>
@@ -812,9 +815,9 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
showBudget
? html`
<div class="rail-card">
<div class="rh">Tool budget</div>
<div class="rh">${t("chat.railToolBudget")}</div>
<div class="progress-row">
<span class="lbl">spend</span>
<span class="lbl">${t("chat.railSpend")}</span>
<div class=${`progress ${budgetTone}`}><div class="progress-fill" style=${`width:${Math.min(100, budgetPct)}%`}></div></div>
<span class="v" style=${budgetTone === "err" ? "color:var(--c-err)" : budgetTone === "warn" ? "color:var(--c-warn)" : ""}>${fmtUsd(stats.totalCostUsd)} / ${fmtUsd(budgetUsd)}</span>
</div>
@@ -827,6 +830,7 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
}
function ActivePlanCard({ plan }: { plan: RailPlan }) {
useLang();
const dots = [];
for (let i = 0; i < plan.totalSteps; i++) {
const done = i < plan.completedSteps;
@@ -840,10 +844,10 @@ function ActivePlanCard({ plan }: { plan: RailPlan }) {
}
return html`
<div class="rail-card">
<div class="rh">Active plan</div>
<div class="rh">${t("chat.railActivePlan")}</div>
<div class="steps" style="margin-bottom:8px">${dots}</div>
<div class="rail-kv"><span class="k" style="font-family:var(--font-sans);color:var(--fg-1);font-size:12.5px">${plan.title}</span></div>
<div class="rail-kv"><span class="k">progress</span><span class="v">${plan.completedSteps} / ${plan.totalSteps}</span></div>
<div class="rail-kv"><span class="k">${t("chat.railProgress")}</span><span class="v">${plan.completedSteps} / ${plan.totalSteps}</span></div>
</div>
`;
}
@@ -894,6 +898,7 @@ function InFlightRow({
onAbort,
tick: _tick,
}: InFlightRowProps) {
useLang();
const elapsedMs = startedAt ? Date.now() - startedAt : 0;
const elapsed = (elapsedMs / 1000).toFixed(1);
const reasoningLen = streaming?.reasoning?.length ?? 0;
@@ -901,12 +906,12 @@ function InFlightRow({
/** Tool dispatch wins over text/reasoning — model is blocked on the tool, show that. */
const toolSummary = summarizeActiveTool(activeTool);
const phase = toolSummary
? "running"
? t("chat.inflightRunning")
: reasoningLen > 0 && textLen === 0
? "thinking"
? t("chat.inflightThinking")
: textLen > 0
? "streaming"
: "waiting";
? t("chat.inflightStreaming")
: t("chat.inflightWaiting");
return html`
<div class="chat-inflight">
<span class="spinner"></span>
@@ -926,9 +931,9 @@ function InFlightRow({
? html`
<span class="chat-inflight-sep">·</span>
<span class="muted">
${reasoningLen > 0 ? html`reasoning ${reasoningLen.toLocaleString()} ch` : null}
${reasoningLen > 0 ? html`${t("chat.inflightReasoning", { count: reasoningLen.toLocaleString() })}` : null}
${reasoningLen > 0 && textLen > 0 ? html`<span> · </span>` : null}
${textLen > 0 ? html`out ${textLen.toLocaleString()} ch` : null}
${textLen > 0 ? html`${t("chat.inflightOut", { count: textLen.toLocaleString() })}` : null}
</span>
`
: null
@@ -941,7 +946,7 @@ function InFlightRow({
`
: null
}
<button class="chat-inflight-abort" onClick=${onAbort}>Abort (Esc)</button>
<button class="chat-inflight-abort" onClick=${onAbort}>${t("chat.abortBtn")}</button>
</div>
`;
}
@@ -952,10 +957,11 @@ interface ChatStatusBarProps {
}
function ChatStatusBar({ stats, model }: ChatStatusBarProps) {
useLang();
if (!stats) {
return html`
<div class="chat-statusbar">
<span class="muted">· · · waiting for live stats</span>
<span class="muted">${t("chat.waitingStats")}</span>
</div>
`;
}
@@ -965,38 +971,38 @@ function ChatStatusBar({ stats, model }: ChatStatusBarProps) {
return html`
<div class="chat-statusbar">
<span class="status-item">
<span class="status-label">model</span>
<span class="status-label">${t("chat.statusModel")}</span>
<code>${model ?? "—"}</code>
</span>
<span class="status-item">
<span class="status-label">ctx</span>
<span class="status-label">${t("chat.statusCtx")}</span>
<span class="status-bar-mini">
<span class="status-bar-mini-fill" style=${`width: ${Math.min(100, ctxPct).toFixed(1)}%;`}></span>
</span>
<span class="muted">${stats.lastPromptTokens.toLocaleString()} / ${(stats.contextCapTokens / 1000).toFixed(0)}K</span>
</span>
<span class="status-item">
<span class="status-label">cache</span>
<span class="status-label">${t("chat.statusCache")}</span>
<span class=${stats.cacheHitRatio >= 0.9 ? "status-ok" : stats.cacheHitRatio >= 0.6 ? "status-warn" : "status-err"}>
${(stats.cacheHitRatio * 100).toFixed(1)}%
</span>
</span>
<span class="status-item">
<span class="status-label">turn</span>
<span class="status-label">${t("chat.statusTurn")}</span>
<code>${fmtUsd(stats.lastTurnCostUsd)}</code>
</span>
<span class="status-item">
<span class="status-label">session</span>
<span class="status-label">${t("chat.statusSession")}</span>
<code>${fmtUsd(stats.totalCostUsd)}</code>
<span class="muted" style="font-size: 10px;">
(${stats.turns} turn${stats.turns === 1 ? "" : "s"})
${t("chat.statusTurns", { count: stats.turns, s: stats.turns === 1 ? "" : "s" })}
</span>
</span>
${
balance
? html`
<span class="status-item">
<span class="status-label">balance</span>
<span class="status-label">${t("chat.statusBalance")}</span>
<code>${balance.total_balance} ${balance.currency}</code>
</span>
`
+17 -17
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface HookHandler {
command?: string;
@@ -61,6 +62,7 @@ interface HooksData {
}
export function HooksPanel() {
useLang();
const [data, setData] = useState<HooksData | null>(null);
const [error, setError] = useState<string | null>(null);
const [drafts, setDrafts] = useState<Record<string, string>>({});
@@ -99,7 +101,7 @@ export function HooksPanel() {
try {
await api("/hooks/save", { method: "POST", body: { scope, hooks: parsed } });
await api("/hooks/reload", { method: "POST", body: {} });
setInfo(`saved + reloaded ${scope}`);
setInfo(t("hooks.savedReloaded", { scope }));
setTimeout(() => setInfo(null), 3000);
await load();
} catch (err) {
@@ -112,7 +114,7 @@ export function HooksPanel() {
);
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">loading hooks…</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("hooks.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
@@ -132,23 +134,22 @@ export function HooksPanel() {
return html`
<div style="display:flex;flex-direction:column;gap:6px">
<div class="chips">
<span class="chip-f active">resolved <span class="ct">${data.resolved.length}</span></span>
<span class="chip-f active">${t("hooks.resolved")} <span class="ct">${data.resolved.length}</span></span>
${data.events.map((ev) => html`<span class="chip-f">${ev}</span>`)}
</div>
${info ? html`<div><span class="pill ok">${info}</span></div>` : null}
${error ? html`<div class="card accent-err">${error}</div>` : null}
${sectionH3("Event matrix", `${matrixRows.length} script${matrixRows.length === 1 ? "" : "s"} × ${events.length} event${events.length === 1 ? "" : "s"}`)}
${
${sectionH3(t("hooks.eventMatrix"), t("hooks.matrixSub", { scripts: matrixRows.length, s: matrixRows.length === 1 ? "" : "s", events: events.length }))}${
matrixRows.length === 0
? html`<div class="card" style="color:var(--fg-3)">
No hooks configured. Edit the JSON below to add some.
${t("hooks.noHooks")}
</div>`
: html`
<div class="card" style="padding:10px 14px;overflow-x:auto">
<div class="matrix" style=${`min-width:fit-content`}>
<div class="row h" style=${`grid-template-columns:${gridCols}`}>
<div>script</div>
<div>${t("hooks.colScript")}</div>
${events.map((ev) => html`<div>${ev}</div>`)}
</div>
${matrixRows.map(
@@ -182,8 +183,7 @@ export function HooksPanel() {
${
scope === "project" && !meta.path
? html`<div class="card" style="color:var(--fg-3)">
No active project — open <code class="mono">/dashboard</code> from
<code class="mono">reasonix code</code> to edit project hooks.
${t("hooks.noProject")}
</div>`
: html`
<div class="card">
@@ -196,9 +196,9 @@ export function HooksPanel() {
></textarea>
<div style="display:flex;gap:6px;margin-top:8px">
<button class="btn primary" disabled=${busy} onClick=${() => saveScope(scope)}>
Save + Reload
${t("hooks.saveReload")}
</button>
<button class="btn ghost" disabled=${busy} onClick=${load}>Discard changes</button>
<button class="btn ghost" disabled=${busy} onClick=${load}>${t("hooks.discard")}</button>
</div>
</div>
`
@@ -206,21 +206,21 @@ export function HooksPanel() {
`;
})}
${sectionH3("Recent runs", `${data.recentRuns?.length ?? 0}`)}
${sectionH3(t("hooks.recentRuns"), `${data.recentRuns?.length ?? 0}`)}
${
!data.recentRuns || data.recentRuns.length === 0
? html`<div class="card" style="color:var(--fg-3)">
No hook runs in the recent session log.
${t("hooks.noRuns")}
</div>`
: html`
<div class="card" style="padding:0;overflow-x:auto">
<table class="tbl" style="width:100%;font-family:var(--font-mono);font-size:11.5px">
<thead>
<tr>
<th style="text-align:left;padding:8px 12px">when</th>
<th style="text-align:left;padding:8px 12px">phase</th>
<th style="text-align:left;padding:8px 12px">hook</th>
<th style="text-align:left;padding:8px 12px">outcome</th>
<th style="text-align:left;padding:8px 12px">${t("hooks.colWhen")}</th>
<th style="text-align:left;padding:8px 12px">${t("hooks.colPhase")}</th>
<th style="text-align:left;padding:8px 12px">${t("hooks.colHook")}</th>
<th style="text-align:left;padding:8px 12px">${t("hooks.colOutcome")}</th>
</tr>
</thead>
<tbody>
+34 -34
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { fmtNum } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface McpServer {
label: string;
@@ -32,6 +33,7 @@ function specCommand(spec: string): string {
type McpFilter = "all" | "live" | "unbridged";
export function McpPanel() {
useLang();
const [data, setData] = useState<McpData | null>(null);
const [specs, setSpecs] = useState<string[] | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -63,7 +65,7 @@ export function McpPanel() {
body: { spec: newSpec.trim() },
});
setInfo(
r.requiresRestart ? "saved — restart `reasonix code` to bridge this server" : "saved",
r.requiresRestart ? t("mcp.savedRestart") : t("mcp.saved"),
);
setTimeout(() => setInfo(null), 4000);
setNewSpec("");
@@ -77,11 +79,11 @@ export function McpPanel() {
const removeSpec = useCallback(
async (spec: string) => {
if (!confirm(`Remove MCP spec from config?\n\n${spec}`)) return;
if (!confirm(t("mcp.removeConfirm", { spec }))) return;
setBusy(true);
try {
await api("/mcp/specs", { method: "DELETE", body: { spec } });
setInfo("removed — restart to drop the live bridge");
setInfo(t("mcp.removed"));
setTimeout(() => setInfo(null), 4000);
await load();
} catch (err) {
@@ -93,7 +95,7 @@ export function McpPanel() {
[load],
);
if (!data && !error) return html`<div class="card" style="color:var(--fg-3)">loading MCP…</div>`;
if (!data && !error) return html`<div class="card" style="color:var(--fg-3)">${t("mcp.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
@@ -107,19 +109,19 @@ export function McpPanel() {
<div class="sessions-grid">
<div class="sessions-list">
<div class="ssl-h" style="font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
MCP servers · ${liveCount} bridged
${t("mcp.servers", { count: liveCount })}
</div>
<div style="padding:8px 12px 4px">
<div class="chips">
<span class=${`chip-f ${filter === "all" ? "active" : ""}`} onClick=${() => setFilter("all")}>all <span class="ct">${liveCount + unbridgedCount}</span></span>
<span class=${`chip-f ${filter === "live" ? "active" : ""}`} onClick=${() => setFilter("live")}>live <span class="ct">${liveCount}</span></span>
<span class=${`chip-f ${filter === "unbridged" ? "active" : ""}`} onClick=${() => setFilter("unbridged")}>unbridged <span class="ct">${unbridgedCount}</span></span>
<span class=${`chip-f ${filter === "all" ? "active" : ""}`} onClick=${() => setFilter("all")}>${t("mcp.all")} <span class="ct">${liveCount + unbridgedCount}</span></span>
<span class=${`chip-f ${filter === "live" ? "active" : ""}`} onClick=${() => setFilter("live")}>${t("mcp.live")} <span class="ct">${liveCount}</span></span>
<span class=${`chip-f ${filter === "unbridged" ? "active" : ""}`} onClick=${() => setFilter("unbridged")}>${t("mcp.unbridged")} <span class="ct">${unbridgedCount}</span></span>
</div>
</div>
<div style="padding:8px 12px;display:flex;gap:6px">
<input
type="text"
placeholder='spec — e.g. fs=npx -y @modelcontextprotocol/...'
placeholder=${t("mcp.specPlaceholder")}
value=${newSpec}
onInput=${(e: Event) => setNewSpec((e.target as HTMLInputElement).value)}
style="flex:1;font-size:11px"
@@ -133,7 +135,7 @@ export function McpPanel() {
${
liveCount === 0 && unbridgedCount === 0
? html`<div style="color:var(--fg-3);padding:14px;font-size:12px">
No MCP servers in this session.
${t("mcp.noServers")}
</div>`
: null
}
@@ -148,9 +150,9 @@ export function McpPanel() {
setOpenUnbridged(null);
}}
>
<span class="name">${s.label} <span class="pill ok">live</span></span>
<span class="name">${s.label} <span class="pill ok">${t("mcp.live")}</span></span>
<span class="preview">${specCommand(s.spec)}</span>
<span class="meta"><span><span class="v">${fmtNum(s.toolCount)}</span> tools</span></span>
<span class="meta"><span><span class="v">${fmtNum(s.toolCount)}</span> ${t("mcp.tools")}</span></span>
</div>
`,
)
@@ -167,9 +169,9 @@ export function McpPanel() {
setOpen(null);
}}
>
<span class="name">${specLabel(spec)} <span class="pill">unbridged</span></span>
<span class="name">${specLabel(spec)} <span class="pill">${t("mcp.unbridged")}</span></span>
<span class="preview">${specCommand(spec)}</span>
<span class="meta"><span class="dim">in config · not loaded</span></span>
<span class="meta"><span class="dim">${t("mcp.inConfig")}</span></span>
</div>
`,
)
@@ -184,44 +186,42 @@ export function McpPanel() {
? html`
<div class="sessions-detail-h">
<span class="name">${specLabel(openUnbridged)}</span>
<span class="ws"><span class="pill">unbridged · in config</span></span>
<span class="ws"><span class="pill">${t("mcp.unbridgedTitle")}</span></span>
<span class="actions">
<button class="btn" disabled=${busy} onClick=${() => removeSpec(openUnbridged)}
style="border-color:var(--c-err);color:var(--c-err)">Remove</button>
<button class="btn ghost" onClick=${() => setOpenUnbridged(null)}>← back</button>
style="border-color:var(--c-err);color:var(--c-err)">${t("mcp.removeBtn")}</button>
<button class="btn ghost" onClick=${() => setOpenUnbridged(null)}>${t("common.back")}</button>
</span>
</div>
<div class="card" style="margin-bottom:12px">
<div class="card-h"><span class="title">spec</span></div>
<div class="card-h"><span class="title">${t("mcp.spec")}</span></div>
<code class="mono" style="font-size:11.5px;color:var(--fg-2);word-break:break-all">${openUnbridged}</code>
</div>
<div class="card accent-warn">
<div class="card-h"><span class="title" style="color:var(--c-warn)">Why unbridged?</span></div>
<div class="card-h"><span class="title" style="color:var(--c-warn)">${t("mcp.whyUnbridged")}</span></div>
<div class="card-b" style="font-size:13px;line-height:1.6">
This spec lives in your <code class="mono">config.json</code> but isn't bridged into the live session.
MCP servers attach when <code class="mono">reasonix code</code> starts; the dashboard alone can't
spawn the child process.
${t("mcp.whyUnbridgedDesc")}
<div style="margin-top:10px;color:var(--fg-3);font-size:12px">
To activate: restart <code class="mono">reasonix code</code>, then refresh this dashboard.
${t("mcp.whyUnbridgedHint")}
</div>
</div>
</div>
`
: open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
Pick an MCP server on the left to inspect tools / resources / prompts.
${t("mcp.pickHint")}
</div>`
: html`
<div class="sessions-detail-h">
<span class="name">${open.label}</span>
<span class="ws">${open.serverInfo?.name ?? "—"} ${open.serverInfo?.version ? `v${open.serverInfo.version}` : ""} · ${open.protocolVersion ?? "—"}</span>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpen(null)}>← back</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
<div class="card" style="margin-bottom:12px">
<div class="card-h"><span class="title">spec</span></div>
<div class="card-h"><span class="title">${t("mcp.spec")}</span></div>
<code class="mono" style="font-size:11.5px;color:var(--fg-2)">${open.spec}</code>
</div>
@@ -234,15 +234,15 @@ export function McpPanel() {
}
<h3 style="margin:18px 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Tools · ${open.tools.length}
${t("mcp.toolsTitle", { count: open.tools.length })}
</h3>
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead><tr><th>name</th><th>description</th></tr></thead>
<thead><tr><th>${t("mcp.colName")}</th><th>${t("mcp.colDesc")}</th></tr></thead>
<tbody>
${open.tools.map(
(t) =>
html`<tr><td><code class="mono">${t.name}</code></td><td class="dim">${t.description ?? ""}</td></tr>`,
(tool) =>
html`<tr><td><code class="mono">${tool.name}</code></td><td class="dim">${tool.description ?? ""}</td></tr>`,
)}
</tbody>
</table>
@@ -252,11 +252,11 @@ export function McpPanel() {
open.resources.length > 0
? html`
<h3 style="margin:18px 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Resources · ${open.resources.length}
${t("mcp.resourcesTitle", { count: open.resources.length })}
</h3>
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead><tr><th>name</th><th>uri</th></tr></thead>
<thead><tr><th>${t("mcp.colName")}</th><th>${t("mcp.colUri")}</th></tr></thead>
<tbody>
${open.resources.map(
(r) =>
@@ -273,11 +273,11 @@ export function McpPanel() {
open.prompts.length > 0
? html`
<h3 style="margin:18px 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Prompts · ${open.prompts.length}
${t("mcp.promptsTitle", { count: open.prompts.length })}
</h3>
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead><tr><th>name</th><th>description</th></tr></thead>
<thead><tr><th>${t("mcp.colName")}</th><th>${t("mcp.colDesc")}</th></tr></thead>
<tbody>
${open.prompts.map(
(p) =>
+19 -17
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { fmtBytes, fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface MemoryFile {
name: string;
@@ -18,6 +19,7 @@ interface MemoryTree {
type Scope = "project" | "global" | "project-mem";
export function MemoryPanel() {
useLang();
const [tree, setTree] = useState<MemoryTree | null>(null);
const [error, setError] = useState<string | null>(null);
const [open, setOpen] = useState<{ scope: Scope; name?: string } | null>(null);
@@ -63,7 +65,7 @@ export function MemoryPanel() {
? "/memory/project"
: `/memory/${open.scope}/${encodeURIComponent(open.name ?? "")}`;
await api(path, { method: "POST", body: { body } });
setInfo(`saved ${open.scope}${open.name ? `/${open.name}` : ""}`);
setInfo(t("memory.saved", { scope: open.scope + (open.name ? `/${open.name}` : "") }));
setTimeout(() => setInfo(null), 3000);
await load();
} catch (err) {
@@ -74,7 +76,7 @@ export function MemoryPanel() {
}, [open, body, load]);
if (!tree && !error)
return html`<div class="card" style="color:var(--fg-3)">loading memory…</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("memory.loading")}</div>`;
if (error && !tree) return html`<div class="card accent-err">${error}</div>`;
if (!tree) return null;
@@ -95,15 +97,16 @@ export function MemoryPanel() {
`;
};
const totalFiles =
(tree.project.path ? 1 : 0) +
tree.global.files.length +
tree.projectMem.files.length;
return html`
<div class="sessions-grid">
<div class="sessions-list">
<div class="ssl-h" style="font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
memory · ${
(tree.project.path ? 1 : 0) +
tree.global.files.length +
tree.projectMem.files.length
} files
${t("memory.files", { count: totalFiles })}
</div>
<div class="ssl-rows">
${
@@ -117,8 +120,8 @@ export function MemoryPanel() {
REASONIX.md
${
tree.project.exists
? html`<span class="pill ok">exists</span>`
: html`<span class="pill">create</span>`
? html`<span class="pill ok">${t("memory.exists")}</span>`
: html`<span class="pill">${t("memory.create")}</span>`
}
</span>
<span class="preview">${tree.project.path}</span>
@@ -134,7 +137,7 @@ export function MemoryPanel() {
tree.projectMem.files.length === 0 &&
!tree.project.path)
? html`<div style="color:var(--fg-3);padding:14px;font-size:12px">
No memory files yet.
${t("memory.noFiles")}
</div>`
: null
}
@@ -145,10 +148,9 @@ export function MemoryPanel() {
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
Pick a memory file on the left.
${t("memory.pickHint")}
<div style="margin-top:12px;font-size:11.5px">
Project REASONIX.md is committable; global notes live in
<code class="mono">~/.reasonix/memory/</code>.
${t("memory.pickDesc")}
</div>
</div>`
: html`
@@ -156,10 +158,10 @@ export function MemoryPanel() {
<span class="name">
${open.scope}${open.name ? `/${open.name}` : ""}
</span>
<span class="ws">${body.length.toLocaleString()} chars</span>
<span class="ws">${t("memory.chars", { count: body.length.toLocaleString() })}</span>
<span class="actions">
<button class="btn primary" disabled=${busy} onClick=${save}>Save</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>← back</button>
<button class="btn primary" disabled=${busy} onClick=${save}>${t("common.save")}</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
${info ? html`<div style="margin-bottom:8px"><span class="pill ok">${info}</span></div>` : null}
@@ -171,7 +173,7 @@ export function MemoryPanel() {
disabled=${busy}
></textarea>
<div style="margin-top:8px;color:var(--fg-3);font-size:11.5px">
re-applied on next <code class="mono">/new</code> or session restart
${t("memory.reloadHint")}
</div>
`
}
+42 -41
View File
@@ -1,6 +1,7 @@
import { fmtCompactNum, fmtNum, fmtRelativeTime, fmtUsd } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface CockpitKpi {
total: number;
@@ -78,47 +79,47 @@ function kpi(label: string, value: unknown, delta?: unknown, deltaTone?: "up" |
}
function deltaPctText(deltaPct: number | null): { text: string; tone: "up" | "down" | "flat" } {
if (deltaPct === null) return { text: "no prior data", tone: "flat" };
if (Math.abs(deltaPct) < 1) return { text: "— stable", tone: "flat" };
if (deltaPct === null) return { text: t("overview.noPriorData"), tone: "flat" };
if (Math.abs(deltaPct) < 1) return { text: t("overview.stable"), tone: "flat" };
const arrow = deltaPct > 0 ? "▲" : "▼";
return {
text: `${arrow} ${Math.abs(deltaPct).toFixed(0)}% vs prior`,
text: t("overview.vsPrior", { arrow, pct: Math.abs(deltaPct).toFixed(0) }),
tone: deltaPct > 0 ? "up" : "down",
};
}
function deltaPpText(deltaPp: number | null): { text: string; tone: "up" | "down" | "flat" } {
if (deltaPp === null) return { text: "no prior data", tone: "flat" };
if (Math.abs(deltaPp) < 0.5) return { text: "— stable", tone: "flat" };
if (deltaPp === null) return { text: t("overview.noPriorData"), tone: "flat" };
if (Math.abs(deltaPp) < 0.5) return { text: t("overview.stable"), tone: "flat" };
const arrow = deltaPp > 0 ? "▲" : "▼";
return { text: `${arrow} ${Math.abs(deltaPp).toFixed(1)}pp`, tone: deltaPp > 0 ? "up" : "down" };
}
function deltaCountText(delta: number | null): { text: string; tone: "up" | "down" | "flat" } {
if (delta === null || delta === 0) return { text: "— stable", tone: "flat" };
if (delta === null || delta === 0) return { text: t("overview.stable"), tone: "flat" };
const arrow = delta > 0 ? "▲" : "▼";
return { text: `${arrow} ${Math.abs(delta)}`, tone: delta > 0 ? "up" : "down" };
}
function balanceKpi(c: CockpitData) {
if (!c.balance) return kpi("balance", "—", "open in TUI", "flat");
if (!c.balance) return kpi(t("overview.balance"), "—", "open in TUI", "flat");
const symbol = c.balance.currency === "CNY" ? "¥" : c.balance.currency === "USD" ? "$" : "";
return kpi("balance", `${symbol}${c.balance.total}`, c.balance.currency, "flat");
return kpi(t("overview.balance"), `${symbol}${c.balance.total}`, c.balance.currency, "flat");
}
function tokens7dKpi(c: CockpitData) {
if (!c.tokens7d) return kpi("tokens · 7d", "—", "no usage yet", "flat");
if (!c.tokens7d) return kpi(t("overview.tokens7d"), "—", t("overview.noUsageYet"), "flat");
const d = deltaPctText(c.tokens7d.deltaPct);
return kpi("tokens · 7d", fmtCompactNum(c.tokens7d.total), d.text, d.tone);
return kpi(t("overview.tokens7d"), fmtCompactNum(c.tokens7d.total), d.text, d.tone);
}
function cacheHitKpi(c: CockpitData) {
if (!c.cacheHit7d) return kpi("cache hit", "—", "no usage yet", "flat");
if (!c.cacheHit7d) return kpi(t("overview.cacheHit"), "—", t("overview.noUsageYet"), "flat");
const pct = (c.cacheHit7d.ratio * 100).toFixed(0);
const d = deltaPpText(c.cacheHit7d.deltaPp);
return html`
<div class="kpi cock-w-1">
<div class="label">cache hit</div>
<div class="label">${t("overview.cacheHit")}</div>
<div class="value">${pct}<span class="unit">%</span></div>
<div class=${`delta ${d.tone}`}>${d.text}</div>
</div>
@@ -126,18 +127,18 @@ function cacheHitKpi(c: CockpitData) {
}
function toolCallsKpi(c: CockpitData) {
if (!c.toolCalls24h) return kpi("tool calls · 24h", "—", "no events", "flat");
if (!c.toolCalls24h) return kpi(t("overview.toolCalls24h"), "—", t("overview.noToolCalls"), "flat");
const d = deltaCountText(c.toolCalls24h.delta);
return kpi("tool calls · 24h", fmtNum(c.toolCalls24h.total), d.text, d.tone);
return kpi(t("overview.toolCalls24h"), fmtNum(c.toolCalls24h.total), d.text, d.tone);
}
function currentSessionBlock(c: CockpitData) {
if (!c.currentSession) {
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">current session</span></div>
<div class="ch"><span class="ttl">${t("overview.currentSession")}</span></div>
<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">
No live session — <code class="mono">/dashboard</code> from inside <code class="mono">reasonix code</code> to attach.
${t("overview.noSession")}
</div>
</div>
`;
@@ -145,14 +146,14 @@ function currentSessionBlock(c: CockpitData) {
const s = c.currentSession;
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">current session</span></div>
<div class="ch"><span class="ttl">${t("overview.currentSession")}</span></div>
<div class="card accent-brand" style="margin:0 0 8px;background:transparent;border:none;padding:0">
<div class="card-h"><span class="glyph">◆</span><span class="title">${s.id}</span><span class="meta">${s.turns} turn${s.turns === 1 ? "" : "s"}</span></div>
</div>
<div style="display:grid;grid-template-columns:repeat(3, 1fr);gap:8px;font-family:var(--font-mono);font-size:11px">
<div><span style="color:var(--fg-3)">prompt tok</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtNum(s.lastPromptTokens)}</div></div>
<div><span style="color:var(--fg-3)">completion tok</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtNum(s.completionTokens)}</div></div>
<div><span style="color:var(--fg-3)">cost</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtUsd(s.totalCostUsd)}</div></div>
<div><span style="color:var(--fg-3)">${t("overview.promptTok")}</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtNum(s.lastPromptTokens)}</div></div>
<div><span style="color:var(--fg-3)">${t("overview.completionTok")}</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtNum(s.completionTokens)}</div></div>
<div><span style="color:var(--fg-3)">${t("overview.cost")}</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtUsd(s.totalCostUsd)}</div></div>
</div>
</div>
`;
@@ -162,8 +163,8 @@ function costTrendSpark(c: CockpitData) {
if (!c.costTrend14d || c.costTrend14d.length === 0) {
return html`
<div class="chart cock-w-2">
<div class="chart-h"><span class="title">cost · 14 day</span></div>
<div class="chart-v" style="color:var(--fg-4)">—<span class="unit">no usage yet</span></div>
<div class="chart-h"><span class="title">${t("overview.costTrend")}</span></div>
<div class="chart-v" style="color:var(--fg-4)">—<span class="unit">${t("overview.noUsageYet")}</span></div>
</div>
`;
}
@@ -183,8 +184,8 @@ function costTrendSpark(c: CockpitData) {
const avg = total / days.length;
return html`
<div class="chart cock-w-2">
<div class="chart-h"><span class="title">cost · 14 day</span></div>
<div class="chart-v">${fmtUsd(avg)}<span class="unit">/day avg</span></div>
<div class="chart-h"><span class="title">${t("overview.costTrend")}</span></div>
<div class="chart-v">${fmtUsd(avg)}<span class="unit">${t("overview.dayAvg")}</span></div>
<div class="chart-spark">
<svg viewBox=${`0 0 ${w} ${h}`} preserveAspectRatio="none">
<polyline fill="none" stroke="var(--c-brand)" stroke-width="1.5" points=${points} />
@@ -198,10 +199,10 @@ function costTrendSpark(c: CockpitData) {
function recentPlansRail(c: CockpitData) {
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">recent plans</span></div>
<div class="ch"><span class="ttl">${t("overview.recentPlans")}</span></div>
${
!c.recentPlans || c.recentPlans.length === 0
? html`<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">No plans yet — submit one with <code class="mono">submit_plan</code>.</div>`
? html`<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">${t("overview.noPlans")}</div>`
: c.recentPlans.map(
(p) => html`
<div class=${`rail-step ${p.status === "done" ? "done" : "active"}`}>
@@ -219,10 +220,10 @@ function recentPlansRail(c: CockpitData) {
function toolActivityFeed(c: CockpitData) {
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">tool activity</span></div>
<div class="ch"><span class="ttl">${t("overview.toolActivity")}</span></div>
${
!c.toolActivity || c.toolActivity.length === 0
? html`<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">No tool calls yet.</div>`
? html`<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">${t("overview.noToolCalls")}</div>`
: c.toolActivity.map(
(r) => html`
<div class=${`feed-row ${r.level}`}>
@@ -238,10 +239,11 @@ function toolActivityFeed(c: CockpitData) {
}
export function OverviewPanel() {
useLang();
const { data, error, loading } = usePoll<OverviewData>("/overview", 2500);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">loading overview…</div>`;
if (error) return html`<div class="card accent-err">overview failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("overview.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("overview.failed", { error: error.message })}</div>`;
if (!data) return null;
const o = data;
const c: CockpitData = o.cockpit ?? {
@@ -256,7 +258,7 @@ export function OverviewPanel() {
};
const upToDate = o.latestVersion ? o.latestVersion === o.version : null;
const versionDelta =
upToDate === null ? "checking" : upToDate ? "latest" : `latest: ${o.latestVersion}`;
upToDate === null ? t("overview.checking") : upToDate ? t("overview.latest") : `latest: ${o.latestVersion}`;
const versionTone: "up" | "down" | "flat" = upToDate === false ? "down" : "flat";
return html`
@@ -265,18 +267,17 @@ export function OverviewPanel() {
o.mode === "standalone"
? html`<div class="card accent-warn">
<div class="card-h">
<span class="title" style="color:var(--c-warn)">Standalone mode</span>
<span class="title" style="color:var(--c-warn)">${t("overview.standaloneTitle")}</span>
</div>
<div class="card-b">
Read-only disk view. Start <code class="mono">/dashboard</code> from inside
<code class="mono">reasonix code</code> for live session state, MCP, and tools.
${t("overview.standaloneDesc")}
</div>
</div>`
: null
}
<h3 style="margin:0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Cockpit
${t("overview.cockpit")}
</h3>
<div class="cockpit">
${balanceKpi(c)}
@@ -290,17 +291,17 @@ export function OverviewPanel() {
${recentPlansRail(c)}
${toolActivityFeed(c)}
${kpi("tools loaded", fmtNum(o.toolCount), o.toolCount ? "active" : "—", "flat")}
${kpi("mcp servers", fmtNum(o.mcpServerCount), o.mcpServerCount ? "all up" : "—", o.mcpServerCount ? "up" : "flat")}
${kpi("edit mode", o.editMode ?? "—", o.editMode === "yolo" ? "all prompts bypassed" : null, o.editMode === "yolo" ? "down" : "flat")}
${kpi("Reasonix", o.version ?? "—", versionDelta, versionTone)}
${kpi(t("overview.toolsLoaded"), fmtNum(o.toolCount), o.toolCount ? t("overview.active") : "—", "flat")}
${kpi(t("overview.mcpServers"), fmtNum(o.mcpServerCount), o.mcpServerCount ? t("overview.allUp") : "—", o.mcpServerCount ? "up" : "flat")}
${kpi(t("overview.editMode"), o.editMode ?? "—", o.editMode === "yolo" ? t("overview.yoloWarning") : null, o.editMode === "yolo" ? "down" : "flat")}
${kpi(t("overview.version"), o.version ?? "—", versionDelta, versionTone)}
</div>
<h3 style="margin:0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Working directory
${t("overview.workingDir")}
</h3>
<div class="card">
<div class="card-h"><span class="title">project root</span></div>
<div class="card-h"><span class="title">${t("overview.projectRoot")}</span></div>
<code class="mono" style="color:var(--fg-2);font-size:12px">${o.cwd ?? "—"}</code>
</div>
</div>
+25 -26
View File
@@ -2,6 +2,7 @@ import { useCallback, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface PermissionsData {
editMode?: string;
@@ -29,6 +30,7 @@ function groupByVerb(list: string[]): [string, string[]][] {
}
export function PermissionsPanel() {
useLang();
const { data, error, loading, refresh } = usePoll<PermissionsData>("/permissions", 5000);
const [draft, setDraft] = useState("");
const [busy, setBusy] = useState(false);
@@ -44,8 +46,8 @@ export function PermissionsPanel() {
method: "POST",
body: { prefix },
});
if (res.alreadyPresent) setFeedback({ kind: "info", text: `${prefix} already in list` });
else setFeedback({ kind: "ok", text: `added: ${prefix}` });
if (res.alreadyPresent) setFeedback({ kind: "info", text: t("permissions.alreadyIn", { prefix }) });
else setFeedback({ kind: "ok", text: t("permissions.added", { prefix }) });
setDraft("");
await refresh();
} catch (err) {
@@ -57,12 +59,12 @@ export function PermissionsPanel() {
const remove = useCallback(
async (prefix: string) => {
if (!confirm(`Remove "${prefix}" from this project's allowlist?`)) return;
if (!confirm(t("permissions.removeConfirm", { prefix }))) return;
setBusy(true);
setFeedback(null);
try {
await api("/permissions", { method: "DELETE", body: { prefix } });
setFeedback({ kind: "ok", text: `removed: ${prefix}` });
setFeedback({ kind: "ok", text: t("permissions.removed", { prefix }) });
await refresh();
} catch (err) {
setFeedback({ kind: "err", text: (err as Error).message });
@@ -74,7 +76,7 @@ export function PermissionsPanel() {
);
const clearAll = useCallback(async () => {
if (!confirm("Wipe every project allowlist entry? Builtin entries are unaffected.")) return;
if (!confirm(t("permissions.clearConfirm"))) return;
setBusy(true);
setFeedback(null);
try {
@@ -84,7 +86,7 @@ export function PermissionsPanel() {
});
setFeedback({
kind: "ok",
text: `cleared ${res.dropped} entr${res.dropped === 1 ? "y" : "ies"}`,
text: t("permissions.cleared", { count: res.dropped, y: res.dropped === 1 ? "y" : "ies" }),
});
await refresh();
} catch (err) {
@@ -95,8 +97,8 @@ export function PermissionsPanel() {
}, [refresh]);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">loading permissions…</div>`;
if (error) return html`<div class="card accent-err">permissions failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("permissions.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "permissions", error: error.message })}</div>`;
if (!data) return null;
const p = data;
@@ -111,18 +113,17 @@ export function PermissionsPanel() {
${
p.editMode === "yolo"
? html`<div class="card accent-warn">
<div class="card-h"><span class="title" style="color:var(--c-warn)">YOLO mode</span></div>
<div class="card-h"><span class="title" style="color:var(--c-warn)">${t("permissions.yoloTitle")}</span></div>
<div class="card-b">
Every shell command auto-runs, allowlist bypassed.
Switch back with <code class="mono">/mode review</code> in the TUI.
${t("permissions.yoloDesc")}
</div>
</div>`
: null
}
<div class="chips">
<span class="chip-f active">project <span class="ct">${p.project.length}</span></span>
<span class="chip-f">builtin <span class="ct">${p.builtin.length}</span></span>
<span class="chip-f active">${t("permissions.project")} <span class="ct">${p.project.length}</span></span>
<span class="chip-f">${t("permissions.builtin")} <span class="ct">${p.builtin.length}</span></span>
</div>
${
@@ -130,13 +131,13 @@ export function PermissionsPanel() {
? html`
<div class="card">
<div class="card-h">
<span class="title">add a prefix</span>
<span class="title">${t("permissions.addPrefix")}</span>
<span class="meta">${p.currentCwd}</span>
</div>
<div style="display:flex;gap:8px;align-items:center">
<input
type="text"
placeholder='e.g. "npm run build" or "deploy.sh"'
placeholder=${t("permissions.addPlaceholder")}
value=${draft}
onInput=${(e: Event) => setDraft((e.target as HTMLInputElement).value)}
onKeyDown=${(e: KeyboardEvent) => {
@@ -145,12 +146,12 @@ export function PermissionsPanel() {
disabled=${busy}
style="flex:1"
/>
<button class="primary" onClick=${add} disabled=${busy || !draft.trim()}>Add</button>
<button class="primary" onClick=${add} disabled=${busy || !draft.trim()}>${t("common.add")}</button>
<button
class="danger"
onClick=${clearAll}
disabled=${busy || p.project.length === 0}
>Clear all</button>
>${t("permissions.clearAll")}</button>
</div>
${feedbackPill ? html`<div style="margin-top:8px">${feedbackPill}</div>` : null}
</div>
@@ -158,27 +159,25 @@ export function PermissionsPanel() {
: html`
<div class="card accent-warn">
<div class="card-b">
Mutations require <code class="mono">/dashboard</code> from inside an active
<code class="mono">reasonix code</code> session — standalone
<code class="mono">reasonix dashboard</code> can't tell which project's allowlist to edit.
${t("permissions.standaloneWarning")}
</div>
</div>
`
}
<h3 style="margin:6px 0 0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Project allowlist · ${p.project.length}
${t("permissions.projectAllowlist", { count: p.project.length })}
</h3>
${
p.project.length === 0
? html`<div class="card" style="color:var(--fg-3)">Nothing stored yet for this project.</div>`
? html`<div class="card" style="color:var(--fg-3)">${t("permissions.nothingStored")}</div>`
: html`
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<th style="width:48px">#</th>
<th>prefix</th>
<th style="width:48px">${t("permissions.colNum")}</th>
<th>${t("permissions.colPrefix")}</th>
<th style="width:120px"></th>
</tr>
</thead>
@@ -195,7 +194,7 @@ export function PermissionsPanel() {
class="danger"
onClick=${() => remove(prefix)}
disabled=${busy}
>remove</button>`
>${t("common.remove")}</button>`
: null
}
</td>
@@ -209,7 +208,7 @@ export function PermissionsPanel() {
}
<h3 style="margin:6px 0 0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Builtin · ${p.builtin.length} · read-only
${t("permissions.builtinTitle", { count: p.builtin.length })}
</h3>
<div class="card" style="font-family:var(--font-mono);font-size:11.5px;line-height:1.8">
${groupByVerb(p.builtin).map(
+17 -16
View File
@@ -2,6 +2,7 @@ import { useState } from "preact/hooks";
import { fmtPct, fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface PlanStep {
id: string;
@@ -26,25 +27,25 @@ interface PlansData {
}
function statusPill(p: ArchivedPlan) {
if (p.completionRatio >= 1) return html`<span class="pill ok">done</span>`;
if (p.completionRatio > 0) return html`<span class="pill info">active</span>`;
if (p.completionRatio >= 1) return html`<span class="pill ok">${t("plans.done")}</span>`;
if (p.completionRatio > 0) return html`<span class="pill info">${t("plans.active")}</span>`;
return html`<span class="pill">idle</span>`;
}
export function PlansPanel() {
useLang();
const { data, error, loading } = usePoll<PlansData>("/plans", 8000);
const [openIdx, setOpenIdx] = useState<number | null>(null);
const [filter, setFilter] = useState("");
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">loading plans…</div>`;
if (error) return html`<div class="card accent-err">plans failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("plans.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "plans", error: error.message })}</div>`;
const plans = data?.plans ?? [];
if (plans.length === 0)
return html`<div class="card" style="color:var(--fg-3)">
No archived plans yet — run a turn that calls <code class="mono">submit_plan</code>
and <code class="mono">mark_step_complete</code>.
${t("plans.noPlans")}
</div>`;
const filtered = filter.trim()
@@ -63,20 +64,20 @@ export function PlansPanel() {
<div class="ssl-h">
<input
type="text"
placeholder="filter plans"
placeholder=${t("plans.filterPlaceholder")}
value=${filter}
onInput=${(e: Event) => setFilter((e.target as HTMLInputElement).value)}
style="flex:1"
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">all <span class="ct">${plans.length}</span></span>
<span class="chip-f active">${t("common.all")} <span class="ct">${plans.length}</span></span>
<span class="chip-f">
active
${t("plans.active")}
<span class="ct">${plans.filter((p) => p.completionRatio > 0 && p.completionRatio < 1).length}</span>
</span>
<span class="chip-f">
done <span class="ct">${plans.filter((p) => p.completionRatio >= 1).length}</span>
${t("plans.done")} <span class="ct">${plans.filter((p) => p.completionRatio >= 1).length}</span>
</span>
</div>
<div class="ssl-rows">
@@ -92,7 +93,7 @@ export function PlansPanel() {
: null
}
<span class="meta">
<span><span class="v">${p.totalSteps}</span> steps</span>
<span><span class="v">${p.totalSteps}</span> ${t("plans.steps")}</span>
<span><span class="v">${p.completedSteps} / ${p.totalSteps}</span> · ${fmtPct(p.completionRatio)}</span>
<span>${fmtRelativeTime(p.completedAt)}</span>
</span>
@@ -106,19 +107,19 @@ export function PlansPanel() {
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
Pick a plan on the left.
${t("plans.pickHint")}
</div>`
: html`
<div class="sessions-detail-h">
<span class="name">${open.summary ?? "(no title)"}</span>
<span class="name">${open.summary ?? t("plans.noTitle")}</span>
<span class="ws">${open.session} · ${fmtRelativeTime(open.completedAt)}</span>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpenIdx(null)}>← back</button>
<button class="btn ghost" onClick=${() => setOpenIdx(null)}>${t("common.back")}</button>
</span>
</div>
<h3 style="margin:0 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Step timeline · ${open.completedSteps} / ${open.totalSteps}
${t("plans.stepTimeline", { done: open.completedSteps, total: open.totalSteps })}
</h3>
<div class="plan-timeline" style="margin-bottom:14px">
${open.steps.map((step, i) => {
@@ -126,7 +127,7 @@ export function PlansPanel() {
const cls = done ? "done" : i === open.completedSteps ? "active" : "";
return html`
<div class=${`plan-step ${cls}`}>
<span class="lbl">step ${i + 1}</span>
<span class="lbl">${t("plans.step", { n: i + 1 })}</span>
<span class="name">${step.title}</span>
${step.action ? html`<span class="meta">${step.action}</span>` : null}
${
+87 -80
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { fmtBytes, fmtNum, fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface SemanticData {
attached?: boolean;
@@ -50,6 +51,7 @@ interface SemanticJob {
}
export function SemanticPanel() {
useLang();
const [data, setData] = useState<SemanticData | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
@@ -81,7 +83,7 @@ export function SemanticPanel() {
setInfo(null);
try {
await api("/semantic/start", { method: "POST", body: { rebuild: !!rebuild } });
setInfo(rebuild ? "rebuild started" : "incremental index started");
setInfo(rebuild ? t("semantic.rebuildStarted") : t("semantic.incrementalStarted"));
await load();
} catch (err) {
setError((err as Error).message);
@@ -97,7 +99,7 @@ export function SemanticPanel() {
setError(null);
try {
await api("/semantic/stop", { method: "POST", body: {} });
setInfo("stopping requested — current chunk batch will finish first");
setInfo(t("semantic.stopRequested"));
await load();
} catch (err) {
setError((err as Error).message);
@@ -109,11 +111,11 @@ export function SemanticPanel() {
const startDaemon = useCallback(async () => {
setBusy(true);
setError(null);
setInfo("starting ollama daemon (15s timeout)…");
setInfo(t("semantic.startingDaemon"));
try {
const r = await api<{ ready: boolean }>("/semantic/ollama/start", { method: "POST", body: {} });
setInfo(
r.ready ? "daemon is up" : "daemon didn't come up in time — check `ollama serve` manually",
r.ready ? t("semantic.daemonUp") : t("semantic.daemonTimeout"),
);
await load();
} catch (err) {
@@ -127,7 +129,7 @@ export function SemanticPanel() {
async (model: string) => {
setBusy(true);
setError(null);
setInfo(`pulling ${model} — this may take a few minutes on first install`);
setInfo(t("semantic.pullingModel", { model }));
try {
await api("/semantic/ollama/pull", { method: "POST", body: { model } });
await load();
@@ -141,14 +143,14 @@ export function SemanticPanel() {
);
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">loading semantic status…</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("common.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
if (!data.attached) {
return html`
<div class="card" style="color:var(--fg-3)">
<div class="card-h"><span class="title">Semantic — code-mode required</span></div>
<div class="card-h"><span class="title">${t("semantic.codeRequired")}</span></div>
<div class="card-b">${data.reason}</div>
</div>
`;
@@ -178,12 +180,12 @@ export function SemanticPanel() {
<div style="display:flex;flex-direction:column;gap:10px;min-width:0">
<div class="chips">
<span class=${`chip-f ${idx?.exists ? "active" : ""}`}>
${idx?.exists ? "index built" : "no index yet"}
${idx?.exists ? t("semantic.indexBuilt") : t("semantic.noIndex")}
</span>
${
ready
? html`<span class="chip-f" style="border-color:var(--c-ok);color:var(--c-ok)">ready</span>`
: html`<span class="chip-f" style="border-color:var(--c-warn);color:var(--c-warn)">setup needed</span>`
? html`<span class="chip-f" style="border-color:var(--c-ok);color:var(--c-ok)">${t("semantic.ready")}</span>`
: html`<span class="chip-f" style="border-color:var(--c-warn);color:var(--c-warn)">${t("semantic.setupNeeded")}</span>`
}
</div>
${info ? html`<div><span class="pill info">${info}</span></div>` : null}
@@ -195,14 +197,14 @@ export function SemanticPanel() {
!binaryFound
? html`
<div class="card">
<div class="card-h"><span class="title">Install Ollama</span></div>
<div class="card-h"><span class="title">${t("semantic.installOllama")}</span></div>
<div class="card-b" style="font-size:13px">
Reasonix doesn't run package managers for you. Install Ollama first, then come back:
${t("semantic.installOllamaDesc")}
<ul style="margin:10px 0 4px 18px;padding:0">
<li><strong>macOS / Windows:</strong> download from <a href="https://ollama.com/download" target="_blank" rel="noreferrer">ollama.com/download</a></li>
<li><strong>Linux:</strong> <code class="mono">curl -fsSL https://ollama.com/install.sh | sh</code></li>
<li><strong>${t("semantic.macWindows")}</strong> ${t("semantic.download")} <a href="https://ollama.com/download" target="_blank" rel="noreferrer">ollama.com/download</a></li>
<li><strong>${t("semantic.linux")}</strong> <code class="mono">curl -fsSL https://ollama.com/install.sh | sh</code></li>
</ul>
<div style="color:var(--fg-3);margin-top:8px">Refresh after install — this panel will offer to start the daemon and pull <code class="mono">${modelName}</code>.</div>
<div style="color:var(--fg-3);margin-top:8px">${t("semantic.refreshHint", { model: modelName })}</div>
</div>
</div>
`
@@ -212,12 +214,12 @@ export function SemanticPanel() {
binaryFound && !daemonRunning
? html`
<div class="card">
<div class="card-h"><span class="title">Daemon</span></div>
<div class="card-h"><span class="title">${t("semantic.daemon")}</span></div>
<div class="card-b" style="font-size:13px">
<code class="mono">ollama</code> is on your PATH but the HTTP daemon isn't reachable.
${t("semantic.daemonDesc")}
<div style="display:flex;gap:8px;margin-top:10px;align-items:center">
<button class="primary" disabled=${busy} onClick=${startDaemon}>Start daemon</button>
<span style="color:var(--fg-3);font-size:12px">runs <code class="mono">ollama serve</code> detached</span>
<button class="primary" disabled=${busy} onClick=${startDaemon}>${t("semantic.startDaemon")}</button>
<span style="color:var(--fg-3);font-size:12px">${t("semantic.runsOllama")}</span>
</div>
</div>
</div>
@@ -228,12 +230,12 @@ export function SemanticPanel() {
daemonRunning && !modelPulled
? html`
<div class="card">
<div class="card-h"><span class="title">Model</span></div>
<div class="card-h"><span class="title">${t("semantic.model")}</span></div>
<div class="card-b" style="font-size:13px">
<code class="mono">${modelName}</code> isn't installed yet.${pulling ? "" : " ~270 MB on first pull."}
${t("semantic.modelMissing", { model: modelName })}${pulling ? "" : ` ${t("semantic.modelSize")}`}
<div style="display:flex;gap:8px;margin-top:10px">
<button class="primary" disabled=${busy || pulling} onClick=${() => pullModel(modelName)}>
${pulling ? "pulling…" : `Pull ${modelName}`}
${pulling ? t("semantic.pulling") : t("semantic.pullModel", { model: modelName })}
</button>
</div>
${
@@ -256,7 +258,7 @@ export function SemanticPanel() {
${
job
? html`
${sectionH3("Job")}
${sectionH3(t("semantic.job"))}
<${SemanticJobView} job=${job} running=${running} />
`
: null
@@ -266,55 +268,55 @@ export function SemanticPanel() {
<aside style="display:flex;flex-direction:column;gap:10px">
<div class="card">
<div class="card-h">
<span class="title">index status</span>
<span class="title">${t("semantic.indexStatus")}</span>
<span class="meta">
${
idx?.exists
? html`<span class="pill ok">● built</span>`
: html`<span class="pill">none</span>`
? html`<span class="pill ok">${t("semantic.builtStatus")}</span>`
: html`<span class="pill">${t("system.none")}</span>`
}
</span>
</div>
${
idx?.exists
? html`
<div class="rail-kv"><span class="k">chunks</span><span class="v">${fmtNum(idx.chunks)}</span></div>
<div class="rail-kv"><span class="k">files</span><span class="v">${fmtNum(idx.files)}</span></div>
<div class="rail-kv"><span class="k">model</span><span class="v" style="font-size:11px">${idx.model ?? modelName}</span></div>
<div class="rail-kv"><span class="k">dim</span><span class="v">${fmtNum(idx.dim)}</span></div>
<div class="rail-kv"><span class="k">size</span><span class="v">${fmtBytes(idx.sizeBytes)}</span></div>
<div class="rail-kv"><span class="k">last build</span><span class="v">${fmtRelativeTime(idx.lastBuiltMs ?? null)}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.chunks")}</span><span class="v">${fmtNum(idx.chunks)}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.files")}</span><span class="v">${fmtNum(idx.files)}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.model")}</span><span class="v" style="font-size:11px">${idx.model ?? modelName}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.dim")}</span><span class="v">${fmtNum(idx.dim)}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.size")}</span><span class="v">${fmtBytes(idx.sizeBytes)}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.lastBuild")}</span><span class="v">${fmtRelativeTime(idx.lastBuiltMs ?? null)}</span></div>
`
: html`
<div style="color:var(--fg-3);font-size:12.5px;padding:6px 0">
Run an index to enable <code class="mono">semantic_search</code>.
${t("semantic.runIndexHint")}
</div>
`
}
<div style="display:flex;gap:6px;margin-top:10px;flex-wrap:wrap">
<button class="primary" disabled=${busy || running || !ready} onClick=${() => start(false)}>${idx?.exists ? "Re-index" : "Build"}</button>
<button class="primary" disabled=${busy || running || !ready} onClick=${() => start(false)}>${idx?.exists ? t("semantic.reIndex") : t("semantic.build")}</button>
${
idx?.exists
? html`<button disabled=${busy || running || !ready} onClick=${() => start(true)}>Rebuild</button>`
? html`<button disabled=${busy || running || !ready} onClick=${() => start(true)}>${t("semantic.rebuild")}</button>`
: null
}
${running ? html`<button onClick=${stop} style="border-color:var(--c-err);color:var(--c-err)">Stop</button>` : null}
${running ? html`<button onClick=${stop} style="border-color:var(--c-err);color:var(--c-err)">${t("semantic.stop")}</button>` : null}
</div>
</div>
<div class="card">
<div class="card-h"><span class="title">ollama</span></div>
<div class="card-h"><span class="title">${t("semantic.ollama")}</span></div>
<div class="rail-kv">
<span class="k">binary</span>
<span class="v">${binaryFound ? html`<span class="pill ok">found</span>` : html`<span class="pill err">missing</span>`}</span>
<span class="k">${t("semantic.binary")}</span>
<span class="v">${binaryFound ? html`<span class="pill ok">${t("semantic.found")}</span>` : html`<span class="pill err">${t("semantic.missing")}</span>`}</span>
</div>
<div class="rail-kv">
<span class="k">daemon</span>
<span class="v">${daemonRunning ? html`<span class="pill ok">up</span>` : html`<span class="pill warn">down</span>`}</span>
<span class="k">${t("semantic.daemonStatus")}</span>
<span class="v">${daemonRunning ? html`<span class="pill ok">${t("semantic.up")}</span>` : html`<span class="pill warn">${t("semantic.down")}</span>`}</span>
</div>
<div class="rail-kv">
<span class="k">model</span>
<span class="v">${modelPulled ? html`<span class="pill ok">pulled</span>` : html`<span class="pill warn">missing</span>`}</span>
<span class="k">${t("semantic.model")}</span>
<span class="v">${modelPulled ? html`<span class="pill ok">${t("semantic.pulled")}</span>` : html`<span class="pill warn">${t("semantic.missing")}</span>`}</span>
</div>
</div>
@@ -369,6 +371,7 @@ interface SearchResponse {
}
function SemanticSearchSection() {
useLang();
const [query, setQuery] = useState("");
const [hits, setHits] = useState<SearchHit[] | null>(null);
const [meta, setMeta] = useState<{ elapsedMs: number; model: string } | null>(null);
@@ -403,7 +406,7 @@ function SemanticSearchSection() {
type="text"
class="mono"
style="width:100%;padding:10px 14px 10px 38px;font-size:13.5px;background:var(--bg-input);border:1px solid var(--bd);border-radius:var(--r);color:var(--fg-0);outline:none"
placeholder="describe what to find — 'where do we handle abort signals'"
placeholder=${t("semantic.searchPlaceholder")}
value=${query}
disabled=${busy}
onInput=${(e: Event) => setQuery((e.target as HTMLInputElement).value)}
@@ -420,11 +423,11 @@ function SemanticSearchSection() {
? html`
<div style="font-family:var(--font-mono);font-size:11px;color:var(--fg-3);margin:8px 0 6px;display:flex;align-items:center;gap:8px">
${busy
? html`<span>searching…</span>`
? html`<span>${t("semantic.searching")}</span>`
: error
? html`<span style="color:var(--c-err)">${error}</span>`
: hits
? html`<span>${hits.length} result${hits.length === 1 ? "" : "s"} · ${meta?.elapsedMs ?? 0}ms · ${meta?.model ?? ""}</span>`
? html`<span>${t("semantic.results", { count: hits.length, s: hits.length === 1 ? "" : "s", ms: meta?.elapsedMs ?? 0, model: meta?.model ?? "" })}</span>`
: null}
</div>
${
@@ -446,7 +449,7 @@ function SemanticSearchSection() {
</div>
`
: hits && hits.length === 0 && !busy
? html`<div class="card" style="color:var(--fg-3);font-size:12px">No matches above the score threshold.</div>`
? html`<div class="card" style="color:var(--fg-3);font-size:12px">${t("semantic.noMatches")}</div>`
: null
}
`
@@ -485,6 +488,7 @@ function fromDraft(d: ExcludeDraft): IndexConfig {
}
function SemanticExcludesCard() {
useLang();
const [data, setData] = useState<IndexConfigResponse | null>(null);
const [draft, setDraft] = useState<ExcludeDraft | null>(null);
const [preview, setPreview] = useState<PreviewData | null>(null);
@@ -522,7 +526,7 @@ function SemanticExcludesCard() {
method: "POST",
body: payload,
});
setInfo(`saved · ${r.changed.length || 0} fields updated · re-run index to apply`);
setInfo(t("semantic.savedConfig", { count: r.changed.length || 0 }));
await load();
} catch (err) {
setError((err as Error).message);
@@ -535,7 +539,7 @@ function SemanticExcludesCard() {
if (!draft) return;
setBusy(true);
setError(null);
setInfo("running dry walk against project root…");
setInfo(t("semantic.runningPreview"));
try {
const payload = fromDraft(draft);
const r = await api<PreviewData>("/index-config/preview", {
@@ -555,8 +559,8 @@ function SemanticExcludesCard() {
if (!draft) {
return html`
<div class="card">
<div class="card-h"><span class="title">index config</span></div>
<div style="color:var(--fg-3);font-size:12.5px">loading…</div>
<div class="card-h"><span class="title">${t("semantic.indexConfig")}</span></div>
<div style="color:var(--fg-3);font-size:12.5px">${t("common.loading")}</div>
</div>
`;
}
@@ -564,39 +568,39 @@ function SemanticExcludesCard() {
return html`
<div class="card">
<div class="card-h">
<span class="title">index config</span>
<span class="title">${t("semantic.indexConfig")}</span>
<span class="meta">
<a
class="mono"
style="color:var(--c-brand);text-decoration:none;font-size:11px;cursor:pointer"
onClick=${reset}
>reset</a>
>${t("semantic.reset")}</a>
</span>
</div>
${info ? html`<div style="margin-bottom:8px"><span class="pill ok">${info}</span></div>` : null}
${error ? html`<div class="card accent-err" style="margin-bottom:8px">${error}</div>` : null}
<${ChipFormRow}
label="exclude dirs"
label=${t("semantic.excludeDirs")}
value=${draft.excludeDirs}
onChange=${(v: string[]) => setDraft({ ...draft, excludeDirs: v })}
placeholder="dist"
/>
<${ChipFormRow}
label="exclude files"
label=${t("semantic.excludeFiles")}
value=${draft.excludeFiles}
onChange=${(v: string[]) => setDraft({ ...draft, excludeFiles: v })}
placeholder="package-lock.json"
/>
<${ChipFormRow}
label="exclude exts"
label=${t("semantic.excludeExts")}
value=${draft.excludeExts}
onChange=${(v: string[]) => setDraft({ ...draft, excludeExts: v })}
placeholder=".lock"
/>
<${ChipFormRow}
label="exclude patterns"
sub="glob"
label=${t("semantic.excludePatterns")}
sub=${t("semantic.glob")}
value=${draft.excludePatterns}
onChange=${(v: string[]) => setDraft({ ...draft, excludePatterns: v })}
placeholder="**/*.test.ts"
@@ -608,11 +612,11 @@ function SemanticExcludesCard() {
onClick=${() => setDraft({ ...draft, respectGitignore: !draft.respectGitignore })}
>
<span class=${`box ${draft.respectGitignore ? "on" : ""}`}>${draft.respectGitignore ? "✓" : ""}</span>
<span>respect <code class="mono">.gitignore</code></span>
<span>${t("semantic.respectGitignore")}</span>
</div>
<div class="form-row" style="margin-top:10px">
<span class="lbl">max file bytes</span>
<span class="lbl">${t("semantic.maxFileBytes")}</span>
<input
class="input mono"
type="number"
@@ -623,14 +627,14 @@ function SemanticExcludesCard() {
setDraft({ ...draft, maxFileBytes: Number((e.target as HTMLInputElement).value) || 0 })}
style="font-size:12px"
/>
<span class="help">skip files larger than ~${(draft.maxFileBytes / 1024 / 1024).toFixed(1)} MiB</span>
<span class="help">${t("semantic.skipLarger", { size: (draft.maxFileBytes / 1024 / 1024).toFixed(1) })}</span>
</div>
<div style="display:flex;gap:6px;margin-top:10px">
<button class="btn ghost" style="flex:1" disabled=${busy} onClick=${runPreview}>
<span class="g">⊕</span><span>Preview</span>
<span class="g">⊕</span><span>${t("semantic.preview")}</span>
</button>
<button class="btn primary" style="flex:1" disabled=${busy} onClick=${save}>Save</button>
<button class="btn primary" style="flex:1" disabled=${busy} onClick=${save}>${t("common.save")}</button>
</div>
${preview ? html`<div style="margin-top:10px"><${ExcludesPreview} preview=${preview} /></div>` : null}
@@ -639,6 +643,7 @@ function SemanticExcludesCard() {
}
function ExcludesPreview({ preview }: { preview: PreviewData }) {
useLang();
const buckets = preview.skipBuckets || {};
const samples = preview.skipSamples || {};
const totalSkipped = Object.values(buckets).reduce((a, b) => a + (b || 0), 0);
@@ -655,11 +660,11 @@ function ExcludesPreview({ preview }: { preview: PreviewData }) {
return html`
<div class="excludes-preview">
<div class="summary">
Preview — would index <strong>${preview.filesIncluded}</strong> file(s), skip <strong>${totalSkipped}</strong>
${t("semantic.previewSummary", { included: preview.filesIncluded, skipped: totalSkipped })}
</div>
${
reasons.length === 0
? html`<div style="color:var(--fg-3)">nothing skipped — all walked files would be indexed.</div>`
? html`<div style="color:var(--fg-3)">${t("semantic.nothingSkipped")}</div>`
: reasons.map(
(r) => html`
<details>
@@ -680,7 +685,7 @@ function ExcludesPreview({ preview }: { preview: PreviewData }) {
preview.sampleIncluded?.length
? html`
<details>
<summary>first ${preview.sampleIncluded.length} included file(s)</summary>
<summary>${t("semantic.firstIncluded", { count: preview.sampleIncluded.length })}</summary>
<ul>
${preview.sampleIncluded.map((p) => html`<li><code>${p}</code></li>`)}
</ul>
@@ -751,13 +756,14 @@ function ChipFormRow({
}
function SemanticJobView({ job, running }: { job: SemanticJob; running: boolean }) {
useLang();
const phaseLabel =
({
scan: "scanning files",
embed: "embedding chunks",
write: "writing index",
done: "done",
error: "error",
scan: t("semantic.phaseScan"),
embed: t("semantic.phaseEmbed"),
write: t("semantic.phaseWrite"),
done: t("semantic.phaseDone"),
error: t("semantic.phaseError"),
} as Record<string, string>)[job.phase] ?? job.phase;
const total = job.chunksTotal ?? 0;
const doneN = job.chunksDone ?? 0;
@@ -768,21 +774,21 @@ function SemanticJobView({ job, running }: { job: SemanticJob; running: boolean
<div class="kv">
<div><span class="kv-key">phase</span>
<span class=${`pill ${job.phase === "error" ? "pill-err" : running ? "pill-active" : "pill-dim"}`}>${phaseLabel}</span>
${job.aborted ? html`<span class="pill warn" style="margin-left: 6px;">stopping</span>` : null}
${job.aborted ? html`<span class="pill warn" style="margin-left: 6px;">${t("semantic.stopping")}</span>` : null}
<span style="color:var(--fg-3);margin-left:8px">${elapsed}s</span>
</div>
${
job.filesScanned !== null && job.filesScanned !== undefined
? html`<div><span class="kv-key">files</span>scanned ${job.filesScanned}${
job.filesChanged != null ? ` · changed ${job.filesChanged}` : ""
}${job.filesSkipped ? ` · skipped ${job.filesSkipped}` : ""}</div>`
? html`<div><span class="kv-key">${t("semantic.files")}</span>${t("semantic.scanned", { count: job.filesScanned })}${
job.filesChanged != null ? ` · ${t("semantic.changed", { count: job.filesChanged })}` : ""
}${job.filesSkipped ? ` · ${t("semantic.skipped", { count: job.filesSkipped })}` : ""}</div>`
: null
}
${
total > 0
? html`
<div>
<span class="kv-key">chunks</span>${doneN} / ${total} (${(ratio * 100).toFixed(0)}%)
<span class="kv-key">${t("semantic.chunks")}</span>${t("semantic.chunksProgress", { done: doneN, total, pct: (ratio * 100).toFixed(0) })}
</div>
<div class="bar" style="margin-top: 4px;">
<div class="fill" style=${`width: ${(ratio * 100).toFixed(1)}%; background: var(--primary);`}></div>
@@ -792,13 +798,13 @@ function SemanticJobView({ job, running }: { job: SemanticJob; running: boolean
}
${
job.error
? html`<div><span class="kv-key">error</span><span class="err">${job.error}</span></div>`
? html`<div><span class="kv-key">${t("semantic.phaseError")}</span><span class="err">${job.error}</span></div>`
: null
}
${
job.result
? html`<div><span class="kv-key">result</span>added ${job.result.chunksAdded} · removed ${job.result.chunksRemoved}${
job.result.chunksSkipped ? ` · failed ${job.result.chunksSkipped}` : ""
? html`<div><span class="kv-key">${t("semantic.result")}</span>${t("semantic.added", { count: job.result.chunksAdded })} · ${t("semantic.removed", { count: job.result.chunksRemoved })}${
job.result.chunksSkipped ? ` · ${t("semantic.failed", { count: job.result.chunksSkipped })}` : ""
} · ${(job.result.durationMs / 1000).toFixed(1)}s</div>`
: null
}
@@ -812,6 +818,7 @@ function SemanticJobView({ job, running }: { job: SemanticJob; running: boolean
}
function SkipBucketsView({ buckets }: { buckets: Record<string, number> }) {
useLang();
const order: [string, string][] = [
["gitignore", "gitignore"],
["pattern", "pattern"],
@@ -827,5 +834,5 @@ function SkipBucketsView({ buckets }: { buckets: Record<string, number> }) {
const parts = order
.filter(([k]) => (buckets[k] || 0) > 0)
.map(([k, label]) => `${label}: ${buckets[k]}`);
return html`<div><span class="kv-key">skipped</span>${total} files <span style="color:var(--fg-3)">(${parts.join(", ")})</span></div>`;
return html`<div><span class="kv-key">${t("semantic.skipped")}</span>${t("semantic.skippedFiles", { total, details: parts.join(", ") })}</div>`;
}
+16 -14
View File
@@ -4,6 +4,7 @@ import { api } from "../lib/api.js";
import { fmtBytes, fmtNum, fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface SessionEntry {
name: string;
@@ -23,6 +24,7 @@ interface OpenSession {
}
export function SessionsPanel() {
useLang();
const { data, error, loading } = usePoll<SessionsData>("/sessions", 5000);
const [open, setOpen] = useState<OpenSession | null>(null);
const [openLoading, setOpenLoading] = useState(false);
@@ -42,12 +44,12 @@ export function SessionsPanel() {
}, []);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">loading sessions…</div>`;
if (error) return html`<div class="card accent-err">sessions failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("sessions.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "sessions", error: error.message })}</div>`;
const sessions = data?.sessions ?? [];
if (sessions.length === 0)
return html`<div class="card" style="color:var(--fg-3)">No saved sessions yet.</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("sessions.noSessions")}</div>`;
const filtered = filter.trim()
? sessions.filter((s) => s.name.toLowerCase().includes(filter.toLowerCase()))
@@ -59,14 +61,14 @@ export function SessionsPanel() {
<div class="ssl-h">
<input
type="text"
placeholder="filter sessions"
placeholder=${t("sessions.filterPlaceholder")}
value=${filter}
onInput=${(e: Event) => setFilter((e.target as HTMLInputElement).value)}
style="flex:1"
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">all <span class="ct">${sessions.length}</span></span>
<span class="chip-f active">${t("common.all")} <span class="ct">${sessions.length}</span></span>
</div>
<div class="ssl-rows">
${filtered.map(
@@ -77,7 +79,7 @@ export function SessionsPanel() {
>
<span class="name">${s.name}</span>
<span class="meta">
<span><span class="v">${fmtNum(s.messageCount)}</span> msgs</span>
<span><span class="v">${fmtNum(s.messageCount)}</span> ${t("sessions.msgs")}</span>
<span><span class="v">${fmtBytes(s.size)}</span></span>
<span>${fmtRelativeTime(s.mtime)}</span>
</span>
@@ -91,7 +93,7 @@ export function SessionsPanel() {
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
Pick a session on the left to read its transcript.
${t("sessions.pickHint")}
</div>`
: html`
<div class="sessions-detail-h">
@@ -99,24 +101,24 @@ export function SessionsPanel() {
<span class="ws">
${
open.messages
? `${open.messages.length} message${open.messages.length === 1 ? "" : "s"}`
: "loading…"
? t("sessions.messages", { count: open.messages.length, s: open.messages.length === 1 ? "" : "s" })
: t("common.loading")
}
</span>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpen(null)}>← back</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
<div class="card accent-brand" style="margin-bottom:10px">
<div class="card-h"><span class="title">Resume in TUI</span></div>
<div class="card-h"><span class="title">${t("sessions.resumeTitle")}</span></div>
<div class="card-b" style="font-size:12.5px;color:var(--fg-2)">
Mid-session swap requires a restart so the message log can rewind cleanly. Quit your current session, then run:
${t("sessions.resumeDesc")}
<code class="mono" style="display:block;margin-top:8px;padding:8px 10px;background:var(--bg-input);border-radius:var(--r);color:var(--fg-0);font-size:12px;user-select:all">reasonix chat --session ${open.name}</code>
</div>
</div>
${
openLoading
? html`<div style="color:var(--fg-3)">loading transcript…</div>`
? html`<div style="color:var(--fg-3)">${t("sessions.loadingTranscript")}</div>`
: open.error
? html`<div class="card accent-err">${open.error}</div>`
: open.messages && open.messages.length > 0
@@ -143,7 +145,7 @@ export function SessionsPanel() {
`,
)}
</div>`
: html`<div style="color:var(--fg-3)">empty transcript.</div>`
: html`<div style="color:var(--fg-3)">${t("sessions.emptyTranscript")}</div>`
}
`
}
+51 -28
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { html } from "../lib/html.js";
import { type DashboardLang, getLang, setLang, t, useLang } from "../i18n/index.js";
interface SettingsData {
apiKey?: string | null;
@@ -13,6 +14,7 @@ interface SettingsData {
}
export function SettingsPanel() {
useLang();
const [data, setData] = useState<SettingsData | null>(null);
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
@@ -39,7 +41,7 @@ export function SettingsPanel() {
try {
await api("/settings", { method: "POST", body: fields });
await load();
setSaved(`saved: ${Object.keys(fields).join(", ")}`);
setSaved(t("settings.saved", { fields: Object.keys(fields).join(", ") }));
setTimeout(() => setSaved(null), 3000);
} catch (err) {
setError((err as Error).message);
@@ -51,7 +53,7 @@ export function SettingsPanel() {
);
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">loading settings…</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("settings.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
const v = data;
@@ -71,6 +73,8 @@ export function SettingsPanel() {
</div>
`;
const currentLang = getLang();
return html`
<div style="max-width:760px;display:flex;flex-direction:column;gap:6px">
${
@@ -80,18 +84,37 @@ export function SettingsPanel() {
error ? html`<div class="card accent-err">${error}</div>` : null
}
${sectionH3("DeepSeek API")}
${sectionH3(t("settings.sectionLanguage"))}
<div class="card">
${fieldRow(
"API key",
html`<code class="mono" style="color:var(--fg-2);font-size:11.5px">${v.apiKey ?? "(not set)"}</code>`,
t("settings.language"),
html`
<select
value=${currentLang}
onChange=${(e: Event) => {
const lang = (e.target as HTMLSelectElement).value as DashboardLang;
setLang(lang);
}}
>
<option value="en">${t("settings.langEn")}</option>
<option value="zh-CN">${t("settings.langZhCn")}</option>
</select>
`,
)}
</div>
${sectionH3(t("settings.sectionApi"))}
<div class="card">
${fieldRow(
t("settings.apiKey"),
html`<code class="mono" style="color:var(--fg-2);font-size:11.5px">${v.apiKey ?? t("settings.notSet")}</code>`,
)}
${fieldRow(
"replace",
t("settings.replace"),
html`
<input
type="password"
placeholder="paste a fresh sk-… token"
placeholder=${t("settings.pasteKey")}
value=${draft.apiKey ?? ""}
onInput=${(e: Event) => setDraft({ ...draft, apiKey: (e.target as HTMLInputElement).value })}
style="flex:1"
@@ -100,16 +123,16 @@ export function SettingsPanel() {
class="btn primary"
disabled=${saving || !(draft.apiKey ?? "").trim()}
onClick=${() => save({ apiKey: draft.apiKey })}
>Save key</button>
>${t("settings.saveKey")}</button>
`,
)}
${fieldRow(
"base url",
t("settings.baseUrl"),
html`
<input
type="text"
value=${draft.baseUrl ?? v.baseUrl ?? ""}
placeholder="https://api.deepseek.com (default)"
placeholder=${t("settings.baseUrlPlaceholder")}
onInput=${(e: Event) => setDraft({ ...draft, baseUrl: (e.target as HTMLInputElement).value })}
style="flex:1"
/>
@@ -117,65 +140,65 @@ export function SettingsPanel() {
class="btn"
disabled=${saving || (draft.baseUrl ?? v.baseUrl ?? "") === (v.baseUrl ?? "")}
onClick=${() => save({ baseUrl: draft.baseUrl })}
>Save</button>
>${t("common.save")}</button>
`,
)}
</div>
${sectionH3("Defaults")}
${sectionH3(t("settings.sectionDefaults"))}
<div class="card">
${fieldRow(
"preset",
t("settings.preset"),
html`
<select
value=${["auto", "flash", "pro"].includes(v.preset ?? "") ? v.preset : "auto"}
onChange=${(e: Event) => save({ preset: (e.target as HTMLSelectElement).value })}
disabled=${saving}
>
<option value="auto">auto — flash → pro on hard turns</option>
<option value="flash">flash — always flash, no auto-escalate</option>
<option value="pro">pro — always pro</option>
<option value="auto">${t("settings.presetAuto")}</option>
<option value="flash">${t("settings.presetFlash")}</option>
<option value="pro">${t("settings.presetPro")}</option>
</select>
`,
"applies next turn",
t("settings.appliesNextTurn"),
)}
${fieldRow(
"effort",
t("settings.effort"),
html`
<select
value=${v.reasoningEffort}
onChange=${(e: Event) => save({ reasoningEffort: (e.target as HTMLSelectElement).value })}
disabled=${saving}
>
<option value="max">max (default — best)</option>
<option value="high">high (cheaper / faster)</option>
<option value="max">${t("settings.effortMax")}</option>
<option value="high">${t("settings.effortHigh")}</option>
</select>
`,
"applies next turn",
t("settings.appliesNextTurn"),
)}
${fieldRow(
"web search",
t("settings.webSearch"),
html`
<button
class=${`btn ${v.search ? "primary" : ""}`}
onClick=${() => save({ search: !v.search })}
disabled=${saving}
>${v.search ? "ON" : "off"}</button>
>${v.search ? t("common.on") : t("common.off")}</button>
`,
"web_fetch + web_search tools",
t("settings.webSearchNote"),
)}
</div>
${sectionH3("Runtime")}
${sectionH3(t("settings.sectionRuntime"))}
<div class="card">
${fieldRow(
"active model",
t("settings.activeModel"),
html`<code class="mono">${v.model ?? "—"}</code>`,
)}
${fieldRow(
"edit mode",
t("settings.editMode"),
html`<code class="mono">${v.editMode}</code>`,
"switch from the Chat tab header",
t("settings.editModeNote"),
)}
</div>
</div>
+25 -23
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface SkillEntry {
name: string;
@@ -18,6 +19,7 @@ interface SkillsData {
type Scope = "project" | "global" | "builtin";
export function SkillsPanel() {
useLang();
const [data, setData] = useState<SkillsData | null>(null);
const [error, setError] = useState<string | null>(null);
const [open, setOpen] = useState<{ scope: Scope; name: string } | null>(null);
@@ -64,7 +66,7 @@ export function SkillsPanel() {
method: "POST",
body: { body },
});
setInfo(`saved ${open.scope}/${open.name}`);
setInfo(t("skills.saved", { scope: open.scope, name: open.name }));
setTimeout(() => setInfo(null), 3000);
await load();
} catch (err) {
@@ -76,7 +78,7 @@ export function SkillsPanel() {
const remove = useCallback(async () => {
if (!open) return;
if (!confirm(`Delete skill ${open.scope}/${open.name}?`)) return;
if (!confirm(t("skills.deleteConfirm", { scope: open.scope, name: open.name }))) return;
setBusy(true);
try {
await api(`/skills/${open.scope}/${encodeURIComponent(open.name)}`, { method: "DELETE" });
@@ -109,7 +111,7 @@ export function SkillsPanel() {
}, [newName, newScope, load, openSkill]);
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">loading skills…</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("skills.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
@@ -132,17 +134,17 @@ export function SkillsPanel() {
<div class="ssl-h">
<input
type="text"
placeholder="filter skills"
placeholder=${t("skills.filterPlaceholder")}
value=${filter}
onInput=${(e: Event) => setFilter((e.target as HTMLInputElement).value)}
style="flex:1"
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">all <span class="ct">${allWith.length}</span></span>
<span class="chip-f">project <span class="ct">${data.project.length}</span></span>
<span class="chip-f">global <span class="ct">${data.global.length}</span></span>
<span class="chip-f">builtin <span class="ct">${data.builtin.length}</span></span>
<span class="chip-f active">${t("common.all")} <span class="ct">${allWith.length}</span></span>
<span class="chip-f">${t("skills.project")} <span class="ct">${data.project.length}</span></span>
<span class="chip-f">${t("skills.global")} <span class="ct">${data.global.length}</span></span>
<span class="chip-f">${t("skills.builtin")} <span class="ct">${data.builtin.length}</span></span>
</div>
<div style="padding:0 12px 8px;display:flex;gap:6px;flex-wrap:wrap">
@@ -151,12 +153,12 @@ export function SkillsPanel() {
onChange=${(e: Event) => setNewScope((e.target as HTMLSelectElement).value as "global" | "project")}
style="flex:0 0 auto;font-size:11.5px;padding:5px 6px"
>
<option value="global">global</option>
${data.paths.project ? html`<option value="project">project</option>` : null}
<option value="global">${t("skills.global")}</option>
${data.paths.project ? html`<option value="project">${t("skills.project")}</option>` : null}
</select>
<input
type="text"
placeholder="new skill"
placeholder=${t("skills.newSkill")}
value=${newName}
onInput=${(e: Event) => setNewName((e.target as HTMLInputElement).value)}
style="flex:1;min-width:0"
@@ -174,13 +176,13 @@ export function SkillsPanel() {
>
<span class="name">
${s.name}
${s.scope === "builtin" ? html`<span class="pill">builtin</span>` : null}
${s.scope === "builtin" ? html`<span class="pill">${t("skills.builtin")}</span>` : null}
</span>
<span class="preview">${s.description ?? "(no description)"}</span>
<span class="preview">${s.description ?? t("skills.noDescription")}</span>
<span class="meta">
${
typeof s.runs7d === "number" && s.runs7d > 0
? html`<span><span class="v">${s.runs7d}</span> runs · 7d</span>`
? html`<span><span class="v">${s.runs7d}</span> ${t("skills.runs7d")}</span>`
: null
}
<span class="dim">${s.scope}</span>
@@ -195,7 +197,7 @@ export function SkillsPanel() {
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
Pick a skill on the left, or create a new one above.
${t("skills.pickHint")}
</div>`
: open.scope === "builtin"
? (() => {
@@ -203,16 +205,16 @@ export function SkillsPanel() {
return html`
<div class="sessions-detail-h">
<span class="name">${open.scope}/${open.name}</span>
<span class="ws"><span class="pill">read-only · builtin</span></span>
<span class="ws"><span class="pill">${t("skills.readOnlyBuiltin")}</span></span>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpen(null)}>← back</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
<div style="color:var(--fg-2);font-size:13px;line-height:1.6">
${builtin?.description ?? "(no description)"}
${builtin?.description ?? t("skills.noDescription")}
</div>
<div style="margin-top:14px;color:var(--fg-3);font-size:11.5px">
Built-in skills ship with Reasonix; the model picks them up automatically. To customize, create a project- or global-scoped skill with the same name.
${t("skills.builtinDesc")}
</div>
`;
})()
@@ -221,10 +223,10 @@ export function SkillsPanel() {
<span class="name">${open.scope}/${open.name}</span>
<span class="ws">${body.length.toLocaleString()} chars</span>
<span class="actions">
<button class="btn primary" disabled=${busy} onClick=${save}>Save</button>
<button class="btn primary" disabled=${busy} onClick=${save}>${t("common.save")}</button>
<button class="btn" disabled=${busy} onClick=${remove}
style="border-color:var(--c-err);color:var(--c-err)">Delete</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>← back</button>
style="border-color:var(--c-err);color:var(--c-err)">${t("common.delete")}</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
${info ? html`<div style="margin-bottom:8px"><span class="pill ok">${info}</span></div>` : null}
@@ -236,7 +238,7 @@ export function SkillsPanel() {
disabled=${busy}
></textarea>
<div style="margin-top:8px;color:var(--fg-3);font-size:11.5px">
re-loaded on next <code class="mono">/new</code> or session restart
${t("skills.reloadHint")}
</div>
`
}
+31 -29
View File
@@ -1,6 +1,7 @@
import { fmtBytes, fmtNum } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface HealthData {
version: string;
@@ -14,97 +15,98 @@ interface HealthData {
}
export function SystemPanel() {
useLang();
const { data, error, loading } = usePoll<HealthData>("/health", 5000);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">loading health…</div>`;
if (error) return html`<div class="card accent-err">health failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("system.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "health", error: error.message })}</div>`;
if (!data) return null;
const h = data;
const upToDate = h.latestVersion ? h.latestVersion === h.version : null;
return html`
<div style="display:flex;flex-direction:column;gap:14px">
<h3 style="margin:0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">Health checks</h3>
<h3 style="margin:0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">${t("system.healthChecks")}</h3>
<div class="health-grid">
<div class=${`health-item ${upToDate === false ? "warn" : ""}`}>
<div class="lbl">
version
${t("system.version")}
${
upToDate === null
? html`<span class="pill">checking</span>`
? html`<span class="pill">${t("system.checking")}</span>`
: upToDate
? html`<span class="pill ok">● latest</span>`
: html`<span class="pill warn">● out of date</span>`
? html`<span class="pill ok">${t("system.latest")}</span>`
: html`<span class="pill warn">${t("system.outOfDate")}</span>`
}
</div>
<div class="v">${h.version}</div>
<div class="meta">${
upToDate === null
? "version check pending"
? t("system.versionPending")
: upToDate
? "up to date"
: `latest: ${h.latestVersion}`
? t("system.upToDate")
: t("system.latestVer", { version: h.latestVersion ?? "" })
}</div>
</div>
<div class="health-item">
<div class="lbl">sessions <span class="pill ok">● ok</span></div>
<div class="lbl">${t("system.sessions")} <span class="pill ok">${t("system.ok")}</span></div>
<div class="v">${fmtBytes(h.sessions.totalBytes)}</div>
<div class="meta">${fmtNum(h.sessions.count)} files</div>
<div class="meta">${fmtNum(h.sessions.count)} ${t("system.files")}</div>
</div>
<div class="health-item">
<div class="lbl">memory <span class="pill ok">● ok</span></div>
<div class="lbl">${t("system.memory")} <span class="pill ok">${t("system.ok")}</span></div>
<div class="v">${fmtBytes(h.memory.totalBytes)}</div>
<div class="meta">${fmtNum(h.memory.fileCount)} files</div>
<div class="meta">${fmtNum(h.memory.fileCount)} ${t("system.files")}</div>
</div>
<div class="health-item">
<div class="lbl">
semantic index
${t("system.semanticIndex")}
${
h.semantic.exists
? html`<span class="pill ok">● built</span>`
: html`<span class="pill">— none</span>`
? html`<span class="pill ok">${t("system.built")}</span>`
: html`<span class="pill">${t("system.none")}</span>`
}
</div>
<div class="v">${h.semantic.exists ? fmtBytes(h.semantic.totalBytes) : "—"}</div>
<div class="meta">
${h.semantic.exists ? `${fmtNum(h.semantic.fileCount)} files` : "run reasonix index to build"}
${h.semantic.exists ? `${fmtNum(h.semantic.fileCount)} ${t("system.files")}` : t("system.runIndex")}
</div>
</div>
<div class="health-item">
<div class="lbl">usage log <span class="pill ok">● ok</span></div>
<div class="lbl">${t("system.usageLog")} <span class="pill ok">${t("system.ok")}</span></div>
<div class="v">${fmtBytes(h.usageLog.bytes)}</div>
<div class="meta">~/.reasonix/usage.jsonl</div>
</div>
<div class="health-item">
<div class="lbl">
background jobs
${t("system.backgroundJobs")}
${
h.jobs === null
? html`<span class="pill">— no session</span>`
? html`<span class="pill">${t("system.noSession")}</span>`
: html`<span class="pill ok">● ${fmtNum(h.jobs)}</span>`
}
</div>
<div class="v">${h.jobs === null ? "—" : `${fmtNum(h.jobs)} running`}</div>
<div class="meta">${h.jobs === null ? "attach a session to see jobs" : "shell + spawn"}</div>
<div class="v">${h.jobs === null ? "—" : t("system.running", { count: fmtNum(h.jobs) })}</div>
<div class="meta">${h.jobs === null ? t("system.attachHint") : t("system.shellSpawn")}</div>
</div>
</div>
<div class="card" style="padding:0">
<div class="card-h" style="padding:12px 14px 6px">
<span class="title">paths</span>
<span class="title">${t("system.paths")}</span>
</div>
<table class="tbl">
<tbody style="font-size:11.5px">
<tr><td class="dim" style="padding:5px 14px">home</td><td class="path">${h.reasonixHome}</td></tr>
<tr><td class="dim" style="padding:5px 14px">sessions</td><td class="path">${h.sessions.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">memory</td><td class="path">${h.memory.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">semantic</td><td class="path">${h.semantic.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">usage</td><td class="path">${h.usageLog.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.home")}</td><td class="path">${h.reasonixHome}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.sessionsPath")}</td><td class="path">${h.sessions.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.memoryPath")}</td><td class="path">${h.memory.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.semanticPath")}</td><td class="path">${h.semantic.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.usagePath")}</td><td class="path">${h.usageLog.path}</td></tr>
</tbody>
</table>
</div>
+17 -15
View File
@@ -1,5 +1,6 @@
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface ToolEntry {
name: string;
@@ -21,47 +22,48 @@ interface ToolsError {
}
export function ToolsPanel() {
useLang();
const { data, error, loading } = usePoll<ToolsData>("/tools", 4000);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">loading tools…</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("tools.loading")}</div>`;
const e = error as ToolsError | null;
if (e?.status === 503) {
return html`<div class="card accent-warn">${e.body?.error ?? "live tools view requires an attached session"}</div>`;
return html`<div class="card accent-warn">${e.body?.error ?? t("common.loadingFailed", { name: "tools", error: "" })}</div>`;
}
if (e) return html`<div class="card accent-err">tools failed: ${e.message}</div>`;
if (e) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "tools", error: e.message })}</div>`;
if (!data) return null;
const t = data;
const d = data;
return html`
<div style="display:flex;flex-direction:column;gap:14px">
<div class="chips">
<span class="chip-f active">all <span class="ct">${t.total}</span></span>
${t.planMode ? html`<span class="chip-f" style="border-color:var(--c-warn);color:var(--c-warn)">plan mode — writes gated</span>` : null}
<span class="chip-f active">${t("common.all")} <span class="ct">${d.total}</span></span>
${d.planMode ? html`<span class="chip-f" style="border-color:var(--c-warn);color:var(--c-warn)">${t("tools.planMode")}</span>` : null}
</div>
${
t.tools.length === 0
? html`<div class="card" style="color:var(--fg-3)">No tools registered.</div>`
d.tools.length === 0
? html`<div class="card" style="color:var(--fg-3)">${t("tools.noTools")}</div>`
: html`
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<th>tool</th>
<th>flags</th>
<th>description</th>
<th>${t("tools.colTool")}</th>
<th>${t("tools.colFlags")}</th>
<th>${t("tools.colDesc")}</th>
</tr>
</thead>
<tbody>
${t.tools.map(
${d.tools.map(
(tool) => html`
<tr>
<td><code class="mono">${tool.name}</code></td>
<td>
${tool.readOnly
? html`<span class="pill ok">read-only</span>`
: html`<span class="pill acc">write</span>`}
${tool.flattened ? html` <span class="pill">flat</span>` : null}
? html`<span class="pill ok">${t("tools.readOnly")}</span>`
: html`<span class="pill acc">${t("tools.write")}</span>`}
${tool.flattened ? html` <span class="pill">${t("tools.flat")}</span>` : null}
</td>
<td class="dim">${tool.description ?? ""}</td>
</tr>
+20 -19
View File
@@ -3,6 +3,7 @@ import { api } from "../lib/api.js";
import { fmtNum, fmtPct, fmtUsd } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
type UPlotInstance = {
destroy(): void;
@@ -132,6 +133,7 @@ interface UsageSummary {
}
export function UsagePanel() {
useLang();
const { data: summary, error, loading } = usePoll<UsageSummary>("/usage", 5000);
const [series, setSeries] = useState<UsageDay[] | null>(null);
@@ -145,7 +147,7 @@ export function UsagePanel() {
/* keep null; chart hides */
}
})();
const t = setInterval(async () => {
const interval = setInterval(async () => {
try {
const s = await api<{ days?: UsageDay[] }>("/usage/series");
if (!cancelled) setSeries(s.days ?? []);
@@ -155,13 +157,13 @@ export function UsagePanel() {
}, 30_000);
return () => {
cancelled = true;
clearInterval(t);
clearInterval(interval);
};
}, []);
if (loading && !summary)
return html`<div class="card" style="color:var(--fg-3)">loading usage…</div>`;
if (error) return html`<div class="card accent-err">usage failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("usage.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "usage", error: error.message })}</div>`;
if (!summary) return null;
const u = summary;
@@ -172,7 +174,7 @@ export function UsagePanel() {
return html`
<div style="display:flex;flex-direction:column;gap:6px">
<div class="chips">
<span class="chip-f active">${u.recordCount.toLocaleString()} records</span>
<span class="chip-f active">${t("usage.records", { count: u.recordCount.toLocaleString() })}</span>
<span class="chip-f">${u.logSize}</span>
</div>
@@ -181,8 +183,8 @@ export function UsagePanel() {
? html`
<div class="card" style="padding:18px">
<div class="card-h">
<span class="title">Daily usage</span>
<span class="meta">cost · cache saved · turns</span>
<span class="title">${t("usage.dailyUsage")}</span>
<span class="meta">${t("usage.dailyMeta")}</span>
</div>
<${UsageChart} days=${series} />
</div>
@@ -193,22 +195,21 @@ export function UsagePanel() {
${
u.recordCount === 0
? html`<div class="card" style="color:var(--fg-3);margin-top:8px">
No usage data yet — run a turn in <code class="mono">reasonix chat</code> /
<code class="mono">code</code> / <code class="mono">run</code> and refresh.
${t("usage.noData")}
</div>`
: html`
${sectionH3("Rolling windows")}
${sectionH3(t("usage.windows"))}
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<th></th>
<th>turns</th>
<th>cache hit</th>
<th>cost (USD)</th>
<th>cache saved</th>
<th>vs Claude</th>
<th>saved</th>
<th>${t("usage.colTurns")}</th>
<th>${t("usage.colCacheHit")}</th>
<th>${t("usage.colCost")}</th>
<th>${t("usage.colCacheSaved")}</th>
<th>${t("usage.colVsClaude")}</th>
<th>${t("usage.colSaved")}</th>
</tr>
</thead>
<tbody>
@@ -240,13 +241,13 @@ export function UsagePanel() {
${
u.byModel.length > 0
? html`
${sectionH3("Most used models")}
${sectionH3(t("usage.mostUsed"))}
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<th>model</th>
<th>turns</th>
<th>${t("usage.colModel")}</th>
<th>${t("usage.colTurns")}</th>
</tr>
</thead>
<tbody>
+203 -83
View File
@@ -254,6 +254,52 @@ main { padding: 32px 48px 40px 32px; min-width: 0; }
color: var(--fg-4); font-weight: 700; margin-right: 12px;
}
.tag .cls { color: var(--c-brand); }
/* Inline pill — bg-tinted chip used inside .mock rows for section labels,
model badges, and inline path refs. Padding lives INSIDE the content
(leading/trailing space chars) so column alignment in monospace
ASCII art is preserved. Terminal implementation: <Text backgroundColor=
color=> with real space chars on either side of the label. */
.mock .pill {
font-weight: 700;
letter-spacing: .04em;
}
/* Section pill — accent-tinted bg, accent fg. One per card type.
Color group matches the card's accent bar. */
.mock .pill.sec-reason { background: #2a1f3d; color: var(--c-accent); }
.mock .pill.sec-tool { background: #0f2230; color: var(--c-info); }
.mock .pill.sec-shell { background: #0f2230; color: var(--c-info); }
.mock .pill.sec-task { background: #0d1d2e; color: var(--c-brand); }
.mock .pill.sec-plan { background: #2a1f3d; color: var(--c-accent); }
.mock .pill.sec-diff { background: #11141a; color: var(--fg-1); }
.mock .pill.sec-user { background: #11141a; color: var(--fg-2); }
.mock .pill.sec-warn { background: #2b1f12; color: var(--c-warn); }
.mock .pill.sec-err { background: #2c1416; color: var(--c-err); }
.mock .pill.sec-ok { background: #102815; color: var(--c-ok); }
/* State variants — same shape, swapped color when the card is in a non-default state. */
.mock .pill.sec-task.s-done { background: #102815; color: var(--c-ok); }
.mock .pill.sec-task.s-failed { background: #2c1416; color: var(--c-err); }
/* Model pill — neutral bg-elev, color signals model class.
flash=brand/blue (cheap fast), pro=accent/purple (premium),
r1=violet (reasoner). Read at a glance without text. */
.mock .pill.mdl-flash { background: #11141a; color: var(--c-brand); }
.mock .pill.mdl-pro { background: #11141a; color: var(--c-accent); }
.mock .pill.mdl-r1 { background: #11141a; color: var(--c-violet); }
/* Path pill — neutral bg-elev for filenames / paths inside tool rows.
Lower-weight so it reads as data not chrome. */
.mock .pill.path { background: #11141a; color: var(--fg-2); font-weight: 500; letter-spacing: 0; }
/* Body anchor — the ↳ corner glyph that sits at the start of the FIRST
body line, telling the eye "this is where the card body branches off
from the header above". Subtle, color-matches the card accent. */
.mock .anchor { color: var(--c-accent); }
.mock .anchor.brand { color: var(--c-brand); }
.mock .anchor.info { color: var(--c-info); }
.mock .anchor.violet{ color: var(--c-violet); }
.mock .anchor.ok { color: var(--c-ok); }
.mock .anchor.err { color: var(--c-err); }
.mock .anchor.warn { color: var(--c-warn); }
.mock .anchor.fg3 { color: var(--fg-3); }
</style>
</head>
<body>
@@ -431,22 +477,22 @@ main { padding: 32px 48px 40px 32px; min-width: 0; }
<pre class="body">
<span class="fg4">◈ session-7 · main · ~/projects/reasonix · deepseek-chat</span>
<span class="fg3">◇</span> <span class="b fg2">you</span> <span class="fg4">· just now</span>
<span class="fg1">refactor the SKIP_DIRS list out of chunker.ts so directory_tree</span>
<span class="fg1">can reuse it</span>
<span class="pill sec-user">&nbsp;YOU&nbsp;</span> <span class="fg4">· just now</span>
<span class="anchor fg3">↳</span> <span class="fg1">refactor the SKIP_DIRS list out of chunker.ts so directory_tree</span>
<span class="fg1">can reuse it</span>
<span class="accent">▎</span> <span class="accent b">◆ Reasoning</span> <span class="fg4">· 3 paragraphs · 412 tok</span> <span class="fg4">▸</span>
<span class="accent">▎</span> <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> <span class="pill mdl-pro">&nbsp;v4-pro&nbsp;</span> <span class="fg4">412 tok · 3 ¶</span> <span class="fg3">3.1s</span>
<span class="brand">▎</span> <span class="brand b">▶ Step 2 of 5 · Refactor exclude config</span> <span class="fg3">4.2s · </span><span class="brand">running</span>
<span class="brand">▎</span> <span class="pill sec-task">&nbsp;TASK&nbsp;</span> <span class="b fg0">2 / 5 Refactor exclude config</span> <span class="fg3">4.2s · </span><span class="brand">running</span>
<span class="brand">▎</span>
<span class="brand">▎</span> <span class="fg2">Pull SKIP_DIRS / SKIP_FILES out of chunker.ts so directory_tree</span>
<span class="brand">▎</span> <span class="fg2">can reuse them.</span>
<span class="brand">▎</span> <span class="anchor brand">↳</span> <span class="fg2">Pull SKIP_DIRS / SKIP_FILES out of chunker.ts so directory_tree</span>
<span class="brand">▎</span> <span class="fg2">can reuse them.</span>
<span class="brand">▎</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">read </span> <span class="fg2">src/index/semantic/chunker.ts</span> <span class="fg3">0.08s · 250 lines</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">read </span> <span class="fg2">src/tools/filesystem.ts</span> <span class="fg3">0.07s · 712 lines</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">write </span> <span class="fg2">src/index/config.ts</span> <span class="fg3">0.12s · created</span>
<span class="brand">▎</span> <span class="brand">▶</span> <span class="b fg1">edit </span> <span class="fg2">src/tools/filesystem.ts</span> <span class="brand">running…</span>
<span class="brand">▎</span> <span class="fg4">○</span> <span class="b fg3">verify </span> <span class="fg3">npm run typecheck &amp;&amp; npm test</span> <span class="fg4">queued</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">read </span> <span class="pill path">&nbsp;src/index/semantic/chunker.ts&nbsp;</span> <span class="fg3">0.08s · 250 lines</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">read </span> <span class="pill path">&nbsp;src/tools/filesystem.ts&nbsp;</span> <span class="fg3">0.07s · 712 lines</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">write </span> <span class="pill path">&nbsp;src/index/config.ts&nbsp;</span> <span class="fg3">0.12s · created</span>
<span class="brand">▎</span> <span class="brand">▶</span> <span class="b fg1">edit </span> <span class="pill path">&nbsp;src/tools/filesystem.ts&nbsp;</span> <span class="brand">running…</span>
<span class="brand">▎</span> <span class="fg4">○</span> <span class="b fg3">verify </span> <span class="fg3">npm run typecheck &amp;&amp; npm test</span> <span class="fg4">queued</span>
<span class="brand">▎</span> <span class="brand b">▶</span> <span class="fg1">The change maps to three edits — I'll start with the config module,</span>
<span class="brand">▎</span> <span class="fg1">then the chunker, then wire it through the CLI command. Each step</span>
@@ -577,111 +623,183 @@ main { padding: 32px 48px 40px 32px; min-width: 0; }
<!-- User message -->
<section class="section" id="c-user">
<h2><span class="num">05</span>Cards · user message</h2>
<p class="lede">No accent bar — the user's input is the conversational anchor, deserves a quieter treatment than agent activity.</p>
<p class="lede">No accent bar — the user's input is the conversational anchor, deserves a quieter treatment than agent activity. The <span class="pill sec-user">&nbsp;YOU&nbsp;</span> pill uses a neutral bg with muted fg so it reads as identification, not status.</p>
<div class="tag">CARD · <span class="cls">.user</span></div>
<pre class="mock"> <span class="fg3">◇</span> <span class="b fg2">you</span> <span class="fg4">· 2 min ago</span>
<span class="fg1">refactor the SKIP_DIRS list out of chunker.ts so directory_tree</span>
<span class="fg1">can reuse it</span>
<pre class="mock"> <span class="pill sec-user">&nbsp;YOU&nbsp;</span> <span class="fg4">· 2 min ago</span>
<span class="anchor fg3">↳</span> <span class="fg1">refactor the SKIP_DIRS list out of chunker.ts so directory_tree</span>
<span class="fg1">can reuse it</span>
</pre>
<p class="lede">Body anchor uses the muted <span class="anchor fg3">↳</span> (fg-3) — the user card has no accent color to take from, so the anchor stays neutral.</p>
</section>
<!-- Reasoning -->
<section class="section" id="c-reason">
<h2><span class="num">06</span>Cards · reasoning</h2>
<p class="lede">Default <strong>collapsed</strong> — reasoning is opt-in noise. Always italic + dim when expanded so it never competes with primary content.</p>
<div class="tag">CARD · <span class="cls">.reasoning</span></div>
<pre class="mock"> <span class="accent">▎</span> <span class="accent b">◆ Reasoning</span> <span class="fg4">· 3 paragraphs · 412 tok</span> <span class="fg4">▸</span>
</pre>
<div class="tag">EXPANDED · <span class="cls">.reasoning[open]</span></div>
<pre class="mock"> <span class="accent">▎</span> <span class="accent b">◆ Reasoning</span> <span class="fg4">· 3 paragraphs · 412 tok</span> <span class="fg4">▾</span>
<p class="lede"><strong>No collapse / expand</strong> — TUI can't host interactive disclosure cleanly. The card adapts to content size in <strong>four tiers</strong>: streaming (live tail), settled-short (full body), settled-long (head + tail, middle elided), <strong>settled-XL (tail only — head dropped)</strong>. The XL drop is deliberate: at &gt;800 tok the opening is almost always restating the prompt the model has since moved past, while the conclusion carries the actionable synthesis. Header carries two <strong>bg-tinted pills</strong> — a <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> section pill and a model pill (color = model class). Body is italic + dim so it never competes with primary content. The <span class="anchor">↳</span> anchor marks the absolute beginning of the body — it appears only when that beginning is actually visible (so it's absent in streaming-with-overflow and in XL).</p>
<div class="tag">HEADER + BODY ANATOMY</div>
<pre class="mock"> <span class="accent">▎</span> <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> <span class="pill mdl-pro">&nbsp;v4-pro&nbsp;</span> <span class="fg4">412 tok · 3 ¶</span> <span class="fg3">3.1s</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="i fg3">Two paths: replace the hardcoded list when config is set, or merge</span>
<span class="accent">▎</span> <span class="i fg3">user values in. The first matches the explicit "config-driven" ask;</span>
<span class="accent">▎</span> <span class="i fg3">the second is safer default. Going with the first since the user's</span>
<span class="accent">▎</span> <span class="i fg3">words outrank my safety instinct here.</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="i fg3">Files to touch: chunker.ts (drop constants, accept resolved config),</span>
<span class="accent">▎</span> <span class="i fg3">filesystem.ts (drop its own copy), and the index command (load + pass).</span>
<span class="accent">▎</span> <span class="anchor">↳</span> <span class="i fg3">first line of body…</span>
<span class="accent">▎</span> <span class="i fg3">subsequent lines align under the anchor's content column</span>
<span class="fg4">↑ rule</span> <span class="fg4">↑ section pill</span> <span class="fg4">↑ model pill</span> <span class="fg4">↑ counts</span> <span class="fg4">↑ duration</span>
</pre>
<p class="lede">Two pills replace the old <code>◆</code> glyph + emoji prefix. Section pill is accent-purple-tinted bg with accent fg — one fixed style per card type. Model pill uses neutral bg-elev with <strong>fg color = model class</strong>: <span class="pill mdl-flash">&nbsp;v4-flash&nbsp;</span> sky-blue (cheap), <span class="pill mdl-pro">&nbsp;v4-pro&nbsp;</span> purple (premium), <span class="pill mdl-r1">&nbsp;r1&nbsp;</span> violet (reasoner). Color carries the signal — no emoji needed. The <span class="anchor">↳</span> body anchor is a project-wide convention: every card body section opens with one in the card's accent color.</p>
<div class="tag">STREAMING · <span class="cls">.reasoning .streaming</span> · live tail-3-lines while bytes arrive</div>
<pre class="mock"> <span class="accent">▎</span> <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> <span class="pill mdl-r1">&nbsp;r1&nbsp;</span> <span class="fg4">247 tok</span> <span class="fg3">1.2s · </span><span class="brand">thinking…</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="fg4">⋮ earlier lines scrolled past preview window</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="i fg3">First weighing two approaches: should I patch the chunker to</span>
<span class="accent">▎</span> <span class="i fg3">accept a config arg, or pull the constants up to a shared</span>
<span class="accent">▎</span> <span class="i fg3">module… going with shared module since it's cleaner.</span><span class="cur"></span>
</pre>
<p class="lede">Tail-3-lines is a fixed window — newer lines push older lines into the dim <span class="fg4">⋮</span> gutter mark. <strong>No <span class="anchor">↳</span> anchor</strong> when overflow is active — the absolute body start has scrolled past, so labelling the visible top as "body begins" would be a lie. The <span class="fg4">⋮</span> gutter is the indicator that content is scrolling past. Block cursor on the live edge. Token count ticks live; duration freezes on stream end. (When streaming starts and content is still under 3 lines, the <span class="anchor">↳</span> appears normally on the absolute first line — it disappears the moment overflow kicks in.)</p>
<div class="tag">SETTLED · SHORT · <span class="cls">.reasoning .settled .short</span> · ≤ ~4 lines, render in full</div>
<pre class="mock"> <span class="accent">▎</span> <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> <span class="pill mdl-pro">&nbsp;v4-pro&nbsp;</span> <span class="fg4">87 tok · 1 ¶</span> <span class="fg3">1.2s</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="anchor">↳</span> <span class="i fg3">The user wants the storm guard to soften, not be removed. Plan: track</span>
<span class="accent">▎</span> <span class="i fg3">first-vs-second storm per turn, only end the turn on the second one.</span>
<span class="accent">▎</span> <span class="i fg3">Keep the warning copy plain.</span>
</pre>
<p class="lede">No elision needed — full reasoning fits in the visual budget. Header gains <span class="fg4">N ¶</span> paragraph count once the stream settles.</p>
<div class="tag">SETTLED · LONG · <span class="cls">.reasoning .settled .long</span> · &gt; 4 lines OR &gt; 200 tok, head + tail paragraphs · middle elided</div>
<pre class="mock"> <span class="accent">▎</span> <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> <span class="pill mdl-r1">&nbsp;r1&nbsp;</span> <span class="fg4">412 tok · 3 ¶</span> <span class="fg3">3.1s</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="anchor">↳</span> <span class="i fg3">Two paths: replace the hardcoded list when config is set, or merge</span>
<span class="accent">▎</span> <span class="i fg3">user values in. The first matches the explicit "config-driven" ask;</span>
<span class="accent">▎</span> <span class="i fg3">the second is safer default.</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="fg4">⋯ 1 ¶ elided · /reasoning last ⋯</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="i fg3">Files to touch: chunker.ts (drop constants, accept resolved config),</span>
<span class="accent">▎</span> <span class="i fg3">filesystem.ts (drop its own copy), and the index command (load + pass).</span>
</pre>
<p class="lede">First paragraph (thesis — "what I'm trying to do") and last paragraph (conclusion — "what I decided") always render. Middle paragraphs collapse to a single faint elision row that names the count <em>and</em> the slash command to retrieve the full body. The tail paragraph does NOT carry its own <span class="anchor">↳</span> — the anchor only marks the absolute beginning of the body. Vertical budget stays bounded (~9 lines).</p>
<div class="tag">SETTLED · XL · <span class="cls">.reasoning .settled .xl</span> · &gt; 800 tok OR any single ¶ &gt; 6 lines · TAIL ONLY · head dropped</div>
<pre class="mock"> <span class="accent">▎</span> <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> <span class="pill mdl-r1">&nbsp;r1&nbsp;</span> <span class="fg4">2,847 tok · 7 ¶</span> <span class="fg3">8.2s</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="fg4">⋯ 6 ¶ + ~2,540 tok scrolled past · /reasoning last to view full ⋯</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="i fg3">All suppressed paths are wired through and the auto-escalate label</span>
<span class="accent">▎</span> <span class="i fg3">flips from "storm-broken" to "repeat-loop". Tests cover both the</span>
<span class="accent">▎</span> <span class="i fg3">bad-args recovery and the second-storm fallback paths.</span>
</pre>
<p class="lede"><strong>Tail-only</strong> — at this scale the head paragraph is almost always restating the prompt or weighing options the model has since moved past. The conclusion is the actionable summary, so we keep that and drop the rest. No <span class="anchor">↳</span> anchor (the absolute body start isn't visible). The <code>⋯</code> elision row reports <em>both</em> paragraph count and approximate tokens scrolled past so the user can judge what they're not seeing — and the <code>/reasoning last</code> command brings up the full body in a pager when they need to. Vertical budget bounded at ~6 lines no matter how big the input. Triggered by total &gt; 800 tok OR any single paragraph that wouldn't fit in 6 lines on its own.</p>
<div class="tag">EMPTY · <span class="cls">.reasoning .none</span> · model returned non-thinking response</div>
<pre class="mock"> <span class="fg4">▎</span> <span class="pill sec-reason" style="opacity:.55">&nbsp;REASONING&nbsp;</span> <span class="fg4">no thinking — direct answer</span>
</pre>
<p class="lede">When the producing model emits an empty <code>reasoning_content</code> (instruct-mode v4 on a simple prompt), surface a single dim line so the absence is explained, not silently missing. Section pill renders at reduced opacity to signal "card type was attempted but skipped". No body, no anchor. Clarifies "did the model skip thinking" vs. "is the panel broken".</p>
</section>
<!-- Task / Step -->
<section class="section" id="c-task">
<h2><span class="num">07</span>Cards · task / step</h2>
<p class="lede">A multi-step work unit — wraps tool calls + reasoning under one collapsible header. Default expanded for the active step, collapsed for completed ones.</p>
<div class="tag">CARD · <span class="cls">.task .running</span></div>
<pre class="mock"> <span class="brand">▎</span> <span class="brand b">▶ Step 2 of 5 · Refactor exclude config</span> <span class="fg3">4.2s · </span><span class="brand">running</span>
<span class="brand">▎</span>
<span class="brand">▎</span> <span class="fg2">Pull SKIP_DIRS / SKIP_FILES out of chunker.ts so directory_tree</span>
<span class="brand">▎</span> <span class="fg2">can reuse them.</span>
<span class="brand">▎</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">read </span> <span class="fg2">src/index/semantic/chunker.ts</span> <span class="fg3">0.08s · 250 lines</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">read </span> <span class="fg2">src/tools/filesystem.ts</span> <span class="fg3">0.07s · 712 lines</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">write </span> <span class="fg2">src/index/config.ts</span> <span class="fg3">0.12s · created</span>
<span class="brand">▎</span> <span class="brand">▶</span> <span class="b fg1">edit </span> <span class="fg2">src/tools/filesystem.ts</span> <span class="brand">running…</span>
<span class="brand">▎</span> <span class="fg4">○</span> <span class="b fg3">verify </span> <span class="fg3">npm run typecheck && npm test</span> <span class="fg4">queued</span>
</pre>
<p class="lede">A multi-step work unit — wraps tool calls + reasoning under one header. The <span class="pill sec-task">&nbsp;TASK&nbsp;</span> section pill recolors with state: <span class="pill sec-task">&nbsp;TASK&nbsp;</span> running (brand), <span class="pill sec-task s-done">&nbsp;TASK&nbsp;</span> done (ok), <span class="pill sec-task s-failed">&nbsp;TASK&nbsp;</span> failed (err). Step counter sits next to the pill so progress is visible without reading title text.</p>
<div class="tag">CARD · <span class="cls">.task .done .collapsed</span></div>
<pre class="mock"> <span class="ok">▎</span> <span class="ok b">✓ Step 1 of 5 · Read chunker + filesystem</span> <span class="fg3">0.4s · 2 tools · </span><span class="ok">done</span> <span class="fg4">▸</span>
<div class="tag">RUNNING · <span class="cls">.task .running</span></div>
<pre class="mock"> <span class="brand">▎</span> <span class="pill sec-task">&nbsp;TASK&nbsp;</span> <span class="b fg0">2 / 5 Refactor exclude config</span> <span class="fg3">4.2s · </span><span class="brand">running</span>
<span class="brand">▎</span>
<span class="brand">▎</span> <span class="anchor brand">↳</span> <span class="fg2">Pull SKIP_DIRS / SKIP_FILES out of chunker.ts so directory_tree</span>
<span class="brand">▎</span> <span class="fg2">can reuse them.</span>
<span class="brand">▎</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">read </span> <span class="pill path">&nbsp;src/index/semantic/chunker.ts&nbsp;</span> <span class="fg3">0.08s · 250 lines</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">read </span> <span class="pill path">&nbsp;src/tools/filesystem.ts&nbsp;</span> <span class="fg3">0.07s · 712 lines</span>
<span class="brand">▎</span> <span class="ok">✓</span> <span class="b fg1">write </span> <span class="pill path">&nbsp;src/index/config.ts&nbsp;</span> <span class="fg3">0.12s · created</span>
<span class="brand">▎</span> <span class="brand">▶</span> <span class="b fg1">edit </span> <span class="pill path">&nbsp;src/tools/filesystem.ts&nbsp;</span> <span class="brand">running…</span>
<span class="brand">▎</span> <span class="fg4">○</span> <span class="b fg3">verify </span> <span class="fg3">npm run typecheck && npm test</span> <span class="fg4">queued</span>
</pre>
<p class="lede">Tool rows inside the task body use the path-pill style for filenames — bg-elev tint, fg-2, regular weight. Reads as data not chrome. Step counter format <code>N / M</code> sits where the title used to start, so glancing at any task row tells you progress at a glance.</p>
<div class="tag">CARD · <span class="cls">.task .failed</span></div>
<pre class="mock"> <span class="err">▎</span> <span class="err b">✗ Step 4 of 5 · Sandbox check</span> <span class="fg3">0.2s · </span><span class="err">failed</span> <span class="fg4">▾</span>
<div class="tag">DONE · <span class="cls">.task .done</span></div>
<pre class="mock"> <span class="ok">▎</span> <span class="pill sec-task s-done">&nbsp;TASK&nbsp;</span> <span class="b fg1">1 / 5 Read chunker + filesystem</span> <span class="fg3">0.4s · 2 tools · </span><span class="ok">done</span>
</pre>
<p class="lede">Done tasks render as a single header row — body is omitted permanently (not collapsed-but-recallable). The user can recall what happened from the events log if needed.</p>
<div class="tag">FAILED · <span class="cls">.task .failed</span></div>
<pre class="mock"> <span class="err">▎</span> <span class="pill sec-task s-failed">&nbsp;TASK&nbsp;</span> <span class="b fg0">4 / 5 Sandbox check</span> <span class="fg3">0.2s · </span><span class="err">failed</span>
<span class="err">▎</span>
<span class="err">▎</span> <span class="ok">✓</span> <span class="b fg1">read </span> <span class="fg2">src/sandbox/policy.ts</span> <span class="fg3">0.04s · 88 lines</span>
<span class="err">▎</span> <span class="err">✗</span> <span class="b fg1">verify </span> <span class="fg2">policy.allows("rm")</span> <span class="err">denied</span>
<span class="err">▎</span> <span class="anchor err">↳</span> <span class="ok">✓</span> <span class="b fg1">read </span> <span class="pill path">&nbsp;src/sandbox/policy.ts&nbsp;</span> <span class="fg3">0.04s · 88 lines</span>
<span class="err">▎</span> <span class="err">✗</span> <span class="b fg1">verify </span> <span class="pill path">&nbsp;policy.allows("rm")&nbsp;</span> <span class="err">denied</span>
</pre>
<p class="lede">Failed tasks always render their body — the user needs the failure trail visible without recall. Anchor uses err color to match the card.</p>
</section>
<!-- Tool call -->
<section class="section" id="c-tool">
<h2><span class="num">08</span>Cards · tool call</h2>
<p class="lede">Single tool invocation. <strong>Collapsed</strong> = one row. <strong>Expanded</strong> = input args summary + output preview inside a sharp-cornered code box.</p>
<p class="lede">Single tool invocation. Section pill <span class="pill sec-tool">&nbsp;TOOL&nbsp;</span> uses info-cyan; the tool function name follows in info-bold; the path/target sits in a path-pill. Quick scan order: card type → which tool → what target → how it went.</p>
<div class="tag">COLLAPSED · <span class="cls">.tool</span></div>
<pre class="mock"> <span class="info">▎</span> <span class="info b">▣ read_file</span> <span class="fg2">src/cli/ui/App.tsx</span> <span class="fg3">0.08s · 1224 lines</span> <span class="fg4">▸</span>
<div class="tag">QUICK · <span class="cls">.tool .quick</span> · single-row, no body — fast read-only ops</div>
<pre class="mock"> <span class="info">▎</span> <span class="pill sec-tool">&nbsp;TOOL&nbsp;</span> <span class="b info">read_file</span> <span class="pill path">&nbsp;src/cli/ui/App.tsx&nbsp;</span> <span class="fg3">0.08s · 1224 lines · </span><span class="ok">ok</span>
</pre>
<p class="lede">Default state for fast read-only tools (read_file, search_content, directory_tree). No body, no recall — the result is summarized in the metadata strip. If the user wants the file content, the file's at the path; reasonix won't waste rows redrawing it.</p>
<div class="tag">EXPANDED · <span class="cls">.tool[open]</span></div>
<pre class="mock"> <span class="info">▎</span> <span class="info b">▣ read_file</span> <span class="fg2">src/cli/ui/App.tsx</span> <span class="fg3">0.08s · 1224 lines</span> <span class="fg4">▾</span>
<div class="tag">PREVIEW · <span class="cls">.tool .preview</span> · short body when output ≤ 6 lines and worth surfacing</div>
<pre class="mock"> <span class="info">▎</span> <span class="pill sec-tool">&nbsp;TOOL&nbsp;</span> <span class="b info">search_content</span> <span class="pill path">&nbsp;"stormBreaker"&nbsp;</span> <span class="fg3">0.21s · 4 hits · </span><span class="ok">ok</span>
<span class="info">▎</span>
<span class="info">▎</span> <span class="fg4"> 1</span> <span class="fg1">/** App.tsx — primary chat surface, owns log + input. */</span>
<span class="info">▎</span> <span class="fg4"> 2</span>
<span class="info">▎</span> <span class="fg4"> 3</span> <span class="fg1">import React, ... from "react";</span>
<span class="info">▎</span> <span class="fg4"> …</span> <span class="fg3">[1218 lines hidden — press space to load all]</span>
<span class="info">▎</span> <span class="fg4">1224</span> <span class="fg1">export default App;</span>
<span class="info">▎</span> <span class="anchor info">↳</span> <span class="pill path">&nbsp;src/repair/storm.ts&nbsp;</span><span class="fg3">:13</span> <span class="fg2">export class StormBreaker {</span>
<span class="info">▎</span> <span class="pill path">&nbsp;src/repair/index.ts&nbsp;</span><span class="fg3">:33</span> <span class="fg2">private readonly storm: StormBreaker;</span>
<span class="info">▎</span> <span class="pill path">&nbsp;src/repair/index.ts&nbsp;</span><span class="fg3">:38</span> <span class="fg2">this.storm = new StormBreaker(opts.stormWindow ?? 6, ...);</span>
<span class="info">▎</span> <span class="pill path">&nbsp;tests/repair/storm.test.ts&nbsp;</span><span class="fg3">:2</span> <span class="fg2">import { StormBreaker } from "...";</span>
</pre>
<p class="lede">Used for grep / search / list outputs where 4-6 hit lines is the answer. Body anchor on the first hit row; subsequent rows align under it.</p>
<div class="tag">SHELL TOOL · <span class="cls">.tool .shell</span></div>
<pre class="mock"> <span class="info">▎</span> <span class="info b">▣ run_command</span> <span class="fg2">npm run verify</span> <span class="fg3">23.4s · </span><span class="ok">exit 0</span> <span class="fg4">▾</span>
<div class="tag">SHELL · <span class="cls">.tool .shell</span> · long stdout · tail-window with overflow ⋮</div>
<pre class="mock"> <span class="info">▎</span> <span class="pill sec-shell">&nbsp;SHELL&nbsp;</span> <span class="b info">run_command</span> <span class="pill path">&nbsp;npm run verify&nbsp;</span> <span class="fg3">23.4s · 1818 lines · </span><span class="ok">exit 0</span>
<span class="info">▎</span>
<span class="info">▎</span> <span class="fg3">$ npm run verify</span>
<span class="info">▎</span> <span class="fg3">> [email protected] verify</span>
<span class="info">▎</span> <span class="fg3">> npm run lint && npm run typecheck && npm run test --silent</span>
<span class="info">▎</span> <span class="fg3">…</span>
<span class="info">▎</span> <span class="fg1"> Test Files </span><span class="ok">99 passed (99)</span>
<span class="info">▎</span> <span class="fg1"> Tests </span><span class="ok">1784 passed (1784)</span>
<span class="info">▎</span> <span class="fg4">⋮ 1812 lines streamed past preview window</span>
<span class="info">▎</span>
<span class="info">▎</span> <span class="anchor info">↳</span> <span class="fg2">Test Files </span><span class="ok">115 passed (115)</span>
<span class="info">▎</span> <span class="fg2"> Tests </span><span class="ok">1818 passed (1818)</span>
<span class="info">▎</span> <span class="fg2"> Duration </span><span class="fg2">23.81s</span>
</pre>
<p class="lede">Long stdout follows the same tail-window pattern as streaming reasoning — tail-3-lines plus a <span class="fg4">⋮</span> overflow gutter. The full stream is on disk in the events log; recall via <code>/output last</code> if needed.</p>
<div class="tag">FAILED · <span class="cls">.tool .failed</span> · err-tinted pill, error message inline</div>
<pre class="mock"> <span class="err">▎</span> <span class="pill sec-tool">&nbsp;TOOL&nbsp;</span> <span class="b info">edit_file</span> <span class="pill path">&nbsp;src/loop.ts&nbsp;</span> <span class="fg3">0.05s · </span><span class="err">failed</span>
<span class="err">▎</span>
<span class="err">▎</span> <span class="anchor err">↳</span> <span class="err">✗</span> <span class="fg1">SEARCH text not found — model emitted `repairCalls` but file</span>
<span class="err">▎</span> <span class="fg1"> has `repairedCalls`. Suggest /retry with corrected name.</span>
</pre>
<p class="lede">Failure cards switch the rule color to err and surface the error inline (not collapsed). Most useful info first: what kind of failure + the actionable hint.</p>
</section>
<!-- Plan / Todo -->
<section class="section" id="c-plan">
<h2><span class="num">09</span>Cards · plan / todo</h2>
<p class="lede">Ordered checklist. State per item via the bracket char + color: <span class="ok">[✓]</span> done · <span class="brand">[▶]</span> running · <span class="fg4">[ ]</span> queued · <span class="warn">[!]</span> blocked · <span class="err">[✗]</span> failed. Footer offers revise / skip actions.</p>
<p class="lede">Ordered checklist. <span class="pill sec-plan">&nbsp;PLAN&nbsp;</span> pill + plan title + progress fraction in the header. State per item via the bracket char + color: <span class="ok">[✓]</span> done · <span class="brand">[▶]</span> running · <span class="fg4">[ ]</span> queued · <span class="warn">[!]</span> blocked · <span class="err">[✗]</span> failed.</p>
<div class="tag">CARD · <span class="cls">.plan</span></div>
<pre class="mock"> <span class="accent">▎</span> <span class="accent b">⊞ Plan · Migrate selection to terminal-native</span> <span class="fg3">5 of 7 done</span> <span class="fg4">▾</span>
<pre class="mock"> <span class="accent">▎</span> <span class="pill sec-plan">&nbsp;PLAN&nbsp;</span> <span class="b fg0">Migrate selection to terminal-native</span> <span class="fg3">5 / 7 done</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="ok">[✓]</span> <span class="fg3">1. Snapshot current selection state</span>
<span class="accent">▎</span> <span class="ok">[✓]</span> <span class="fg3">2. Drop @xterm/headless dep</span>
<span class="accent">▎</span> <span class="ok">[✓]</span> <span class="fg3">3. Remove screen-mirror.ts</span>
<span class="accent">▎</span> <span class="ok">[✓]</span> <span class="fg3">4. Strip LogSelection from log-frame.tsx</span>
<span class="accent">▎</span> <span class="ok">[✓]</span> <span class="fg3">5. Strip drag handlers from App.tsx</span>
<span class="accent">▎</span> <span class="brand">[▶]</span> <span class="b fg0">6. Add /copy slash command</span> <span class="fg4">←</span> <span class="brand">in progress</span>
<span class="accent">▎</span> <span class="fg4">[ ]</span> <span class="fg2">7. Update CHANGELOG &amp; push</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="fg3">[r] revise [s] skip step [↵] expand item</span>
<span class="accent">▎</span> <span class="anchor">↳</span> <span class="ok">[✓]</span> <span class="fg3">1. Snapshot current selection state</span>
<span class="accent">▎</span> <span class="ok">[✓]</span> <span class="fg3">2. Drop @xterm/headless dep</span>
<span class="accent">▎</span> <span class="ok">[✓]</span> <span class="fg3">3. Remove screen-mirror.ts</span>
<span class="accent">▎</span> <span class="ok">[✓]</span> <span class="fg3">4. Strip LogSelection from log-frame.tsx</span>
<span class="accent">▎</span> <span class="ok">[✓]</span> <span class="fg3">5. Strip drag handlers from App.tsx</span>
<span class="accent">▎</span> <span class="brand">[▶]</span> <span class="b fg0">6. Add /copy slash command</span> <span class="fg4">←</span> <span class="brand">in progress</span>
<span class="accent">▎</span> <span class="fg4">[ ]</span> <span class="fg2">7. Update CHANGELOG &amp; push</span>
</pre>
<p class="lede">Body anchor on the first plan item; subsequent items align under it. The footer action row from the previous design is dropped — TUI doesn't host per-item interactive shortcuts cleanly. Plan revision happens via slash commands (<code>/plan revise</code>, <code>/plan skip 4</code>) which are discoverable through <code>/help</code>.</p>
<div class="tag">XL · <span class="cls">.plan .xl</span> · &gt; 12 items · head + tail with middle elided, same as Reasoning XL</div>
<pre class="mock"> <span class="accent">▎</span> <span class="pill sec-plan">&nbsp;PLAN&nbsp;</span> <span class="b fg0">v0.24 release readiness</span> <span class="fg3">8 / 18 done</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="anchor">↳</span> <span class="ok">[✓]</span> <span class="fg3">1. Bump version + CHANGELOG entry</span>
<span class="accent">▎</span> <span class="ok">[✓]</span> <span class="fg3">2. Run full verify gate</span>
<span class="accent">▎</span> <span class="brand">[▶]</span> <span class="b fg0">3. Update docs/MIGRATION.md</span> <span class="fg4">←</span> <span class="brand">in progress</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="fg4">⋯ 12 items elided · /plan view ⋯</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="fg4">[ ]</span> <span class="fg2">17. Tag release</span>
<span class="accent">▎</span> <span class="fg4">[ ]</span> <span class="fg2">18. Publish to npm</span>
</pre>
<p class="lede">Same head + tail elision pattern as Reasoning XL — first 3 items + last 2 items + a middle elision row. The currently-running item is always promoted into the head window even if it would otherwise fall in the elided range, so progress stays visible.</p>
</section>
<!-- Diff -->
@@ -765,7 +883,7 @@ main { padding: 32px 48px 40px 32px; min-width: 0; }
<span class="violet">▎</span> <span class="fg3">Tools </span> <span class="fg2">read_file, search_content</span>
<span class="violet">▎</span>
<span class="violet">▎</span> <span class="fg3">▸ sub-agent stream</span>
<span class="violet">▎</span> <span class="violet">▎</span> <span class="accent">◆</span> <span class="fg3 i">Reasoning · 2 paragraphs</span> <span class="fg4">▸</span>
<span class="violet">▎</span> <span class="violet">▎</span> <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> <span class="pill mdl-flash">&nbsp;v4-flash&nbsp;</span> <span class="fg4">134 tok · 2 ¶</span>
<span class="violet">▎</span> <span class="violet">▎</span> <span class="info">▣</span> <span class="b fg1">read_file</span> <span class="fg2">src/index/config.ts</span> <span class="fg3">0.08s</span>
<span class="violet">▎</span> <span class="violet">▎</span> <span class="brand">▶</span> <span class="brand">streaming response …</span>
</pre>
@@ -1230,7 +1348,7 @@ main { padding: 32px 48px 40px 32px; min-width: 0; }
<span class="fg1">abandon fullscreen mode, switch to inline scrollback</span>
<span class="accent">▎</span> <span class="accent b">◆ Reasoning</span> <span class="fg4">· 4 paragraphs</span> <span class="fg4">▸</span>
<span class="accent">▎</span> <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> <span class="pill mdl-pro">&nbsp;v4-pro&nbsp;</span> <span class="fg4">587 tok · 4 ¶</span> <span class="fg3">4.7s</span>
<span class="accent">▎</span> <span class="accent b">⊞ Plan · 5 steps</span> <span class="fg3">5 of 5 done</span> <span class="fg4">▾</span>
@@ -1311,8 +1429,10 @@ main { padding: 32px 48px 40px 32px; min-width: 0; }
</pre>
<h3 id="s-stream-reason">Streaming reasoning<span class="desc">live italic dim while bytes arrive; settles into the collapsed reasoning card on completion</span></h3>
<pre class="mock"> <span class="accent">▎</span> <span class="accent b">◆ Reasoning</span> <span class="fg4">· streaming…</span> <span class="fg4">▾</span>
<h3 id="s-stream-reason">Streaming reasoning<span class="desc">live tail-3-lines while bytes arrive; settles into one of the three sized variants in §06 once the stream ends</span></h3>
<pre class="mock"> <span class="accent">▎</span> <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> <span class="pill mdl-r1">&nbsp;r1&nbsp;</span> <span class="fg4">247 tok</span> <span class="fg3">1.2s · </span><span class="brand">thinking…</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="fg4">⋮ earlier lines scrolled past preview window</span>
<span class="accent">▎</span>
<span class="accent">▎</span> <span class="i fg3">Two paths: replace the hardcoded list when config is set, or merge</span>
<span class="accent">▎</span> <span class="i fg3">user values in. The first matches the explicit "config-driven" ask;</span>
@@ -1342,7 +1462,7 @@ main { padding: 32px 48px 40px 32px; min-width: 0; }
<span class="violet">▎</span> <span class="violet">▎</span> <span class="violet b">⌬ Sub-agent · code-reader</span> <span class="violet">running</span> <span class="fg4">▾</span>
<span class="violet">▎</span> <span class="violet">▎</span>
<span class="violet">▎</span> <span class="violet">▎</span> <span class="violet">▎</span> <span class="info b">▣ read_file</span> <span class="fg2">src/cli/ui/App.tsx</span> <span class="fg3">0.08s</span>
<span class="violet">▎</span> <span class="violet">▎</span> <span class="violet">▎</span> <span class="accent">◆</span> <span class="i fg3">Reasoning · 1 paragraph</span> <span class="fg4">▸</span>
<span class="violet">▎</span> <span class="violet">▎</span> <span class="violet">▎</span> <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> <span class="pill mdl-flash">&nbsp;v4-flash&nbsp;</span> <span class="fg4">62 tok · 1 ¶</span>
<span class="violet">▎</span> <span class="violet">▎</span>
<span class="violet">▎</span> <span class="violet">▎</span> <span class="brand">▶</span> <span class="brand">summarising findings…</span>
<span class="violet">▎</span>
@@ -1987,7 +2107,7 @@ main { padding: 32px 48px 40px 32px; min-width: 0; }
<span class="fg3">▎</span> <span class="b fg2">⌑ Context</span> <span class="fg3">· 4 user · 2 feedback · 1 reference</span> <span class="fg3">~1.2K tok</span> <span class="fg4">▸</span>
<span class="accent">▎</span> <span class="accent b">◆ Reasoning</span> <span class="fg4">· 3 paragraphs</span> <span class="fg4">▸</span>
<span class="accent">▎</span> <span class="pill sec-reason">&nbsp;REASONING&nbsp;</span> <span class="pill mdl-r1">&nbsp;r1&nbsp;</span> <span class="fg4">412 tok · 3 ¶</span> <span class="fg3">3.1s</span>
<span class="accent">▎</span> <span class="accent b">⊞ Plan · 5 steps</span> <span class="fg3">0 of 5 done</span> <span class="fg4">▾</span>
+2834 -82
View File
File diff suppressed because it is too large. Load diff
+12 -5
View File
@@ -1,6 +1,6 @@
{
"name": "reasonix",
"version": "0.21.0",
"version": "0.26.0",
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
"type": "module",
"bin": {
@@ -30,6 +30,8 @@
"chat": "tsx src/cli/index.ts chat",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"test:mutation": "stryker run",
"lint": "biome check src tests",
"lint:fix": "biome check --write src tests",
"format": "biome format --write src tests",
@@ -70,23 +72,28 @@
"commander": "^12.1.0",
"eventsource-parser": "^3.0.0",
"ignore": "^7.0.5",
"ink": "^5.1.0",
"ink-spinner": "^5.0.0",
"ink-text-input": "^6.0.0",
"picomatch": "^4.0.4",
"react": "^18.3.1",
"react-reconciler": "^0.29.2",
"string-width": "^7.2.0",
"yoga-layout": "^3.2.1",
"zod": "^4.4.1"
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@stryker-mutator/core": "^9.6.1",
"@stryker-mutator/vitest-runner": "^9.6.1",
"@types/node": "^22.9.0",
"@types/picomatch": "^4.0.3",
"@types/react": "^18.3.12",
"@types/react-reconciler": "^0.28.9",
"@vitest/coverage-v8": "^2.1.5",
"esbuild": "^0.21.5",
"highlight.js": "^11.10.0",
"htm": "^3.1.1",
"marked": "^12.0.2",
"ink": "^5.1.0",
"ink-text-input": "^6.0.0",
"marked": "^15.0.12",
"preact": "^10.22.0",
"simple-git-hooks": "^2.13.1",
"tsup": "^8.3.5",
+44
View File
@@ -0,0 +1,44 @@
import { readFileSync, appendFileSync } from "node:fs";
import { join } from "node:path";
const ROOT = new URL("..", import.meta.url).pathname;
const SUMMARY_PATH = join(ROOT, "coverage", "coverage-summary.json");
const GITHUB_STEP_SUMMARY = process.env.GITHUB_STEP_SUMMARY;
if (!GITHUB_STEP_SUMMARY) {
console.log("Not running in GitHub Actions (no GITHUB_STEP_SUMMARY). Skipping.");
process.exit(0);
}
let data;
try {
data = JSON.parse(readFileSync(SUMMARY_PATH, "utf-8"));
} catch (err) {
console.error("Failed to read coverage summary:", err.message);
process.exit(0); // don't fail the build if coverage report is missing
}
const { total } = data;
if (!total) {
console.error("No 'total' key in coverage summary. Skipping.");
process.exit(0);
}
const pct = (metric) => {
const m = total[metric];
if (!m) return "-";
return `${m.pct.toFixed(1)}%`;
};
const rows = [
"| Metric | Coverage |",
"| ------ | -------- |",
`| Statements | ${pct("statements")} |`,
`| Branches | ${pct("branches")} |`,
`| Functions | ${pct("functions")} |`,
`| Lines | ${pct("lines")} |`,
];
const md = `## Coverage\n\n${rows.join("\n")}\n`;
appendFileSync(GITHUB_STEP_SUMMARY, md + "\n");
console.log("Coverage summary written to job summary.");
+156
View File
@@ -0,0 +1,156 @@
/**
* Probes whether mutating a mid-history message destroys DeepSeek's prompt
* cache for everything after the mutation point.
*
* Hypothesis: our compactInPlace() rewrites old tool results, which shifts
* the byte offsets of every subsequent message. DeepSeek caches by exact
* prefix, so the next request would cache-hit only up to the mutation
* point, even though most of the conversation is unchanged.
*
* Run: node scripts/probe-cache.mjs
* Reads DEEPSEEK_API_KEY / DEEPSEEK_BASE_URL from .env.testbak.
*/
import { readFileSync } from "node:fs";
function loadDotenv(path) {
const txt = readFileSync(path, "utf8");
for (const line of txt.split(/\r?\n/)) {
const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
if (m) process.env[m[1]] ??= m[2];
}
}
loadDotenv("./.env.testbak");
const KEY = process.env.DEEPSEEK_API_KEY;
const BASE = process.env.DEEPSEEK_BASE_URL ?? "https://api.deepseek.com";
if (!KEY) throw new Error("DEEPSEEK_API_KEY missing");
const filler = (label, n) =>
Array.from({ length: n }, (_, i) => `${label} line ${i}: lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.`).join("\n");
const SYS = "You are a terse echo bot. Reply with a single short sentence.";
const MSG_A_FULL = `Long context block A. Detail follows:\n${filler("A", 80)}`;
const MSG_A_TRUNCATED = `Long context block A. Detail follows:\n${filler("A", 8)}\n[truncated]`;
const MSG_B = `Block B reference: ${filler("B", 30)}`;
const MSG_C = `Block C reference: ${filler("C", 30)}`;
async function call(label, messages) {
const t0 = Date.now();
const res = await fetch(`${BASE}/chat/completions`, {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${KEY}`,
},
body: JSON.stringify({
model: "deepseek-chat",
messages,
temperature: 0,
max_tokens: 16,
stream: false,
}),
});
const ms = Date.now() - t0;
if (!res.ok) {
const text = await res.text();
throw new Error(`${label} http ${res.status}: ${text.slice(0, 300)}`);
}
const j = await res.json();
const u = j.usage ?? {};
const hit = u.prompt_cache_hit_tokens ?? 0;
const miss = u.prompt_cache_miss_tokens ?? 0;
const prompt = u.prompt_tokens ?? 0;
const ratio = hit + miss > 0 ? (hit / (hit + miss)) * 100 : 0;
console.log(
`[${label}] prompt=${prompt} hit=${hit} miss=${miss} hit%=${ratio.toFixed(1)} ${ms}ms`,
);
return { hit, miss, prompt };
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function main() {
console.log("=== Phase 1: warm cache with full conversation ===");
const warm = [
{ role: "system", content: SYS },
{ role: "user", content: MSG_A_FULL },
{ role: "assistant", content: "ack A" },
{ role: "user", content: MSG_B },
{ role: "assistant", content: "ack B" },
{ role: "user", content: MSG_C },
{ role: "assistant", content: "ack C" },
{ role: "user", content: "say hi" },
];
await call("warm-1", warm);
await sleep(1500);
await call("warm-2", warm);
console.log("\n=== Phase 2: append a new turn (cache should hit on prefix) ===");
const appended = [
...warm,
{ role: "assistant", content: "hi" },
{ role: "user", content: "say bye" },
];
await sleep(1500);
const appendResult = await call("append", appended);
console.log("\n=== Phase 3: mutate MSG_A in place + append same new turn ===");
const mutated = [
{ role: "system", content: SYS },
{ role: "user", content: MSG_A_TRUNCATED },
{ role: "assistant", content: "ack A" },
{ role: "user", content: MSG_B },
{ role: "assistant", content: "ack B" },
{ role: "user", content: MSG_C },
{ role: "assistant", content: "ack C" },
{ role: "user", content: "say hi" },
{ role: "assistant", content: "hi" },
{ role: "user", content: "say bye" },
];
await sleep(1500);
const mutateResult = await call("mutate", mutated);
console.log("\n=== Result (Phases 1-3) ===");
const lostHit = appendResult.hit - mutateResult.hit;
console.log(
`append: hit=${appendResult.hit}/${appendResult.prompt} mutate: hit=${mutateResult.hit}/${mutateResult.prompt}`,
);
console.log(`cache tokens lost to in-place mutation: ${lostHit}`);
if (lostHit > 100) {
console.log("VERDICT: in-place mutation destroys cache. Hypothesis confirmed.");
} else {
console.log("VERDICT: cache survived mutation. Hypothesis rejected.");
}
console.log("\n=== Phase 4: append-only across many turns (the new code's behavior) ===");
const session = [
{ role: "system", content: SYS },
{ role: "user", content: MSG_A_FULL },
{ role: "assistant", content: "ack A" },
{ role: "user", content: MSG_B },
{ role: "assistant", content: "ack B" },
];
const ratios = [];
for (let i = 0; i < 5; i++) {
session.push({ role: "user", content: `turn ${i}: ${filler(`Q${i}`, 10)}` });
await sleep(1200);
const r = await call(`turn-${i}`, session);
session.push({ role: "assistant", content: `reply ${i}` });
const total = r.hit + r.miss;
ratios.push(total > 0 ? (r.hit / total) * 100 : 0);
}
const avg = ratios.reduce((a, b) => a + b, 0) / ratios.length;
console.log(`\nappend-only cache hit % across 5 turns: ${ratios.map((x) => x.toFixed(1)).join(", ")}`);
console.log(`average: ${avg.toFixed(1)}%`);
if (avg > 80) {
console.log("VERDICT: append-only keeps cache warm across turns. New strategy validated.");
} else {
console.log("VERDICT: cache hit lower than expected — investigate.");
}
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+167
View File
@@ -0,0 +1,167 @@
/**
* Long-session probe — drives CacheFirstLoop through 20 real turns
* with oversized tool results (each ~4k tokens, the size that USED to
* trigger the old turn-end auto-compaction every turn).
*
* Reports per-turn: prompt size, cache hit %, miss tokens, USD cost.
* Surfaces: cache trajectory, cost shape, anything degrading over time.
*
* Run: REASONIX_LOG_LEVEL=ERROR npx tsx scripts/probe-long-session.mts
*/
import { readFileSync } from "node:fs";
import { DeepSeekClient } from "../src/client.js";
import { CacheFirstLoop } from "../src/loop.js";
import { ImmutablePrefix } from "../src/memory/runtime.js";
import { DEEPSEEK_CONTEXT_TOKENS } from "../src/telemetry/stats.js";
import { ToolRegistry } from "../src/tools.js";
// Force a small ctx window so the 50% fold threshold trips in a few
// turns instead of needing 200+ turns at the real 1M cap. Same model
// id, real API call, just the local gauge is shrunk.
DEEPSEEK_CONTEXT_TOKENS["deepseek-chat"] = 50_000;
function loadDotenv(path: string) {
const txt = readFileSync(path, "utf8");
for (const line of txt.split(/\r?\n/)) {
const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
}
}
loadDotenv("./.env.testbak");
const PRICE_HIT_PER_M = 0.07;
const PRICE_MISS_PER_M = 0.27;
const PRICE_COMPLETION_PER_M = 1.1;
const docLine = (i: number, sec: string) =>
`[${sec}#${i}] section ${sec} entry ${i}: requirement traces to constraint ${(i % 7) + 1}, status ${i % 3 === 0 ? "open" : "closed"}, owner team-${(i % 5) + 1}, last touched 2026-04-${(i % 28) + 1}.`;
async function main() {
const reg = new ToolRegistry();
reg.register({
name: "read_doc",
description: "Read a section of a project document.",
parameters: {
type: "object",
properties: { section: { type: "string" } },
required: ["section"],
},
fn: async (args: Record<string, unknown>) => {
const sec = String(args.section ?? "default");
const lines = Array.from({ length: 65 }, (_, i) => docLine(i, sec));
return lines.join("\n");
},
});
const client = new DeepSeekClient();
const model = "deepseek-chat";
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({
system:
"You are a documentation triage agent. For each turn, call read_doc with the section the user asks about, then reply with one short sentence summarizing what you found.",
toolSpecs: reg.specs(),
}),
tools: reg,
stream: false,
model,
maxToolIters: 4,
});
let mutations = 0;
let folds = 0;
const origCompactInPlace = loop.log.compactInPlace.bind(loop.log);
loop.log.compactInPlace = (...args) => {
mutations++;
return origCompactInPlace(...args);
};
const sections = [
"auth",
"billing",
"telemetry",
"rate-limit",
"webhooks",
"search",
"indexing",
"permissions",
"audit",
"exports",
"imports",
"cdn",
"analytics",
"rbac",
"sso",
"scheduler",
"workflows",
"notifications",
"reports",
"api-v2",
];
console.log("turn | prompt | hit | miss | hit% | $/turn | $cum");
console.log("-----+----------+---------+---------+------+----------+--------");
let cumCost = 0;
let forceSummaryHit = false;
for (let i = 0; i < sections.length; i++) {
const t0 = Date.now();
let usage: {
promptTokens: number;
completionTokens: number;
promptCacheHitTokens: number;
promptCacheMissTokens: number;
} | null = null;
let warning = "";
for await (const ev of loop.step(`Read the "${sections[i]}" section.`)) {
if (ev.role === "assistant_final" && ev.stats?.usage) {
usage = ev.stats.usage as typeof usage;
}
if (ev.role === "warning" && ev.content) {
warning = ev.content;
if (/folded \d+ messages/.test(ev.content)) folds++;
}
if (ev.forcedSummary) forceSummaryHit = true;
}
const ms = Date.now() - t0;
if (!usage) {
console.log(
`${String(i).padStart(3)} | (no usage) -- ${warning ? `warning: ${warning}` : ""}`,
);
continue;
}
const total = usage.promptCacheHitTokens + usage.promptCacheMissTokens;
const ratio = total > 0 ? (usage.promptCacheHitTokens / total) * 100 : 0;
const cost =
(usage.promptCacheHitTokens * PRICE_HIT_PER_M +
usage.promptCacheMissTokens * PRICE_MISS_PER_M +
usage.completionTokens * PRICE_COMPLETION_PER_M) /
1_000_000;
cumCost += cost;
console.log(
`${String(i).padStart(3)} | ${String(usage.promptTokens).padStart(7)} | ${String(usage.promptCacheHitTokens).padStart(7)} | ${String(usage.promptCacheMissTokens).padStart(7)} | ${ratio.toFixed(1).padStart(4)} | $${cost.toFixed(5)} | $${cumCost.toFixed(4)} ${ms}ms${warning ? ` (${warning.slice(0, 60)}…)` : ""}`,
);
if (forceSummaryHit) {
console.log(
`\n>> force-summary triggered at turn ${i} (${ratio.toFixed(1)}% cache hit, ${usage.promptTokens} tokens)`,
);
break;
}
}
console.log(`\ntotal log.compactInPlace() calls: ${mutations} (expected: ${folds} folds)`);
console.log(`total cost across session: $${cumCost.toFixed(4)}`);
if (mutations !== folds) {
console.log(`FAIL: ${mutations} mutations but only ${folds} fold events — unexpected mutation`);
process.exit(1);
}
console.log(`\nVERDICT: ${folds} fold(s) fired, no other mutations.`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+118
View File
@@ -0,0 +1,118 @@
/**
* End-to-end cache probe — drives CacheFirstLoop through real turns
* against the live DeepSeek API and reports cache hit % per turn.
*
* The point: validate that the post-PR code (no auto-compaction)
* actually sustains high cache hit on a long-ish session, not just
* that the API-level append-vs-mutate primitive behaves as expected.
*
* Run: REASONIX_LOG_LEVEL=ERROR npx tsx scripts/probe-loop-cache.mts
* Reads DEEPSEEK_API_KEY from .env.testbak.
*/
import { readFileSync } from "node:fs";
import { CacheFirstLoop } from "../src/loop.js";
import { DeepSeekClient } from "../src/client.js";
import { ImmutablePrefix } from "../src/memory/runtime.js";
import { ToolRegistry } from "../src/tools.js";
function loadDotenv(path: string) {
const txt = readFileSync(path, "utf8");
for (const line of txt.split(/\r?\n/)) {
const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
}
}
loadDotenv("./.env.testbak");
const filler = (label: string, n: number): string =>
Array.from(
{ length: n },
(_, i) =>
`${label} line ${i}: lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.`,
).join("\n");
async function main() {
const reg = new ToolRegistry();
reg.register({
name: "echo",
description: "echo the input back",
parameters: {
type: "object",
properties: { msg: { type: "string" } },
required: ["msg"],
},
fn: async (args: Record<string, unknown>) => `echoed: ${String(args.msg ?? "")}`,
});
const client = new DeepSeekClient();
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({
system:
"You are a terse echo bot. Reply with one short sentence. Do not call any tools unless explicitly asked.",
toolSpecs: reg.specs(),
}),
tools: reg,
stream: false,
maxToolIters: 4,
});
// Pre-seed log with a moderate prior conversation (~6k tokens of
// user/assistant turns) so the cache has something substantial to
// hit across subsequent turns.
loop.log.append({ role: "user", content: `prior context: ${filler("ctx", 60)}` });
loop.log.append({ role: "assistant", content: "noted." });
loop.log.append({ role: "user", content: `more context: ${filler("more", 40)}` });
loop.log.append({ role: "assistant", content: "noted." });
const ratios: number[] = [];
let mutations = 0;
const origCompactInPlace = loop.log.compactInPlace.bind(loop.log);
loop.log.compactInPlace = (...args: Parameters<typeof origCompactInPlace>) => {
mutations++;
return origCompactInPlace(...args);
};
for (let i = 0; i < 6; i++) {
let usage: { promptTokens: number; promptCacheHitTokens: number; promptCacheMissTokens: number } | null = null;
for await (const ev of loop.step(`Turn ${i}: just say "ok ${i}".`)) {
if (ev.role === "assistant_final" && ev.stats?.usage) {
usage = ev.stats.usage as typeof usage;
}
}
if (!usage) {
console.log(`turn-${i}: no usage captured`);
ratios.push(0);
continue;
}
const total = usage.promptCacheHitTokens + usage.promptCacheMissTokens;
const ratio = total > 0 ? (usage.promptCacheHitTokens / total) * 100 : 0;
console.log(
`turn-${i}: prompt=${usage.promptTokens} hit=${usage.promptCacheHitTokens} miss=${usage.promptCacheMissTokens} hit%=${ratio.toFixed(1)}`,
);
ratios.push(ratio);
}
console.log(`\ntotal log.compactInPlace() calls: ${mutations}`);
console.log(`cache hit % per turn: ${ratios.map((x) => x.toFixed(1)).join(", ")}`);
const warmRatios = ratios.slice(1);
const avgWarm = warmRatios.reduce((a, b) => a + b, 0) / warmRatios.length;
console.log(`warm-turn average (excluding cold start): ${avgWarm.toFixed(1)}%`);
if (mutations > 0) {
console.log(`\nFAIL: log was mutated ${mutations} time(s) — append-only invariant broken`);
process.exit(1);
}
if (avgWarm < 80) {
console.log(`\nFAIL: warm-turn average ${avgWarm.toFixed(1)}% below 80% threshold`);
process.exit(1);
}
console.log(`\nPASS: append-only sustained, cache hit avg ${avgWarm.toFixed(1)}%`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+59 -26
View File
@@ -3,10 +3,17 @@
import { type Dirent, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { readdir, stat } from "node:fs/promises";
import { isAbsolute, join, relative, resolve } from "node:path";
import {
type GitignoreLayer,
ignoredByLayers,
loadGitignoreAt,
loadGitignoreAtSync,
} from "./gitignore.js";
/** Caps match tool-result dispatch truncation (0.5.2). */
export const DEFAULT_AT_MENTION_MAX_BYTES = 64 * 1024;
/** Universally-uninteresting build / VCS dirs. Framework-specific dirs (Pods, target, …) live in .gitignore. */
export const DEFAULT_PICKER_IGNORE_DIRS: readonly string[] = [
"node_modules",
".git",
@@ -25,10 +32,12 @@ export const DEFAULT_PICKER_IGNORE_DIRS: readonly string[] = [
];
export interface ListFilesOptions {
/** Cap the walk once we've collected this many entries. Default 500. */
/** Cap the walk once we've collected this many entries. Default 2000. */
maxResults?: number;
/** Directory names to skip entirely. Defaults to {@link DEFAULT_PICKER_IGNORE_DIRS}. */
ignoreDirs?: readonly string[];
/** Walk nested .gitignores (root + every subdir). Default true. */
respectGitignore?: boolean;
}
/** Sync on purpose — fits the TUI's single-turn-per-tick model. Skips dot-DIRS but keeps dotfiles. */
@@ -45,13 +54,19 @@ export interface FileWithStats {
/** Stat failures kept as `mtimeMs: 0` — entry still appears, sinks to bottom of recency sort. */
export function listFilesWithStatsSync(root: string, opts: ListFilesOptions = {}): FileWithStats[] {
const maxResults = Math.max(1, opts.maxResults ?? 500);
const ignore = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);
const maxResults = Math.max(1, opts.maxResults ?? 2000);
const ignoreDirs = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);
const rootAbs = resolve(root);
const respectGi = opts.respectGitignore !== false;
const out: FileWithStats[] = [];
const walk = (dirAbs: string, dirRel: string) => {
const walk = (dirAbs: string, dirRel: string, layers: readonly GitignoreLayer[]) => {
if (out.length >= maxResults) return;
let effectiveLayers = layers;
if (respectGi) {
const ig = loadGitignoreAtSync(dirAbs);
if (ig) effectiveLayers = [...layers, { dirAbs, ig }];
}
let entries: Dirent[];
try {
entries = readdirSync(dirAbs, { withFileTypes: true });
@@ -62,13 +77,16 @@ export function listFilesWithStatsSync(root: string, opts: ListFilesOptions = {}
for (const ent of entries) {
if (out.length >= maxResults) return;
const relPath = dirRel ? `${dirRel}/${ent.name}` : ent.name;
const absPath = join(dirAbs, ent.name);
if (ent.isDirectory()) {
if (ent.name.startsWith(".") || ignore.has(ent.name)) continue;
walk(join(dirAbs, ent.name), relPath);
if (ent.name.startsWith(".") || ignoreDirs.has(ent.name)) continue;
if (ignoredByLayers(effectiveLayers, absPath, true)) continue;
walk(absPath, relPath, effectiveLayers);
} else if (ent.isFile()) {
if (ignoredByLayers(effectiveLayers, absPath, false)) continue;
let mtimeMs = 0;
try {
mtimeMs = statSync(join(dirAbs, ent.name)).mtimeMs;
mtimeMs = statSync(absPath).mtimeMs;
} catch {
/* stat failed (permission / EAGAIN) — keep the entry with mtime=0 */
}
@@ -77,7 +95,7 @@ export function listFilesWithStatsSync(root: string, opts: ListFilesOptions = {}
}
};
walk(rootAbs, "");
walk(rootAbs, "", []);
return out;
}
@@ -86,13 +104,23 @@ export async function listFilesWithStatsAsync(
root: string,
opts: ListFilesOptions = {},
): Promise<FileWithStats[]> {
const maxResults = Math.max(1, opts.maxResults ?? 500);
const ignore = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);
const maxResults = Math.max(1, opts.maxResults ?? 2000);
const ignoreDirs = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);
const rootAbs = resolve(root);
const respectGi = opts.respectGitignore !== false;
const out: FileWithStats[] = [];
const walk = async (dirAbs: string, dirRel: string): Promise<void> => {
const walk = async (
dirAbs: string,
dirRel: string,
layers: readonly GitignoreLayer[],
): Promise<void> => {
if (out.length >= maxResults) return;
let effectiveLayers = layers;
if (respectGi) {
const ig = await loadGitignoreAt(dirAbs);
if (ig) effectiveLayers = [...layers, { dirAbs, ig }];
}
let entries: Dirent[];
try {
entries = await readdir(dirAbs, { withFileTypes: true });
@@ -100,34 +128,34 @@ export async function listFilesWithStatsAsync(
return;
}
entries.sort((a, b) => a.name.localeCompare(b.name));
// Pull file stats for THIS directory in parallel before
// recursing — readdir gave us all the names at once, may as
// well issue all the stats at once too. Recursion stays
// sequential so the alphabetical ordering of the merged list
// matches the sync walk's contract.
// Stats batched per directory to amortize syscall overhead. Recursion stays
// sequential so the merged DFS order matches the sync walker's contract.
const fileEnts: Dirent[] = [];
for (const ent of entries) {
if (out.length >= maxResults) break;
const relPath = dirRel ? `${dirRel}/${ent.name}` : ent.name;
const absPath = join(dirAbs, ent.name);
if (ent.isDirectory()) {
if (ent.name.startsWith(".") || ignore.has(ent.name)) continue;
if (ent.name.startsWith(".") || ignoreDirs.has(ent.name)) continue;
if (ignoredByLayers(effectiveLayers, absPath, true)) continue;
// Drain pending file stats from THIS directory before
// descending so the output order stays DFS-alphabetical.
if (fileEnts.length > 0) {
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults);
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults, effectiveLayers);
fileEnts.length = 0;
if (out.length >= maxResults) return;
}
await walk(join(dirAbs, ent.name), dirRel ? `${dirRel}/${ent.name}` : ent.name);
await walk(absPath, relPath, effectiveLayers);
} else if (ent.isFile()) {
fileEnts.push(ent);
}
}
if (fileEnts.length > 0 && out.length < maxResults) {
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults);
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults, effectiveLayers);
}
};
await walk(rootAbs, "");
await walk(rootAbs, "", []);
return out;
}
@@ -137,18 +165,23 @@ async function statBatch(
dirRel: string,
out: FileWithStats[],
maxResults: number,
layers: readonly GitignoreLayer[],
): Promise<void> {
const remaining = Math.max(0, maxResults - out.length);
const batch = ents.slice(0, remaining);
const accepted: Dirent[] = [];
for (const e of ents) {
if (out.length + accepted.length >= maxResults) break;
if (ignoredByLayers(layers, join(dirAbs, e.name), false)) continue;
accepted.push(e);
}
const stats = await Promise.all(
batch.map((e) =>
accepted.map((e) =>
stat(join(dirAbs, e.name))
.then((s) => s.mtimeMs)
.catch(() => 0),
),
);
for (let i = 0; i < batch.length; i++) {
const ent = batch[i]!;
for (let i = 0; i < accepted.length; i++) {
const ent = accepted[i]!;
out.push({
path: dirRel ? `${dirRel}/${ent.name}` : ent.name,
mtimeMs: stats[i] ?? 0,
+20 -9
View File
@@ -4,11 +4,12 @@ import { loadApiKey, readConfig, searchEnabled } from "../../config.js";
import { loadDotenv } from "../../env.js";
import { McpClient } from "../../mcp/client.js";
import { type InspectionReport, inspectMcpServer } from "../../mcp/inspect.js";
import { bridgeMcpTools } from "../../mcp/registry.js";
import { type McpClientHost, bridgeMcpTools } from "../../mcp/registry.js";
import { parseMcpSpec } from "../../mcp/spec.js";
import { SseTransport } from "../../mcp/sse.js";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
import { StreamableHttpTransport } from "../../mcp/streamable-http.js";
import { buildMcpServerSummary } from "../../mcp/summary.js";
import {
deleteSession,
listSessionsForWorkspace,
@@ -209,6 +210,7 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
if (!tools) tools = new ToolRegistry();
for (const raw of requestedSpecs) {
let label = "anon";
let mcp: McpClient | undefined;
try {
const spec = parseMcpSpec(raw);
label = spec.name ?? "anon";
@@ -229,12 +231,17 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
: spec.transport === "streamable-http"
? new StreamableHttpTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
const mcp = new McpClient({ transport });
mcp = new McpClient({ transport });
await mcp.initialize();
// Host indirection lets `/mcp reconnect` swap the underlying client
// without re-bridging the registered tools (closures resolve via
// host.client at call time).
const host: McpClientHost = { client: mcp };
const bridge = await bridgeMcpTools(mcp, {
registry: tools,
namePrefix: prefix,
serverName: label,
host,
onProgress: (info) => progressSink.current?.(info),
onSlow: (info) =>
process.stderr.write(
@@ -273,18 +280,22 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
);
clients.push(mcp);
successfulSpecs.push(raw);
mcpServers.push({
label,
spec: raw,
toolCount: bridge.registeredNames.length,
report,
client: mcp,
});
mcpServers.push(
buildMcpServerSummary({
label,
spec: raw,
toolCount: bridge.registeredNames.length,
report,
host,
bridgeEnv: bridge.env,
}),
);
} catch (err) {
// Per-server failure is non-fatal: one broken server shouldn't
// kill a chat that has working servers configured. Recover by
// recording the failure and continuing; user fixes via `reasonix
// setup` without losing their other servers.
await mcp?.close().catch(() => undefined);
const reason = (err as Error).message;
failedSpecs.push({ spec: raw, reason });
process.stderr.write(
+1 -1
View File
@@ -226,7 +226,7 @@ async function checkSessions(): Promise<Check> {
return {
label: "sessions ",
level: "warn",
detail: `${detail} · ${stale} idle ≥90d (run /prune-sessions)`,
detail: `${detail} · ${stale} idle ≥90d (run \`reasonix prune-sessions\`)`,
};
}
return { label: "sessions ", level: "ok", detail };
+38
View File
@@ -0,0 +1,38 @@
import { listSessions, pruneStaleSessions } from "../../memory/session.js";
export interface PruneSessionsOptions {
days?: number;
dryRun?: boolean;
}
export function pruneSessionsCommand(opts: PruneSessionsOptions): void {
const days = opts.days ?? 90;
if (!Number.isFinite(days) || days < 1) {
console.error(`--days must be a positive integer (got ${days}).`);
process.exit(1);
}
if (opts.dryRun) {
const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
const stale = listSessions().filter((s) => s.mtime.getTime() < cutoff);
if (stale.length === 0) {
console.log(`no sessions idle ≥${days} days. Nothing would be pruned.`);
return;
}
console.log(`would prune ${stale.length} session(s) idle ≥${days} days:`);
for (const s of stale) {
console.log(` ${s.name}`);
}
console.log("");
console.log("re-run without --dry-run to actually delete.");
return;
}
const removed = pruneStaleSessions(days);
if (removed.length === 0) {
console.log(`no sessions idle ≥${days} days. Nothing pruned.`);
return;
}
console.log(`pruned ${removed.length} session(s) idle ≥${days} days:`);
for (const name of removed) {
console.log(` ${name}`);
}
}
+3 -1
View File
@@ -88,6 +88,7 @@ export async function runCommand(opts: RunOptions): Promise<void> {
tools = new ToolRegistry();
for (const raw of requestedSpecs) {
let label = "anon";
let mcp: McpClient | undefined;
try {
const spec = parseMcpSpec(raw);
label = spec.name ?? "anon";
@@ -108,7 +109,7 @@ export async function runCommand(opts: RunOptions): Promise<void> {
: spec.transport === "streamable-http"
? new StreamableHttpTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
const mcp = new McpClient({ transport });
mcp = new McpClient({ transport });
await mcp.initialize();
const bridge = await bridgeMcpTools(mcp, {
registry: tools,
@@ -134,6 +135,7 @@ export async function runCommand(opts: RunOptions): Promise<void> {
// one-shot `run` invocation with a broken MCP server otherwise
// fails the whole run over a side-concern tool the task might
// not even touch.
await mcp?.close().catch(() => undefined);
process.stderr.write(
`${formatMcpLifecycleEvent({ state: "failed", name: label, reason: (err as Error).message })}\n → run \`reasonix setup\` to remove broken entries from your saved config.\n`,
);
+106 -180
View File
@@ -1,26 +1,11 @@
import { Command } from "commander";
import { readConfig } from "../config.js";
import { t } from "../i18n/index.js";
import { VERSION } from "../index.js";
import { listSessions } from "../memory/session.js";
import { applyMemoryStack } from "../memory/user.js";
import { ESCALATION_CONTRACT } from "../prompt-fragments.js";
import { chatCommand } from "./commands/chat.js";
import { codeCommand } from "./commands/code.js";
import { commitCommand } from "./commands/commit.js";
import { diffCommand } from "./commands/diff.js";
import { doctorCommand } from "./commands/doctor.js";
import { eventsCommand } from "./commands/events.js";
import { indexCommand } from "./commands/index.js";
import { mcpInspectCommand } from "./commands/mcp-inspect.js";
import { mcpListCommand } from "./commands/mcp.js";
import { replayCommand } from "./commands/replay.js";
import { runCommand } from "./commands/run.js";
import { sessionsCommand } from "./commands/sessions.js";
import { setupCommand } from "./commands/setup.js";
import { statsCommand } from "./commands/stats.js";
import { updateCommand } from "./commands/update.js";
import { versionCommand } from "./commands/version.js";
import { resolveContinueFlag, resolveDefaults } from "./resolve.js";
const DEFAULT_SYSTEM = `You are Reasonix, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.
@@ -43,6 +28,23 @@ Your training data has a cutoff. When an answer's correctness depends on somethi
The signal isn't a topic list — it's: "if I'm wrong about this, is it because reality moved on?". If yes, ground the answer in fresh evidence; if no (definitions, mechanisms, well-established APIs), answer from memory.
${ESCALATION_CONTRACT}`;
import { codeCommand } from "./commands/code.js";
import { commitCommand } from "./commands/commit.js";
import { diffCommand } from "./commands/diff.js";
import { doctorCommand } from "./commands/doctor.js";
import { eventsCommand } from "./commands/events.js";
import { indexCommand } from "./commands/index.js";
import { mcpInspectCommand } from "./commands/mcp-inspect.js";
import { mcpListCommand } from "./commands/mcp.js";
import { pruneSessionsCommand } from "./commands/prune-sessions.js";
import { replayCommand } from "./commands/replay.js";
import { runCommand } from "./commands/run.js";
import { sessionsCommand } from "./commands/sessions.js";
import { setupCommand } from "./commands/setup.js";
import { statsCommand } from "./commands/stats.js";
import { updateCommand } from "./commands/update.js";
import { versionCommand } from "./commands/version.js";
import { resolveContinueFlag, resolveDefaults } from "./resolve.js";
/** Lenient: malformed → undefined (no cap) so a bad flag doesn't abort launch. */
function parseBudgetFlag(raw: number | undefined): number | undefined {
@@ -59,12 +61,9 @@ function parseBudgetFlag(raw: number | undefined): number | undefined {
const program = new Command();
program
.name("reasonix")
.description("DeepSeek-native agent framework — built for cache hits and cheap tokens.")
.description(t("cli.description"))
.version(VERSION)
.option(
"-c, --continue",
"Resume the most recently used chat session without showing the picker.",
);
.option("-c, --continue", t("cli.continue"));
// `reasonix` with no subcommand → launch the friendliest flow.
// First run (no config yet) → interactive setup wizard.
@@ -97,42 +96,24 @@ program.action(async (opts: { continue?: boolean }) => {
program
.command("setup")
.description("Interactive wizard — API key, preset, MCP servers. Re-run any time to reconfigure.")
.description(t("cli.setup"))
.action(async () => {
await setupCommand({});
});
program
.command("code [dir]")
.description(
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, v4-flash baseline. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk. Use /preset pro or /pro to lock v4-pro on hard tasks.",
)
.option("-m, --model <id>", "Override default model (v4-flash)")
.option("--no-session", "Disable session persistence for this run")
.option("-r, --resume", "Skip the session picker — always continue prior messages")
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
.option("--transcript <path>", "Write a JSONL transcript to this path")
.option(
"--harvest",
"Opt-in Pillar-2 plan-state extraction. Adds one flash call per turn; off by default (no preset enables it).",
)
.option(
"--budget <usd>",
"Soft USD cap on session spend. Off by default. Warns at 80%, refuses next turn at 100%. Mid-session: /budget <usd> or /budget off.",
(v) => Number.parseFloat(v),
)
.option(
"--no-dashboard",
"Suppress the auto-launched embedded web dashboard. Default behavior boots it on TUI mount and shows the URL in the status bar (clickable in OSC-8-aware terminals).",
)
.option(
"--system-append <prompt>",
"Append instructions to the code system prompt. Does NOT replace the default prompt — adds after it.",
)
.option(
"--system-append-file <path>",
"Append file contents to the code system prompt. Does NOT replace the default prompt. UTF-8, relative to cwd or absolute.",
)
.description(t("cli.code"))
.option("-m, --model <id>", t("ui.modelOverride"))
.option("--no-session", t("ui.noSession"))
.option("-r, --resume", t("ui.resumeHint"))
.option("-n, --new", t("ui.newHint"))
.option("--transcript <path>", t("ui.transcriptHint"))
.option("--harvest", t("ui.harvestHint"))
.option("--budget <usd>", t("ui.budgetHint"), (v) => Number.parseFloat(v))
.option("--no-dashboard", t("ui.noDashboard"))
.option("--system-append <prompt>", t("ui.systemAppendHint"))
.option("--system-append-file <path>", t("ui.systemAppendFileHint"))
.action(async (dir: string | undefined, opts) => {
await codeCommand({
dir,
@@ -151,51 +132,28 @@ program
program
.command("chat")
.description("Interactive Ink TUI with live cache/cost panel.")
.option("-m, --model <id>", "DeepSeek model id (overrides preset)")
.option("-s, --system <prompt>", "System prompt (pinned in the immutable prefix)", DEFAULT_SYSTEM)
.option("--transcript <path>", "Write a JSONL transcript to this path")
.option(
"--preset <name>",
"Model bundle. One of: auto (flash → pro on hard turns, default), flash (always flash), pro (always pro). Overrides config.preset.",
)
.option(
"--harvest",
"Opt-in Pillar-2 plan-state extraction. Off by default — no preset enables it.",
)
.option(
"--branch <n>",
"Self-consistency: run N parallel samples per turn (N× cost). Manual only — never auto-enabled.",
(v) => Number.parseInt(v, 10),
)
.option(
"--budget <usd>",
"Soft USD cap on session spend. Off by default. Warns at 80%, refuses next turn at 100%. Mid-session: /budget <usd> or /budget off.",
(v) => Number.parseFloat(v),
)
.option("--session <name>", "Use a named session (default: from config, usually 'default').")
.option("--no-session", "Disable session persistence for this run (ephemeral chat)")
.option("-r, --resume", "Skip the session picker — always continue prior messages")
.option(
"-c, --continue",
"Resume the most-recently-used session (any name) without showing the picker.",
)
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
.description(t("cli.chat"))
.option("-m, --model <id>", t("ui.modelIdHint"))
.option("-s, --system <prompt>", t("ui.systemPromptHint"), DEFAULT_SYSTEM)
.option("--transcript <path>", t("ui.transcriptHint"))
.option("--preset <name>", t("ui.presetHint"))
.option("--harvest", t("ui.harvestOptInHint"))
.option("--branch <n>", t("ui.branchHint"), (v) => Number.parseInt(v, 10))
.option("--budget <usd>", t("ui.budgetHint"), (v) => Number.parseFloat(v))
.option("--session <name>", t("ui.sessionNameHint"))
.option("--no-session", t("ui.ephemeralHint"))
.option("-r, --resume", t("ui.resumeHint"))
.option("-c, --continue", t("cli.continue"))
.option("-n, --new", t("ui.newHint"))
.option(
"--mcp <spec>",
'MCP server spec; repeatable. "name=cmd args...", "cmd args...", or a URL (http/https → SSE transport). Overrides config.mcp when provided.',
t("ui.mcpSpecHint"),
(value: string, previous: string[] = []) => [...previous, value],
[] as string[],
)
.option(
"--mcp-prefix <str>",
"Global prefix applied to every MCP tool (only honored when no per-spec name is set; avoids collisions with a single anonymous server)",
)
.option("--no-config", "Ignore `~/.reasonix/config.json` — useful for CI or reproducing issues")
.option(
"--no-dashboard",
"Suppress the auto-launched embedded web dashboard. Default behavior boots it on TUI mount and shows the URL in the status bar (clickable in OSC-8-aware terminals).",
)
.option("--mcp-prefix <str>", t("ui.mcpPrefixHint"))
.option("--no-config", t("ui.noConfigHint"))
.option("--no-dashboard", t("ui.noDashboard"))
.action(async (opts) => {
const defaults = resolveDefaults({
model: opts.model,
@@ -236,33 +194,22 @@ program
program
.command("run <task>")
.description("Run a single task non-interactively, streaming output.")
.option("-m, --model <id>", "DeepSeek model id (overrides preset)")
.option("-s, --system <prompt>", "System prompt", DEFAULT_SYSTEM)
.option("--preset <name>", "Model bundle: auto | flash | pro (default: auto)")
.option("--harvest", "Extract typed plan state from R1 reasoning (Pillar 2)")
.option(
"--branch <n>",
"Self-consistency: run N parallel samples per turn and pick the most confident",
(v) => Number.parseInt(v, 10),
)
.option(
"--budget <usd>",
"Soft USD cap on session spend. Off by default. Refuses to start a new turn once cumulative cost ≥ cap.",
(v) => Number.parseFloat(v),
)
.option("--transcript <path>", "Write a JSONL transcript to this path for replay/diff")
.description(t("cli.run"))
.option("-m, --model <id>", t("ui.modelIdHint"))
.option("-s, --system <prompt>", t("ui.systemPromptHint"), DEFAULT_SYSTEM)
.option("--preset <name>", t("ui.presetHintShort"))
.option("--harvest", t("ui.harvestHintShort"))
.option("--branch <n>", t("ui.branchHintShort"), (v) => Number.parseInt(v, 10))
.option("--budget <usd>", t("ui.budgetHintShort"), (v) => Number.parseFloat(v))
.option("--transcript <path>", t("ui.transcriptHintShort"))
.option(
"--mcp <spec>",
'MCP server spec; repeatable. "name=cmd args...", "cmd args...", or a URL (http/https → SSE).',
t("ui.mcpSpecHintShort"),
(value: string, previous: string[] = []) => [...previous, value],
[] as string[],
)
.option(
"--mcp-prefix <str>",
"Global prefix (only honored when no per-spec name is set; for a single anonymous server)",
)
.option("--no-config", "Ignore `~/.reasonix/config.json` — useful for CI or reproducing issues")
.option("--mcp-prefix <str>", t("ui.mcpPrefixHintShort"))
.option("--no-config", t("ui.noConfigHint"))
.action(async (task: string, opts) => {
const defaults = resolveDefaults({
model: opts.model,
@@ -287,58 +234,52 @@ program
program
.command("stats [transcript]")
.description(
"Show usage dashboard (today / week / month / all-time · turns · cache hit · cost · savings vs Claude). " +
"Pass a transcript path to fall back to the per-file summary (assistant turns + tool calls).",
)
.description(t("cli.stats"))
.action((transcript: string | undefined) => {
statsCommand({ transcript });
});
program
.command("doctor")
.description(
"One-command health check — API key, config, /user/balance reachability, tokenizer, sessions, hooks, Ollama (if used), project markers. Exit 1 on any fail; 0 on warn / clean.",
)
.description(t("cli.doctor"))
.action(async () => {
await doctorCommand();
});
program
.command("commit")
.description(
"Draft a commit message from the staged diff (or working tree, if nothing staged), matching your repo's recent commit style. Review interactively before it lands.",
)
.option("-m, --model <id>", "Override the default model (deepseek-v4-flash)")
.option(
"-y, --yes",
"Skip the [a]ccept / [r]egenerate prompt and commit the first draft. Useful in scripts.",
)
.description(t("cli.commit"))
.option("-m, --model <id>", t("ui.modelOverrideFlash"))
.option("-y, --yes", t("ui.skipConfirmHint"))
.action(async (opts) => {
await commitCommand({ model: opts.model, yes: !!opts.yes });
});
program
.command("sessions [name]")
.description("List saved chat sessions, or inspect one by name.")
.option("-v, --verbose", "Include system prompts + tool-call metadata when inspecting")
.description(t("cli.sessions"))
.option("-v, --verbose", t("ui.verboseHint"))
.action((name: string | undefined, opts) => {
sessionsCommand({ name, verbose: !!opts.verbose });
});
program
.command("prune-sessions")
.description(t("cli.pruneSessions"))
.option("--days <n>", t("ui.pruneDaysHint"), (v) => Number.parseInt(v, 10))
.option("--dry-run", t("ui.pruneDryRunHint"))
.action((opts) => {
pruneSessionsCommand({ days: opts.days, dryRun: !!opts.dryRun });
});
program
.command("events <name>")
.description(
"Pretty-print the kernel event-log sidecar (~/.reasonix/sessions/<name>.events.jsonl) — every typed Event the session produced.",
)
.option("--type <type>", "Show only events of this type (e.g., tool.intent)")
.option("--since <id>", "Show only events with id >= N", (v) => Number.parseInt(v, 10))
.option("--tail <n>", "Show only the last N events", (v) => Number.parseInt(v, 10))
.option("--json", "Emit raw JSONL passthrough instead of formatted lines (for jq pipelines)")
.option(
"--projection",
"Replace the listing with the final reduced ProjectionSet (conversation, budget, plan, …)",
)
.description(t("cli.events"))
.option("--type <type>", t("ui.eventTypeHint"))
.option("--since <id>", t("ui.eventSinceHint"), (v) => Number.parseInt(v, 10))
.option("--tail <n>", t("ui.eventTailHint"), (v) => Number.parseInt(v, 10))
.option("--json", t("ui.jsonHint"))
.option("--projection", t("ui.projectionHint"))
.action((name: string, opts) => {
eventsCommand({
name,
@@ -352,12 +293,10 @@ program
program
.command("replay <transcript>")
.description(
"Interactive Ink TUI to scrub through a transcript + rebuild its session summary (cost, cache, prefix stability). No API calls.",
)
.option("--print", "Dump to stdout instead of mounting the TUI (auto when piped)")
.option("--head <n>", "stdout mode only — show first N records", (v) => Number.parseInt(v, 10))
.option("--tail <n>", "stdout mode only — show last N records", (v) => Number.parseInt(v, 10))
.description(t("cli.replay"))
.option("--print", t("ui.printHint"))
.option("--head <n>", t("ui.headHint"), (v) => Number.parseInt(v, 10))
.option("--tail <n>", t("ui.tailHint"), (v) => Number.parseInt(v, 10))
.action(async (transcript: string, opts) => {
await replayCommand({
path: transcript,
@@ -369,14 +308,12 @@ program
program
.command("diff <a> <b>")
.description(
"Compare two transcripts in a split-pane Ink TUI (default) or stdout table. Use n/N to jump across divergences.",
)
.option("--md <path>", "Write a markdown report (blog-ready) to this path")
.option("--print", "Force stdout table instead of the TUI (auto when piped)")
.option("--tui", "Force the TUI even when piped (rare)")
.option("--label-a <label>", "Display label for transcript A (default: filename)")
.option("--label-b <label>", "Display label for transcript B (default: filename)")
.description(t("cli.diff"))
.option("--md <path>", t("ui.mdReportHint"))
.option("--print", t("ui.printHintTable"))
.option("--tui", t("ui.tuiHint"))
.option("--label-a <label>", t("ui.labelAHint"))
.option("--label-b <label>", t("ui.labelBHint"))
.action(async (a: string, b: string, opts) => {
await diffCommand({
a,
@@ -389,24 +326,20 @@ program
});
});
const mcp = program
.command("mcp")
.description("Model Context Protocol helpers — discover servers, test your setup.");
const mcp = program.command("mcp").description(t("cli.mcp"));
mcp
.command("list")
.description("Show a curated catalog of popular MCP servers with ready-to-use --mcp commands.")
.option("--json", "Emit the catalog as JSON instead of the human-readable table")
.description(t("ui.mcpListDescription"))
.option("--json", t("ui.jsonHintCatalog"))
.action((opts) => {
mcpListCommand({ json: !!opts.json });
});
mcp
.command("inspect <spec>")
.description(
'Connect to one MCP server and print its server info + tools/resources/prompts. <spec> takes the same forms as --mcp ("name=cmd args", "cmd args", or an SSE URL).',
)
.option("--json", "Emit the full inspection report as JSON instead of the human-readable summary")
.description(t("ui.mcpInspectDescription"))
.option("--json", t("ui.jsonHintReport"))
.action(async (spec: string, opts) => {
try {
await mcpInspectCommand({ spec, json: !!opts.json });
@@ -416,31 +349,24 @@ mcp
}
});
program.command("version").description("Print Reasonix version.").action(versionCommand);
program.command("version").description(t("cli.version")).action(versionCommand);
program
.command("update")
.description(
"Check the npm registry for a newer Reasonix and install it. Detects npx vs global install; for npx users, prints a cache-refresh hint instead of running `npm i -g`.",
)
.option("--dry-run", "Print the plan without executing the install")
.description(t("cli.update"))
.option("--dry-run", t("ui.dryRunHint"))
.action(async (opts: { dryRun?: boolean }) => {
await updateCommand({ dryRun: !!opts.dryRun });
});
program
.command("index")
.description(
"Build (or incrementally refresh) a local semantic search index for the project so `reasonix code` can answer 'where do we…' questions by meaning, not just by token. Uses Ollama as the embedding backend; missing daemon / model is offered to the user with a confirm prompt.",
)
.option("--rebuild", "Wipe and rebuild from scratch")
.option("--model <name>", "Embedding model (default: nomic-embed-text)")
.option("--dir <path>", "Project root to index (default: cwd)")
.option("--ollama-url <url>", "Override Ollama base URL (default: http://localhost:11434)")
.option(
"-y, --yes",
"Skip preflight prompts — auto-start the daemon and pull the model if missing (use in scripts)",
)
.description(t("cli.index"))
.option("--rebuild", t("ui.rebuildHint"))
.option("--model <name>", t("ui.embedModelHint"))
.option("--dir <path>", t("ui.projectDirHint"))
.option("--ollama-url <url>", t("ui.ollamaUrlHint"))
.option("-y, --yes", t("ui.skipPromptsHint"))
.action(
async (opts: {
rebuild?: boolean;
+576 -602
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -5,6 +5,7 @@ import React from "react";
import type { ChoiceOption } from "../../tools/choice.js";
import { SingleSelect } from "./Select.js";
import { ApprovalCard } from "./cards/ApprovalCard.js";
import { useReserveRows } from "./layout/viewport-budget.js";
export type ChoiceConfirmChoice =
| { kind: "pick"; optionId: string }
@@ -22,6 +23,9 @@ const CUSTOM_VALUE = "__custom__";
const CANCEL_VALUE = "__cancel__";
function ChoiceConfirmInner({ question, options, allowCustom, onChoose }: ChoiceConfirmProps) {
const optionRows = options.length + (allowCustom ? 1 : 0) + 1; // +1 for cancel
useReserveRows("modal", { min: 6, max: Math.max(10, optionRows + 6) });
const items: Array<{ value: string; label: string; hint?: string }> = options.map((opt) => ({
value: opt.id,
label: `${opt.id} · ${opt.title}`,
+8 -4
View File
@@ -1,4 +1,4 @@
import { Box, Text, useStdout } from "ink";
import { Box, Text } from "ink";
import React, { useMemo, useState } from "react";
import { formatEditBlockSplit } from "../../code/diff-preview.js";
import type { EditBlock } from "../../code/edit-blocks.js";
@@ -6,6 +6,7 @@ import { DenyContextInput } from "./DenyContextInput.js";
import { SplitDiff } from "./SplitDiff.js";
import { ApprovalCard } from "./cards/ApprovalCard.js";
import { useKeystroke } from "./keystroke-context.js";
import { useReserveRows, useTotalRows } from "./layout/viewport-budget.js";
export type EditReviewChoice = "apply" | "reject" | "apply-rest-of-turn" | "flip-to-auto";
@@ -21,9 +22,12 @@ const REVIEW_FOOTER =
"[y/Enter] apply · [n] reject with reason · [a] apply rest · [A] flip AUTO · [↑↓/Space] scroll · [Esc] abort";
export function EditConfirm({ block, onChoose }: EditConfirmProps) {
const { stdout } = useStdout();
const rows = stdout?.rows ?? 40;
const budget = Math.max(MIN_DIFF_ROWS, rows - MODAL_OVERHEAD_ROWS);
const rows = useTotalRows();
const allocated = useReserveRows("modal", {
min: MODAL_OVERHEAD_ROWS + MIN_DIFF_ROWS,
max: Math.max(MODAL_OVERHEAD_ROWS + MIN_DIFF_ROWS, rows - 4),
});
const budget = Math.max(MIN_DIFF_ROWS, allocated - MODAL_OVERHEAD_ROWS);
const allRows = useMemo(
() => formatEditBlockSplit(block, { contextLines: 2, maxLines: 100_000 }),
+69
View File
@@ -0,0 +1,69 @@
import { Text, useInput } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React, { useRef } from "react";
import { FG } from "./theme/tokens.js";
export interface MaskedInputProps {
value: string;
onChange: (next: string) => void;
onSubmit: (final: string) => void;
mask?: string;
placeholder?: string;
}
/** Windows ConPTY splits bracketed-paste wrappers across stdin chunks; Ink's parser sees them as printable `[`, `2`, `0`, `0`, `~` and they leak into the buffer. Strip them at the input boundary and again at submit. */
function stripPasteMarkers(s: string): string {
// biome-ignore lint/suspicious/noControlCharactersInRegex: ESC (0x1b) is exactly what we're stripping — bracketed-paste wrappers and stray escape bytes leaked from Ink's parser.
return s.replace(/\u001b?\[20[01]~/g, "").replace(/\u001b/g, "");
}
export function MaskedInput({
value,
onChange,
onSubmit,
mask = "•",
placeholder = "",
}: MaskedInputProps): React.ReactElement {
const valueRef = useRef(value);
valueRef.current = value;
useInput((input, key) => {
if (key.return) {
onSubmit(stripPasteMarkers(valueRef.current));
return;
}
if (key.backspace || key.delete) {
if (valueRef.current.length === 0) return;
const next = valueRef.current.slice(0, -1);
valueRef.current = next;
onChange(next);
return;
}
if (input && !key.ctrl && !key.meta && !key.escape) {
const cleaned = stripPasteMarkers(input);
if (cleaned.length === 0) return;
const next = stripPasteMarkers(valueRef.current + cleaned);
valueRef.current = next;
onChange(next);
}
});
if (value.length === 0) {
if (placeholder.length === 0) {
return <Text inverse> </Text>;
}
return (
<>
<Text inverse>{placeholder[0]}</Text>
<Text color={FG.faint}>{placeholder.slice(1)}</Text>
</>
);
}
return (
<>
<Text>{mask.repeat(value.length)}</Text>
<Text inverse> </Text>
</>
);
}
+30 -9
View File
@@ -4,6 +4,9 @@ import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React, { useState } from "react";
import { useKeystroke } from "./keystroke-context.js";
import { toggleMcpDisabled } from "./mcp-disable.js";
import { healthBadge } from "./mcp-health.js";
import { type ApplyAppend, kickOffMcpReconnect } from "./mcp-reconnect-kickoff.js";
import type { McpServerSummary } from "./slash/types.js";
import { COLOR } from "./theme.js";
@@ -11,9 +14,19 @@ export interface McpBrowserProps {
servers: McpServerSummary[];
configPath: string;
onClose: () => void;
/** Pushed by the modal when a key triggers async work (`r` reconnect). */
postInfo: (text: string) => void;
/** Optional — opt-in to append-drift acceptance on `r`. Without it, append-drift refuses. */
applyAppend?: ApplyAppend;
}
export function McpBrowser({ servers, configPath, onClose }: McpBrowserProps) {
export function McpBrowser({
servers,
configPath,
onClose,
postInfo,
applyAppend,
}: McpBrowserProps) {
const [index, setIndex] = useState(0);
const max = Math.max(0, servers.length - 1);
@@ -22,6 +35,21 @@ export function McpBrowser({ servers, configPath, onClose }: McpBrowserProps) {
if (ev.upArrow) setIndex((i) => Math.max(0, i - 1));
else if (ev.downArrow) setIndex((i) => Math.min(max, i + 1));
else if (ev.escape) onClose();
else if (ev.input === "r") {
const target = servers[index];
if (!target) return;
// Hand the "starting" lifecycle line to scrollback and let the
// kickoff schedule the result line via postInfo. Close the modal
// so the line is visible immediately.
postInfo(kickOffMcpReconnect(target, postInfo, applyAppend));
onClose();
} else if (ev.input === "d") {
const target = servers[index];
if (!target) return;
// Persist `mcpDisabled` and close — takes effect on next launch.
postInfo(toggleMcpDisabled("disable", target.label));
onClose();
}
});
return (
@@ -46,7 +74,7 @@ export function McpBrowser({ servers, configPath, onClose }: McpBrowserProps) {
)}
</Box>
<Box marginTop={1}>
<Text dimColor>↑↓ pick · [r] reconnect (Stage C) · [d] disable (Stage C) · esc quit</Text>
<Text dimColor>↑↓ pick · [r] reconnect · [d] disable · esc quit</Text>
</Box>
</Box>
);
@@ -79,13 +107,6 @@ function ServerRow({ server, active }: { server: McpServerSummary; active: boole
);
}
function healthBadge(elapsedMs: number): { glyph: string; label: string; color: string } {
if (elapsedMs === 0) return { glyph: "✗", label: "no inspect data", color: COLOR.err };
if (elapsedMs < 500) return { glyph: "●", label: `healthy · ${elapsedMs}ms`, color: COLOR.ok };
if (elapsedMs < 3000) return { glyph: "◌", label: `slow · ${elapsedMs}ms`, color: COLOR.warn };
return { glyph: "✗", label: `very slow · ${elapsedMs}ms`, color: COLOR.err };
}
function capabilityList(s: McpServerSummary): string {
const caps: string[] = ["tools/list", "tools/call"];
if (s.report.resources.supported) caps.push("resources/list");
+4
View File
@@ -7,6 +7,7 @@ import type { PlanStep } from "../../tools/plan.js";
import { PlanStepList, type StepStatus } from "./PlanStepList.js";
import { SingleSelect } from "./Select.js";
import { ApprovalCard } from "./cards/ApprovalCard.js";
import { useReserveRows } from "./layout/viewport-budget.js";
export type CheckpointChoice = "continue" | "revise" | "stop";
@@ -31,6 +32,9 @@ function PlanCheckpointConfirmInner({
completedStepIds,
onChoose,
}: PlanCheckpointConfirmProps) {
const stepRows = steps?.length ?? 0;
useReserveRows("modal", { min: 10, max: Math.max(14, stepRows + 12) });
const label = title ? `${stepId} · ${title}` : stepId;
const counter = total > 0 ? `${completed}/${total}` : "";
const isLast = total > 0 && completed >= total;
+4
View File
@@ -7,6 +7,7 @@ import type { PlanStep } from "../../tools/plan.js";
import { PlanStepList } from "./PlanStepList.js";
import { SingleSelect } from "./Select.js";
import { ApprovalCard } from "./cards/ApprovalCard.js";
import { useReserveRows } from "./layout/viewport-budget.js";
import { CARD, TONE } from "./theme/tokens.js";
export type PlanConfirmChoice = "approve" | "refine" | "revise" | "cancel";
@@ -21,6 +22,9 @@ export interface PlanConfirmProps {
}
function PlanConfirmInner({ plan, steps, onChoose }: PlanConfirmProps) {
const stepRows = steps?.length ?? 0;
useReserveRows("modal", { min: 10, max: Math.max(16, stepRows + 14) });
const hasOpenQuestions =
/^#{1,6}\s*(open[-\s]?questions?|risks?|unknowns?|assumptions?|unclear)/im.test(plan) ||
/^#{1,6}\s*(待确认|开放问题|风险|未知|假设|不确定)/im.test(plan);
+10 -1
View File
@@ -6,7 +6,7 @@ import { CARD, FG } from "./theme/tokens.js";
import { useTick } from "./ticker.js";
export interface PlanRefineInputProps {
mode: "approve" | "refine" | "checkpoint-revise" | "choice-custom";
mode: "approve" | "refine" | "reject" | "checkpoint-revise" | "choice-custom";
onSubmit: (feedback: string) => void;
onCancel: () => void;
}
@@ -37,6 +37,15 @@ const MODES: Record<PlanRefineInputProps["mode"], ModeMeta> = {
hint: "Describe what's wrong or missing, or answer questions the plan raised.",
blankHint: " (Enter with blank = ask the model to list concrete questions.)",
},
reject: {
title: "rejecting — tell the model why (optional)",
glyph: "✗",
tone: "error",
cursorColor: CARD.error.color,
hint: "Say what the model got wrong about your goal, or what you actually want instead.",
blankHint:
" (Enter with blank = cancel without explanation; the model will ask what you want.)",
},
"checkpoint-revise": {
title: "revising — what should change before the next step?",
glyph: "✎",
+10
View File
@@ -1,7 +1,9 @@
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value (classic transform compiles JSX to React.createElement)
import React, { useRef, useState } from "react";
import { useCursor } from "../../renderer/index.js";
import { useKeystroke } from "./keystroke-context.js";
import { useReserveRows } from "./layout/viewport-budget.js";
import { type MultilineKey, lineAndColumn, processMultilineKey } from "./multiline-keys.js";
import {
PASTE_SENTINEL_RANGE,
@@ -43,6 +45,10 @@ export function PromptInput({
onHistoryPrev,
onHistoryNext,
}: PromptInputProps) {
// Cap at 24 — collapseLinesForDisplay hides content past ~20 logical lines.
const inputLineCount = value.length > 0 ? value.split("\n").length : 1;
useReserveRows("input", { min: 1, max: Math.min(inputLineCount + 3, 24) });
const [cursor, setCursor] = useState(value.length);
// Paste registry — keyed by sentinel id, holds original content.
@@ -99,6 +105,8 @@ export function PromptInput({
escape: ev.escape,
pageUp: ev.pageUp,
pageDown: ev.pageDown,
home: ev.home,
end: ev.end,
};
const action = processMultilineKey(lastLocalValueRef.current, cursorRef.current, key);
if (action.pasteRequest) {
@@ -145,6 +153,8 @@ export function PromptInput({
const accentColor = disabled ? FG.faint : TONE.brand;
const cursorVisible = true;
const { line: cursorLine, col: cursorCol } = lineAndColumn(value, cursor);
// PromptInput paints its own cursor (`▌` / inverse char) — hide the real terminal cursor so it doesn't double up at the bottom of the screen.
useCursor({ col: 0, rowFromBottom: 0, visible: false });
const renderItems = collapseLinesForDisplay(lines, cursorLine);
const showHugeBufferHints = lines.length > 20;
+6
View File
@@ -19,6 +19,8 @@ export interface SingleSelectProps<V extends string> {
initialValue?: V;
onSubmit: (value: V) => void;
onCancel?: () => void;
/** Fired when Tab is pressed on the currently highlighted item. */
onTab?: (value: V) => void;
/** Optional dim footer beneath the list. */
footer?: string;
}
@@ -27,6 +29,7 @@ export function SingleSelect<V extends string>({
items,
initialValue,
onSubmit,
onTab,
onCancel,
footer,
}: SingleSelectProps<V>) {
@@ -45,6 +48,9 @@ export function SingleSelect<V extends string>({
} else if (ev.return) {
const chosen = items[index];
if (chosen && !chosen.disabled) onSubmit(chosen.value);
} else if (ev.tab) {
const chosen = items[index];
if (chosen && !chosen.disabled) onTab?.(chosen.value);
} else if (ev.escape && onCancel) {
onCancel();
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { Box, Text, useApp } from "ink";
import TextInput from "ink-text-input";
import React, { useState } from "react";
import { defaultConfigPath, isPlausibleKey, redactKey, saveApiKey } from "../../config.js";
import { MaskedInput } from "./MaskedInput.js";
import { COLOR, GLYPH, GRADIENT } from "./theme.js";
export interface SetupProps {
@@ -63,7 +63,7 @@ export function Setup({ onReady }: SetupProps) {
<Text bold color={COLOR.primary}>
{" › "}
</Text>
<TextInput
<MaskedInput
value={value}
onChange={setValue}
onSubmit={handleSubmit}
+9 -3
View File
@@ -4,6 +4,7 @@ import React, { useState } from "react";
import { DenyContextInput } from "./DenyContextInput.js";
import { SingleSelect } from "./Select.js";
import { ApprovalCard } from "./cards/ApprovalCard.js";
import { useReserveRows } from "./layout/viewport-budget.js";
import { FG, TONE } from "./theme/tokens.js";
export type ShellConfirmChoice = "run_once" | "always_allow" | "deny";
@@ -18,6 +19,8 @@ export interface ShellConfirmProps {
}
export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConfirmProps) {
useReserveRows("modal", { min: 8, max: 14 });
const isBackground = kind === "run_background";
const subtitle = isBackground
? "long-running process — keeps running after approval, /kill to stop"
@@ -32,7 +35,7 @@ export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConf
glyph="✗"
title="Deny — provide context"
metaRight="optional"
footerHint="⏎ submit · esc skip (deny without reason)"
footerHint="type context · ⏎ submit with reason · esc skip (deny without reason)"
>
<DenyContextInput
onSubmit={(context) => onChoose("deny", context || undefined)}
@@ -48,7 +51,7 @@ export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConf
glyph={isBackground ? "⏱" : "?"}
title={isBackground ? "Background process" : "Shell command"}
metaRight="awaiting"
footerHint="↑↓ pick · ⏎ confirm · esc cancel"
footerHint="↑↓ pick · ⏎ confirm · Tab add context · esc cancel"
>
<Box marginBottom={1}>
<Text color={FG.faint}>{subtitle}</Text>
@@ -77,13 +80,16 @@ export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConf
{
value: "deny",
label: "deny",
hint: "skip; agent will pick an alternative",
hint: "press Tab to add context telling the model why",
},
]}
onSubmit={(v) => {
if (v === "deny") setPhase("deny");
else onChoose(v as ShellConfirmChoice);
}}
onTab={(v) => {
if (v === "deny") setPhase("deny");
}}
onCancel={() => onChoose("deny")}
/>
</ApprovalCard>
+5 -1
View File
@@ -1,6 +1,7 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
import React from "react";
import { t } from "../../i18n/index.js";
import type { SlashCommandSpec } from "./slash.js";
import { COLOR, GLYPH } from "./theme.js";
@@ -82,6 +83,9 @@ export function SlashSuggestions({
function SuggestionRow({ spec, isSelected }: { spec: SlashCommandSpec; isSelected: boolean }) {
const name = `/${spec.cmd}`;
const argsSuffix = spec.argsHint ? spec.argsHint : "";
const key = `slash.${spec.cmd}.description`;
const translated = t(key);
const summary = translated === key ? spec.summary : translated;
return (
<Box>
<Text color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
@@ -93,7 +97,7 @@ function SuggestionRow({ spec, isSelected }: { spec: SlashCommandSpec; isSelecte
<Text dimColor>{argsSuffix.padEnd(14)}</Text>
<Text>{" "}</Text>
<Text color={isSelected ? COLOR.user : COLOR.info} dimColor={!isSelected}>
{spec.summary}
{summary}
</Text>
</Box>
);
+43 -107
View File
@@ -1,8 +1,9 @@
/** Empty-session welcome card — sharp ASCII box + tagline + 4 starter slash commands. */
/** Empty-session welcome card — REASONIX × 🐋 DeepSeek brand row + tagline + starter slash commands. */
import { Box, Text, useStdout } from "ink";
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { t } from "../../i18n/index.js";
import { FG, TONE } from "./theme/tokens.js";
export interface WelcomeBannerProps {
@@ -10,135 +11,70 @@ export interface WelcomeBannerProps {
inCodeMode?: boolean;
/** Live URL of the embedded dashboard, or null when it isn't running. */
dashboardUrl?: string | null;
/** Bumped on language change; forces re-render so t() picks up new locale. */
languageVersion?: number;
}
const TAGLINE_CHAT = "DeepSeek-native agent";
const TAGLINE_CODE = "DeepSeek-native coding agent";
const TAGLINE_SUB = "cache-first · flash-first";
const HINTS = ["/help", "/init", "/memory", "/cost"] as const;
const BOX_INNER_WIDTH = 35;
export function WelcomeBanner({
inCodeMode,
dashboardUrl,
}: WelcomeBannerProps): React.ReactElement {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const tagline = inCodeMode ? TAGLINE_CODE : TAGLINE_CHAT;
const boxWidth = BOX_INNER_WIDTH + 2;
const boxIndent = Math.max(2, Math.floor((cols - boxWidth) / 2));
const top = `╔${"═".repeat(BOX_INNER_WIDTH)}╗`;
const bot = `╚${"═".repeat(BOX_INNER_WIDTH)}╝`;
const hintsRow = HINTS.join(" · ");
const hintsIndent = Math.max(2, Math.floor((cols - hintsRow.length) / 2));
const startTextRaw = "type a message to start your session";
const startIndent = Math.max(2, Math.floor((cols - startTextRaw.length) / 2));
const tagline = inCodeMode ? t("ui.taglineCode") : t("ui.taglineChat");
const taglineSub = t("ui.taglineSub");
const startTextRaw = t("ui.startSessionHint");
return (
<Box flexDirection="column" marginY={1}>
<BoxRow indent={boxIndent}>
<Text color={TONE.brand}>{top}</Text>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>{""}</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>
<Text bold color={TONE.brand}>
{centerInside("◈ REASONIX", BOX_INNER_WIDTH)}
<Box flexDirection="column" alignItems="center" marginY={1}>
<Box
flexDirection="column"
alignItems="center"
borderStyle="round"
borderColor={TONE.brand}
paddingX={4}
paddingY={1}
>
<Box flexDirection="row" gap={2}>
<Text color={TONE.brand} bold>
{"REASONIX"}
</Text>
</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>{""}</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>
<Text color={FG.sub}>{centerInside(tagline, BOX_INNER_WIDTH)}</Text>
</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>
<Text color={FG.meta}>{centerInside(TAGLINE_SUB, BOX_INNER_WIDTH)}</Text>
</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>{""}</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<Text color={TONE.brand}>{bot}</Text>
</BoxRow>
<Text color={FG.faint}>{"×"}</Text>
<Box flexDirection="row" gap={1}>
<Text>{"🐋"}</Text>
<Text color={TONE.accent} bold>
{"DeepSeek"}
</Text>
</Box>
</Box>
<Box marginTop={1}>
<Text>{" ".repeat(startIndent)}</Text>
<Text color={FG.sub}>{startTextRaw}</Text>
<Box marginTop={1} flexDirection="column" alignItems="center">
<Text color={FG.body}>{tagline}</Text>
<Text color={FG.meta}>{taglineSub}</Text>
</Box>
</Box>
<Box marginTop={1}>
<Text>{" ".repeat(hintsIndent)}</Text>
{HINTS.map((cmd, i) => (
<React.Fragment key={cmd}>
<Text color={FG.meta}>{cmd}</Text>
{i < HINTS.length - 1 && <Text color={FG.faint}>{" · "}</Text>}
</React.Fragment>
<Text color={FG.sub}>{startTextRaw}</Text>
</Box>
<Box marginTop={1} flexDirection="row" gap={3}>
{HINTS.map((cmd) => (
<Text key={cmd} color={FG.meta}>
{cmd}
</Text>
))}
</Box>
{dashboardUrl ? (
<Box marginTop={1} flexDirection="row" justifyContent="center">
<Box marginTop={1} flexDirection="row" gap={1}>
<Text color={TONE.brand} bold>
{"▸ web · "}
{"▸ web"}
</Text>
<Text color={FG.faint}>{"·"}</Text>
<Text color={TONE.accent}>{dashboardUrl}</Text>
</Box>
) : null}
</Box>
);
}
function BoxRow({
indent,
children,
}: {
indent: number;
children: React.ReactNode;
}): React.ReactElement {
return (
<Box>
<Text>{" ".repeat(indent)}</Text>
{children}
</Box>
);
}
function BoxLine({
pad,
children,
}: {
pad: number;
children?: React.ReactNode;
}): React.ReactElement {
if (children === "" || children === undefined) {
return (
<>
<Text color={TONE.brand}>{"║"}</Text>
<Text>{" ".repeat(pad)}</Text>
<Text color={TONE.brand}>{"║"}</Text>
</>
);
}
return (
<>
<Text color={TONE.brand}>{"║"}</Text>
{children}
<Text color={TONE.brand}>{"║"}</Text>
</>
);
}
function centerInside(text: string, pad: number): string {
if (text.length >= pad) return text.slice(0, pad);
const left = Math.floor((pad - text.length) / 2);
const right = pad - text.length - left;
return `${" ".repeat(left)}${text}${" ".repeat(right)}`;
}
+17 -22
View File
@@ -1,40 +1,35 @@
import { Text } from "ink";
import { Box } from "ink";
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { BranchCard as BranchCardData } from "../state/cards.js";
import { CARD, FG, TONE } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
const BAR_CELLS = 28;
export function BranchCard({ card }: { card: BranchCardData }): React.ReactElement {
const ratio = card.total > 0 ? card.completed / card.total : 0;
const filled = Math.max(0, Math.min(BAR_CELLS, Math.round(ratio * BAR_CELLS)));
const tone = card.done ? TONE.ok : CARD.streaming.color;
const tone = card.done ? TONE.ok : CARD.branch.color;
return (
<Box flexDirection="column">
<Card tone={tone}>
<CardHeader
tone="streaming"
glyph="⎇"
title={card.done ? "Branching done" : "Branching"}
meta={`· ${card.completed} of ${card.total} samples`}
barColor={tone}
tone={tone}
title={card.done ? "branching done" : "branching"}
meta={[`${card.completed} of ${card.total} samples`]}
/>
<BarRow tone="streaming" indent={0} />
<BarRow tone="streaming">
<Box flexDirection="row" gap={1}>
<Text color={tone}>{"█".repeat(filled)}</Text>
<Text color={FG.faint}>{"░".repeat(BAR_CELLS - filled)}</Text>
<Text color={FG.faint}>{` ${(ratio * 100).toFixed(0)}%`}</Text>
</BarRow>
{!card.done && card.completed > 0 && (
<BarRow tone="streaming">
<Text color={FG.faint}>
{`latest: #${card.latestIndex} · T=${card.latestTemperature.toFixed(2)} · ${card.latestUncertainties} unc`}
</Text>
</BarRow>
)}
</Box>
<Text color={FG.faint}>{`${(ratio * 100).toFixed(0)}%`}</Text>
</Box>
{!card.done && card.completed > 0 ? (
<Text color={FG.faint}>
{`latest · #${card.latestIndex} · T=${card.latestTemperature.toFixed(2)} · ${card.latestUncertainties} unc`}
</Text>
) : null}
</Card>
);
}
-96
View File
@@ -1,96 +0,0 @@
import { Box, Spacer, Text } from "ink";
import React from "react";
import { CARD, type CardTone, FG } from "../theme/tokens.js";
import { STATUS, STRUCT } from "./glyphs.js";
const CardToneCtx = React.createContext<CardTone>("user");
export interface CardProps {
tone: CardTone;
glyph?: string;
title?: string;
meta?: string;
collapsed?: boolean;
trailing?: React.ReactNode;
children?: React.ReactNode;
}
export function Card({
tone,
glyph,
title,
meta,
collapsed,
trailing,
children,
}: CardProps): React.ReactElement {
const t = CARD[tone];
const headerGlyph = glyph ?? t.glyph;
const showBar = tone !== "user";
return (
<CardToneCtx.Provider value={tone}>
<Box flexDirection="column">
<Box flexDirection="row">
<Text>{" "}</Text>
{showBar ? <Text color={t.color}>{STRUCT.bar}</Text> : <Text> </Text>}
<Text> </Text>
<Text bold color={t.color}>
{headerGlyph}
</Text>
{title !== undefined && (
<Text bold color={tone === "user" ? FG.sub : FG.strong}>
{" "}
{title}
</Text>
)}
<Spacer />
{meta !== undefined && <Text color={FG.meta}>{meta}</Text>}
{trailing !== undefined && (
<>
<Text> </Text>
{trailing}
</>
)}
{collapsed !== undefined && (
<Text color={FG.faint}>
{" "}
{collapsed ? STATUS.collapsed : STATUS.expanded}
</Text>
)}
</Box>
{children}
</Box>
</CardToneCtx.Provider>
);
}
export function CardLine({
children,
}: {
children?: React.ReactNode;
}): React.ReactElement {
const tone = React.useContext(CardToneCtx);
const t = CARD[tone];
const showBar = tone !== "user";
return (
<Box flexDirection="row">
<Text>{" "}</Text>
{showBar ? <Text color={t.color}>{STRUCT.bar}</Text> : <Text> </Text>}
<Text>{" "}</Text>
<Box flexGrow={1}>{children}</Box>
</Box>
);
}
export function CardSpacer(): React.ReactElement {
const tone = React.useContext(CardToneCtx);
const t = CARD[tone];
const showBar = tone !== "user";
return (
<Box flexDirection="row">
<Text>{" "}</Text>
{showBar ? <Text color={t.color}>{STRUCT.bar}</Text> : <Text> </Text>}
</Box>
);
}
-67
View File
@@ -1,67 +0,0 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { CARD, type CardTone, FG } from "../theme/tokens.js";
import { STRUCT } from "./glyphs.js";
export interface CardHeaderProps {
tone: CardTone;
glyph: string;
/** Bold + colored heading text right after the glyph. */
title: string;
/** Dimmed continuation appended after the title (e.g. " src/cli/ui/App.tsx"). */
subtitle?: string;
/** Right-aligned dim meta (e.g. "0.08s · 1224 lines"). */
meta?: string;
/** Right-aligned colored badge slot, painted after `meta` (e.g. running/done badge). */
trailing?: React.ReactNode;
/** Inline node painted between the title and the subtitle — for spinners etc. */
inline?: React.ReactNode;
/** Override the bar color (default = card tone color). */
barColor?: string;
/** Override the title color (default = strong fg). User card uses sub fg. */
titleColor?: string;
}
export function CardHeader({
tone,
glyph,
title,
subtitle,
meta,
trailing,
inline,
barColor,
titleColor,
}: CardHeaderProps): React.ReactElement {
const t = CARD[tone];
const bar = barColor ?? t.color;
return (
<Box flexDirection="row">
<Text>{" "}</Text>
<Text color={bar}>{STRUCT.bar}</Text>
<Text> </Text>
<Text bold color={t.color}>
{glyph}
</Text>
<Text bold color={titleColor ?? FG.strong}>
{` ${title}`}
</Text>
{inline && (
<>
<Text> </Text>
{inline}
</>
)}
{subtitle && <Text color={FG.sub}>{` ${subtitle}`}</Text>}
<Box flexGrow={1} />
{meta && <Text color={FG.faint}>{meta}</Text>}
{trailing && (
<>
<Text> </Text>
{trailing}
</>
)}
</Box>
);
}
+5 -16
View File
@@ -2,7 +2,6 @@ import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import type { Card } from "../state/cards.js";
import { useAgentState } from "../state/provider.js";
import { FG } from "../theme/tokens.js";
import { BranchCard } from "./BranchCard.js";
import { CtxCard } from "./CtxCard.js";
@@ -23,25 +22,17 @@ import { UserCard } from "./UserCard.js";
import { WarnCard } from "./WarnCard.js";
export function CardRenderer({ card }: { card: Card }): React.ReactElement {
// Once assistant content starts streaming, reasoning collapses so the
// answer takes the live region budget.
const contentStreaming = useAgentState((s) =>
s.cards.some((c) => c.kind === "streaming" && c.text.length > 0 && !c.done),
);
return (
<Box flexDirection="column" marginTop={1}>
{renderCard(card, contentStreaming)}
</Box>
);
// No marginTop here — Card primitive owns inter-card spacing. Doubling it
// bakes 2 blank rows into every static-emitted block of bytes.
return <Box flexDirection="column">{renderCard(card)}</Box>;
}
function renderCard(card: Card, contentStreaming: boolean): React.ReactElement {
function renderCard(card: Card): React.ReactElement {
switch (card.kind) {
case "user":
return <UserCard card={card} />;
case "reasoning":
// Yield to content while it streams; otherwise show a body preview.
return <ReasoningCard card={card} expanded={!(card.streaming && contentStreaming)} />;
return <ReasoningCard card={card} expanded={true} />;
case "streaming":
return <StreamingCard card={card} />;
case "tool":
@@ -64,8 +55,6 @@ function renderCard(card: Card, contentStreaming: boolean): React.ReactElement {
return <SubAgentCard card={card} />;
case "search":
return <SearchCard card={card} />;
case "approval":
return <FallbackCard card={card} />;
case "live":
return <LiveCard card={card} />;
case "ctx":
+27 -31
View File
@@ -1,22 +1,25 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { CtxCard as CtxCardData } from "../state/cards.js";
import { CARD, FG, TONE } from "../theme/tokens.js";
import { FG, TONE } from "../theme/tokens.js";
const BAR_CELLS = 32;
function row(label: string, tokens: number, ratio: number, color: string): React.ReactElement {
const filled = Math.max(0, Math.min(BAR_CELLS, Math.round(ratio * BAR_CELLS)));
return (
<BarRow tone="usage">
<Text color={FG.sub}>{label.padEnd(8)}</Text>
<Box flexDirection="row" gap={1}>
<Text color={FG.sub}>{label.padEnd(7)}</Text>
<Text color={color}>{"█".repeat(filled)}</Text>
<Text color={FG.faint}>{"░".repeat(BAR_CELLS - filled)}</Text>
<Text bold color={FG.body}>{` ${tokens.toLocaleString()}`}</Text>
<Text color={FG.faint}>{` ${(ratio * 100).toFixed(1)}%`}</Text>
</BarRow>
<Text bold color={FG.body}>
{tokens.toLocaleString()}
</Text>
<Text color={FG.faint}>{`· ${(ratio * 100).toFixed(1)}%`}</Text>
</Box>
);
}
@@ -26,37 +29,30 @@ export function CtxCard({ card }: { card: CtxCardData }): React.ReactElement {
const usedPct = (used / cap) * 100;
return (
<Box flexDirection="column">
<Box flexDirection="row">
<Text>{" "}</Text>
<Text bold color={CARD.usage.color}>
{"⌘ Context window"}
</Text>
<Text color={FG.faint}>
{` · ${used.toLocaleString()} / ${cap.toLocaleString()} (${usedPct.toFixed(1)}%)`}
</Text>
</Box>
<BarRow tone="usage" indent={0} />
<Card tone={TONE.brand}>
<CardHeader
glyph="⌘"
tone={TONE.brand}
title="context"
meta={[`${used.toLocaleString()} / ${cap.toLocaleString()} (${usedPct.toFixed(1)}%)`]}
/>
{row("system", card.systemTokens, card.systemTokens / cap, TONE.brand)}
{row("tools", card.toolsTokens, card.toolsTokens / cap, TONE.warn)}
{row("log", card.logTokens, card.logTokens / cap, TONE.ok)}
{row("input", card.inputTokens, card.inputTokens / cap, TONE.accent)}
{card.topTools.length > 0 && (
{card.topTools.length > 0 ? (
<>
<BarRow tone="usage" indent={0} />
<BarRow tone="usage">
<Text color={FG.faint}>
{`top tools (${card.toolsCount} total · ${card.logMessages} log msgs):`}
</Text>
</BarRow>
<Text color={FG.faint}>
{`top tools · ${card.toolsCount} total · ${card.logMessages} log msgs`}
</Text>
{card.topTools.slice(0, 5).map((t) => (
<BarRow key={`${t.turn}-${t.name}`} tone="usage">
<Text color={FG.sub}>{` ${t.name}`}</Text>
<Text color={FG.faint}>{` · turn ${t.turn} · ${t.tokens.toLocaleString()}`}</Text>
</BarRow>
<Box key={`${t.turn}-${t.name}`} flexDirection="row" gap={1}>
<Text color={FG.sub}>{t.name}</Text>
<Text color={FG.faint}>{`· turn ${t.turn} · ${t.tokens.toLocaleString()}`}</Text>
</Box>
))}
</>
)}
</Box>
) : null}
</Card>
);
}
+39 -33
View File
@@ -1,10 +1,10 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { DiffCard as DiffCardData } from "../state/cards.js";
import { FG, TONE } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
const LINE_COLOR = {
ctx: FG.sub,
@@ -13,47 +13,53 @@ const LINE_COLOR = {
fold: FG.faint,
} as const;
const LINE_GLYPH = {
ctx: " ",
add: "+",
del: "-",
fold: "⋮",
} as const;
export function DiffCard({ card }: { card: DiffCardData }): React.ReactElement {
const meta = (
<>
<Text color={TONE.ok}>{`+${card.stats.add}`}</Text>
<Text color={FG.faint}>{" / "}</Text>
<Text color={TONE.err}>{`-${card.stats.del}`}</Text>
</>
);
const showFooter = card.hunks.length > 0;
return (
<Box flexDirection="column">
<CardHeader tone="diff" glyph="±" title="Edit" subtitle={card.file} trailing={meta} />
<Card tone={TONE.ok}>
<CardHeader
glyph="±"
tone={TONE.ok}
title={card.file}
titleColor={FG.body}
meta={[
{ text: `+${card.stats.add}`, color: TONE.ok },
{ text: `-${card.stats.del}`, color: TONE.err },
]}
/>
{card.hunks.map((hunk) => (
<Box key={`${card.id}:${hunk.header}`} flexDirection="column">
<BarRow tone="diff" indent={0} />
<BarRow tone="diff">
<Text italic color={FG.faint}>
{hunk.header}
</Text>
</BarRow>
<Text italic color={FG.faint}>
{hunk.header}
</Text>
{hunk.lines.map((line, li) => (
<BarRow key={`${card.id}:${hunk.header}:${li}`} tone="diff">
<Text color={LINE_COLOR[line.kind]}>{line.text}</Text>
</BarRow>
<Box key={`${card.id}:${hunk.header}:${li}`} flexDirection="row" gap={1}>
<Text color={LINE_COLOR[line.kind]}>{LINE_GLYPH[line.kind]}</Text>
<Text color={LINE_COLOR[line.kind]} dimColor={line.kind === "ctx"}>
{line.text}
</Text>
</Box>
))}
</Box>
))}
{showFooter && (
<>
<BarRow tone="diff" indent={0} />
<BarRow tone="diff">
<Text bold color={TONE.ok}>
{"[a] apply"}
</Text>
<Text color={FG.sub}>{" [s] skip "}</Text>
<Text bold color={TONE.err}>
{"[r] reject"}
</Text>
</BarRow>
</>
<Box flexDirection="row" gap={2}>
<Text bold color={TONE.ok}>
[a] apply
</Text>
<Text color={FG.sub}>[s] skip</Text>
<Text bold color={TONE.err}>
[r] reject
</Text>
</Box>
)}
</Box>
</Card>
);
}
+13 -12
View File
@@ -1,10 +1,10 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { DoctorCard as DoctorCardData, DoctorCheckEntry } from "../state/cards.js";
import { CARD, FG, TONE } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
const LEVEL_COLOR: Record<DoctorCheckEntry["level"], string> = {
ok: TONE.ok,
@@ -15,7 +15,7 @@ const LEVEL_COLOR: Record<DoctorCheckEntry["level"], string> = {
const LEVEL_GLYPH: Record<DoctorCheckEntry["level"], string> = {
ok: "✓",
warn: "⚠",
fail: "✗",
fail: "✖",
};
const LEVEL_TAG: Record<DoctorCheckEntry["level"], string> = {
@@ -28,21 +28,22 @@ export function DoctorCard({ card }: { card: DoctorCardData }): React.ReactEleme
const ok = card.checks.filter((c) => c.level === "ok").length;
const warn = card.checks.filter((c) => c.level === "warn").length;
const fail = card.checks.filter((c) => c.level === "fail").length;
const summary = `${card.checks.length} checks · ${ok} passed${warn > 0 ? ` · ${warn} warn` : ""}${fail > 0 ? ` · ${fail} fail` : ""}`;
const labelWidth = card.checks.reduce((m, c) => Math.max(m, c.label.length), 0);
const summary = `${card.checks.length} checks · ${ok} passed${warn > 0 ? ` · ${warn} warn` : ""}${fail > 0 ? ` · ${fail} fail` : ""}`;
return (
<Box flexDirection="column">
<CardHeader tone="tool" glyph="⚕" title="Doctor" meta={summary} barColor={CARD.tool.color} />
<BarRow tone="tool" indent={0} />
<Card tone={CARD.tool.color}>
<CardHeader glyph="⚕" tone={CARD.tool.color} title="doctor" meta={[summary]} />
{card.checks.map((c) => (
<BarRow key={c.label} tone="tool">
<Box key={c.label} flexDirection="row" gap={1}>
<Text color={LEVEL_COLOR[c.level]}>{LEVEL_GLYPH[c.level]}</Text>
<Text bold color={FG.body}>{` ${c.label.padEnd(labelWidth + 1)}`}</Text>
<Text bold color={FG.body}>
{c.label.padEnd(labelWidth + 1)}
</Text>
<Text color={FG.sub}>{c.detail}</Text>
<Text color={LEVEL_COLOR[c.level]}>{` ${LEVEL_TAG[c.level]}`}</Text>
</BarRow>
<Text color={LEVEL_COLOR[c.level]}>{LEVEL_TAG[c.level]}</Text>
</Box>
))}
</Box>
</Card>
);
}
+34 -41
View File
@@ -1,60 +1,53 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { ErrorCard as ErrorCardData } from "../state/cards.js";
import { CARD, FG, TONE } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
import { FG, TONE } from "../theme/tokens.js";
const STACK_TAIL = 5;
export function ErrorCard({ card }: { card: ErrorCardData }): React.ReactElement {
const meta =
const retryNote =
card.retries !== undefined && card.retries > 0
? `· ${card.retries} retr${card.retries === 1 ? "y" : "ies"}`
: undefined;
? `${card.retries} retr${card.retries === 1 ? "y" : "ies"}`
: null;
const stackLines = card.stack ? card.stack.split("\n") : [];
const stackTrunc = stackLines.length > STACK_TAIL;
const stackVisible = stackTrunc ? stackLines.slice(-STACK_TAIL) : stackLines;
const stackHidden = stackTrunc ? stackLines.length - stackVisible.length : 0;
const hasStack = stackVisible.length > 0;
const messageLines = card.message.split("\n");
return (
<Box flexDirection="column">
<CardHeader tone="error" glyph="✖" title="Error" subtitle={card.title} meta={meta} />
<BarRow tone="error" indent={0} />
{card.message.split("\n").map((line, i) => (
<BarRow key={`${card.id}:msg:${i}`} tone="error">
<Text color={CARD.error.color}>{line}</Text>
</BarRow>
))}
{hasStack && (
<>
<BarRow tone="error" indent={0} />
<BarRow tone="error">
<Text color={FG.meta}>{"stack trace"}</Text>
</BarRow>
{stackHidden > 0 && (
<BarRow tone="error">
<Text color={FG.faint}>
{`⋮ ${stackHidden} earlier stack line${stackHidden === 1 ? "" : "s"} hidden`}
</Text>
</BarRow>
)}
{stackVisible.map((line, i) => (
<BarRow key={`${card.id}:stk:${stackHidden + i}`} tone="error">
<Text color={FG.meta}>{line}</Text>
</BarRow>
))}
</>
)}
<BarRow tone="error" indent={0} />
<BarRow tone="error">
<Text bold color={TONE.err}>
{"[r] retry"}
<Card tone={TONE.err}>
<CardHeader
glyph="✖"
tone={TONE.err}
title={card.title || "error"}
meta={retryNote ? [retryNote] : undefined}
/>
{messageLines.map((line, i) => (
<Text key={`${card.id}:msg:${i}`} color={TONE.err}>
{line || " "}
</Text>
<Text color={FG.sub}>{" [s] skip"}</Text>
</BarRow>
</Box>
))}
{hasStack ? (
<Box flexDirection="column" marginTop={1}>
<Text color={FG.meta}>stack trace</Text>
{stackHidden > 0 ? (
<Text color={FG.faint}>
{`⋮ ${stackHidden} earlier stack line${stackHidden === 1 ? "" : "s"} hidden`}
</Text>
) : null}
{stackVisible.map((line, i) => (
<Text key={`${card.id}:stk:${stackHidden + i}`} color={FG.meta}>
{line || " "}
</Text>
))}
</Box>
) : null}
</Card>
);
}
+3 -4
View File
@@ -31,8 +31,7 @@ export function LiveCard({ card }: { card: LiveCardData }): React.ReactElement {
const color = TONE_TO_COLOR[card.tone];
const glyph = VARIANT_GLYPH[card.variant];
return (
<Box flexDirection="row">
<Text>{" "}</Text>
<Box paddingLeft={2} flexDirection="row" gap={1}>
{card.variant === "thinking" ? (
<Spinner kind="circle" color={color} bold />
) : (
@@ -40,8 +39,8 @@ export function LiveCard({ card }: { card: LiveCardData }): React.ReactElement {
{glyph}
</Text>
)}
<Text color={FG.body}>{` ${card.text}`}</Text>
{card.meta !== undefined && <Text color={FG.faint}>{` ${card.meta}`}</Text>}
<Text color={FG.body}>{card.text}</Text>
{card.meta !== undefined ? <Text color={FG.faint}>{`· ${card.meta}`}</Text> : null}
</Box>
);
}
+16 -26
View File
@@ -1,10 +1,10 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { MemoryCard as MemoryCardData, MemoryEntry } from "../state/cards.js";
import { FG, TONE } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
const CATEGORY_ORDER: ReadonlyArray<MemoryEntry["category"]> = [
"user",
@@ -14,10 +14,10 @@ const CATEGORY_ORDER: ReadonlyArray<MemoryEntry["category"]> = [
];
const CATEGORY_LABEL: Record<MemoryEntry["category"], string> = {
user: "USER",
feedback: "FEEDBACK",
project: "PROJECT",
reference: "REFERENCE",
user: "user",
feedback: "feedback",
project: "project",
reference: "reference",
};
const CATEGORY_GLYPH: Record<MemoryEntry["category"], string> = {
@@ -42,14 +42,13 @@ export function MemoryCard({ card }: { card: MemoryCardData }): React.ReactEleme
const tokens =
card.tokens > 1024 ? `~${(card.tokens / 1024).toFixed(1)}K tok` : `~${card.tokens} tok`;
return (
<Box flexDirection="column">
<Card tone={FG.meta}>
<CardHeader
tone="memory"
glyph="⌑"
title="Context"
subtitle={`· ${summary}`}
meta={tokens}
tone={FG.meta}
title="context"
titleColor={FG.sub}
meta={summary ? [summary, tokens] : [tokens]}
/>
{CATEGORY_ORDER.filter((c) => counts[c] > 0).map((category) => {
const all = card.entries.filter((e) => e.category === category);
@@ -57,27 +56,18 @@ export function MemoryCard({ card }: { card: MemoryCardData }): React.ReactEleme
const remaining = all.length - shown.length;
return (
<Box key={category} flexDirection="column">
<BarRow tone="memory" indent={0} />
<BarRow tone="memory">
<Text color={FG.faint}>
{CATEGORY_LABEL[category]} ({counts[category]})
</Text>
</BarRow>
<Text color={FG.faint}>{`${CATEGORY_LABEL[category]} (${counts[category]})`}</Text>
{shown.map((entry) => (
<BarRow key={`${category}:${entry.summary}`} tone="memory">
<Text color={CATEGORY_GLYPH_COLOR[category]}>{CATEGORY_GLYPH[category]} </Text>
<Box key={`${category}:${entry.summary}`} flexDirection="row" gap={1}>
<Text color={CATEGORY_GLYPH_COLOR[category]}>{CATEGORY_GLYPH[category]}</Text>
<Text color={FG.sub}>{entry.summary}</Text>
</BarRow>
</Box>
))}
{remaining > 0 && (
<BarRow tone="memory">
<Text color={FG.faint}>{`⋮ +${remaining} more`}</Text>
</BarRow>
)}
{remaining > 0 ? <Text color={FG.faint}>{`⋮ +${remaining} more`}</Text> : null}
</Box>
);
})}
</Box>
</Card>
);
}
+71 -28
View File
@@ -1,13 +1,13 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { PlanCard as PlanCardData, PlanStep } from "../state/cards.js";
import { FG, TONE } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
import { FG, TONE, TONE_ACTIVE } from "../theme/tokens.js";
const STATUS_GLYPH: Record<PlanStep["status"], string> = {
queued: " ",
queued: "○",
running: "▶",
done: "✓",
failed: "✗",
@@ -17,47 +17,90 @@ const STATUS_GLYPH: Record<PlanStep["status"], string> = {
const STATUS_COLOR: Record<PlanStep["status"], string> = {
queued: FG.faint,
running: TONE.brand,
running: TONE_ACTIVE.brand,
done: TONE.ok,
failed: TONE.err,
blocked: TONE.warn,
skipped: FG.faint,
};
const ACTIVE_PLAN_FOOTER = "[r] revise [s] skip step [↵] expand item";
const VISIBLE_WINDOW = 5;
export function PlanCard({ card }: { card: PlanCardData }): React.ReactElement {
const doneCount = card.steps.filter((s) => s.status === "done").length;
const variantTag =
card.variant === "resumed" ? " · resumed" : card.variant === "replay" ? " · ⏪ archive" : "";
const meta = `${variantTag} · ${doneCount} of ${card.steps.length} done`;
const showFooter = card.variant === "active";
card.variant === "resumed" ? "resumed · " : card.variant === "replay" ? "⏪ archive · " : "";
const progress = `${variantTag}${doneCount}/${card.steps.length} done`;
const hasRunning = card.steps.some((s) => s.status === "running");
const tone = hasRunning ? TONE_ACTIVE.accent : TONE.accent;
const window = pickWindow(card.steps);
return (
<Box flexDirection="column">
<CardHeader tone="plan" glyph="⊞" title={card.title} meta={meta} />
<BarRow tone="plan" indent={0} />
{card.steps.map((step, i) => {
<Card tone={tone}>
<CardHeader glyph="⊞" tone={tone} title={card.title} meta={[progress]} />
{window.hiddenBefore > 0 ? (
<Box flexDirection="row" gap={1}>
<Text color={TONE.ok}>✓</Text>
<Text color={FG.faint}>{`⋯ ${window.hiddenBefore} done`}</Text>
</Box>
) : null}
{window.steps.map((step) => {
const isActive = step.status === "running";
const titleColor = isActive ? FG.strong : step.status === "queued" ? FG.sub : FG.sub;
const titleColor = isActive ? FG.strong : FG.sub;
return (
<BarRow key={step.id} tone="plan">
<Text color={STATUS_COLOR[step.status]}>{`[${STATUS_GLYPH[step.status]}]`}</Text>
<Box key={step.id} flexDirection="row" gap={1}>
<Text color={STATUS_COLOR[step.status]}>{STATUS_GLYPH[step.status]}</Text>
<Text bold={isActive} color={titleColor}>
{` ${i + 1}. ${step.title}`}
{`${step.indexLabel}. ${step.title}`}
</Text>
{isActive && <Text color={TONE.brand}>{" ← in progress"}</Text>}
</BarRow>
{isActive ? <Text color={TONE_ACTIVE.brand}>← in progress</Text> : null}
</Box>
);
})}
{showFooter && (
<>
<BarRow tone="plan" indent={0} />
<BarRow tone="plan">
<Text color={FG.meta}>{ACTIVE_PLAN_FOOTER}</Text>
</BarRow>
</>
)}
</Box>
{window.hiddenAfter > 0 ? (
<Box flexDirection="row" gap={1}>
<Text color={FG.faint}>○</Text>
<Text color={FG.faint}>{`⋯ ${window.hiddenAfter} upcoming`}</Text>
</Box>
) : null}
</Card>
);
}
interface WindowedStep extends PlanStep {
indexLabel: number;
}
interface StepWindow {
steps: WindowedStep[];
hiddenBefore: number;
hiddenAfter: number;
}
/** Fixed window keeps the live strip's height constant — variable-height plan cards in the live region cause Yoga to thrash on every step transition. */
function pickWindow(steps: ReadonlyArray<PlanStep>): StepWindow {
if (steps.length <= VISIBLE_WINDOW) {
return {
steps: steps.map((s, i) => ({ ...s, indexLabel: i + 1 })),
hiddenBefore: 0,
hiddenAfter: 0,
};
}
const anchor = anchorIndex(steps);
const start = Math.max(0, Math.min(anchor, steps.length - VISIBLE_WINDOW));
const end = start + VISIBLE_WINDOW;
return {
steps: steps.slice(start, end).map((s, i) => ({ ...s, indexLabel: start + i + 1 })),
hiddenBefore: start,
hiddenAfter: Math.max(0, steps.length - end),
};
}
function anchorIndex(steps: ReadonlyArray<PlanStep>): number {
const runningIdx = steps.findIndex((s) => s.status === "running");
if (runningIdx >= 0) return runningIdx;
const firstPending = steps.findIndex((s) => s.status === "queued" || s.status === "blocked");
if (firstPending >= 0) return firstPending;
return Math.max(0, steps.length - VISIBLE_WINDOW);
}
+143 -48
View File
@@ -1,16 +1,19 @@
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { clipToCells } from "../../../frame/width.js";
import { BarRow, CursorBlock } from "../primitives/BarRow.js";
import { clipToCells, wrapToCells } from "../../../frame/width.js";
import { Card } from "../primitives/Card.js";
import { CardHeader, type MetaItem } from "../primitives/CardHeader.js";
import { CursorBlock } from "../primitives/CursorBlock.js";
import { PILL_MODEL, PILL_SECTION, Pill, modelBadgeFor } from "../primitives/Pill.js";
import { Spinner } from "../primitives/Spinner.js";
import type { ReasoningCard as ReasoningCardData } from "../state/cards.js";
import { FG } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
import { FG, TONE, TONE_ACTIVE } from "../theme/tokens.js";
/** Fixed tail for streaming — prevents the live region from growing past the terminal and forcing the OS to scroll on every byte. Full content lands in scrollback when streaming completes. */
const STREAMING_TAIL = 6;
const DONE_PREVIEW_TAIL = 3;
const BODY_INDENT_CELLS = 5;
/** Streaming preview tail length — wide enough to feel responsive, small enough not to thrash on every chunk. Full body lives in the events log. */
const STREAMING_PREVIEW_LINES = 4;
/** Once settled, only the conclusion is actionable; the rest is in `/reasoning last`. */
const SETTLED_TAIL_LINES = 2;
export function ReasoningCard({
card,
@@ -21,49 +24,141 @@ export function ReasoningCard({
}): React.ReactElement {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const lineCells = Math.max(20, cols - BODY_INDENT_CELLS - 1);
const meta = card.aborted
? "aborted"
: card.streaming
? "streaming…"
: `${card.paragraphs} paragraph${card.paragraphs === 1 ? "" : "s"} · ${card.tokens} tok`;
const lineCells = Math.max(20, cols - 4);
const allLines = card.text.length > 0 ? card.text.split("\n") : [];
const tailSize = card.streaming ? STREAMING_TAIL : DONE_PREVIEW_TAIL;
const overflows = allLines.length > tailSize;
const lineSlots = overflows ? tailSize - 1 : allLines.length;
const visible = overflows ? allLines.slice(-lineSlots) : allLines;
const headDropped = overflows ? allLines.length - visible.length : 0;
const showBody = expanded && allLines.length > 0;
const showBody = expanded && (allLines.length > 0 || card.streaming);
const tone = card.aborted ? TONE.err : card.streaming ? TONE_ACTIVE.accent : TONE.accent;
return (
<Box flexDirection="column">
<CardHeader tone="reasoning" glyph="◆" title="Reasoning" meta={`· ${meta}`} />
{showBody && (
<>
<BarRow tone="reasoning" indent={0} />
{headDropped > 0 && (
<BarRow tone="reasoning">
<Text color={FG.faint}>
{card.streaming
? `… ${headDropped} earlier line${headDropped === 1 ? "" : "s"} (will appear in scrollback)`
: `⋮ ${headDropped} earlier line${headDropped === 1 ? "" : "s"}`}
</Text>
</BarRow>
)}
{visible.map((line, i) => {
const isLast = i === visible.length - 1;
return (
<BarRow key={`${card.id}:${headDropped + i}`} tone="reasoning">
<Text italic color={FG.meta}>
{clipToCells(line, lineCells)}
</Text>
{isLast && card.streaming && <CursorBlock />}
</BarRow>
);
})}
</>
)}
</Box>
<Card tone={tone}>
<ReasoningHeader card={card} />
{showBody &&
(card.streaming ? (
<StreamingPreview card={card} allLines={allLines} lineCells={lineCells} />
) : (
<SettledPreview card={card} allLines={allLines} lineCells={lineCells} />
))}
</Card>
);
}
function ReasoningHeader({ card }: { card: ReasoningCardData }): React.ReactElement {
const streamingActive = card.streaming && !card.aborted;
const headColor = card.aborted ? TONE.err : streamingActive ? TONE_ACTIVE.accent : TONE.accent;
const glyph = streamingActive ? "◇" : "◆";
const title = streamingActive ? "reasoning…" : card.aborted ? "reasoning (aborted)" : "reasoning";
const meta: MetaItem[] = [];
const m = headerMeta(card);
if (m) meta.push(m);
const duration = headerDuration(card);
if (duration) meta.push(duration);
const modelBadge = card.model ? modelBadgeFor(card.model) : null;
return (
<CardHeader
glyph={glyph}
tone={headColor}
title={title}
titleColor={PILL_SECTION.reason.fg}
titleBg={PILL_SECTION.reason.bg}
meta={meta.length > 0 ? meta : undefined}
right={
<>
{streamingActive ? <Spinner kind="braille" color={TONE_ACTIVE.accent} /> : null}
{modelBadge ? (
<Pill label={modelBadge.label} {...PILL_MODEL[modelBadge.kind]} bold={false} />
) : null}
</>
}
/>
);
}
function headerMeta(card: ReasoningCardData): string {
if (card.streaming) {
return card.tokens > 0 ? `${card.tokens.toLocaleString()} tok` : "";
}
const parts: string[] = [];
if (card.tokens > 0) parts.push(`${card.tokens.toLocaleString()} tok`);
if (card.paragraphs > 0) parts.push(`${card.paragraphs}`);
return parts.join(" · ");
}
function headerDuration(card: ReasoningCardData): string {
if (card.streaming || !card.endedAt) return "";
const seconds = Math.max(0, (card.endedAt - card.ts) / 1000);
return `${seconds.toFixed(1)}s`;
}
interface BodyProps {
card: ReasoningCardData;
allLines: string[];
lineCells: number;
}
function StreamingPreview({ card, allLines, lineCells }: BodyProps): React.ReactElement {
const visualLines = allLines.flatMap((l) => wrapToCells(l, lineCells));
const visible = visualLines.slice(-STREAMING_PREVIEW_LINES);
return <BodyLines card={card} lines={visible} lineCells={lineCells} cursorOnLast />;
}
function SettledPreview({ card, allLines, lineCells }: BodyProps): React.ReactElement {
const visualLines = allLines.flatMap((l) => wrapToCells(l, lineCells));
const visible = visualLines.slice(-SETTLED_TAIL_LINES);
const droppedLines = Math.max(0, visualLines.length - visible.length);
return (
<>
{droppedLines > 0 ? <ElisionHint droppedLines={droppedLines} card={card} /> : null}
<BodyLines card={card} lines={visible} lineCells={lineCells} indexOffset={droppedLines} />
</>
);
}
interface BodyLinesProps {
card: ReasoningCardData;
lines: string[];
lineCells: number;
cursorOnLast?: boolean;
indexOffset?: number;
}
function BodyLines({
card,
lines,
lineCells,
cursorOnLast = false,
indexOffset = 0,
}: BodyLinesProps): React.ReactElement {
return (
<>
{lines.map((line, i) => {
const isLast = i === lines.length - 1;
return (
<Box key={`${card.id}:b:${indexOffset + i}`} flexDirection="row">
<Text italic color={FG.meta}>
{clipToCells(line, lineCells)}
</Text>
{isLast && cursorOnLast && <CursorBlock />}
</Box>
);
})}
</>
);
}
function ElisionHint({
droppedLines,
card,
}: {
droppedLines: number;
card: ReasoningCardData;
}): React.ReactElement {
const parts: string[] = [];
if (card.paragraphs > 1) {
parts.push(`${card.paragraphs}`);
} else {
parts.push(`${droppedLines} line${droppedLines === 1 ? "" : "s"}`);
}
if (card.tokens > 0) parts.push(`${card.tokens.toLocaleString()} tok`);
return <Text color={FG.faint}>{`⋯ ${parts.join(" · ")} above · /reasoning last`}</Text>;
}
+31 -31
View File
@@ -1,46 +1,46 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { SearchCard as SearchCardData, SearchHit } from "../state/cards.js";
import { FG } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
import { FG, TONE } from "../theme/tokens.js";
export function SearchCard({ card }: { card: SearchCardData }): React.ReactElement {
const fileCount = new Set(card.hits.map((h) => h.file)).size;
const meta = `${card.hits.length} hit${card.hits.length === 1 ? "" : "s"} in ${fileCount} file${
const elapsed = `${(card.elapsedMs / 1000).toFixed(2)}s`;
const stats = `${card.hits.length} hit${card.hits.length === 1 ? "" : "s"} · ${fileCount} file${
fileCount === 1 ? "" : "s"
} · ${(card.elapsedMs / 1000).toFixed(2)}s`;
}`;
const grouped = groupByFile(card.hits.slice(0, 10));
return (
<Box flexDirection="column">
<CardHeader tone="search" glyph="⊙" title="Search" subtitle={`"${card.query}"`} meta={meta} />
{card.hits.length > 0 && (
<>
<BarRow tone="search" indent={0} />
{groupByFile(card.hits.slice(0, 10)).map(([file, hits]) => (
<Box key={file} flexDirection="column">
<BarRow tone="search">
<Text bold color={FG.strong}>
{file}
</Text>
</BarRow>
{hits.map((h, i) => (
<BarRow key={`${file}:${h.line}:${i}`} tone="search">
<Text color={FG.faint}>{`${h.line.toString().padStart(4)} │ `}</Text>
<HighlightedLine text={h.preview} start={h.matchStart} end={h.matchEnd} />
</BarRow>
))}
<Card tone={TONE.info}>
<CardHeader
glyph="⊙"
tone={TONE.info}
title="search"
subtitle={`"${card.query}"`}
meta={[stats, elapsed]}
/>
{grouped.map(([file, hits]) => (
<Box key={file} flexDirection="column">
<Text bold color={FG.strong}>
{file}
</Text>
{hits.map((h, i) => (
<Box key={`${file}:${h.line}:${i}`} flexDirection="row" gap={1}>
<Text color={FG.faint}>{`${h.line.toString().padStart(4)} │`}</Text>
<HighlightedLine text={h.preview} start={h.matchStart} end={h.matchEnd} />
</Box>
))}
{card.hits.length > 10 && (
<BarRow tone="search">
<Text color={FG.faint}>{`⋮ +${card.hits.length - 10} more hits`}</Text>
</BarRow>
)}
</>
)}
</Box>
</Box>
))}
{card.hits.length > 10 ? (
<Text color={FG.faint}>{`⋮ +${card.hits.length - 10} more hits`}</Text>
) : null}
</Card>
);
}
+50 -55
View File
@@ -1,74 +1,69 @@
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { clipToCells } from "../../../frame/width.js";
import { clipToCells, wrapToCells } from "../../../frame/width.js";
import { useReserveRows } from "../layout/viewport-budget.js";
import { Markdown } from "../markdown.js";
import { BarRow, CursorBlock } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import { PILL_MODEL, Pill, modelBadgeFor } from "../primitives/Pill.js";
import { Spinner } from "../primitives/Spinner.js";
import type { StreamingCard as StreamingCardData } from "../state/cards.js";
import { FG, TONE } from "../theme/tokens.js";
import { FG, TONE, TONE_ACTIVE } from "../theme/tokens.js";
const RESERVED_CHROME_ROWS = 14;
const BODY_INDENT_CELLS = 5;
/** Streaming preview tail length — bounded live region so chunks don't thrash whole-card layout. */
const STREAMING_PREVIEW_LINES = 4;
export function StreamingCard({ card }: { card: StreamingCardData }): React.ReactElement {
// Done cards render via Markdown in <Static>; live frame stays plain
// text since markdown on partial streamed chunks would jitter.
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
useReserveRows("stream", {
min: STREAMING_PREVIEW_LINES + 1,
max: STREAMING_PREVIEW_LINES + 2,
});
const modelBadge = card.model ? modelBadgeFor(card.model) : null;
const modelPill = modelBadge ? (
<Pill label={modelBadge.label} {...PILL_MODEL[modelBadge.kind]} bold={false} />
) : null;
if (card.done && !card.aborted) {
return (
<Box flexDirection="column" paddingLeft={3}>
<Card tone={TONE.ok}>
<CardHeader glyph="‹" tone={TONE.ok} title="reply" right={modelPill} />
<Markdown text={card.text} />
</Box>
</Card>
);
}
const { stdout } = useStdout();
const rows = stdout?.rows ?? 40;
const cols = stdout?.columns ?? 80;
const lineCells = Math.max(20, cols - BODY_INDENT_CELLS - 1);
const lineCells = Math.max(20, cols - 4);
const allLines = card.text.length > 0 ? card.text.split("\n") : [""];
const budget = Math.max(8, rows - RESERVED_CHROME_ROWS);
const reserved = (card.aborted ? 2 : 0) + 1;
const lineSlots = Math.max(4, budget - reserved);
const overflows = !card.done && allLines.length > lineSlots;
const visible = overflows ? allLines.slice(-lineSlots) : allLines;
const headDropped = overflows ? allLines.length - visible.length : 0;
const visualLines = allLines.flatMap((l) => wrapToCells(l, lineCells));
const visible = visualLines.slice(-STREAMING_PREVIEW_LINES);
const aborted = !!card.aborted;
const headColor = aborted ? TONE.err : TONE_ACTIVE.brand;
const glyph = aborted ? "‹" : "◈";
const headLabel = aborted ? "aborted" : "writing…";
return (
<Box flexDirection="column">
{card.aborted && (
<BarRow tone="streaming" glyph="—">
<Text color={FG.faint} bold>
— aborted —
</Text>
<Text color={TONE.warn}>{" stopped"}</Text>
</BarRow>
)}
{headDropped > 0 && (
<BarRow tone="streaming" glyph="▾">
<Text
color={FG.faint}
>{`… ${headDropped} earlier line${headDropped === 1 ? "" : "s"} (will appear in scrollback)`}</Text>
</BarRow>
)}
{visible.map((line, i) => {
const isLast = i === visible.length - 1;
const isFirstRendered = !card.aborted && headDropped === 0 && i === 0;
return (
<BarRow
key={`${card.id}:${headDropped + i}`}
tone="streaming"
glyph={isFirstRendered ? "▶" : undefined}
>
<Text color={card.aborted ? FG.meta : FG.body}>{clipToCells(line, lineCells)}</Text>
{isLast && !card.done && <CursorBlock />}
</BarRow>
);
})}
{card.aborted && (
<BarRow tone="streaming">
<Text color={FG.faint}>{"[truncated by esc]"}</Text>
</BarRow>
)}
</Box>
<Card tone={headColor}>
<CardHeader
glyph={glyph}
tone={headColor}
title={headLabel}
right={
<>
{aborted ? null : <Spinner kind="braille" color={TONE_ACTIVE.brand} />}
{modelPill}
</>
}
/>
{visible.map((line, i) => (
<Box key={`${card.id}:${allLines.length - visible.length + i}`} flexDirection="row">
<Text color={aborted ? FG.meta : FG.body}>{clipToCells(line, lineCells)}</Text>
</Box>
))}
{aborted ? <Text color={FG.faint}>[truncated by esc]</Text> : null}
</Card>
);
}
+121 -78
View File
@@ -1,102 +1,145 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import React, { useContext } from "react";
import { ActiveCardContext, Card as CardWrap } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import { Spinner } from "../primitives/Spinner.js";
import type { Card, SubAgentCard as SubAgentCardData } from "../state/cards.js";
import { CARD, FG, TONE } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
import { CARD, FG, TONE, TONE_ACTIVE } from "../theme/tokens.js";
const STATUS_COLOR: Record<SubAgentCardData["status"], string> = {
running: TONE.violet,
running: TONE_ACTIVE.violet,
done: TONE.ok,
failed: TONE.err,
};
export function SubAgentCard({ card }: { card: SubAgentCardData }): React.ReactElement {
const headColor = STATUS_COLOR[card.status];
const headGlyph = card.status === "failed" ? "✖" : "⌬";
const runningChildren = card.children.filter((c) => !isChildDone(c)).length;
const isRunning = card.status === "running";
const inLive = useContext(ActiveCardContext);
const headerMeta = isRunning
? runningChildren > 0
? [`${runningChildren} running`]
: ["working"]
: [{ text: card.status, color: headColor }];
return (
<Box flexDirection="column">
<CardWrap tone={headColor}>
<CardHeader
tone="subagent"
glyph="⌬"
title={`Sub-agent · ${card.name}`}
trailing={<Text color={STATUS_COLOR[card.status]}>{card.status}</Text>}
glyph={headGlyph}
tone={headColor}
title="subagent"
titleColor={TONE.violet}
subtitle={card.task}
meta={headerMeta}
/>
<BarRow tone="subagent" indent={0} />
<BarRow tone="subagent">
<Text color={FG.faint}>{"Task "}</Text>
<Text color={FG.sub}>{card.task}</Text>
</BarRow>
{card.name ? <Text color={FG.faint}>{`agent · ${card.name}`}</Text> : null}
{card.tools && card.tools.length > 0 && (
<BarRow tone="subagent">
<Text color={FG.faint}>{"Tools "}</Text>
<Text color={FG.sub}>{card.tools.join(", ")}</Text>
</BarRow>
<Text color={FG.faint}>{`tools · ${card.tools.join(", ")}`}</Text>
)}
{card.children.length > 0 && (
<>
<BarRow tone="subagent" indent={0} />
<BarRow tone="subagent">
<Text color={FG.meta}>{"sub-agent stream"}</Text>
</BarRow>
{card.children.map((child) => (
<BarRow key={child.id} tone="subagent">
<Text color={CARD.subagent.color}>{"▎ "}</Text>
<ChildSummary card={child} />
</BarRow>
))}
</>
)}
</Box>
{card.children.map((child) => (
<Box key={child.id} flexDirection="row" gap={1}>
{inLive ? null : <Text color={TONE.violet}>▎</Text>}
<ChildRow card={child} />
</Box>
))}
</CardWrap>
);
}
function ChildSummary({ card }: { card: Card }): React.ReactElement {
function isChildDone(card: Card): boolean {
switch (card.kind) {
case "reasoning":
return (
<>
<Text color={CARD.reasoning.color}>{"◆ "}</Text>
<Text italic color={FG.meta}>
{`Reasoning · ${card.paragraphs} paragraph${card.paragraphs === 1 ? "" : "s"}`}
</Text>
</>
);
case "tool":
return (
<>
<Text color={CARD.tool.color}>{"▣ "}</Text>
<Text bold color={FG.body}>
{card.name}
</Text>
{card.elapsedMs > 0 && (
<Text color={FG.faint}>{` ${(card.elapsedMs / 1000).toFixed(2)}s`}</Text>
)}
</>
);
case "streaming":
return (
<>
<Text color={CARD.streaming.color}>{"▶ "}</Text>
<Text color={card.done ? FG.sub : TONE.brand}>
{card.done ? "response" : "streaming response …"}
</Text>
</>
);
case "diff":
return (
<>
<Text color={CARD.diff.color}>{"± "}</Text>
<Text color={FG.sub}>{card.file}</Text>
</>
);
case "error":
return (
<>
<Text color={CARD.error.color}>{"✖ "}</Text>
<Text color={FG.sub}>{card.title}</Text>
</>
);
return card.done;
case "reasoning":
return !card.streaming;
default:
return <Text color={FG.faint}>{`· ${card.kind}`}</Text>;
return true;
}
}
interface ChildVisual {
statusGlyph: React.ReactElement;
kindGlyph: string;
kindColor: string;
text: string;
}
function ChildRow({ card }: { card: Card }): React.ReactElement {
const v = childVisual(card);
const isDone = isChildDone(card);
return (
<>
{v.statusGlyph}
<Text color={v.kindColor}>{v.kindGlyph}</Text>
<Text dimColor={isDone} color={FG.body}>
{v.text}
</Text>
</>
);
}
function runningGlyph(color: string): React.ReactElement {
return <Spinner kind="circle" color={color} />;
}
function doneGlyph(color: string): React.ReactElement {
return <Text color={color}>✓</Text>;
}
function failedGlyph(): React.ReactElement {
return <Text color={TONE.err}>✖</Text>;
}
function childVisual(card: Card): ChildVisual {
switch (card.kind) {
case "reasoning": {
const done = !card.streaming;
return {
statusGlyph: done ? doneGlyph(TONE.ok) : runningGlyph(CARD.reasoning.color),
kindGlyph: "◆",
kindColor: CARD.reasoning.color,
text: `reasoning · ${card.paragraphs}`,
};
}
case "tool": {
const elapsed = card.elapsedMs > 0 ? ` · ${(card.elapsedMs / 1000).toFixed(2)}s` : "";
return {
statusGlyph: card.done ? doneGlyph(TONE.ok) : runningGlyph(CARD.tool.color),
kindGlyph: "▣",
kindColor: CARD.tool.color,
text: `${card.name}${elapsed}`,
};
}
case "streaming":
return {
statusGlyph: card.done ? doneGlyph(TONE.ok) : runningGlyph(CARD.streaming.color),
kindGlyph: "◈",
kindColor: CARD.streaming.color,
text: card.done ? "response" : "writing …",
};
case "diff":
return {
statusGlyph: doneGlyph(TONE.ok),
kindGlyph: "±",
kindColor: CARD.diff.color,
text: card.file,
};
case "error":
return {
statusGlyph: failedGlyph(),
kindGlyph: "✖",
kindColor: CARD.error.color,
text: card.title,
};
default:
return {
statusGlyph: <Text color={FG.faint}>·</Text>,
kindGlyph: "·",
kindColor: FG.faint,
text: card.kind,
};
}
}
+24 -29
View File
@@ -1,10 +1,10 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { TaskCard as TaskCardData, TaskStep } from "../state/cards.js";
import { CARD, FG, TONE } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
import { FG, TONE } from "../theme/tokens.js";
const STEP_GLYPH: Record<TaskStep["status"], string> = {
queued: "○",
@@ -15,13 +15,13 @@ const STEP_GLYPH: Record<TaskStep["status"], string> = {
const STEP_COLOR: Record<TaskStep["status"], string> = {
queued: FG.faint,
running: TONE.brand,
running: TONE.warn,
done: TONE.ok,
failed: TONE.err,
};
const TASK_COLOR: Record<TaskCardData["status"], string> = {
running: CARD.task.color,
running: TONE.warn,
done: TONE.ok,
failed: TONE.err,
};
@@ -34,33 +34,28 @@ const TASK_GLYPH: Record<TaskCardData["status"], string> = {
export function TaskCard({ card }: { card: TaskCardData }): React.ReactElement {
const elapsed = `${(card.elapsedMs / 1000).toFixed(1)}s`;
const showSteps = card.steps.length > 0;
return (
<Box flexDirection="column">
<Card tone={TASK_COLOR[card.status]}>
<CardHeader
tone="task"
glyph={TASK_GLYPH[card.status]}
title={`Step ${card.index} of ${card.total} · ${card.title}`}
meta={`${elapsed} · `}
trailing={<Text color={TASK_COLOR[card.status]}>{card.status}</Text>}
barColor={TASK_COLOR[card.status]}
tone={TASK_COLOR[card.status]}
title={`step ${card.index}/${card.total}`}
subtitle={card.title}
meta={[elapsed, card.status]}
/>
{showSteps && (
<>
<BarRow tone="task" indent={0} />
{card.steps.map((step) => (
<BarRow key={step.id} tone="task">
<Text color={STEP_COLOR[step.status]}>{STEP_GLYPH[step.status]}</Text>
<Text bold color={FG.body}>{` ${(step.toolName ?? "step").padEnd(7)} `}</Text>
<Text color={FG.sub}>{step.title}</Text>
{step.detail && <Text color={FG.faint}>{` ${step.detail}`}</Text>}
{step.elapsedMs !== undefined && (
<Text color={FG.faint}>{` ${(step.elapsedMs / 1000).toFixed(2)}s`}</Text>
)}
</BarRow>
))}
</>
)}
</Box>
{card.steps.map((step) => (
<Box key={step.id} flexDirection="row" gap={1}>
<Text color={STEP_COLOR[step.status]}>{STEP_GLYPH[step.status]}</Text>
<Text bold color={FG.body}>
{(step.toolName ?? "step").padEnd(7)}
</Text>
<Text color={FG.sub}>{step.title}</Text>
{step.detail ? <Text color={FG.faint}>{step.detail}</Text> : null}
{step.elapsedMs !== undefined ? (
<Text color={FG.faint}>{`${(step.elapsedMs / 1000).toFixed(2)}s`}</Text>
) : null}
</Box>
))}
</Card>
);
}
+112 -39
View File
@@ -2,15 +2,14 @@ import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { clipToCells } from "../../../frame/width.js";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader, type MetaItem } from "../primitives/CardHeader.js";
import { Spinner } from "../primitives/Spinner.js";
import type { ToolCard as ToolCardData } from "../state/cards.js";
import { CARD, FG, TONE } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
import { FG, TONE, TONE_ACTIVE } from "../theme/tokens.js";
const READ_TAIL = 2;
const OTHER_TAIL = 5;
const BODY_INDENT_CELLS = 5;
/** Read-style tools dump file/list bodies — short tail is enough; the model already has the full text in context. */
function tailLinesFor(name: string): number {
@@ -24,53 +23,120 @@ function tailLinesFor(name: string): number {
export function ToolCard({ card }: { card: ToolCardData }): React.ReactElement {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const lineCells = Math.max(20, cols - BODY_INDENT_CELLS - 1);
const lineCells = Math.max(20, cols - 4);
const argsLabel = formatArgsSummary(card.args);
const meta = formatMeta(card);
const allLines = card.output.length > 0 ? card.output.split("\n") : [];
const tail = tailLinesFor(card.name);
const truncated = allLines.length > tail;
const visible = truncated ? allLines.slice(-tail) : allLines;
const hidden = truncated ? allLines.length - visible.length : 0;
const errColor = card.exitCode && card.exitCode !== 0 ? CARD.error.color : FG.sub;
const showBody = visible.length > 0;
const status = toolStatus(card);
const headColor = headerColorFor(status);
const errColor = card.exitCode && card.exitCode !== 0 ? TONE.err : FG.sub;
// Rejected calls show a single trailing badge — the verbose JSON error body
// is already conveyed by the badge, so dropping the body keeps the card tight.
const showBody = !card.rejected && visible.length > 0;
const meta: MetaItem[] = [];
if (card.retry) {
meta.push({ text: `↻ ${card.retry.attempt}/${card.retry.max}`, color: TONE.warn });
}
if (card.rejected) {
meta.push({ text: "rejected", color: TONE.err });
}
for (const part of metaTrail(card)) meta.push(part);
return (
<Box flexDirection="column">
<Card tone={headColor}>
<CardHeader
tone="tool"
glyph="▣"
glyph={statusGlyph(status)}
tone={headColor}
title={card.name}
subtitle={argsLabel || undefined}
meta={meta || undefined}
inline={!card.done ? <Spinner kind="braille" color={CARD.tool.color} bold /> : undefined}
trailing={
card.retry ? (
<Text color={TONE.warn} bold>{`↻ retry ${card.retry.attempt}/${card.retry.max}`}</Text>
meta={meta.length > 0 ? meta : undefined}
right={
status === "running" ? (
<Spinner kind="braille" color={TONE_ACTIVE.brand} bold />
) : undefined
}
/>
{showBody && (
<>
<BarRow tone="tool" indent={0} />
{hidden > 0 && (
<BarRow tone="tool">
<Text color={FG.faint}>
{`⋮ ${hidden} earlier line${hidden === 1 ? "" : "s"} (use /tool to read full)`}
</Text>
</BarRow>
)}
{hidden > 0 ? (
<Text color={FG.faint}>
{`⋮ ${hidden} earlier line${hidden === 1 ? "" : "s"} (use /tool to read full)`}
</Text>
) : null}
{visible.map((line, i) => (
<BarRow key={`${card.id}:${hidden + i}`} tone="tool">
<Text color={errColor}>{clipToCells(line, lineCells)}</Text>
</BarRow>
<Text
key={`${card.id}:${hidden + i}`}
color={errColor}
dimColor={!card.exitCode || card.exitCode === 0}
>
{clipToCells(line, lineCells) || " "}
</Text>
))}
</>
)}
</Box>
</Card>
);
}
type ToolStatus = "running" | "ok" | "rejected" | "error" | "aborted";
function toolStatus(card: ToolCardData): ToolStatus {
if (card.rejected) return "rejected";
if (card.aborted) return "aborted";
if (!card.done) return "running";
if (card.exitCode !== undefined && card.exitCode !== 0) return "error";
return "ok";
}
function statusGlyph(s: ToolStatus): string {
switch (s) {
case "running":
return "▢";
case "ok":
return "✓";
case "rejected":
return "✗";
case "error":
return "✖";
case "aborted":
return "⊘";
}
}
function headerColorFor(s: ToolStatus): string {
switch (s) {
case "ok":
return TONE.ok;
case "rejected":
case "error":
case "aborted":
return TONE.err;
case "running":
return TONE_ACTIVE.brand;
}
}
function metaTrail(card: ToolCardData): string[] {
const parts: string[] = [];
const inputBytes = largestStringInputBytes(card.args);
if (inputBytes !== null) parts.push(`${formatBytes(inputBytes)} in`);
if (card.elapsedMs > 0) parts.push(`${(card.elapsedMs / 1000).toFixed(2)}s`);
if (
card.done &&
!card.rejected &&
!card.aborted &&
card.exitCode !== undefined &&
card.exitCode !== 0
) {
parts.push(`exit ${card.exitCode}`);
}
return parts;
}
function formatArgsSummary(args: unknown): string {
if (typeof args === "string") return args.length > 60 ? `${args.slice(0, 60)}…` : args;
if (args && typeof args === "object") {
@@ -87,16 +153,23 @@ function formatArgsSummary(args: unknown): string {
return "";
}
function formatMeta(card: ToolCardData): string {
const parts: string[] = [];
if (card.elapsedMs > 0) parts.push(`${(card.elapsedMs / 1000).toFixed(2)}s`);
if (card.aborted) {
parts.push("aborted");
} else if (card.done) {
if (card.exitCode === 0) parts.push("exit 0");
else if (card.exitCode !== undefined) parts.push(`exit ${card.exitCode}`);
} else {
parts.push("running");
const INPUT_SIZE_THRESHOLD = 1024;
/** Largest string field on args, when above threshold. Surfaces input bulk for write_file (content), edit_file (replace), run_command (long stdin), etc. without per-tool special cases. */
export function largestStringInputBytes(args: unknown): number | null {
let max = 0;
if (typeof args === "string") {
max = args.length;
} else if (args && typeof args === "object") {
for (const v of Object.values(args as Record<string, unknown>)) {
if (typeof v === "string" && v.length > max) max = v.length;
}
}
return parts.length > 0 ? `· ${parts.join(" · ")}` : "";
return max >= INPUT_SIZE_THRESHOLD ? max : null;
}
function formatBytes(n: number): string {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
}
+48 -48
View File
@@ -1,10 +1,10 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { UsageCard as UsageCardData } from "../state/cards.js";
import { FG, TONE, formatCNY } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
const BAR_CELLS = 30;
@@ -31,68 +31,68 @@ export function UsageCard({ card }: { card: UsageCardData }): React.ReactElement
const promptRatio = card.tokens.prompt / cap;
const reasonRatio = card.tokens.reason / cap;
const outputRatio = card.tokens.output / cap;
const elapsed = card.elapsedMs !== undefined ? ` · ${(card.elapsedMs / 1000).toFixed(1)}s` : "";
const meta = `${formatCNY(card.cost)}${elapsed}`;
const headerMeta: string[] = [`turn ${card.turn}`, formatCNY(card.cost)];
if (card.elapsedMs !== undefined) headerMeta.push(`${(card.elapsedMs / 1000).toFixed(1)}s`);
return (
<Box flexDirection="column">
<CardHeader tone="usage" glyph="Σ" title="Usage" subtitle={`turn ${card.turn}`} meta={meta} />
<BarRow tone="usage" indent={0} />
<BarRow tone="usage">
<Text color={FG.sub}>{"prompt "}</Text>
<Card tone={FG.meta}>
<CardHeader glyph="Σ" tone={FG.meta} title="usage" meta={headerMeta} />
<Box flexDirection="row" gap={1}>
<Text color={FG.sub}>prompt</Text>
{bar(promptRatio, TONE.brand)}
<Text bold color={FG.body}>{` ${card.tokens.prompt.toLocaleString()}`}</Text>
<Text color={FG.faint}>{` / 1M · ${(promptRatio * 100).toFixed(1)}%`}</Text>
</BarRow>
<BarRow tone="usage">
<Text color={FG.sub}>{"reason "}</Text>
<Text bold color={FG.body}>
{card.tokens.prompt.toLocaleString()}
</Text>
<Text color={FG.faint}>{`/ 1M · ${(promptRatio * 100).toFixed(1)}%`}</Text>
</Box>
<Box flexDirection="row" gap={1}>
<Text color={FG.sub}>reason</Text>
{bar(reasonRatio, TONE.accent)}
<Text bold color={FG.body}>{` ${card.tokens.reason.toLocaleString()}`}</Text>
</BarRow>
<BarRow tone="usage">
<Text color={FG.sub}>{"output "}</Text>
<Text bold color={FG.body}>
{card.tokens.reason.toLocaleString()}
</Text>
</Box>
<Box flexDirection="row" gap={1}>
<Text color={FG.sub}>output</Text>
{bar(outputRatio, TONE.brand)}
<Text bold color={FG.body}>{` ${card.tokens.output.toLocaleString()}`}</Text>
</BarRow>
<BarRow tone="usage" indent={0} />
<BarRow tone="usage">
<Text color={FG.sub}>{"cache hit "}</Text>
<Text bold color={FG.body}>
{card.tokens.output.toLocaleString()}
</Text>
</Box>
<Box flexDirection="row" gap={1}>
<Text color={FG.sub}>cache </Text>
{bar(card.cacheHit, TONE.ok)}
<Text bold color={TONE.ok}>{` ${(card.cacheHit * 100).toFixed(1)}%`}</Text>
</BarRow>
<BarRow tone="usage" indent={0} />
<BarRow tone="usage">
<Text color={FG.faint}>{"session "}</Text>
<Text bold color={TONE.ok}>{`${(card.cacheHit * 100).toFixed(1)}%`}</Text>
</Box>
<Box flexDirection="row" gap={1}>
<Text color={FG.faint}>session</Text>
<Text bold color={FG.body}>{`⛁ ${formatCNY(card.sessionCost, 3)}`}</Text>
{card.balance !== undefined && (
{card.balance !== undefined ? (
<>
<Text color={FG.meta}>{" · "}</Text>
<Text color={FG.faint}>{"balance "}</Text>
<Text color={FG.faint}>· balance</Text>
<Text bold color={TONE.brand}>{`¥${card.balance.toFixed(2)}`}</Text>
</>
)}
</BarRow>
</Box>
) : null}
</Box>
</Card>
);
}
function CompactUsageRow({ card }: { card: UsageCardData }): React.ReactElement {
const elapsed = card.elapsedMs !== undefined ? ` · ${(card.elapsedMs / 1000).toFixed(1)}s` : "";
const elapsed = card.elapsedMs !== undefined ? ` · ${(card.elapsedMs / 1000).toFixed(1)}s` : "";
return (
<Box>
<Text color={FG.faint}>{` Σ turn ${card.turn} · `}</Text>
<Text
color={FG.meta}
>{`${compactNum(card.tokens.prompt)} prompt · ${compactNum(card.tokens.output)} out`}</Text>
<Text color={FG.faint}>{" · cache "}</Text>
<Box flexDirection="row" gap={1} marginTop={1}>
<Text color={FG.meta}>Σ</Text>
<Text color={FG.faint}>{`turn ${card.turn}`}</Text>
<Text color={FG.meta}>
{`· ${compactNum(card.tokens.prompt)} prompt · ${compactNum(card.tokens.output)} out`}
</Text>
<Text color={FG.faint}>· cache</Text>
<Text color={TONE.ok}>{`${(card.cacheHit * 100).toFixed(0)}%`}</Text>
<Text color={FG.faint}>{` · ${formatCNY(card.cost)}${elapsed}`}</Text>
{card.balance !== undefined && (
<>
<Text color={FG.faint}>{" · "}</Text>
<Text color={TONE.brand}>{`¥${card.balance.toFixed(2)}`}</Text>
</>
)}
<Text color={FG.faint}>{`· ${formatCNY(card.cost)}${elapsed}`}</Text>
{card.balance !== undefined ? (
<Text color={TONE.brand}>{`· ¥${card.balance.toFixed(2)}`}</Text>
) : null}
</Box>
);
}
+13 -15
View File
@@ -1,25 +1,23 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { Markdown } from "../markdown.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { UserCard as UserCardData } from "../state/cards.js";
import { FG } from "../theme/tokens.js";
import { FG, TONE } from "../theme/tokens.js";
import { formatRelativeTime } from "./time.js";
export function UserCard({ card }: { card: UserCardData }): React.ReactElement {
return (
<Box flexDirection="column">
<Box flexDirection="row">
<Text>{" "}</Text>
<Text color={FG.meta}>◇</Text>
<Text bold color={FG.sub}>
{" you"}
</Text>
<Text color={FG.faint}>{` · ${formatRelativeTime(card.ts)}`}</Text>
</Box>
<Box flexDirection="column" paddingLeft={4}>
<Markdown text={card.text} />
</Box>
</Box>
<Card tone={TONE.accent}>
<CardHeader
glyph="›"
tone={TONE.accent}
title="you"
titleColor={FG.sub}
meta={[formatRelativeTime(card.ts)]}
/>
<Markdown text={card.text} />
</Card>
);
}
+14 -19
View File
@@ -1,31 +1,26 @@
import { Box, Text } from "ink";
import { Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { BarRow } from "../primitives/BarRow.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { WarnCard as WarnCardData } from "../state/cards.js";
import { FG } from "../theme/tokens.js";
import { CardHeader } from "./CardHeader.js";
import { FG, TONE } from "../theme/tokens.js";
export function WarnCard({ card }: { card: WarnCardData }): React.ReactElement {
const showBody = card.message.length > 0;
const messageLines = card.message.length > 0 ? card.message.split("\n") : [];
return (
<Box flexDirection="column">
<Card tone={TONE.warn}>
<CardHeader
tone="warn"
glyph="⚠"
tone={TONE.warn}
title={card.title}
meta={card.detail ? `· ${card.detail}` : undefined}
meta={card.detail ? [card.detail] : undefined}
/>
{showBody && (
<>
<BarRow tone="warn" indent={0} />
{card.message.split("\n").map((line, i) => (
<BarRow key={`${card.id}:${i}`} tone="warn">
<Text color={FG.body}>{line}</Text>
</BarRow>
))}
</>
)}
</Box>
{messageLines.map((line, i) => (
<Text key={`${card.id}:${i}`} color={FG.body}>
{line || " "}
</Text>
))}
</Card>
);
}
-27
View File
@@ -1,27 +0,0 @@
export const STATUS = {
ok: "✓",
running: "▶",
queued: "○",
failed: "✗",
blocked: "!",
collapsed: "▸",
expanded: "▾",
focused: "●",
} as const;
export const STRUCT = {
bar: "▎",
thinBar: "▏",
rule: "─",
dot: "·",
arrow: "›",
} as const;
export const DENSITY = {
full: "█",
high: "▓",
mid: "▒",
low: "░",
on: "▰",
off: "▱",
} as const;
+1 -1
View File
@@ -145,7 +145,7 @@ export function CtxBreakdownBlock({ data }: { data: CtxBreakdownData }): React.R
</Box>
) : null}
<Box marginTop={1}>
<Text dimColor>{" /compact shrinks oversized tool results · /new wipes log"}</Text>
<Text dimColor>{" /compact folds (auto at 50%) · /new wipes log"}</Text>
</Box>
</Box>
);
+2 -124
View File
@@ -16,7 +16,7 @@ export interface ToolEventContext {
toolStartedAtRef: MutableRefObject<number | null>;
toolHistoryRef: MutableRefObject<Array<{ toolName: string; text: string }>>;
setPendingShell: Dispatch<
SetStateAction<{ command: string; kind: "run_command" | "run_background" } | null>
SetStateAction<{ id: number; command: string; kind: "run_command" | "run_background" } | null>
>;
setPendingPlan: Dispatch<SetStateAction<string | null>>;
setPendingRevision: Dispatch<
@@ -25,9 +25,6 @@ export interface ToolEventContext {
setPendingChoice: Dispatch<
SetStateAction<{ question: string; options: ChoiceOption[]; allowCustom: boolean } | null>
>;
setPendingCheckpoint: Dispatch<
SetStateAction<{ stepId: string; title?: string; completed: number; total: number } | null>
>;
planStepsRef: MutableRefObject<PlanStep[] | null>;
completedStepIdsRef: MutableRefObject<Set<string>>;
planBodyRef: MutableRefObject<string | null>;
@@ -55,125 +52,9 @@ export function handleToolEvent(ev: LoopEvent, ctx: ToolEventContext): void {
});
}
if (
ctx.codeModeOn &&
(ev.toolName === "run_command" || ev.toolName === "run_background") &&
ev.content.includes('"NeedsConfirmationError:') &&
ev.toolArgs
) {
try {
const parsed = JSON.parse(ev.toolArgs) as { command?: unknown };
if (typeof parsed.command === "string" && parsed.command.trim()) {
ctx.setPendingShell({
command: parsed.command.trim(),
kind: ev.toolName as "run_command" | "run_background",
});
}
} catch {
/* malformed args — skip the prompt */
}
}
if (
ctx.codeModeOn &&
ev.toolName === "submit_plan" &&
ev.content.includes('"PlanProposedError:')
) {
try {
const parsed = JSON.parse(ev.content) as {
plan?: unknown;
steps?: unknown;
summary?: unknown;
};
if (typeof parsed.plan === "string" && parsed.plan.trim()) {
const planText = parsed.plan.trim();
ctx.setPendingPlan(planText);
const steps = Array.isArray(parsed.steps) ? (parsed.steps as PlanStep[]) : null;
ctx.planStepsRef.current = steps;
ctx.completedStepIdsRef.current = new Set();
ctx.planBodyRef.current = planText;
ctx.planSummaryRef.current =
typeof parsed.summary === "string" && parsed.summary.trim()
? parsed.summary.trim()
: null;
ctx.persistPlanState();
const summary =
typeof parsed.summary === "string" && parsed.summary.trim() ? parsed.summary.trim() : "";
const title = summary ? `Plan · ${summary}` : "Plan submitted";
ctx.log.showPlan({
title,
steps: (steps ?? []).map((s) => ({ id: s.id, title: s.title, status: "queued" })),
variant: "active",
});
}
} catch {
/* malformed payload — skip the picker */
}
}
if (ev.toolName === "revise_plan" && ev.content.includes('"PlanRevisionProposedError:')) {
try {
const parsed = JSON.parse(ev.content) as {
reason?: unknown;
remainingSteps?: unknown;
summary?: unknown;
};
const reason = typeof parsed.reason === "string" ? parsed.reason.trim() : "";
const remainingSteps = Array.isArray(parsed.remainingSteps)
? (parsed.remainingSteps as PlanStep[]).filter(
(s) =>
s &&
typeof s.id === "string" &&
s.id.trim() &&
typeof s.title === "string" &&
s.title.trim() &&
typeof s.action === "string" &&
s.action.trim(),
)
: [];
if (reason && remainingSteps.length > 0) {
const summary =
typeof parsed.summary === "string" ? parsed.summary.trim() || undefined : undefined;
ctx.setPendingRevision({ reason, remainingSteps, summary });
}
} catch {
/* malformed payload — skip the picker */
}
}
if (ev.toolName === "ask_choice" && ev.content.includes('"ChoiceRequestedError:')) {
try {
const parsed = JSON.parse(ev.content) as {
question?: unknown;
options?: unknown;
allowCustom?: unknown;
};
const question = typeof parsed.question === "string" ? parsed.question.trim() : "";
const options = Array.isArray(parsed.options)
? (parsed.options as ChoiceOption[]).filter(
(o) =>
o &&
typeof o.id === "string" &&
o.id.trim() &&
typeof o.title === "string" &&
o.title.trim(),
)
: [];
if (question && options.length >= 2) {
ctx.setPendingChoice({
question,
options,
allowCustom: parsed.allowCustom === true,
});
}
} catch {
/* malformed payload — skip the picker */
}
}
if (ev.toolName === "mark_step_complete") {
try {
const parsed = JSON.parse(ev.content) as Partial<StepCompletion> & { error?: string };
const parsed = JSON.parse(ev.content) as Partial<StepCompletion>;
const stepId = parsed.stepId;
if (parsed.kind === "step_completed" && typeof stepId === "string") {
ctx.completedStepIdsRef.current.add(stepId);
@@ -192,9 +73,6 @@ export function handleToolEvent(ev: LoopEvent, ctx: ToolEventContext): void {
);
}
}
if (typeof parsed.error === "string" && parsed.error.startsWith("PlanCheckpointError:")) {
ctx.setPendingCheckpoint({ stepId, title, completed, total });
}
}
} catch {
/* malformed payload — skip the progress row */
+21 -18
View File
@@ -2,7 +2,8 @@ import { Static } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { CardRenderer } from "../cards/CardRenderer.js";
import type { Card, CardId } from "../state/cards.js";
import { ActiveCardContext } from "../primitives/Card.js";
import type { Card } from "../state/cards.js";
import { useAgentState } from "../state/provider.js";
/** Settled = no future event can mutate it; safe to commit via Ink's Static. */
@@ -11,32 +12,34 @@ function isSettled(card: Card): boolean {
case "streaming":
case "tool":
case "branch":
return card.done;
return card.done || !!card.aborted;
case "reasoning":
return !card.streaming;
case "plan":
if (card.variant !== "active") return true;
return card.steps.every((s) => s.status === "done" || s.status === "skipped");
return !card.streaming || !!card.aborted;
default:
return true;
}
}
export function CardStream({ excludeId }: { excludeId?: CardId } = {}): React.ReactElement {
export function CardStream(): React.ReactElement {
const cards = useAgentState((s) => s.cards);
const filtered = excludeId ? cards.filter((c) => c.id !== excludeId) : cards;
let cutoff = filtered.length;
for (let i = 0; i < filtered.length; i++) {
if (!isSettled(filtered[i] as Card)) {
cutoff = i;
break;
}
}
const committed = filtered.slice(0, cutoff);
const live = filtered.slice(cutoff);
const lastIdx = cards.length - 1;
const lastCard = lastIdx >= 0 ? (cards[lastIdx] as Card) : null;
const lastIsLive = !!lastCard && !isSettled(lastCard);
const committed: Card[] = lastIsLive ? cards.slice(0, lastIdx) : cards.slice();
const live: Card[] = lastIsLive && lastCard ? [lastCard] : [];
// Static items are emitted via bridge.emitStatic, which renders them in an
// off-tree React reconciler — context from the live tree does NOT propagate.
// The ActiveCardContext.Provider must therefore live inside the children
// function so it travels with the rendered subtree.
return (
<>
<Static items={committed}>{(card) => <CardRenderer key={card.id} card={card} />}</Static>
<Static items={committed}>
{(card) => (
<ActiveCardContext.Provider value={false} key={card.id}>
<CardRenderer card={card} />
</ActiveCardContext.Provider>
)}
</Static>
{live.map((card) => (
<CardRenderer key={card.id} card={card} />
))}
+48 -60
View File
@@ -5,21 +5,25 @@ import type { ApplyResult } from "../../../code/edit-blocks.js";
import type { EditMode } from "../../../config.js";
import type { JobRegistry } from "../../../tools/jobs.js";
import { CharBar } from "../char-bar.js";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import { PILL_MODEL, PILL_SECTION, Pill, modelBadgeFor } from "../primitives/Pill.js";
import { Spinner } from "../primitives/Spinner.js";
import { CARD, FG, TONE } from "../theme/tokens.js";
import { useElapsedSeconds, useSlowTick, useTick } from "../ticker.js";
export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
/** "Thinking" row — circle spinner per design (model wait, not tool call). */
/** "Thinking" row — soft pulse + italic label (model wait, not tool call). */
export function ThinkingRow({ text }: { text: string }) {
const elapsed = useElapsedSeconds();
return (
<Box marginY={1} paddingX={1}>
<Spinner kind="circle" color={TONE.brand} bold />
<Text>{" "}</Text>
<Text color={TONE.brand}>{text}</Text>
<Text color={FG.faint}>{` · ${elapsed}s`}</Text>
<Box marginY={1} paddingX={1} gap={1}>
<Spinner kind="circle" color={TONE.accent} />
<Text italic color={FG.sub}>
{text}
</Text>
<Text color={FG.faint}>{`${elapsed}s`}</Text>
</Box>
);
}
@@ -155,7 +159,7 @@ function subagentTitle(skillName: string | undefined, task: string): string {
return `Sub-agent · ${short || "anonymous"}`;
}
/** Live block for a running subagent. Fixed row count — never grows as inner events arrive, so the screen doesn't jump. */
/** Live block for a running subagent — Card-styled, fixed row count for flicker-safety. */
export function SubagentRow({
activity,
}: {
@@ -169,49 +173,37 @@ export function SubagentRow({
lastInner: { glyph: string; color: string; label: string; meta?: string } | null;
};
}) {
const tick = useTick();
useTick();
const seconds = (activity.elapsedMs / 1000).toFixed(1);
const phase = subagentPhaseLabel(activity.phase, activity.iter, activity.elapsedMs);
const last = activity.lastInner;
const subtitle = activity.skillName ?? truncate(activity.task, 48);
const modelBadge = activity.model ? modelBadgeFor(activity.model) : null;
return (
<Box flexDirection="column" marginY={1}>
<Box>
<Text>{" "}</Text>
<Text color={CARD.subagent.color}>{"▎ "}</Text>
<Text bold color={CARD.subagent.color}>
{`⌬ ${subagentTitle(activity.skillName, activity.task)}`}
</Text>
<Box flexGrow={1} />
<Text color={CARD.subagent.color}>{`iter ${activity.iter} · ${seconds}s`}</Text>
<Text>{" "}</Text>
<Text color={CARD.subagent.color} bold>
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
</Text>
</Box>
<Box>
<Text>{" "}</Text>
<Text color={CARD.subagent.color}>{"▎"}</Text>
</Box>
<Box>
<Text>{" "}</Text>
<Text color={CARD.subagent.color}>{"▎ "}</Text>
<Text color={FG.faint}>{"Task "}</Text>
<Card tone={CARD.subagent.color}>
<CardHeader
glyph="⌬"
tone={CARD.subagent.color}
title="subagent"
titleColor={PILL_SECTION.plan.fg}
titleBg={PILL_SECTION.plan.bg}
subtitle={subtitle}
meta={[`iter ${activity.iter}`, `${seconds}s`]}
right={
<>
{modelBadge ? (
<Pill label={modelBadge.label} {...PILL_MODEL[modelBadge.kind]} bold={false} />
) : null}
<Spinner kind="braille" color={CARD.subagent.color} />
</>
}
/>
<Text color={FG.faint}>
{"task "}
<Text color={FG.sub}>{activity.task}</Text>
</Box>
<Box>
<Text>{" "}</Text>
<Text color={CARD.subagent.color}>{"▎ "}</Text>
<Text color={FG.faint}>{"Model "}</Text>
<Text color={FG.sub}>{activity.model ?? "—"}</Text>
</Box>
<Box>
<Text>{" "}</Text>
<Text color={CARD.subagent.color}>{"▎"}</Text>
</Box>
<Box>
<Text>{" "}</Text>
<Text color={CARD.subagent.color}>{"▎ "}</Text>
<Text color={FG.faint}>{"Last "}</Text>
</Text>
<Text color={FG.faint}>
{"last "}
{last ? (
<>
<Text color={last.color}>{`${last.glyph} `}</Text>
@@ -219,25 +211,21 @@ export function SubagentRow({
{last.meta ? <Text color={FG.faint}>{` ${last.meta}`}</Text> : null}
</>
) : (
<Text color={FG.faint}>{"queued…"}</Text>
<Text color={FG.faint}>queued…</Text>
)}
</Box>
<Box>
<Text>{" "}</Text>
<Text color={CARD.subagent.color}>{"▎"}</Text>
</Box>
<Box>
<Text>{" "}</Text>
<Text color={CARD.subagent.color}>{"▎ "}</Text>
<Text bold color={TONE.brand}>
{"▶ "}
</Text>
<Text color={TONE.brand}>{phase}</Text>
</Box>
</Box>
</Text>
<Text color={TONE.brand}>
{"▶ "}
{phase}
</Text>
</Card>
);
}
function truncate(text: string, max: number): string {
return text.length > max ? `${text.slice(0, max)}…` : text;
}
/** Live spinner + arg summary while a tool call is in flight; absorbs MCP progress frames. */
export function OngoingToolRow({
tool,
+23
View File
@@ -0,0 +1,23 @@
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { PlanCard } from "../cards/PlanCard.js";
import type { Card, PlanCard as PlanCardData } from "../state/cards.js";
import { useAgentState } from "../state/provider.js";
export function isActivePlanInFlight(card: Card): boolean {
if (card.kind !== "plan") return false;
if (card.variant !== "active") return false;
return !card.steps.every((s) => s.status === "done" || s.status === "skipped");
}
export function PlanLiveRow(): React.ReactElement | null {
const planCard = useAgentState((s) => {
for (let i = s.cards.length - 1; i >= 0; i--) {
const c = s.cards[i] as Card;
if (isActivePlanInFlight(c)) return c as PlanCardData;
}
return null;
});
if (!planCard) return null;
return <PlanCard card={planCard} />;
}
+160
View File
@@ -0,0 +1,160 @@
/** Single allocator for vertical viewport rows; consumers claim per-zone via useReserveRows. */
import { useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React, { createContext, useContext, useEffect, useMemo, useReducer } from "react";
export type ZoneId = "modal" | "status" | "input" | "stream" | "safety";
/** Higher number = claims rows first. */
const ZONE_PRIORITY: Record<ZoneId, number> = {
modal: 100,
status: 60,
input: 50,
stream: 10,
safety: 5,
};
export interface ClaimSpec {
/** Smallest acceptable allocation. May exceed total rows on tiny terminals. */
min: number;
/** Hard ceiling. `Number.POSITIVE_INFINITY` = "soak whatever's left". */
max: number;
}
interface InternalClaim extends ClaimSpec {
zone: ZoneId;
priority: number;
}
/** Pure allocator — used by the provider and tested in isolation. */
export function allocateRows(
claims: ReadonlyArray<InternalClaim>,
totalRows: number,
): ReadonlyMap<ZoneId, number> {
const sorted = [...claims].sort((a, b) => b.priority - a.priority);
const out = new Map<ZoneId, number>();
let remaining = Math.max(0, totalRows);
for (const c of sorted) {
const want = Math.min(c.max, Math.max(c.min, remaining));
out.set(c.zone, want);
remaining = Math.max(0, remaining - want);
}
return out;
}
interface BudgetState {
/** Active claims keyed by zone — one consumer per zone. */
claims: ReadonlyMap<ZoneId, ClaimSpec>;
totalRows: number;
}
type BudgetAction =
| { type: "claim"; zone: ZoneId; spec: ClaimSpec }
| { type: "release"; zone: ZoneId }
| { type: "resize"; rows: number };
function reducer(state: BudgetState, action: BudgetAction): BudgetState {
switch (action.type) {
case "claim": {
const next = new Map(state.claims);
next.set(action.zone, action.spec);
return { ...state, claims: next };
}
case "release": {
if (!state.claims.has(action.zone)) return state;
const next = new Map(state.claims);
next.delete(action.zone);
return { ...state, claims: next };
}
case "resize":
if (action.rows === state.totalRows) return state;
return { ...state, totalRows: action.rows };
}
}
interface BudgetContextValue {
totalRows: number;
allocations: ReadonlyMap<ZoneId, number>;
claims: ReadonlyMap<ZoneId, ClaimSpec>;
dispatch: React.Dispatch<BudgetAction>;
}
const BudgetContext = createContext<BudgetContextValue | null>(null);
export interface ViewportBudgetProviderProps {
children: React.ReactNode;
/** Test seam — bypasses useStdout. */
initialRows?: number;
}
export function ViewportBudgetProvider({
children,
initialRows,
}: ViewportBudgetProviderProps): React.ReactElement {
const { stdout } = useStdout();
const [state, dispatch] = useReducer(reducer, undefined, () => ({
claims: new Map<ZoneId, ClaimSpec>(),
totalRows: initialRows ?? stdout?.rows ?? 40,
}));
// Single resize listener — children read totalRows from context.
useEffect(() => {
if (initialRows !== undefined) return undefined;
if (!stdout) return undefined;
const onResize = () => dispatch({ type: "resize", rows: stdout.rows ?? 40 });
onResize();
stdout.on("resize", onResize);
return () => {
stdout.off("resize", onResize);
};
}, [stdout, initialRows]);
const allocations = useMemo(() => {
const list: InternalClaim[] = [];
for (const [zone, spec] of state.claims) {
list.push({ zone, priority: ZONE_PRIORITY[zone], ...spec });
}
return allocateRows(list, state.totalRows);
}, [state.claims, state.totalRows]);
const value = useMemo<BudgetContextValue>(
() => ({
totalRows: state.totalRows,
allocations,
claims: state.claims,
dispatch,
}),
[state.totalRows, allocations, state.claims],
);
return <BudgetContext.Provider value={value}>{children}</BudgetContext.Provider>;
}
/** Returns actual allocation; falls back to spec.max when no provider is mounted. */
export function useReserveRows(zone: ZoneId, spec: ClaimSpec): number {
const ctx = useContext(BudgetContext);
// Deps key off dispatch (stable) + primitives — whole ctx changes every claim and would loop.
const dispatch = ctx?.dispatch;
useEffect(() => {
if (!dispatch) return undefined;
dispatch({ type: "claim", zone, spec: { min: spec.min, max: spec.max } });
return () => {
dispatch({ type: "release", zone });
};
}, [dispatch, zone, spec.min, spec.max]);
if (!ctx) return Number.isFinite(spec.max) ? spec.max : 40;
const allocated = ctx.allocations.get(zone);
if (allocated !== undefined) return allocated;
// Optimistic max for pre-effect first render.
return Number.isFinite(spec.max) ? spec.max : ctx.totalRows;
}
/** Total terminal rows from the provider; falls back to useStdout if unmounted. */
export function useTotalRows(): number {
const ctx = useContext(BudgetContext);
const { stdout } = useStdout();
return ctx?.totalRows ?? stdout?.rows ?? 40;
}
+268
View File
@@ -0,0 +1,268 @@
/** Pure markdown → flat MdLine[]. Streaming-safe: marked.lexer tolerates partial input. */
import { type Token, type Tokens, marked } from "marked";
export interface InlineStyle {
bold?: boolean;
italic?: boolean;
strike?: boolean;
code?: boolean;
link?: string;
fileRef?: { path: string; line?: number; lineEnd?: number };
}
export interface InlineSpan extends InlineStyle {
text: string;
}
export type MdLine =
| { kind: "blank" }
| { kind: "hr" }
| { kind: "heading"; level: number; spans: InlineSpan[] }
| { kind: "paragraph"; spans: InlineSpan[] }
| {
kind: "list";
ordered: boolean;
index: number;
depth: number;
task?: "todo" | "done";
spans: InlineSpan[];
}
| { kind: "code"; lang: string; text: string }
| { kind: "blockquote"; spans: InlineSpan[] };
const FILE_REF_RE = /\b([A-Za-z0-9_./@\-]+\.[A-Za-z0-9]{1,6})(?::(\d+)(?:-(\d+))?)?\b/g;
marked.use({ gfm: true, breaks: false });
export function markdownToLines(text: string): MdLine[] {
if (text.length === 0) return [];
const tokens = marked.lexer(text);
const out: MdLine[] = [];
for (const tok of tokens) emitBlock(tok, out, 0);
return out;
}
function emitBlock(tok: Token, out: MdLine[], depth: number): void {
switch (tok.type) {
case "heading": {
const h = tok as Tokens.Heading;
out.push({ kind: "heading", level: h.depth, spans: inline(h.tokens ?? []) });
return;
}
case "paragraph": {
const p = tok as Tokens.Paragraph;
out.push({ kind: "paragraph", spans: inline(p.tokens ?? []) });
return;
}
case "code": {
const c = tok as Tokens.Code;
out.push({ kind: "code", lang: (c.lang ?? "").split(/\s+/)[0] ?? "", text: c.text });
return;
}
case "list": {
const l = tok as Tokens.List;
const startIndex = Number(l.start) || 1;
l.items.forEach((item, i) => emitListItem(item, out, l.ordered, startIndex + i, depth));
return;
}
case "hr":
out.push({ kind: "hr" });
return;
case "blockquote": {
const bq = tok as Tokens.Blockquote;
for (const child of bq.tokens ?? []) {
if (child.type === "paragraph") {
out.push({ kind: "blockquote", spans: inline((child as Tokens.Paragraph).tokens ?? []) });
} else if (child.type === "space") {
// skip
} else {
// For nested non-paragraph blocks (lists, code), fall back to a flat blockquote span.
const flat = plainTokens(child);
if (flat.length > 0) out.push({ kind: "blockquote", spans: [{ text: flat }] });
}
}
return;
}
case "space":
out.push({ kind: "blank" });
return;
case "html": {
const h = tok as Tokens.HTML;
out.push({ kind: "paragraph", spans: [{ text: h.text }] });
return;
}
default: {
// Unknown / table / def — render the raw text as a paragraph fallback.
const raw = (tok as { raw?: string }).raw ?? "";
if (raw.trim().length > 0) out.push({ kind: "paragraph", spans: [{ text: raw }] });
}
}
}
function emitListItem(
item: Tokens.ListItem,
out: MdLine[],
ordered: boolean,
index: number,
depth: number,
): void {
const task = item.task ? (item.checked ? "done" : "todo") : undefined;
const head: MdLine = {
kind: "list",
ordered,
index,
depth,
spans: [],
...(task ? { task } : {}),
};
out.push(head);
for (const tok of item.tokens) {
if (tok.type === "text") {
const t = tok as Tokens.Text;
const spans = t.tokens ? inline(t.tokens) : inlineFromText(t.text);
head.spans.push(...spans);
} else if (tok.type === "list") {
const sub = tok as Tokens.List;
const subStart = Number(sub.start) || 1;
sub.items.forEach((s, i) => emitListItem(s, out, sub.ordered, subStart + i, depth + 1));
} else {
emitBlock(tok, out, depth);
}
}
}
function inline(tokens: Token[]): InlineSpan[] {
const out: InlineSpan[] = [];
walk(tokens, {}, out);
return mergeAdjacent(out);
}
function walk(tokens: Token[], style: InlineStyle, out: InlineSpan[]): void {
for (const tok of tokens) {
switch (tok.type) {
case "text": {
const t = tok as Tokens.Text;
if (t.tokens && t.tokens.length > 0) walk(t.tokens, style, out);
else pushTextSpans(t.text, style, out);
break;
}
case "strong":
walk((tok as Tokens.Strong).tokens, { ...style, bold: true }, out);
break;
case "em":
walk((tok as Tokens.Em).tokens, { ...style, italic: true }, out);
break;
case "del":
walk((tok as Tokens.Del).tokens, { ...style, strike: true }, out);
break;
case "codespan":
out.push({ text: (tok as Tokens.Codespan).text, code: true, ...style });
break;
case "link": {
const l = tok as Tokens.Link;
// A link's children are still subject to ancestor styles; emit each
// descendant span with the link href so OSC8 can wrap it later.
const before = out.length;
walk(l.tokens, style, out);
for (let i = before; i < out.length; i++) {
const span = out[i]!;
if (!span.link) span.link = l.href;
}
break;
}
case "image": {
const im = tok as Tokens.Image;
out.push({ text: `[image: ${im.text || im.href}]`, ...style });
break;
}
case "br":
out.push({ text: "\n", ...style });
break;
case "escape":
pushTextSpans((tok as Tokens.Escape).text, style, out);
break;
case "html":
pushTextSpans((tok as Tokens.HTML).text, style, out);
break;
default:
pushTextSpans((tok as { raw?: string }).raw ?? "", style, out);
}
}
}
function pushTextSpans(text: string, style: InlineStyle, out: InlineSpan[]): void {
if (text.length === 0) return;
// Split out file refs so the renderer can OSC8-link them.
let cursor = 0;
for (const m of text.matchAll(FILE_REF_RE)) {
const start = m.index ?? 0;
const end = start + m[0].length;
if (start > cursor) out.push({ text: text.slice(cursor, start), ...style });
const path = m[1]!;
const ln = m[2] ? Number(m[2]) : undefined;
const lnEnd = m[3] ? Number(m[3]) : undefined;
out.push({
text: m[0],
...style,
fileRef: {
path,
...(ln !== undefined ? { line: ln } : {}),
...(lnEnd !== undefined ? { lineEnd: lnEnd } : {}),
},
});
cursor = end;
}
if (cursor < text.length) out.push({ text: text.slice(cursor), ...style });
}
function inlineFromText(text: string): InlineSpan[] {
const out: InlineSpan[] = [];
pushTextSpans(text, {}, out);
return out;
}
function mergeAdjacent(spans: InlineSpan[]): InlineSpan[] {
if (spans.length < 2) return spans;
const out: InlineSpan[] = [];
for (const s of spans) {
const last = out[out.length - 1];
if (last && stylesEqual(last, s)) {
out[out.length - 1] = { ...last, text: last.text + s.text };
} else {
out.push(s);
}
}
return out;
}
function stylesEqual(a: InlineSpan, b: InlineSpan): boolean {
return (
!!a.bold === !!b.bold &&
!!a.italic === !!b.italic &&
!!a.strike === !!b.strike &&
!!a.code === !!b.code &&
a.link === b.link &&
fileRefEqual(a.fileRef, b.fileRef)
);
}
function fileRefEqual(a: InlineSpan["fileRef"], b: InlineSpan["fileRef"]): boolean {
if (!a && !b) return true;
if (!a || !b) return false;
return a.path === b.path && a.line === b.line && a.lineEnd === b.lineEnd;
}
function plainTokens(tok: Token): string {
if ("raw" in tok && typeof (tok as { raw?: string }).raw === "string") {
return (tok as { raw: string }).raw.trim();
}
return "";
}
/** Extract just the visible characters from a span list — handy for tests / previews. */
export function spansText(spans: ReadonlyArray<InlineSpan>): string {
let s = "";
for (const span of spans) s += span.text;
return s;
}
+177
View File
@@ -0,0 +1,177 @@
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { inkCompat } from "../../renderer/index.js";
import { type InlineSpan, type MdLine, markdownToLines } from "./markdown-lines.js";
const FG_BODY = "#c9d1d9";
const FG_FAINT = "#6e7681";
const FG_STRONG = "#f0f6fc";
const FG_META = "#8b949e";
const TONE_BRAND = "#79c0ff";
const TONE_OK = "#7ee787";
const TONE_WARN = "#f0b07d";
const SURFACE_ELEV = "#161b22";
export function MarkdownView({ text }: { text: string }): React.ReactElement {
// No useMemo: the renderer's Static-path uses a one-shot tree walker that
// doesn't set up a React dispatcher, so hook calls would throw. Parsing on
// every render is cheap (marked.lexer is allocation-light).
return <MarkdownLines lines={markdownToLines(text)} />;
}
export function MarkdownLines({
lines,
}: {
lines: ReadonlyArray<MdLine>;
}): React.ReactElement {
return (
<inkCompat.Box flexDirection="column">
{lines.map((line, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: lines are positional + stable per render
<LineRow key={`md-${i}-${line.kind}`} line={line} />
))}
</inkCompat.Box>
);
}
function LineRow({ line }: { line: MdLine }): React.ReactElement | null {
switch (line.kind) {
case "blank":
return <inkCompat.Text> </inkCompat.Text>;
case "hr":
return <inkCompat.Text color={FG_FAINT}>──────</inkCompat.Text>;
case "heading":
return (
<inkCompat.Box>
<inkCompat.Text bold color={FG_STRONG}>
{`${"#".repeat(line.level)} `}
</inkCompat.Text>
<Spans spans={line.spans} bold strongColor />
</inkCompat.Box>
);
case "paragraph":
return (
<inkCompat.Box>
<Spans spans={line.spans} />
</inkCompat.Box>
);
case "list": {
const indent = " ".repeat(line.depth * 2);
const marker =
line.task === "done"
? "✓"
: line.task === "todo"
? "○"
: line.ordered
? `${line.index}.`
: "·";
const markerColor =
line.task === "done" ? TONE_OK : line.task === "todo" ? FG_FAINT : FG_META;
return (
<inkCompat.Box>
<inkCompat.Text color={markerColor}>{`${indent}${marker} `}</inkCompat.Text>
<Spans spans={line.spans} dim={line.task === "done"} strike={line.task === "done"} />
</inkCompat.Box>
);
}
case "code":
return <CodeBlock lang={line.lang} text={line.text} />;
case "blockquote":
return (
<inkCompat.Box>
<inkCompat.Text color={TONE_BRAND}>{"▎ "}</inkCompat.Text>
<Spans spans={line.spans} italic />
</inkCompat.Box>
);
}
}
function spanKey(span: InlineSpan, i: number): string {
return `${i}-${span.text.length}-${span.bold ? "b" : ""}${span.italic ? "i" : ""}${span.code ? "c" : ""}${span.strike ? "s" : ""}${span.link ? "l" : ""}`;
}
function CodeBlock({ lang, text }: { lang: string; text: string }): React.ReactElement {
const lines = text.split("\n");
return (
<inkCompat.Box flexDirection="column">
{lang.length > 0 ? <inkCompat.Text color={FG_META}>{` ${lang}`}</inkCompat.Text> : null}
{lines.map((ln, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: code lines are positional + stable per render
<inkCompat.Text key={`code-${i}`} backgroundColor={SURFACE_ELEV}>
{` ${ln} `}
</inkCompat.Text>
))}
</inkCompat.Box>
);
}
interface SpansProps {
readonly spans: ReadonlyArray<InlineSpan>;
readonly bold?: boolean;
readonly italic?: boolean;
readonly dim?: boolean;
readonly strike?: boolean;
readonly strongColor?: boolean;
}
function Spans({ spans, bold, italic, dim, strike, strongColor }: SpansProps): React.ReactElement {
if (spans.length === 0) return <inkCompat.Text> </inkCompat.Text>;
return (
<>
{spans.map((span, i) => (
<SpanText
key={spanKey(span, i)}
span={span}
ambientBold={bold}
ambientItalic={italic}
ambientDim={dim}
ambientStrike={strike}
strongColor={strongColor}
/>
))}
</>
);
}
function SpanText({
span,
ambientBold,
ambientItalic,
ambientDim,
ambientStrike,
strongColor,
}: {
span: InlineSpan;
ambientBold?: boolean;
ambientItalic?: boolean;
ambientDim?: boolean;
ambientStrike?: boolean;
strongColor?: boolean;
}): React.ReactElement {
if (span.code) {
return (
<inkCompat.Text color={FG_STRONG} backgroundColor={SURFACE_ELEV}>
{` ${span.text} `}
</inkCompat.Text>
);
}
const color = span.fileRef
? TONE_BRAND
: span.link
? TONE_BRAND
: strongColor
? FG_STRONG
: FG_BODY;
return (
<inkCompat.Text
color={color}
bold={!!(span.bold || ambientBold)}
italic={!!(span.italic || ambientItalic)}
dimColor={!!ambientDim}
strikethrough={!!(span.strike || ambientStrike)}
underline={!!(span.link || span.fileRef)}
>
{span.text}
</inkCompat.Text>
);
}
+155 -31
View File
@@ -1,29 +1,37 @@
/** Markdown → Ink. Parsing via marked; visual mapping mirrors dashboard/app.css `.md` rules. Code blocks pass through cli-highlight for ANSI syntax coloring. */
import { highlight, supportsLanguage } from "cli-highlight";
import { Box, Text } from "ink";
import { Box, Text, useStdout } from "ink";
import { type Token, type Tokens, marked } from "marked";
import React from "react";
import stringWidth from "string-width";
import { wrapToCells } from "../../frame/width.js";
import { FG, SURFACE, TONE } from "./theme/tokens.js";
/** Right-pad to `cells` visual columns — wide chars (CJK, emoji) count as 2. */
function padToCells(text: string, cells: number): string {
const w = stringWidth(text);
if (w >= cells) return text;
return text + " ".repeat(cells - w);
/** Left margin consumed by card outer marginLeft + body paddingLeft + safety. */
const BODY_LEFT_CELLS = 7;
const MarkdownWidthCtx = React.createContext<number | undefined>(undefined);
function useWidth(): number {
const ctx = React.useContext(MarkdownWidthCtx);
if (ctx !== undefined) return ctx;
return (useStdout()?.stdout?.columns ?? process.stdout.columns ?? 80) - BODY_LEFT_CELLS;
}
marked.setOptions({ gfm: true, breaks: false });
export function Markdown({ text }: { text: string }): React.ReactElement {
export function Markdown({ text, width }: { text: string; width?: number }): React.ReactElement {
const tokens = React.useMemo(() => marked.lexer(text), [text]);
const ctxWidth = width !== undefined ? Math.max(1, width) : undefined;
return (
<Box flexDirection="column" gap={1}>
{tokens.map((token, i) => (
<BlockToken key={`${i}-${token.type}`} token={token} />
))}
</Box>
<MarkdownWidthCtx.Provider value={ctxWidth}>
<Box flexDirection="column" gap={1}>
{tokens.map((token, i) => (
<BlockToken key={`${i}-${token.type}`} token={token} />
))}
</Box>
</MarkdownWidthCtx.Provider>
);
}
@@ -100,7 +108,7 @@ function ListItem({
const marker = item.task ? (item.checked ? "✓" : "○") : ordered ? `${index}.` : "·";
const markerColor = item.task ? (item.checked ? TONE.ok : FG.faint) : FG.meta;
const dim = item.task && item.checked === true;
const indent = " ".repeat(depth + 1);
const indent = " ".repeat(depth + 1);
return (
<Box>
<Text color={markerColor}>{`${indent}${marker} `}</Text>
@@ -135,14 +143,14 @@ function CodeBlock({ token }: { token: Tokens.Code }): React.ReactElement {
<Box flexDirection="column">
{lang ? (
<Box>
<Text color={FG.meta}>{` ${lang}`}</Text>
<Text color={FG.meta}>{` ${lang}`}</Text>
</Box>
) : null}
<Box flexDirection="column">
{lines.map((line, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: code lines are positional and stable per render
<Text key={`code-${i}`} backgroundColor={SURFACE.bgElev}>
{` ${line} `}
{` ${line} `}
</Text>
))}
</Box>
@@ -165,7 +173,7 @@ function Blockquote({ token }: { token: Tokens.Blockquote }): React.ReactElement
<Box flexDirection="column">
{(token.tokens ?? []).map((child, i) => (
<Box key={`${i}-${child.type}`} flexDirection="row">
<Text color={TONE.brand}>{" ▎ "}</Text>
<Text color={TONE.brand}>{" ▎ "}</Text>
<Box flexDirection="column" flexGrow={1}>
{child.type === "paragraph" ? (
<Text italic color={FG.sub}>
@@ -181,50 +189,124 @@ function Blockquote({ token }: { token: Tokens.Blockquote }): React.ReactElement
);
}
function HorizontalRule(): React.ReactElement {
return <Text color={FG.faint}>{" ────────────────────────────────────"}</Text>;
/** Right-pad to `cells` visual columns — wide chars (CJK, emoji) count as 2. */
function padToCells(text: string, cells: number): string {
const w = stringWidth(text);
if (w >= cells) return text;
return text + " ".repeat(cells - w);
}
function Table({ token }: { token: Tokens.Table }): React.ReactElement {
const colCount = token.header.length;
const headerCells = token.header.map((c) => plainText(c.tokens));
const bodyCells = token.rows.map((row) => row.map((c) => plainText(c.tokens)));
const widths = new Array(colCount).fill(0);
function HorizontalRule(): React.ReactElement {
const width = useWidth();
const rule = "─".repeat(Math.max(width, 1));
return <Text color={FG.faint}>{` ${rule}`}</Text>;
}
/** Pure function — no React deps. */
export function tableLayout(
headerCells: string[],
bodyCells: string[][],
availableWidth: number,
): ColumnarLayout | FallbackLayout {
const colCount = headerCells.length;
const GAP = " ";
const GAP_W = stringWidth(GAP);
const widths = new Array<number>(colCount).fill(0);
for (let c = 0; c < colCount; c++) {
widths[c] = Math.max(
stringWidth(headerCells[c] ?? ""),
...bodyCells.map((r) => stringWidth(r[c] ?? "")),
);
}
const GAP = " ";
const ruleRow = widths.map((w) => "─".repeat(w)).join(GAP);
const totalWidth = widths.reduce((s, w) => s + w, 0) + GAP_W * (colCount - 1);
if (totalWidth <= availableWidth) {
return { fallback: false, widths, colCount, gap: GAP };
}
// Fallback: key/value pairs, label column = widest header, value gets the rest.
const rawLabel = Math.max(...headerCells.map((h) => stringWidth(h))) + 2; // label + ": "
const labelPad = Math.min(rawLabel, availableWidth - 1);
const valueCells = availableWidth - labelPad;
return { fallback: true, labelPad, valueCells };
}
interface ColumnarLayout {
fallback: false;
widths: number[];
colCount: number;
gap: string;
}
interface FallbackLayout {
fallback: true;
labelPad: number;
valueCells: number;
}
function Table({ token }: { token: Tokens.Table }): React.ReactElement {
const width = useWidth();
const headerCells = token.header.map((c) => plainText(c.tokens));
const bodyCells = token.rows.map((row) => row.map((c) => plainText(c.tokens)));
const layout = tableLayout(headerCells, bodyCells, width);
if (!layout.fallback)
return (
<ColumnarTable
headerCells={headerCells}
bodyCells={bodyCells}
widths={layout.widths}
colCount={headerCells.length}
gap={layout.gap}
/>
);
return (
<FallbackTable
headerCells={headerCells}
bodyCells={bodyCells}
labelPad={layout.labelPad}
valueCells={layout.valueCells}
/>
);
}
function ColumnarTable({
headerCells,
bodyCells,
widths,
colCount,
gap,
}: {
headerCells: string[];
bodyCells: string[][];
widths: number[];
colCount: number;
gap: string;
}): React.ReactElement {
const ruleRow = widths.map((w) => "─".repeat(w)).join(gap);
return (
<Box flexDirection="column">
<Box>
<Text>{" "}</Text>
<Text> </Text>
{headerCells.map((cell, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: header cells positional
<React.Fragment key={`h-${i}`}>
<Text bold color={FG.sub}>
{padToCells(cell, widths[i]!)}
</Text>
{i < colCount - 1 ? <Text>{GAP}</Text> : null}
{i < colCount - 1 ? <Text>{gap}</Text> : null}
</React.Fragment>
))}
</Box>
<Box>
<Text>{" "}</Text>
<Text> </Text>
<Text color={FG.faint}>{ruleRow}</Text>
</Box>
{bodyCells.map((row, ri) => (
// biome-ignore lint/suspicious/noArrayIndexKey: body rows positional
<Box key={`tr-${ri}`}>
<Text>{" "}</Text>
<Text> </Text>
{row.map((cell, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: cells positional
<React.Fragment key={`c-${ri}-${i}`}>
<Text color={FG.body}>{padToCells(cell ?? "", widths[i]!)}</Text>
{i < colCount - 1 ? <Text>{GAP}</Text> : null}
{i < colCount - 1 ? <Text>{gap}</Text> : null}
</React.Fragment>
))}
</Box>
@@ -233,6 +315,48 @@ function Table({ token }: { token: Tokens.Table }): React.ReactElement {
);
}
function FallbackTable({
headerCells,
bodyCells,
labelPad,
valueCells,
}: {
headerCells: string[];
bodyCells: string[][];
labelPad: number;
valueCells: number;
}): React.ReactElement {
return (
<Box flexDirection="column">
{headerCells.map((h, ci) => {
const label = `${padToCells(h, labelPad - 2)}: `;
const values = bodyCells.map((r) => r[ci] ?? "");
return (
// biome-ignore lint/suspicious/noArrayIndexKey: header cells positional
<Box key={`fk-${ci}`} flexDirection="column">
{values.map((v, ri) => {
const lines = wrapToCells(v, valueCells);
return lines.map((line, li) => (
// biome-ignore lint/suspicious/noArrayIndexKey: fallback table lines are positional
<Box key={`fv-${ri}-${li}`}>
{li === 0 ? (
<Text bold color={FG.sub}>
{label}
</Text>
) : (
<Text>{padToCells("", labelPad)}</Text>
)}
<Text color={FG.body}>{line}</Text>
</Box>
));
})}
</Box>
);
})}
</Box>
);
}
function Inline({ tokens }: { tokens: Token[] }): React.ReactElement {
return (
<>
@@ -347,7 +471,7 @@ function InlineToken({ token }: { token: Token }): React.ReactElement {
}
}
function plainText(tokens: Token[] | undefined): string {
export function plainText(tokens: Token[] | undefined): string {
if (!tokens) return "";
let out = "";
for (const t of tokens) {
+44
View File
@@ -0,0 +1,44 @@
/** Applies an MCP append-drift mid-session: registers each new tool in the loop's registry + prefix, and returns an updated summary. Immutable — does not mutate the input `target`. */
import type { CacheFirstLoop } from "../../loop.js";
import { registerSingleMcpTool } from "../../mcp/registry.js";
import type { McpTool } from "../../mcp/types.js";
import type { JSONSchema, ToolSpec } from "../../types.js";
import type { McpServerSummary } from "./slash/types.js";
export function applyMcpAppend(
loop: CacheFirstLoop,
target: McpServerSummary,
addedTools: McpTool[],
): McpServerSummary {
const accepted: McpTool[] = [];
for (const mcpTool of addedTools) {
if (!mcpTool.name) continue;
const registeredName = registerSingleMcpTool(mcpTool, target.bridgeEnv);
if (!registeredName) continue;
const spec: ToolSpec = {
type: "function",
function: {
name: registeredName,
description: mcpTool.description ?? "",
parameters: mcpTool.inputSchema as unknown as JSONSchema,
},
};
loop.prefix.addTool(spec);
accepted.push(mcpTool);
}
if (accepted.length === 0 || !target.report.tools.supported) return target;
const merged = [...target.report.tools.items, ...accepted];
return {
...target,
toolCount: merged.length,
report: {
...target.report,
tools: {
supported: true as const,
items: merged,
},
},
};
}
+2 -19
View File
@@ -1,6 +1,5 @@
/** `/resource` + `/prompt` handlers — async (round-trip to MCP server), so App.tsx calls directly instead of `handleSlash`. */
import type { McpClient } from "../../mcp/client.js";
import type {
GetPromptResult,
McpPromptMessage,
@@ -161,16 +160,8 @@ export async function handleMcpBrowseSlash(
);
return;
}
const client: McpClient | undefined = server.client;
if (!client) {
log.pushWarning(
`server [${server.label}] is not connected (display-only)`,
"Resource read requires a live MCP client.",
);
return;
}
try {
const result = await client.readResource(arg);
const result = await server.readResource(arg);
log.pushInfo(formatResourceContents(arg, result));
} catch (err) {
log.pushWarning("readResource failed", (err as Error).message);
@@ -187,16 +178,8 @@ export async function handleMcpBrowseSlash(
);
return;
}
const client: McpClient | undefined = server.client;
if (!client) {
log.pushWarning(
`server [${server.label}] is not connected (display-only)`,
"Prompt fetch requires a live MCP client.",
);
return;
}
try {
const result = await client.getPrompt(arg);
const result = await server.getPrompt(arg);
log.pushInfo(formatPromptMessages(arg, result));
} catch (err) {
log.pushWarning("getPrompt failed", (err as Error).message);
+26
View File
@@ -0,0 +1,26 @@
/** Persists `mcpDisabled` to ~/.reasonix/config.json — shared between `/mcp disable / enable` slash and the McpBrowser `d` keybind. */
import { readConfig, writeConfig } from "../../config.js";
export function toggleMcpDisabled(action: "disable" | "enable", name: string): string {
const trimmed = name.trim();
if (!trimmed) {
return `usage: /mcp ${action} <name> · pick a name shown in /mcp (anonymous servers can't be named-toggled).`;
}
const cfg = readConfig();
const current = new Set(cfg.mcpDisabled ?? []);
if (action === "disable") {
if (current.has(trimmed)) {
return `▸ ${trimmed} is already disabled — restart to apply, or /mcp enable ${trimmed}.`;
}
current.add(trimmed);
writeConfig({ ...cfg, mcpDisabled: [...current].sort() });
return `▸ ${trimmed} disabled — takes effect on next launch. /mcp enable ${trimmed} to revert.`;
}
if (!current.has(trimmed)) {
return `▸ ${trimmed} is not disabled.`;
}
current.delete(trimmed);
writeConfig({ ...cfg, mcpDisabled: current.size > 0 ? [...current].sort() : undefined });
return `▸ ${trimmed} re-enabled — takes effect on next launch.`;
}
+21
View File
@@ -0,0 +1,21 @@
import { COLOR } from "./theme.js";
export interface HealthBadge {
glyph: string;
label: string;
color: string;
}
export function healthBadge(elapsedMs: number): HealthBadge {
if (elapsedMs === 0) return { glyph: "✗", label: "no inspect data", color: COLOR.err };
if (elapsedMs < 500) return { glyph: "●", label: `healthy · ${elapsedMs}ms`, color: COLOR.ok };
if (elapsedMs < 3000) return { glyph: "◌", label: `slow · ${elapsedMs}ms`, color: COLOR.warn };
return { glyph: "✗", label: `very slow · ${elapsedMs}ms`, color: COLOR.err };
}
// Preserves original slash thresholds: 0 → "● healthy · 0ms" (no === 0 branch)
export function slashHealthBadge(elapsedMs: number): string {
if (elapsedMs < 500) return `● healthy · ${elapsedMs}ms`;
if (elapsedMs < 3000) return `◌ slow · ${elapsedMs}ms`;
return `✗ very slow · ${elapsedMs}ms`;
}
+4 -1
View File
@@ -11,13 +11,15 @@ export type McpLifecycleEvent =
ms: number;
}
| { state: "failed"; name: string; reason: string }
| { state: "disabled"; name: string };
| { state: "disabled"; name: string }
| { state: "reconnect"; name: string };
const STATE: Record<McpLifecycleEvent["state"], { glyph: string; label: string }> = {
handshake: { glyph: "↻", label: "handshake…" },
connected: { glyph: "✓", label: "connected" },
failed: { glyph: "✖", label: "failed" },
disabled: { glyph: "○", label: "disabled" },
reconnect: { glyph: "↻", label: "reconnect…" },
};
const NAME_COL = 22;
@@ -35,6 +37,7 @@ function describeDetail(ev: McpLifecycleEvent): string {
if (ev.state === "handshake") return "initialise → tools/list → resources/list";
if (ev.state === "failed") return ev.reason;
if (ev.state === "disabled") return `via /mcp disable ${ev.name}`;
if (ev.state === "reconnect") return "tearing down · re-handshake · listing tools";
const parts: string[] = [`${ev.tools} tools`];
if (ev.resources && ev.resources > 0) parts.push(`${ev.resources} resources`);
if (ev.prompts && ev.prompts > 0) parts.push(`${ev.prompts} prompts`);
+68
View File
@@ -0,0 +1,68 @@
/** Shared async-fire-and-forget reconnect trigger — called by both `/mcp reconnect` and the McpBrowser `r` keybind. */
import { reconnectMcpServer } from "../../mcp/reconnect.js";
import type { McpTool } from "../../mcp/types.js";
import { formatMcpLifecycleEvent } from "./mcp-lifecycle.js";
import type { McpServerSummary } from "./slash/types.js";
/** Applies append-drift mid-session: registers each new MCP tool in the registry + prefix. Returns the updated summary. */
export type ApplyAppend = (target: McpServerSummary, addedTools: McpTool[]) => McpServerSummary;
/** Kicks off async reconnect; returns the start-line, schedules result via postInfo. */
export function kickOffMcpReconnect(
target: McpServerSummary,
postInfo: (text: string) => void,
applyAppend?: ApplyAppend,
): string {
const beforeTools = target.report.tools.supported ? target.report.tools.items : [];
// Only opt into "append" when the caller wired an applyAppend handler;
// otherwise the reconnect refuses append-drift with a "restart" message.
const accept = applyAppend ? (["identity", "append"] as const) : (["identity"] as const);
// Use a mutable local so the async closure can update it after applyAppend
// without reassigning the function parameter (linter: noParameterAssign).
let liveTarget = target;
void (async () => {
try {
const result = await reconnectMcpServer({
host: liveTarget.host,
spec: liveTarget.spec,
beforeTools,
accept,
});
if (result.ok) {
if (result.kind === "append" && applyAppend) {
liveTarget = applyAppend(liveTarget, result.addedTools);
}
postInfo(
formatMcpLifecycleEvent({
state: "connected",
name: target.label,
tools: result.afterTools.length,
ms: result.ms,
}),
);
if (result.kind === "append") {
const names = result.addedTools.map((t) => t.name).join(", ");
postInfo(`▸ ${target.label}: added ${result.addedTools.length} tool(s) — ${names}`);
}
} else {
postInfo(
formatMcpLifecycleEvent({
state: "failed",
name: target.label,
reason: `${result.reason} · ${result.message}`,
}),
);
}
} catch (err) {
postInfo(
formatMcpLifecycleEvent({
state: "failed",
name: target.label,
reason: (err as Error).message,
}),
);
}
})();
return formatMcpLifecycleEvent({ state: "reconnect", name: target.label });
}
+13
View File
@@ -0,0 +1,13 @@
import type { McpServerSummary } from "./slash/types.js";
export function sameMcpServerSummary(a: McpServerSummary, b: McpServerSummary): boolean {
return a === b || (a.label === b.label && a.spec === b.spec);
}
export function replaceMcpServerSummary(
servers: McpServerSummary[],
target: McpServerSummary,
updated: McpServerSummary,
): McpServerSummary[] {
return servers.map((server) => (sameMcpServerSummary(server, target) ? updated : server));
}
+39 -6
View File
@@ -16,6 +16,8 @@ export interface MultilineKey {
escape?: boolean;
pageUp?: boolean;
pageDown?: boolean;
home?: boolean;
end?: boolean;
}
export interface MultilineAction {
@@ -98,12 +100,12 @@ export function processMultilineKey(
return moved === cursor ? NOOP : { next: null, cursor: moved, submit: false };
}
// Emacs-style line jumps (universal across terminals; Home/End aren't
// reliably reported by Ink so we don't depend on them).
if (key.ctrl && key.input === "a") {
// Emacs-style line jumps. Home/End come through our own stdin reader
// (see stdin-reader.ts CSI_TAIL_MAP); Ctrl+A/E stay as universal aliases.
if ((key.ctrl && key.input === "a") || key.home) {
return { next: null, cursor: startOfLine(value, cursor), submit: false };
}
if (key.ctrl && key.input === "e") {
if ((key.ctrl && key.input === "e") || key.end) {
return { next: null, cursor: endOfLine(value, cursor), submit: false };
}
// Bash / readline conventions:
@@ -111,11 +113,25 @@ export function processMultilineKey(
// "clear from cursor to start"; for our text-area we treat it
// as "clear all" because there's no ergonomic way to clear a
// huge paste otherwise).
// Ctrl+W — delete the word before the cursor.
// Ctrl+K — kill from cursor to end of current line.
// Ctrl+W / Alt+Backspace — delete the word before the cursor.
// Alt+B / Alt+F — jump cursor backward / forward by one word.
if (key.ctrl && key.input === "u") {
return value.length === 0 ? NOOP : { next: "", cursor: 0, submit: false };
}
if (key.ctrl && key.input === "w") {
if (key.ctrl && key.input === "k") {
const lineEnd = endOfLine(value, cursor);
if (lineEnd === cursor) return NOOP;
return {
next: value.slice(0, cursor) + value.slice(lineEnd),
cursor,
submit: false,
};
}
if (
(key.ctrl && key.input === "w") ||
(key.meta && (key.backspace || key.input === "\x7f" || key.input === "\b"))
) {
if (cursor === 0) return NOOP;
const wordStart = previousWordStart(value, cursor);
return {
@@ -124,6 +140,14 @@ export function processMultilineKey(
submit: false,
};
}
if (key.meta && key.input === "b") {
const target = previousWordStart(value, cursor);
return target === cursor ? NOOP : { next: null, cursor: target, submit: false };
}
if (key.meta && key.input === "f") {
const target = nextWordEnd(value, cursor);
return target === cursor ? NOOP : { next: null, cursor: target, submit: false };
}
// Paste-burst detection. If `input` contains a newline (or
// bracketed-paste markers from a terminal that supports them),
@@ -239,6 +263,15 @@ function previousWordStart(value: string, cursor: number): number {
return i;
}
/** Symmetric to previousWordStart: skip leading whitespace, then run to next word boundary. */
function nextWordEnd(value: string, cursor: number): number {
let i = cursor;
const n = value.length;
while (i < n && /\s/.test(value[i] ?? "")) i++;
while (i < n && !/\s/.test(value[i] ?? "")) i++;
return i;
}
function endOfLine(value: string, cursor: number): number {
const nl = value.indexOf("\n", cursor);
return nl === -1 ? value.length : nl;
-50
View File
@@ -1,50 +0,0 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { STRUCT } from "../cards/glyphs.js";
import { CARD, type CardTone } from "../theme/tokens.js";
import { useTick } from "../ticker.js";
export interface BarRowProps {
tone: CardTone;
glyph?: string;
glyphBold?: boolean;
indent?: 0 | 3;
children?: React.ReactNode;
}
export function BarRow({
tone,
glyph,
glyphBold = true,
indent = 3,
children,
}: BarRowProps): React.ReactElement {
const t = CARD[tone];
return (
<Box flexDirection="row">
<Text>{" "}</Text>
<Text color={t.color}>{STRUCT.bar}</Text>
{glyph !== undefined ? (
<Text bold={glyphBold} color={t.color}>
{" "}
{glyph}
{indent === 3 ? " " : " "}
</Text>
) : indent > 0 ? (
<Text>{" ".repeat(indent + 1)}</Text>
) : null}
{children}
</Box>
);
}
export function CursorBlock(): React.ReactElement {
const tick = useTick();
const on = Math.floor(tick / 4) % 2 === 0;
return (
<Text inverse={on} color={CARD.streaming.color}>
{" "}
</Text>
);
}
+48
View File
@@ -0,0 +1,48 @@
import { Box } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React, { useContext } from "react";
/** Settled cards (in scrollback) drop the border + paddingX so history reads as flat lines. */
export const ActiveCardContext = React.createContext(true);
export interface CardProps {
tone: string;
children: React.ReactNode;
}
const STRIPE_BORDER = {
topLeft: " ",
top: " ",
topRight: " ",
left: "▎",
right: " ",
bottomLeft: " ",
bottom: " ",
bottomRight: " ",
} as const;
export function Card({ tone, children }: CardProps): React.ReactElement {
const active = useContext(ActiveCardContext);
if (!active) {
return (
<Box flexDirection="column" marginTop={1}>
{children}
</Box>
);
}
return (
<Box
flexDirection="column"
borderStyle={STRIPE_BORDER}
borderColor={tone}
borderTop={false}
borderRight={false}
borderBottom={false}
paddingLeft={1}
marginTop={1}
width="100%"
>
{children}
</Box>
);
}
+62
View File
@@ -0,0 +1,62 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { FG } from "../theme/tokens.js";
export type MetaItem = string | { text: string; color: string };
export interface CardHeaderProps {
glyph: string;
tone: string;
title: string;
/** Override the default tone-colored bold title (e.g. demoted cards use FG.sub). */
titleColor?: string;
/** When set, render the title as a backgrounded pill (e.g. `▎ ◆ reasoning ` with a tinted block). */
titleBg?: string;
/** Body-tone text after the title, separated by a space (no `·`). */
subtitle?: string;
/** Faint trailing fields, prefixed with ` · ` and joined by ` · `. */
meta?: ReadonlyArray<MetaItem>;
/** Inline ad-hoc element after meta — for spinners, badges, anything outside the meta vocabulary. */
right?: React.ReactNode;
}
export function CardHeader({
glyph,
tone,
title,
titleColor,
titleBg,
subtitle,
meta,
right,
}: CardHeaderProps): React.ReactElement {
return (
<Box flexDirection="row" gap={1}>
<Text color={tone}>{glyph}</Text>
{titleBg ? (
<Text backgroundColor={titleBg} color={titleColor ?? tone} bold>
{` ${title} `}
</Text>
) : (
<Text bold color={titleColor ?? tone}>
{title}
</Text>
)}
{subtitle ? <Text color={FG.body}>{subtitle}</Text> : null}
{meta?.map((item, i) => {
const isStr = typeof item === "string";
const text = isStr ? item : item.text;
const color = isStr ? FG.faint : item.color;
return (
// biome-ignore lint/suspicious/noArrayIndexKey: meta items are positional
<React.Fragment key={`m-${i}`}>
<Text color={FG.faint}>·</Text>
<Text color={color}>{text}</Text>
</React.Fragment>
);
})}
{right}
</Box>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { CARD } from "../theme/tokens.js";
import { useTick } from "../ticker.js";
export function CursorBlock(): React.ReactElement {
const tick = useTick();
const on = Math.floor(tick / 4) % 2 === 0;
return (
<Text inverse={on} color={CARD.streaming.color}>
{" "}
</Text>
);
}
+52
View File
@@ -0,0 +1,52 @@
/** Bg-tinted inline chip — section labels (REASONING / TASK / TOOL) and badges (model / path). */
import { Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
export interface PillProps {
label: string;
bg: string;
fg: string;
bold?: boolean;
}
export function Pill({ label, bg, fg, bold = true }: PillProps): React.ReactElement {
return <Text backgroundColor={bg} color={fg} bold={bold}>{` ${label} `}</Text>;
}
/** Section pill bg tints — muted accent-of-card-tone, paired with the tone's fg. */
export const PILL_SECTION = {
reason: { bg: "#2a1f3d", fg: "#d2a8ff" },
output: { bg: "#0d1d2e", fg: "#79c0ff" },
tool: { bg: "#0f2230", fg: "#79c0ff" },
shell: { bg: "#0f2230", fg: "#79c0ff" },
task: { bg: "#0d1d2e", fg: "#79c0ff" },
taskDone: { bg: "#102815", fg: "#7ee787" },
taskFailed: { bg: "#2c1416", fg: "#ff8b81" },
plan: { bg: "#2a1f3d", fg: "#d2a8ff" },
user: { bg: "#11141a", fg: "#8b949e" },
} as const;
/** Model pill — neutral bg, color signals model class. */
export const PILL_MODEL = {
flash: { bg: "#11141a", fg: "#79c0ff" },
pro: { bg: "#11141a", fg: "#d2a8ff" },
r1: { bg: "#11141a", fg: "#b395f5" },
unknown: { bg: "#11141a", fg: "#8b949e" },
} as const;
export interface ModelBadge {
label: string;
kind: keyof typeof PILL_MODEL;
}
/** Map full DeepSeek model id to short label + color class. */
export function modelBadgeFor(model: string | undefined): ModelBadge {
if (!model) return { label: "?", kind: "unknown" };
const stripped = model.replace(/^deepseek-/, "");
if (stripped === "v4-flash" || stripped === "chat") return { label: "v4-flash", kind: "flash" };
if (stripped === "v4-pro") return { label: "v4-pro", kind: "pro" };
if (stripped === "r1" || stripped === "reasoner") return { label: "r1", kind: "r1" };
return { label: stripped, kind: "unknown" };
}
+8 -8
View File
@@ -47,6 +47,12 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
"session USD cap — warns at 80%, refuses next turn at 100%. Off by default. /budget alone shows status",
argCompleter: ["off", "1", "5", "10", "20", "50"],
},
{
cmd: "language",
argsHint: "<EN|zh-CN>",
summary: "switch the runtime language",
argCompleter: ["EN", "zh-CN"],
},
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
{
cmd: "resource",
@@ -113,12 +119,12 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
{
cmd: "compact",
argsHint: "[tokens]",
summary:
"shrink oversized tool results AND tool-call args (edit_file search/replace) in the log; cap in tokens, default 4000",
"fold older turns into a summary message (cache-safe). Auto-fires at 50% ctx; this is the manual trigger.",
},
{ cmd: "keys", summary: "show all keyboard shortcuts and prompt prefixes" },
{ cmd: "plans", summary: "list this session's active + archived plans, newest first" },
{ cmd: "stop", summary: "abort the current model turn (typed alternative to Esc)" },
{
cmd: "replay",
summary: "load an archived plan as a read-only Time Travel snapshot (default: newest)",
@@ -132,12 +138,6 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
summary: "show the launch command to resume a saved session",
},
{ cmd: "forget", summary: "delete the current session from disk" },
{
cmd: "prune-sessions",
summary: "delete sessions idle ≥N days (default 90) — frees disk on long-time installs",
argsHint: "[days]",
},
{ cmd: "setup", summary: "reminds you to exit and run `reasonix setup`" },
{
cmd: "semantic",
summary: "show semantic_search status — built? Ollama installed? how to enable",
+2
View File
@@ -5,6 +5,7 @@ import { handlers as dashboardHandlers } from "./handlers/dashboard.js";
import { handlers as editsHandlers } from "./handlers/edits.js";
import { handlers as initHandlers } from "./handlers/init.js";
import { handlers as jobsHandlers } from "./handlers/jobs.js";
import { handlers as languageHandlers } from "./handlers/language.js";
import { handlers as mcpHandlers } from "./handlers/mcp.js";
import { handlers as memoryHandlers } from "./handlers/memory.js";
import { handlers as modelHandlers } from "./handlers/model.js";
@@ -26,6 +27,7 @@ const HANDLERS: Record<string, SlashHandler> = {
...editsHandlers,
...initHandlers,
...jobsHandlers,
...languageHandlers,
...mcpHandlers,
...memoryHandlers,
...modelHandlers,
+36 -41
View File
@@ -5,23 +5,23 @@ import {
globalSettingsPath,
projectSettingsPath,
} from "../../../../hooks.js";
import { t } from "../../../../i18n/index.js";
import { aggregateUsage, defaultUsageLogPath, readUsageLog } from "../../../../telemetry/usage.js";
import { VERSION, compareVersions, isNpxInstall } from "../../../../version.js";
import { runDoctorChecks } from "../../../commands/doctor.js";
import { renderDashboard } from "../../../commands/stats.js";
import type { SlashHandler } from "../dispatch.js";
/** Async via postDoctor — slash dispatch is sync, doctor checks aren't. */
const doctor: SlashHandler = (_args, _loop, ctx) => {
const root = ctx.codeRoot ?? process.cwd();
if (!ctx.postDoctor) return { info: "/doctor needs a TUI context (postDoctor wired)." };
if (!ctx.postDoctor) return { info: t("handlers.admin.doctorNeedsTui") };
void (async () => {
const checks = await runDoctorChecks(root);
ctx.postDoctor!(
checks.map((c) => ({ label: c.label.trim(), level: c.level, detail: c.detail })),
);
})();
return { info: "⚕ Doctor — running health checks…" };
return { info: t("handlers.admin.doctorRunning") };
};
const hooks: SlashHandler = (args, loop, ctx) => {
@@ -29,18 +29,14 @@ const hooks: SlashHandler = (args, loop, ctx) => {
if (sub === "reload") {
if (!ctx.reloadHooks) {
return {
info: "/hooks reload is not available in this context (no reload callback wired).",
};
return { info: t("handlers.admin.hooksReloadUnavailable") };
}
const count = ctx.reloadHooks();
return { info: `▸ reloaded hooks · ${count} active` };
return { info: t("handlers.admin.hooksReloaded", { count }) };
}
if (sub !== "" && sub !== "list" && sub !== "ls") {
return {
info: "usage: /hooks list active hooks\n /hooks reload re-read settings.json files",
};
return { info: t("handlers.admin.hooksUsage") };
}
const all = loop.hooks;
@@ -48,16 +44,16 @@ const hooks: SlashHandler = (args, loop, ctx) => {
const globPath = globalSettingsPath();
if (all.length === 0) {
const lines = [
"no hooks configured.",
t("handlers.admin.hooksNone"),
"",
"drop a settings.json with a `hooks` key into either of:",
t("handlers.admin.hooksDropHint"),
ctx.codeRoot
? ` · ${projPath} (project)`
: " · <project>/.reasonix/settings.json (project)",
` · ${globPath} (global)`,
? t("handlers.admin.hooksProject", { path: projPath! })
: t("handlers.admin.hooksProjectFallback"),
t("handlers.admin.hooksGlobal", { path: globPath }),
"",
"events: PreToolUse, PostToolUse, UserPromptSubmit, Stop",
"exit 0 = pass · exit 2 = block (Pre*) · other = warn",
t("handlers.admin.hooksEvents"),
t("handlers.admin.hooksExitCodes"),
];
return { info: lines.join("\n") };
}
@@ -66,7 +62,7 @@ const hooks: SlashHandler = (args, loop, ctx) => {
for (const event of HOOK_EVENTS) grouped.set(event, []);
for (const h of all) grouped.get(h.event)?.push(h);
const lines: string[] = [`▸ ${all.length} hook(s) loaded`];
const lines: string[] = [t("handlers.admin.hooksLoaded", { count: all.length })];
for (const event of HOOK_EVENTS) {
const list = grouped.get(event) ?? [];
if (list.length === 0) continue;
@@ -77,47 +73,46 @@ const hooks: SlashHandler = (args, loop, ctx) => {
lines.push(` [${h.scope}]${match} ${h.command}${desc}`);
}
}
lines.push("", `sources: project=${projPath ?? "(none — chat mode)"} · global=${globPath}`);
lines.push(
"",
t("handlers.admin.hooksSources", {
project: projPath ?? "(none — chat mode)",
global: globPath,
}),
);
return { info: lines.join("\n") };
};
/** No in-TUI npm spawn — stdio:inherit corrupts Ink and Windows locks the running binary. */
const update: SlashHandler = (_args, _loop, ctx) => {
const latest = ctx.latestVersion ?? null;
const lines: string[] = [`current: reasonix ${VERSION}`];
const lines: string[] = [t("handlers.admin.updateCurrent", { version: VERSION })];
if (latest === null) {
// Kick off a fresh fetch so a follow-up /update a few seconds
// later has a real answer instead of the same pending message.
ctx.refreshLatestVersion?.();
lines.push(
"latest: (not yet resolved — background check in flight or offline)",
t("handlers.admin.updateLatestPending"),
"",
"triggered a fresh registry fetch — retry `/update` in a few seconds,",
"or run `reasonix update` in another terminal to force it synchronously.",
t("handlers.admin.updateRetryHint"),
t("handlers.admin.updateRetryHint2"),
);
return { info: lines.join("\n") };
}
lines.push(`latest: reasonix ${latest}`);
lines.push(t("handlers.admin.updateLatest", { version: latest }));
const diff = compareVersions(VERSION, latest);
if (diff >= 0) {
lines.push("", "you're on the latest. nothing to do.");
lines.push("", t("handlers.admin.updateUpToDate"));
return { info: lines.join("\n") };
}
if (isNpxInstall()) {
lines.push(
"",
"you're running via npx — the next `npx reasonix ...` launch will auto-fetch.",
"to force a refresh sooner: `npm cache clean --force`.",
);
lines.push("", t("handlers.admin.updateNpxHint"), t("handlers.admin.updateNpxForce"));
} else {
lines.push(
"",
"to upgrade, exit this session and run:",
" reasonix update (interactive, dry-run supported via --dry-run)",
" npm install -g reasonix@latest (direct)",
t("handlers.admin.updateUpgradeHint"),
t("handlers.admin.updateUpgradeCmd1"),
t("handlers.admin.updateUpgradeCmd2"),
"",
"in-session install is deliberately disabled — the npm spawn would",
"corrupt this TUI's rendering and Windows can lock the running binary.",
t("handlers.admin.updateInSessionDisabled"),
t("handlers.admin.updateInSessionDisabled2"),
);
}
return { info: lines.join("\n") };
@@ -129,12 +124,12 @@ const stats: SlashHandler = () => {
if (records.length === 0) {
return {
info: [
"no usage data yet.",
t("handlers.admin.statsNoData"),
"",
` ${path}`,
"",
"every turn you run here appends one record — this session's turns",
"will show up in the dashboard once you send a message.",
t("handlers.admin.statsEveryTurn"),
t("handlers.admin.statsWillAppear"),
].join("\n"),
};
}
+119 -137
View File
@@ -1,3 +1,4 @@
import { t } from "../../../../i18n/index.js";
import { formatDuration, formatLoopStatus, parseLoopCommand } from "../../loop.js";
import type { SlashHandler } from "../dispatch.js";
@@ -5,175 +6,161 @@ const exit: SlashHandler = () => ({ exit: true });
const clear: SlashHandler = () => ({
clear: true,
info: "▸ terminal cleared (viewport + scrollback). Context (message log) is intact — next turn still sees everything. Use /new to start fresh, or /forget to delete the session entirely.",
info: t("handlers.basic.clearInfo"),
});
const resetLog: SlashHandler = (_args, loop) => {
// Actually drop the in-memory log + rewrite the session file so the
// NEXT call has no prior context. Keeps session name, model, and
// other config — just the conversation is reset.
const { dropped } = loop.clearLog();
return {
clear: true,
info: `▸ new conversation — dropped ${dropped} message(s) from context. Same session, fresh slate.`,
info: t("handlers.basic.newInfo", { count: dropped }),
};
};
const keys: SlashHandler = () => ({
info: [
"Keyboard & prompt shortcuts:",
t("handlers.basic.keysTitle"),
"",
" Enter submit the current prompt",
" Shift+Enter / Ctrl+J insert a newline (multi-line prompt)",
" \\<Enter> bash-style line continuation",
" ← → ↑ ↓ move cursor / recall history at buffer boundary",
" PageUp / PageDown jump to top / bottom of the WHOLE buffer (handy after a big paste)",
" Ctrl+A / Ctrl+E jump to start / end of the CURRENT line",
" Ctrl+U clear the entire input buffer",
" Ctrl+W delete the word before the cursor",
" Backspace delete left; Delete delete under cursor",
" Esc abort the in-flight turn",
" y / n accept / reject pending edits (code mode)",
" Shift+Tab cycle edit gate: review ↔ AUTO (code mode, persists to config)",
" u undo the latest non-undone edit batch (session-wide, not just banner)",
t("handlers.basic.keysEnter"),
t("handlers.basic.keysNewline"),
t("handlers.basic.keysContinue"),
t("handlers.basic.keysArrow"),
t("handlers.basic.keysPage"),
t("handlers.basic.keysHomeEnd"),
t("handlers.basic.keysClearLine"),
t("handlers.basic.keysDeleteWord"),
t("handlers.basic.keysBackspace"),
t("handlers.basic.keysEsc"),
t("handlers.basic.keysEditYn"),
t("handlers.basic.keysEditTab"),
t("handlers.basic.keysEditUndo"),
"",
"Prompt prefixes:",
" /<name> slash command; Tab/Enter picks from the suggestion list",
" @<path> inline a file under [Referenced files] (code mode).",
" Trailing `@…` opens a file picker; ↑/↓ navigate, Tab/Enter pick.",
" @https://... fetch the URL, strip HTML, inline under [Referenced URLs].",
" Cached per session — same URL twice fetches once.",
" !<cmd> run <cmd> as shell in the sandbox root; output goes into context",
" so the model sees it next turn. No allowlist gate.",
" #<note> append <note> to <project>/REASONIX.md (committable, team-shared).",
" #g <note> append <note> to ~/.reasonix/REASONIX.md (global, never committed).",
" Both pin into the immutable prefix every future session.",
" Use `\\#literal` if you actually want a `#` heading sent to the model.",
t("handlers.basic.keysPromptTitle"),
t("handlers.basic.keysSlash"),
t("handlers.basic.keysAtFile"),
t("handlers.basic.keysAtFilePicker"),
t("handlers.basic.keysAtUrl"),
t("handlers.basic.keysAtUrlCache"),
t("handlers.basic.keysBang"),
t("handlers.basic.keysBangDetail"),
t("handlers.basic.keysHash"),
t("handlers.basic.keysHashGlobal"),
t("handlers.basic.keysHashBoth"),
t("handlers.basic.keysHashEscape"),
"",
"Pickers (slash + @-mention):",
" ↑ / ↓ navigate the suggestion list",
" Tab insert the highlighted item without submitting",
" Enter insert and (slash) run it, (@) keep editing",
t("handlers.basic.keysPickersTitle"),
t("handlers.basic.keysPickerNav"),
t("handlers.basic.keysPickerTab"),
t("handlers.basic.keysPickerEnter"),
"",
"MCP exploration:",
" /mcp servers + tool/resource/prompt counts",
" /resource [uri] browse & read resources exposed by your MCP servers",
" /prompt [name] browse & fetch prompts exposed by your MCP servers",
t("handlers.basic.keysMcpTitle"),
t("handlers.basic.keysMcpServers"),
t("handlers.basic.keysMcpResource"),
t("handlers.basic.keysMcpPrompt"),
"",
"Useful slashes: /help · /context · /stats · /compact · /new · /exit",
t("handlers.basic.keysUseful"),
].join("\n"),
});
const help: SlashHandler = () => ({
info: [
"Commands:",
" /help this message",
" /keys keyboard shortcuts + prompt prefixes (!, @, /)",
" /status show current settings",
" /preset <auto|flash|pro> model bundle — see below",
" /model <id> deepseek-v4-flash or deepseek-v4-pro",
" /pro [off] arm v4-pro for NEXT turn only (one-shot, auto-disarms)",
" /harvest [on|off] Pillar 2: structured plan-state extraction (OPT-IN — costs extra)",
" /branch <N|off> run N parallel samples (N>=2) — MANUAL ONLY, N× cost",
" /effort <high|max> reasoning_effort cap (max=full thinking, high=cheaper/faster)",
" /mcp list MCP servers + tools attached to this session",
" /resource [uri] browse + read MCP resources (no arg → list URIs; <uri> → fetch)",
" /prompt [name] browse + fetch MCP prompts (no arg → list names; <name> → render)",
" /setup (exit + reconfigure) → run `reasonix setup`",
" /compact [tokens] shrink large tool results in history (default 4000 tokens/result)",
" /think dump the most recent turn's full R1 reasoning (reasoner only)",
" /tool [N] list tool calls (or dump full output of #N, 1=most recent)",
" /cost [text] bare → last turn's spend; with text → estimate cost of sending it next",
" /memory [sub] show pinned memory (REASONIX.md + ~/.reasonix/memory).",
" subs: list | show <name> | forget <name> | clear <scope> confirm",
" /skill [sub] list / run user skills (project/.reasonix/skills + ~/.reasonix/skills).",
" subs: list | show <name> | <name> [args] (injects skill body as user turn)",
" /retry truncate & resend your last message (fresh sample from the model)",
" /apply [N|1,3|1-4] (code mode) commit pending edit blocks (no arg → all; index → subset)",
" /discard [N|1,3|1-4] (code mode) drop pending edits (no arg → all; index → subset)",
" /walk (code mode) step through pending edits one block at a time (y/n per block, a apply rest, A flip AUTO)",
" /undo (code mode) roll back the latest non-undone edit batch",
" /history (code mode) list every edit batch this session",
" /show [id] (code mode) dump a stored edit diff (newest when id omitted)",
' /commit "msg" (code mode) git add -A && git commit -m "msg"',
" /plan [on|off] (code mode) toggle read-only plan mode; writes gated behind submit_plan + your approval",
" /apply-plan (code mode) force-approve pending/in-text plan (fallback)",
" /mode [review|auto|yolo] (code mode) review = queue · auto = apply+undo banner · yolo = apply+auto-shell. Shift+Tab cycles all three.",
" /jobs (code mode) list background processes (run_background) — running and exited",
" /kill <id> (code mode) stop a background job by id (SIGTERM → SIGKILL)",
" /logs <id> [lines] (code mode) tail a background job's output (default 80 lines)",
" /sessions list saved sessions (current is marked with ▸)",
" /forget delete the current session from disk",
" /new start fresh: drop all context + clear scrollback",
" /clear clear displayed scrollback only (context kept — model still sees it)",
" /loop <interval> <prompt> auto-resubmit <prompt> every <interval> (5s..6h). /loop stop · type anything to cancel.",
" /exit quit",
t("handlers.basic.helpTitle"),
t("handlers.basic.helpHelp"),
t("handlers.basic.helpKeys"),
t("handlers.basic.helpStatus"),
t("handlers.basic.helpPreset"),
t("handlers.basic.helpModel"),
t("handlers.basic.helpPro"),
t("handlers.basic.helpHarvest"),
t("handlers.basic.helpBranch"),
t("handlers.basic.helpEffort"),
t("handlers.basic.helpMcp"),
t("handlers.basic.helpResource"),
t("handlers.basic.helpPrompt"),
t("handlers.basic.helpCompact"),
t("handlers.basic.helpThink"),
t("handlers.basic.helpTool"),
t("handlers.basic.helpCost"),
t("handlers.basic.helpMemory"),
t("handlers.basic.helpMemorySub"),
t("handlers.basic.helpSkill"),
t("handlers.basic.helpSkillSub"),
t("handlers.basic.helpRetry"),
t("handlers.basic.helpApply"),
t("handlers.basic.helpDiscard"),
t("handlers.basic.helpWalk"),
t("handlers.basic.helpUndo"),
t("handlers.basic.helpHistory"),
t("handlers.basic.helpShow"),
t("handlers.basic.helpCommit"),
t("handlers.basic.helpPlan"),
t("handlers.basic.helpApplyPlan"),
t("handlers.basic.helpMode"),
t("handlers.basic.helpJobs"),
t("handlers.basic.helpKill"),
t("handlers.basic.helpLogs"),
t("handlers.basic.helpSessions"),
t("handlers.basic.helpForget"),
t("handlers.basic.helpNew"),
t("handlers.basic.helpClear"),
t("handlers.basic.helpLoop"),
t("handlers.basic.helpExit"),
"",
"Shell shortcut:",
" !<cmd> run <cmd> in the sandbox root; output goes into",
" the conversation so the model sees it next turn.",
" No allowlist gate — user-typed = explicit consent.",
" Example: !git status !ls src/ !npm test",
t("handlers.basic.helpShellTitle"),
t("handlers.basic.helpShell"),
t("handlers.basic.helpShellDetail"),
t("handlers.basic.helpShellConsent"),
t("handlers.basic.helpShellExample"),
"",
"Quick memory:",
" #<note> append <note> to <project>/REASONIX.md (committable).",
" Example: #findByEmail must be case-insensitive",
" #g <note> append <note> to ~/.reasonix/REASONIX.md (global, never committed).",
" Example: #g always run pnpm not npm",
" Both pin into every future session's prefix. Faster than /memory.",
" Use `\\#text` to send a literal `#text` to the model.",
t("handlers.basic.helpMemoryTitle"),
t("handlers.basic.helpMemoryPin"),
t("handlers.basic.helpMemoryPinEx"),
t("handlers.basic.helpMemoryGlobal"),
t("handlers.basic.helpMemoryGlobalEx"),
t("handlers.basic.helpMemoryPinBoth"),
t("handlers.basic.helpMemoryEscape"),
"",
"File references (code mode):",
" @path/to/file inline file content under [Referenced files] on send.",
" Type `@` to open the picker (↑↓ navigate, Tab/Enter pick).",
t("handlers.basic.helpFileTitle"),
t("handlers.basic.helpFile"),
t("handlers.basic.helpFilePicker"),
"",
"URL references:",
" @https://example.com fetch the URL, strip HTML, inline under [Referenced URLs].",
" Same URL twice in one session fetches once (in-mem cache).",
" Trailing sentence punctuation (./,/)) is stripped automatically.",
t("handlers.basic.helpUrlTitle"),
t("handlers.basic.helpUrl"),
t("handlers.basic.helpUrlCache"),
t("handlers.basic.helpUrlPunct"),
"",
"Presets (branch + harvest are NEVER auto-enabled — opt-in only):",
" auto v4-flash → v4-pro on hard turns ← default · cheap when easy, smart when hard",
" flash v4-flash always cheapest · predictable per-turn cost",
" pro v4-pro always ~3× flash (5/31) · hard multi-turn work",
t("handlers.basic.helpPresetsTitle"),
t("handlers.basic.helpPresetAuto"),
t("handlers.basic.helpPresetFlash"),
t("handlers.basic.helpPresetPro"),
"",
"Sessions (auto-enabled by default, named 'default'):",
" reasonix chat --session <name> use a different named session",
" reasonix chat --no-session disable persistence for this run",
t("handlers.basic.helpSessionsTitle"),
t("handlers.basic.helpSessionCustom"),
t("handlers.basic.helpSessionNone"),
"",
"Known limitation:",
" Resizing the terminal mid-session may stack ghost header frames in",
" scrollback (Ink library's live-region clear doesn't account for line",
" re-wrapping at the new width). Scroll-up history is unaffected; the",
" artifact is purely visual and clears the next time you /clear.",
t("handlers.basic.helpLimitationTitle"),
t("handlers.basic.helpLimitation1"),
t("handlers.basic.helpLimitation2"),
t("handlers.basic.helpLimitation3"),
t("handlers.basic.helpLimitation4"),
].join("\n"),
});
const setup: SlashHandler = () => ({
info:
"To reconfigure (preset, MCP servers, API key), exit this chat and run " +
"`reasonix setup`. Changes take effect on next launch.",
});
const retry: SlashHandler = (_args, loop) => {
const prev = loop.retryLastUser();
if (!prev) {
return {
info: "nothing to retry — no prior user message in this session's log.",
};
return { info: t("handlers.basic.retryNone") };
}
const preview = prev.length > 80 ? `${prev.slice(0, 80)}…` : prev;
return {
info: `▸ retrying: "${preview}"`,
info: t("handlers.basic.retryInfo", { preview }),
resubmit: prev,
};
};
const loop: SlashHandler = (args, _loop, ctx) => {
if (!ctx.startLoop || !ctx.stopLoop || !ctx.getLoopStatus) {
return {
info: "/loop is only available in the interactive TUI (not in run/replay).",
};
return { info: t("handlers.basic.loopTuiOnly") };
}
const cmd = parseLoopCommand(args);
if (cmd.kind === "error") return { info: cmd.message };
@@ -181,26 +168,22 @@ const loop: SlashHandler = (args, _loop, ctx) => {
const wasActive = ctx.getLoopStatus() !== null;
ctx.stopLoop();
return {
info: wasActive ? "▸ loop stopped." : "no active loop to stop.",
info: wasActive ? t("handlers.basic.loopStopped") : t("handlers.basic.loopNoActive"),
};
}
if (cmd.kind === "status") {
const status = ctx.getLoopStatus();
if (!status) {
return {
info:
"no active loop. Start one with `/loop <interval> <prompt>` (e.g. /loop 30s npm test).\n" +
"Cancels on: /loop stop · Esc · /clear · /new · any user-typed prompt.",
};
return { info: t("handlers.basic.loopNoActiveHint") };
}
return { info: `▸ ${formatLoopStatus(status.prompt, status.nextFireMs, status.iter)}` };
}
// kind === "start"
ctx.startLoop(cmd.intervalMs, cmd.prompt);
return {
info: `▸ loop started — re-submitting "${cmd.prompt}" every ${formatDuration(
cmd.intervalMs,
)}. Type anything (or /loop stop) to cancel.`,
info: t("handlers.basic.loopStarted", {
prompt: cmd.prompt,
duration: formatDuration(cmd.intervalMs),
}),
};
};
@@ -213,7 +196,6 @@ export const handlers: Record<string, SlashHandler> = {
keys,
help,
"?": help,
setup,
retry,
loop,
};
Loaded 100 of 259 files, more files were not shown because too many files have changed in this diff. Show more