The CI sync step failed on v0.43.0 because the release commit had
already bumped Cargo.toml to the target version. The old guard fired
on `nextCargo === cargoToml` — true both when the regex didn't match
AND when the value was already correct. Switch to checking whether
the version line exists at all; re-syncing to the same value is
legitimate.
Co-authored-by: test <[email protected]>
Today a skill_run dispatches via the palette and the user sees nothing
until the assistant response streams — no signal that "a skill kicked
this off" vs "a regular long turn." Closes#882.
Add two surfaces, both driven by client-side state (no protocol
churn):
1. Live status row — `InterruptBar` now reads `state.activeSkill` and
labels itself `Skill · <name>` instead of `Reasoning` for the
duration of the turn, with the same elapsed timer + esc-to-stop
affordance.
2. User-message card chip — the synthetic user card injected by
`start_skill` carries a `skill: { name, runAs }` field. `UserMsg`
renders a warning-toned `/name` chip in the header (plus a
subagent micro-badge when `runAs === "subagent"`).
State:
- `activeSkill: SkillOrigin | null` on `State`; set by `start_skill`,
cleared on `$turn_complete`, `clear`, `$session_loaded`, `error`,
and `rpc_exit`.
- `start_skill` action also pushes a user-card row tagged with the
skill, so the thread now shows `/skillname` instead of being silent
until the assistant replies.
No backend changes — `$turn_complete` is the natural cleanup signal,
no new event types needed.
Co-authored-by: test <[email protected]>
The sidebar's per-workspace session filter compared paths via strict
`===` against `meta.workspace`. On Windows that's fragile — drive
letter case, separator style (`\` vs `/`), and trailing slashes drift
between session writes and reads, so yesterday's sessions silently
disappeared from today's sidebar even though the .jsonl files were
still on disk.
Add `normalizeWorkspace` that resolves and canonicalizes the path
before comparison (forward-slash separators, lowercase drive letter
on win32). Apply on both sides of the filter so sessions whose meta
was written before this fix recover automatically — no migration
needed.
Sessions with no `meta.workspace` stay hidden, same as before;
resume by name still works.
Closes#878
Co-authored-by: test <[email protected]>
The slash command popup hard-coded 9 built-in actions and never
folded in the user's `~/.reasonix/skills` and `.reasonix/skills`
entries — typing `/myskill` produced "no matches" even though the
skill loaded fine and showed up in the Skills tab. Skills also had
no execution path on the desktop side at all: `user_input` ships
text straight to the model loop, so a typed `/skill_name` reached
the model as plain text rather than triggering the skill.
- Add a `skill_run` RPC to the desktop protocol.
- Bridge handler resolves the skill via `SkillStore`, builds the
same `# Skill: <name>\n> <desc>\n\n<body>` payload the CLI uses,
and feeds it through `runTurn` so the skill enters the
conversation as user-authored content.
- `App.tsx` merges `state.skills` into `slashCommands` so each
user-authored skill shows up in the popup with its description
and an invocation handler that fires `skill_run`.
Issue #854 also asked for a "skill is running" indicator. That's a
separate UX surface (status row / live row) and lands separately.
Closes#854 (autocomplete half) — follow-up issue for the indicator.
`/api/plans` walked every session via `listSessions()` (which calls
`countLines()` on every `.jsonl`) and then `listPlanArchives(name)`
per session (which re-scanned the same directory each time). On a
real developer machine with hundreds of sessions and large JSONL
files the handler ran past the 5s test timeout and got flagged in
CI as flaky.
Replace the per-session loop with a single dir-scan helper —
`listAllPlanArchives()` in `plan-store.ts` — that derives the
session name from the archive filename. The dashboard plans
handler now does O(N) work over plan-archive files instead of
O(sessions × archives) over the full session corpus.
Confirmed locally: full test suite drops from intermittent timeouts
to consistently green.
Co-authored-by: test <[email protected]>
Two follow-ups to #877 plus a long-standing typecheck cleanup:
Font family — sans / system / serif segmented control under appearance.
Driven by a new `--font-sans` CSS variable on the root element;
styles.css and the inline `IBM Plex Sans` reference in App.tsx now
read through `var(--font-sans, ...)`. Mono is left hardcoded so code
blocks and transcripts stay monospace either way.
Language — promote the existing `/lang` palette command into a 中文 /
English segmented control in the same section. Reads `useLang()` and
writes through `setLang()`; the slash command keeps working.
i18n cleanup — add the long-missing `contextPanel`, `extraCards`,
and `thread` namespaces (en + zh-CN). These keys were referenced in
code but absent from the dictionaries, surfacing as 8 TKey errors in
every `tsc --noEmit` run.
All settings persist in localStorage like theme and font-scale.
Co-authored-by: test <[email protected]>
The API key + base URL inputs in settings were gated behind
`settings.baseUrl !== undefined` — so first-time users with no base
URL set never saw the inputs and couldn't change them from the UI.
Drop the guard; show the section whenever general is the active page.
Add a font-scale setting (small / medium / large) next to the theme
toggle. Persists in localStorage like theme, applies via
`document.documentElement.style.zoom` so every px-based size scales
without a CSS rewrite. Three presets — 0.875× / 1.0× / 1.125× —
cover the common high-DPI / cramped-display asks without a free-form
slider.
* fix(slash): /help hanging-indent wrap + fill btw/search-engine zh-CN keys
`/help` rendered broken on zh-CN: CJK summaries are double-wide so
long descriptions overflowed the terminal width and the continuation
landed at column 0, breaking the visual column alignment of the
command list. Two zh-CN entries (`btw`, `search-engine`) were also
missing, falling back to the hardcoded English summary even under
the Chinese locale.
- renderRow now wraps the description with `wrapToCells` (grapheme-
safe, accounts for visual width) and hangs continuation lines at
column 32 (2 indent + 28 name + 2 gap). Width budget matches the
info card's BODY_LEFT_CELLS=7 chrome.
- Add zh-CN + EN entries for `slash.btw.description` and
`slash.search-engine.description`.
- New regression test asserts every SLASH_COMMANDS entry has both an
EN and a zh-CN `slash.<cmd>.description` key.
Closes#865
* fix(tui): strip bidi + zero-width controls from pasted text
A clipboard payload from a browser (e.g. copying a Bilibili tab title)
can carry bidi overrides (RLE/PDF/isolates), zero-width spaces, BOMs,
and soft hyphens. These render as 0 cells but still occupy buffer
offsets, so the composer's cursor and line-split math drift —
characters appear hidden, overlaid, or "lost" after submit.
Add `sanitizePasteText` and apply it at the paste dispatch in
`StdinReader.handleChunk`. The strip set covers bidi controls (LRE
through RLO, LRM/RLM, FSI/PDI), ZWSP, WJ, soft hyphen, BOM. ZWJ /
ZWNJ / variation selectors / combining marks are deliberately
preserved so emoji sequences and accented letters keep their semantics.
Closes#849
`/help` rendered broken on zh-CN: CJK summaries are double-wide so
long descriptions overflowed the terminal width and the continuation
landed at column 0, breaking the visual column alignment of the
command list. Two zh-CN entries (`btw`, `search-engine`) were also
missing, falling back to the hardcoded English summary even under
the Chinese locale.
- renderRow now wraps the description with `wrapToCells` (grapheme-
safe, accounts for visual width) and hangs continuation lines at
column 32 (2 indent + 28 name + 2 gap). Width budget matches the
info card's BODY_LEFT_CELLS=7 chrome.
- Add zh-CN + EN entries for `slash.btw.description` and
`slash.search-engine.description`.
- New regression test asserts every SLASH_COMMANDS entry has both an
EN and a zh-CN `slash.<cmd>.description` key.
Closes#865
Every TabRuntime stays mounted (display:none on the inactive ones) and
each registers its own window-level keydown listener. Without an
`active` gate Cmd+N fires `newChat()` in every tab — both clear their
state, so the inactive tab's sidebar suddenly shows no active session
and any in-flight turn is aborted. The same path catches Cmd+L, Cmd+O,
Cmd+, and Escape-while-busy.
`useCommandPalette` had the same shape, so Cmd+K toggled every tab's
palette in parallel.
Add `active` to both listeners; only attach on the visible tab.
The pauseGate listener's if-chain in desktop.ts had no default
branch. Any new PauseKind added to pause-gate.ts without a matching
handler here would be silently dropped — the gate request stays
pending forever and the agent loop hangs waiting on a response that
never arrives, with no visible signal to the user.
Add a `never` cast at the end of the chain so a new kind without a
handler is a compile error, plus a runtime stderr warning + auto-
cancel via `pauseGate.cancel()` as the last-mile defense if a build
ever slips past the typecheck.
ConPTY occasionally strips the leading ESC off CSI sequences. Mouse
reports — `\x1b[<btn;col;rowM/m` — then arrive in the byte stream as
`[<btn;col;rowM/m`, slip past the escapeless-CSI lookahead (which only
knows arrow / page tails), and fall into the printable accumulator. The
composer receives the literal SGR text and the user has to backspace
through every wheel nudge.
Add `tryEscapelessSgrMouse` alongside the existing escapeless-paste and
escapeless-arrow guards. Recognised reports dispatch the same
mouseScroll/Click/Drag/Release events the with-ESC path already emits;
unmapped buttons are consumed and dropped. Share `decodeSgrMouseBody`
with `dispatchCsi` so both paths surface the same shape.
Closes#867
Without this, the fold summarizer paraphrased inline skill bodies into
prose. Past the fold threshold the model lost the explicit step-by-step
paradigm and drifted back to generic tool-thrashing mid-skill — visible
as the activity row flickering between error and thinking glyphs.
run_skill wraps its inline result in a <skill-pin name="..."> sentinel.
ContextManager.fold extracts every pinned block from the head before
summarizing, stubs the original tool message so the summarizer doesn't
paraphrase it, and re-attaches the bodies verbatim to the synthesized
assistant message. Repeat invocations dedupe by name; last one wins.
Remove the feature that auto-escalated flash→pro after 8 consecutive
read-only tool calls without a write. Deleted:
- src/loop/read-only-loop-tracker.ts (entire file)
- All references in src/loop.ts (import, field, init, method, call site)
- 3 related test cases in tests/loop.test.ts
- i18n keys readOnlyLoopEscalation in EN.ts, zh-CN.ts, types.ts
Reported in #855 (v0.42.0-3 on Windows): with both side and context
panels open at moderate window widths, the composer footer (commands /
mention / Review-Auto-YOLO / model pill / send) extends past the
textarea's right edge and gets clipped by the right panel.
Root cause was the responsive rules collapsing labels and shrinking the
model pill keyed off viewport `max-width`, so a wide window with both
panels open never tripped them even though the actual composer column
was narrower than the no-panel case.
Switch to container queries against `.composer-inner` (now an
`inline-size` container named `composer`) so the same thresholds fire
on the column's own width regardless of which panels are open.
#848 added docs/architecture.html and docs/cli-reference.html but
left configuration.html's two "Architecture deep dive" / "CLI
reference" CTAs aimed at GitHub blob URLs — so the bouncing-out
behavior issue #623 was filed against still happens from that page.
Swap the two hrefs to the local pages and drop the now-irrelevant
target/rel attributes.
* fix(cli): await profile stop inside the action so the .cpuprofile actually lands
beforeExit async handlers aren't awaited by Node, and while the
inspector Session is connected the loop never empties anyway — on
Ctrl+C the process tore down before V8 flushed the profile, and the
writeFileSync never ran. Reproducer: --profile a TUI session, exit,
no file appears.
Moves stop+save into the commander action's try/finally so it runs
inside the explicit await chain. Ink's exitOnCtrlC resolves
waitUntilExit(), then finally awaits stopAndSaveCpuProfile() before
the action returns — Node then exits naturally with the inspector
session already disconnected.
While here: gzip the output and print drop-into-GitHub instructions
on save. Real .cpuprofiles are 5-20 MB raw, gzipped they fit inside
GitHub's 10 MB comment-attachment limit.
* fix(cli): flush profile before useQuit's process.exit so --profile actually writes
PR #846 set up --profile but no file landed on Ctrl+C from `reasonix
code`. Root cause was deeper than the commander-action try/finally:
the TUI's useQuit calls `process.exit(0)` directly (intentionally —
the singleton stdin reader would otherwise hang the terminal), which
skips the whole await chain. waitUntilExit() never resolves, the
action's finally never runs, V8 buffer drops on the floor.
Hooks the stop+save into the two TUI quit paths that call
process.exit:
- src/cli/ui/hooks/useQuit.ts (Ctrl+C / SIGINT) — awaits
stopAndSaveCpuProfile() before process.exit(0).
- src/cli/commands/chat.tsx:187 (session-picker quit) — same.
stopAndSaveCpuProfile is a no-op when --profile isn't active so the
TUI's normal quit path adds nothing.
Refs #843.
Adds `--profile [path]` to `reasonix code` and `reasonix chat`. Starts a
V8 CPU profile on launch via node:inspector/promises, saves the
.cpuprofile to the given path (or cwd with a timestamped default) when
the process exits. Stops on SIGINT/SIGTERM/SIGHUP and on natural exit
via `beforeExit`.
Reason: #843-style perf reports come in vague ("卡了"). A real .cpuprofile
from the user's actual terminal + workload is the only way to tell
CPU-bound from terminal-emulator-bound. Profiling synthetic harnesses
on my box keeps showing 98%+ idle, so the bottleneck is elsewhere; this
flag lets users send back the actual evidence.
Bundles two reusable harnesses + an analyzer under scripts/perf/:
profile-tui-streaming.tsx (throttled, mimics real streaming),
profile-tui-sync.tsx (synchronous, measures raw reducer+commit), and
analyze-cpu-prof.mjs (top-N self/total with idle excluded).
Long conversations on the desktop got laggy because every streaming
chunk re-rendered the whole `state.messages.map(...)` tree. Each
historical `<AssistantMsg>` re-ran `<Markdown>` → `<ReactMarkdown>` +
`remark-gfm` on text that hadn't changed. At 50+ turns the per-chunk
cost stacked into thousands of redundant markdown parses per second.
- `UserMsg`, `AssistantMsg` (`desktop/src/ui/thread.tsx`) — wrapped
in `React.memo`.
- `AssistantText` (`desktop/src/ui/cards.tsx`), `Markdown`
(`desktop/src/Markdown.tsx`) — same.
- The three approval callbacks (`onApproveConfirm`, `onRejectConfirm`,
`onAlwaysAllowConfirm`) were minted inline at the `<AssistantMsg>`
call site on every render, defeating the memo's shallow compare.
Hoisted them to stable `useCallback` refs.
The TUI and dashboard already have this memo discipline
(`src/cli/ui/cards/CardRenderer.tsx:26` and
`dashboard/src/components/chat-internals.ts:308`), so no changes
there.
Closes#844
Refs #843
The desktop already had the full i18n machinery (en.ts / zh-CN.ts /
t() / useLang() / localStorage + browser autodetect) and most chrome
went through it, but three holes made the panel unusable for English
users:
- Settings UI was entirely hardcoded Chinese — side nav, page bodies,
API-key section, shortcuts list — none of it touched t().
- The Language / langEn / langZhCn keys existed in both dictionaries
but were never referenced; switching language required knowing the
/lang slash command.
- index.html shipped a static `<html lang="zh-CN">`, so screen
readers and `:lang()` CSS selectors saw Chinese regardless of UI
language.
Adds a Language section to PageGeneral with en / zh-CN buttons,
routes every visible string in settings.tsx through t(), and pushes
`document.documentElement.lang` from the i18n module on load + on
setLang. index.html ships `lang="en"` as a neutral fallback; the
runtime overrides it from getLang() before paint.
Each Page* component pulls useLang() so language changes re-render
immediately without closing/reopening the modal.
Closes#841
The agent emits a `plan_checkpoint` pause request after each completed
step. The TUI handled it by setting `pendingCheckpoint` and rendering
the local Continue / Revise / Stop card, but the dashboard side was
silent — the broadcast effect that mirrors plan / edit-review /
revision modals over SSE had no checkpoint case. From the user's
perspective the web UI just froze: the model was waiting on a button
the page never rendered.
Also adds the missing branch to `getActiveModal` so a dashboard that
connects mid-checkpoint replays the modal instead of starting blank.
The dashboard modal component (`CheckpointModal`), the resolve route
(`/api/modal/resolve` with `kind: "checkpoint"`), and the App-side
`resolveCheckpointConfirm` resolver were already in place — only the
broadcast was missing.
Closes#832
When a subagent yielded `paused`, the parent agent had no signal about
what was actually done — only the resume token and an iter count. That
forced the orchestrator to either resume blindly or accept partial
work blindly, defeating the point of pause-as-checkpoint.
Adds one no-tools call (`summarizePartialProgress`, pinned to flash
+ effort=high) before yielding `paused`. The call returns 3-6
sentences of progress / remaining / blockers, attached to the paused
event as `partialSummary`. Subagent JSON now surfaces it as
`partial_summary`.
The summary is NOT persisted to session messages — the resumed child
picks up clean state. Failure is non-fatal: pause still works, the
parent just gets the old opaque shape back.
Closes#838
Adds a context-fill indicator to the bottom status row so the user can
tell at a glance how close the current prompt is to the model's
context window — same role claude-dashboard plays for Claude Code.
Rendered as `ctx 72%` by default, `ctx 72% · 144K/1M` at ≥90 cols,
and `ctx ████░░░░ 72% · 144K/1M` at ≥110 cols. Tier-colored: green
under 50%, amber 50–80%, red ≥80%.
Plumbed via the existing `turn.end` event (already carries
`usage.prompt` + optional `promptCap`); cap falls back to the model's
entry in DEEPSEEK_CONTEXT_TOKENS, then to DEFAULT_CONTEXT_TOKENS.
Opt-out lives next to the other status-row toggles
(`statusBar.showCtxUsage` in user config).
Closes#828
`desktopCommand` awaited `buildCodeToolset` inside `createTab` before
emitting ANY event. That bundled semantic bootstrap, MCP probes,
tokenizer cold-load, and runtime construction into 1.5–3s of dead
time during which the Tauri window had nothing to render — feels
much slower than the web dashboard (which piggybacks on an already-
warm CLI process).
Split into a synchronous skeleton + async toolset init:
- `createTabSkeleton(dir)` — sets `toolset: null`, `runtime: null`,
`system: ""`. Returns instantly.
- `initTabToolset(tab)` — awaits `buildCodeToolset`, fills in
`tab.toolset` / `tab.system`, builds the runtime if an API key is
present, bridges MCP in the background.
Boot path fires `$tab_opened`, `$sessions`, `$settings`, `$mcp_specs`,
`$skills`, `$memory`, `$needs_setup?`, `$balance` IMMEDIATELY (all
disk-only or fire-and-forget). `initTabToolset` runs concurrently
and emits `$ready` + `$ctx_breakdown` on completion. UI's
`disabled={!state.ready}` keeps the composer locked until then —
existing safety, no new gate needed.
Subtler bits:
- `Tab.toolset` is now `Toolset | null`; the few hot paths that
touch it (`buildRuntimeFor`, `bridgeTabMcp`, `closeTab`,
`switchWorkspace`, settings-save preset change) gain a null guard.
`buildRuntimeFor` keeps an explicit "called before init" throw —
callers that need a runtime were already gated on `tab.runtime`.
- `setup_save_key` now tolerates a still-bootstrapping tab: skip
the `buildRuntimeFor` branch, `initTabToolset`'s tail reads
`loadApiKey()` after the new key was persisted and constructs the
runtime there.
- `tab_open` (multi-tab) follows the same skeleton + lazy-init shape.
P0 from the desktop perf analysis; P1 (semantic / MCP lazy-load
inside `buildCodeToolset`) and P2 (Tauri-side splash before Node
spawn) stay separate.
The default 1024×720 logical-px window doesn't fit on a Windows
laptop at 200% scaling (1920×1080 panel → 960×540 effective logical
space): the window opens partially off-screen, the user has to drag
or resize to see the right edge / bottom rows. The minWidth=640 /
minHeight=400 floor also locked out 1366×768 @ 200% setups entirely
(683×384 effective).
Fix:
- main.rs setup hook: query the current monitor's logical size,
clamp the window to 90% of available when 1024/720 overflows,
then recenter.
- tauri.conf.json: drop minWidth → 480, minHeight → 320 (still
comfortable on a normal display, lets the window actually meet
its minimum on tight HiDPI setups). Add `center: true` so the
window is centered on first launch.
The normal-DPI case (no overflow) is unchanged: the clamp branch
only fires when the configured size doesn't fit the monitor.
Refs #827.
The three coloured dots (red / yellow / green) in the top-left of
the titlebar were pure decoration — no onClick handlers, no Tauri
window-API wiring, just `<span>`s styled to look like macOS
traffic-light buttons. Users (rightly) clicked them expecting
close / minimize / maximize and got nothing. Remove the markup, the
matching `.traffic` / `.dot` CSS, and the now-redundant `margin-left`
on `.brand` that compensated for the removed block.
Native window chrome handles min / max / close on every OS we ship to.
The three coloured dots (red / yellow / green) in the top-left of
the titlebar were pure decoration — no onClick handlers, no Tauri
window-API wiring, just `<span>`s styled to look like macOS
traffic-light buttons. Users (rightly) clicked them expecting
close / minimize / maximize and got nothing. Remove the markup, the
matching `.traffic` / `.dot` CSS, and the now-redundant `margin-left`
on `.brand` that compensated for the removed block.
Native window chrome handles min / max / close on every OS we ship to.
The right-hand memory panel only got an `\$memory` event on tab open
— so when the agent called `remember` (or `forget`) mid-turn the
file was written to disk but the panel stayed on the prior list
until the user reopened the tab.
Re-emit `\$memory` from the turn loop whenever a `remember` /
`forget` tool event flows past. Same shape as how we re-emit
sessions / balance on turn complete; just on the tool boundary
instead so the UI sees the new entry the moment it's written.
* fix(desktop): expire the @-mention file index after 10s
The file index cached at tab construction lived for the lifetime of
the tab — files deleted, renamed, or added inside the workspace never
showed up (or refused to disappear) in the @ picker. #816 reported
this on the desktop client.
Add a 10s TTL: the next @ query past that window triggers a rebuild.
Balances "fresh enough for edit-then-mention flows" against scanning
5000 files on every keystroke.
* feat(desktop): tree-style @ picker — bare @ shows workspace top level
Bare @ in the desktop composer used to flood the popup with a flat
fuzzy match across all 5000 files in the workspace. Mirrors the TUI's
@+Tab pattern: empty query lists the workspace root's top-level
entries, and Tab on a directory item enters it (replaces `@src` with
`@src/` and re-queries to show that directory's children). Enter on
a directory still picks the directory itself.
Backend side (mention_query treeWalk branch) landed in the previous
commit on this branch as part of the desktop.ts change set.
Part of #816.
* feat(desktop): drag-and-drop files / folders → @-mention
Files dragged onto the Reasonix desktop window now append as
@-mentions in the draft. Paths inside `workspaceDir` are normalised
to relative; everything else passes through as absolute. While the
drag is over the window, an overlay shows "Drop to attach as
@-mention" so the user knows we'll accept it.
Tauri 2's webview `onDragDropEvent` provides the path list — uses
the standard {enter, over, drop, leave} state machine, no native
plugin needed.
Part of #816.
The dashboard installs `window.addEventListener("error", ...)` and
`unhandledrejection` to surface app crashes through the error overlay.
Both handlers forwarded unconditionally — so when a user's browser ran
an ad-blocker userscript that threw `require is not defined`, the
overlay caught it and prompted the user to file an issue against
*us*. #818 is exactly that: a `ReferenceError` from
`chrome-extension://…/userscript.html?name=屏蔽广告…`, nothing to do
with the dashboard.
Filter by origin: if the error's stack or the ErrorEvent's filename
contains `chrome-extension://`, `moz-extension://`,
`safari-web-extension://`, `safari-extension://`, or
`ms-browser-extension://`, skip reporting. The error still propagates
to `console.error` via the browser's default behavior; we just don't
treat it as ours.
Closes#818
`reasonix code` was passing `opts.model ?? "deepseek-v4-flash"` into
chatCommand + the system-prompt builder, so a user with preset=pro or
preset=auto in their config was silently downgraded to flash. Resolve
the preset (`loadPreset()` → `resolvePreset()`) and use its model id
instead — mirrors the same fix#819 landed on the desktop path.
Original implementation by @rokyplay in #820; cherry-picked here as a
standalone fix so it can land independently of the typeahead/steer
work in that PR.
Co-authored-by: rokyplay <[email protected]>
* fix(cli): route bare project launches to code mode
Detect project-like working directories for bare reasonix invocations so filesystem tools are rooted at cwd, while preserving explicit chat and first-run setup behavior.
* fix(test): import React for plan confirm tests
Reframes subagent iters from "hard budget" to "checkpoint cadence":
the subagent yields a `paused` event when its per-window iter count
runs out, the parent decides to either accept the partial state or
call spawn_subagent again with `resume_session` to continue. Total
iters bounded only by parent's own budget + natural termination.
Built on the existing session-persistence layer — pause leaves
messages on disk, resume reloads them. Prompt-cache prefix is
byte-stable across pauses so resumption is essentially free.
Validated end-to-end against the real DeepSeek API: phase 1 spawns
with max_iters=2, subagent pauses with a resume_session; phase 2
resumes with that token, subagent completes the remaining 8 of 10
topics in the new window.
What changed:
- loop.ts + loop/types.ts: new onIterBudgetExhausted option
(default "summarize" for top-level chat, "pause" for subagents);
pause yields a `paused` LoopEvent role with the session name.
- subagent.ts:
- Child loop runs with onIterBudgetExhausted=pause + minted
session subagent-<runId>-<ts>.
- SubagentResult gains paused / pausedSession.
- formatSubagentResult on pause emits {success:false, paused:true,
resume_session, note} — the note teaches the parent how to
resume in-band.
- spawn_subagent JSON arg gains resume_session; max_iters loses
minimum/maximum (no clamp).
- MIN/MAX/DEFAULT_MAX_ITERS gone; one internal DEFAULT_PAUSE_EVERY
= 16. clampMaxIters → parseMaxIters (no clamp).
- On resume, prepend a one-line nudge to the user task so the
model doesn't read lingering "finalize NOW" hints from the
previous window as still in force.
- skills.ts: frontmatter max-iters no longer clamped at a cap;
values below 1 still fall back. Doc rewritten as pause cadence.
PR #822 widened the cap 32 → 256 as a measurement step. Real-API
probes showed the model picks sensible values across task sizes —
confirming the cap was theater. This PR removes the cap entirely
and replaces it with a mechanism that scales with whatever the
work actually needs.
Closes#783
* experiment(subagent): widen iter cap 32 → 256, add telemetry to evidence model picks
Goal: empirically test whether the model picks pathological values for
`max_iters` (the kind we worried about — 1 or 9999) when given a much
wider range. If real workloads consistently land in a sensible band
(say 5-64), the cap was always theater and the next PR can remove it.
Changes:
- `subagent.ts` MAX_MAX_ITERS 32 → 256; tool description updated to
match. MIN stays at 1.
- `skills.ts` SKILL_MAX_ITERS_MAX 32 → 256; auto-injected skill docs
reworded so authors don't read 32 as the natural ceiling.
- New `IterCapSource` field on SpawnSubagentOptions + a single-line
stderr emitter so we can grep what each spawn resolved to and where
the value came from (json-arg / type / frontmatter / default).
- App.tsx skill subagentRunner now propagates `skill.maxToolIters`
(it didn't before — a latent divergence from the `reasonix code`
setup path that meant chat-mode skills silently ignored their
frontmatter `max-iters`).
- `REASONIX_ITER_CAP_TELEMETRY=off` opt-out; test setup turns it off
so CI logs stay quiet.
- Tests updated to assert the new bound and to cover 128 (in-range).
Mid-experiment safety:
- Cap still exists at 256 — the pause/resume work is not yet shipped,
so an extreme model pick can't burn through unbounded budget.
- 70% loop warning + 3-iter end-of-budget hint + budgetUsd cap all
still in effect.
* remove iter-cap telemetry after real-API validation
Probe results (deepseek-v4-flash, max_iters arg picked by the model
against the new 256 ceiling):
tiny task → 3
medium task → 30
large task → 80 (also auto-escalated to pro mid-loop)
unbounded → 256 (hit the ceiling, but the prompt said "unbounded
audit, take as many tool calls as needed")
No pathological 1, no hallucinated 999 → real values, scales with the
task description. The cap-as-safety-theater hypothesis holds.
This commit drops the experiment-only scaffolding while keeping the
substantive change (32 → 256 cap + the App.tsx skill maxToolIters
propagation fix it surfaced):
- emitIterCapTelemetry function gone
- IterCapSource type, itersSource / itersRaw fields gone
- callers in App.tsx, setup.ts, subagent.ts no longer compute or pass
the source tag
- scripts/iter-cap-experiment.mjs deleted
- REASONIX_ITER_CAP_TELEMETRY opt-out in tests/setup-lang.ts deleted
The native redirect parser called `pathMod.resolve(cwd, target)` for
every redirect target, so `2>nul` (Windows habit) and `2>/dev/null`
(POSIX habit) both opened a real file at `<cwd>/nul` or
`<cwd>/dev/null`. On Windows this materialized a stray `nul` file at
the project root containing whatever stderr was meant to be discarded
("File Not Found" from `dir`, typically).
Detect the two well-known aliases — case-insensitive `/dev/null` on
any platform, plus `nul` on win32 only (it is a legitimate filename
on POSIX) — and route them to `os.devNull` instead of the cwd.
The desktop JSON-RPC entry built CacheFirstLoop without passing
autoEscalate, so it defaulted to true regardless of preset. Picking
`flash` in the UI (advertised as "cheapest · predictable") still let
the loop escalate flash → pro on hard turns, billing users at pro
rates. The TUI's applyPresetLive already wires autoEscalate from the
resolved preset; do the same in buildRuntimeFor.
* chore(docs): move new landing + download site into docs/ for GitHub Pages
Routes:
- `/` (docs/index.html) — new editorial landing
- `/download.html` (docs/download.html) — smart-mirror download page
- `/configuration.html` — existing bilingual config guide,
untouched, still served alongside
The new design's components moved from `download-site/src/` to
`docs/src/`; the index now also carries the SEO bundle from the
previous landing (canonical, hreflang, og:, twitter:, JSON-LD
SoftwareApplication + WebSite) so search rankings don't drop.
Nav gains a "Guide" link pointing at `configuration.html` since
the in-page #config section is a quick reference, not a replacement
for the full guide.
`_headers` / `_redirects` are dropped — those were Cloudflare Pages
features and don't apply to GitHub Pages.
`term-anim.js` was only used by the old landing; deleted.
`styles.css`, `guide.css`, `i18n.js`, `guide-i18n.js`, `motion.js`
stay because `configuration.html` still references them.
`sitemap.xml` gains the download page entry.
* feat(web): EN/中 language switch + restyle configuration guide to match
Three changes ride together:
- **Language switch.** New `src/i18n.jsx` exposes `LangProvider`, `useLang`,
and a `t({zh, en})` helper. The nav now carries an EN/中文 toggle that
persists to `localStorage` under `reasonix.lang` and reflects in
`?lang=…` for deep-linking. Every prose string in nav, hero, install,
agents (three pillars), features, config (MCP/Skills/Memory/Slash),
community, roadmap, FAQ, footer, download page, mirrors grid, and CLI
alt block is now bilingual. `configuration.html` uses the same storage
key via `i18n.js`, so switching language on any page propagates to the
others.
- **Guide restyle.** `configuration.html` no longer ships its own
navy-palette chrome; it now loads `src/fonts.css` + `src/styles.css`,
uses the same nav + footer markup as the new design (active "Guide"
link in the accent colour), and `guide.css` was rewritten to use the
new design tokens (--cream, --accent, --rule, --serif, --mono) so the
article body — TOC, callouts, cmd tables, code blocks, CTA — sits
cohesively inside the warm-sepia aesthetic of the rest of the site.
- **Live community stats.** Community card on the landing now fetches
the real star count, fork count, and contributor list from the GitHub
REST API, replacing the mockup's fixed 1,128 and 24-initial placeholder.
Adds `download-site/` — a static React (UMD + Babel standalone) site with
two routes:
- `/` (index.html) — editorial landing page: hero with an animated terminal
replay of an actual reasonix code session, CLI install panel, three-pillar
agent breakdown, feature grid, configuration explorer (MCP / Skills /
Memory / Slash), community card with live GitHub stars + contributor wall,
roadmap, FAQ.
- `/download` (download.html) — smart-mirror download page. On load, races
HEAD probes against R2 and GitHub Releases, highlights the fastest as
"Fastest", and offers a per-platform installer link. Three platform tabs
(macOS / Windows / Linux) with first-launch caveats (Gatekeeper, SmartScreen,
AppImage chmod + libfuse2).
Substitutions from the mockup:
- Version `0.30.5` → `0.42.0-3` everywhere (mirrors / hero / footer / nav /
AppImage chmod example / terminal replay).
- File names match the actual `tauri-action` bundle output.
- Mirror list trimmed from {R2, Gitee, GitHub} to {R2, GitHub}; the Gitee row
in the matrix went away when we dropped that mirror upstream.
- Hero stats updated (test count → 2837).
- Community card fetches real GitHub repo metadata + contributors from
api.github.com instead of the hand-rolled chart and 24 placeholder initials.
- "新账号有免费额度" wording removed — DeepSeek pulled that perk in 2026-05.
Implementation notes:
- React + ReactDOM pinned to `cdn.jsdelivr.net` (better mainland-CN access
than unpkg). Babel standalone same CDN.
- `src/fonts.css` is a system-font stack — no external font CDN. The Google
Fonts <link> the mockup shipped with would degrade ugly on CN networks
exactly where the page matters most.
- `tweaks-panel.jsx` (dev-only design knob panel) is not copied; `app.jsx`
was simplified accordingly.
- `_headers` sets MIME type for `.jsx` (Babel needs `text/babel`-ish) and
basic security headers.
- `_redirects` maps `/download` → `/download.html` for clean URLs.
Deploys to Cloudflare Pages — no build step, root dir = `download-site`,
auto-deploys on push to main. README covers the manual setup.
GitHub Actions → Gitee bandwidth is unreliable enough that even
small files (47 MB rpm, 49 MB deb) hit the 3-min per-file timeout.
The runners live in US Azure regions and the path back into
mainland China is throttled / lossy; that's structural and not
something a longer timeout or more careful retry logic will fix.
R2 (via Cloudflare's edge) is fast enough from China to serve as
the primary mirror for CN users, plus the download page's latency
probe picks the best mirror per visitor. Gitee was supposed to be
the CN-native fallback; without reliable upload there's nothing to
fall back to.
Removes the Mirror to Gitee step and the helper script. GITEE_TOKEN
secret can stay or be deleted at the maintainer's discretion — it's
no longer referenced.
Last run got stuck for 15+ min uploading what should have been a
~50 MB file — Gitee accepted the connection then stalled, and
undici's default headersTimeout (5 min) wasn't aggressive enough
to free the loop, so the rest of the batch never ran.
Wrap each upload in an AbortController with a 3-min cap. Files
that don't complete in that window are reported as failures and
the loop moves on, matching the per-file error isolation added in
the previous fix.
Two robustness fixes on top of v0.42.0-3 mirror run #4:
- Gitee free accounts cap individual release assets at 100 MB. Our
AppImage (118 MB) was hanging the upload until undici's 5-min
HeadersTimeoutError fired, which crashed the whole script and
left assets queued after it unmirrored. Now skip files > 90 MB
with a clear log line; users still get those from GitHub / R2.
- Per-file uploads now catch their own errors and continue. A
flaky single upload no longer kills the rest of the batch.
Script still exits non-zero at the end if any upload failed, so
the workflow stays red.
R2 mirror was already passing end-to-end on the prior run.
Gitee's POST /repos/{owner}/{repo}/releases rejects an empty body
with 400 "发行版的描述不能为空" (release description cannot be empty).
The previous default kicked in only when the env var was unset; when
the GitHub release has no notes, the workflow passes RELEASE_BODY=""
which bypassed the `??` fallback.
Treat empty / whitespace-only body as "no body" and substitute a
link back to the GitHub release. Keeps mirror-only metadata
discoverable and lets the run succeed regardless of how thorough
the maintainer was with release notes.
Gitee's GET /repos/{owner}/{repo}/releases/tags/{tag} returns
200 OK with the literal JSON body `null` when the tag has no
release yet, not 404 like every other release API. The script
read .id off that null and crashed before the create path could
run. Treat null/missing-id as "no release exists" and fall
through to the POST /releases create branch.
Two issues surfaced on the first real run (v0.42.0-3):
- Gitee path `reasonix/deep-seek-reasonix` 404'd; the actual repo is
`reasonix/DeepSeek-Reasonix` (case-sensitive on Gitee). Fixed.
- Gitee failing took out R2 because step-level `if:` defaults to
`success()`. Added `continue-on-error: true` to both mirror steps
and `if: always() && ...` to R2 / its aws-cli setup so the two
targets are now fully independent — one failing surfaces a failed
workflow but doesn't suppress the other.
Summary step now reports per-mirror status (✓ / ✗ / skipped) and
exits non-zero if any required mirror failed, so the run stays red
in the Actions UI even though individual steps soft-failed.
Add argCompleter: "skills" to the /skill command so users see a
picker with available user-defined skills (project + global scope)
when typing '/skill ' — excludes built-in skills to reduce noise.
- Add "skills" to the argCompleter type union in SlashCommandSpec
- Register argCompleter on the skill command spec
- Add SkillStore-based resolver in useCompletionPickers
A new workflow fires on `release: published` (and is manually
runnable for backfills). It downloads the GH release assets,
creates / reuses a Gitee Release of the same tag, and uploads
each asset; in parallel it syncs the same files to R2 under
`<tag>/` and `latest/`.
Both mirror steps gate on their secrets being present, so the
workflow no-ops cleanly until tokens are configured. Required
secrets:
- GITEE_TOKEN
- R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ACCOUNT_ID, R2_BUCKET
Refs #802
* fix(desktop): bundled CLI loads on installed targets; drop CDN fonts
Two unrelated issues both surfaced as a black-screen on the v0.42.0-2
release.
CLI sidecar: tsup was emitting `dist/cli/index.js` as an ESM bundle
with `commander`, `ink`, `undici`, etc. left external. That's fine
for `npm i -g reasonix` (npm brings the deps), but the desktop ships
`dist/cli/` as a static resource with no `node_modules` next to it,
so the spawned Node process died on `ERR_MODULE_NOT_FOUND` for the
first import and the IPC channel never came up → empty UI. Switch
the CLI entry to a self-contained bundle: `noExternal: [/.*/]` plus
`platform: "node"`, with `react-devtools-core` whitelisted as
external (it's an optional peer dep that ink dynamically pulls only
when devtools are enabled, which we never do).
undici's dispatcher uses `require()` at runtime; in ESM output the
esbuild shim refuses dynamic require. Banner-inject a `createRequire`
into `globalThis.require` so the shim picks it up.
Drop a one-line `dist/cli/package.json` with `{"type":"module"}` so
Node skips the CJS-first parse attempt and the
MODULE_TYPELESS_PACKAGE_JSON warning.
Fonts: `index.html` loaded IBM Plex from googleapis.com, which the
bundled CSP (`style-src 'self' 'unsafe-inline'; font-src 'self'
data:`) blocks. Switch to `@fontsource/ibm-plex-{sans,mono,serif}`
so the woff2s are bundled into `dist/assets/` at build time —
identical typeface, zero runtime network. The previously-imported
`@fontsource-variable/inter` + `jetbrains-mono` packages were dead
weight (CSS never referenced those families); removed.
Enable tauri's `devtools` feature while the desktop is prerelease —
F12 is what surfaced both bugs, and it stays useful while the
desktop is being shaken out. Revisit before stable.
* test(bundle-smoke): assert runtime deps are inlined, not external
Companion to the CLI bundling change: the smoke guardrail was the
inverse of what we now want — it asserted ink was kept external so
npm could resolve it from the user's tree. The desktop sidecar
runs from a static `dist/cli/` with no node_modules, so external
imports are exactly the failure mode we're guarding against now.
Flips the assertion: no `dist/cli/*.js` should `import from "commander"
| "ink" | "undici"` — those are the three that broke v0.42.0-2.
StreamingCard re-ran split('\n') + wrapToCells() over the whole
accumulated text on every chunk. wrapToCells walks each grapheme
through Intl.Segmenter (~3.7µs/char), so a 5000-char reply costs
18.5ms per frame at 20Hz — well over the 50ms budget.
Cache the wrap and re-fold only the last logical line on monotonic
append; fall back to a full recompute on shrink (abort), resize,
or any non-prefix change. ReasoningCard's StreamingPreview and
SettledPreview now share the parent's wrap result instead of
each running their own flatMap.
Also bumps the live token calibration interval from 500 to 1000
chars — the post-fix calibration frame became the dominant cost
and t/s precision is already an approximation.
Closes#798
The macos-13 Intel runner pool on GH is heavily throttled — v0.42.0-1
sat queued for hours. Tauri 2 ships a `universal-apple-darwin` target
that lipos x86_64 + arm64 builds into a single fat binary, so one
Apple Silicon runner now produces a Mac DMG that installs on both
Apple Silicon and Intel.
Restructures the matrix entry so `rust` is the comma-separated list
fed to dtolnay/rust-toolchain (both real targets need installing for
the universal build) and `tauri` is the target name fed to
`cargo tauri build`. Other shards just repeat their triple in both
fields.
Drops the macos-x64 row entirely. The universal DMG covers the same
hardware that macos-x64 shard was producing for.
v0.42.0-0 run got past compile + bundle (MSI included — numeric
prerelease works as expected) but died at "GITHUB_TOKEN is required"
when tauri-action tried to create the draft release. The previous
codesign failure on v0.42.0-desktop.0 masked this: the build never
reached the upload phase, so nobody noticed the missing token.
tauri-action v0 needs GITHUB_TOKEN in env to call the GitHub API for
draft creation + asset upload. Wires `secrets.GITHUB_TOKEN` into all
three build-step variants (unsigned, Windows signed, macOS signed).
Windows matrix shard produced its full set of artifacts in the
previous run before failing the upload:
Reasonix_0.42.0-0_x64_en-US.msi
Reasonix_0.42.0-0_x64-setup.exe (NSIS)
+ .sig files for both
#794 used `secrets.WINDOWS_CERTIFICATE != ''` directly inside step
`if:` conditions. GitHub Actions rejects that at workflow-validation
time — secrets context isn't available to job/step conditionals.
Result: every push to main / PR branch produced a workflow-file-issue
failure run, and the v0.42.0-0 tag run never even started.
Lifts the presence check into a job-level `env:` that resolves at
job-start (where secrets context IS accessible). Steps gate on the
"true"/"false" string instead. Same three-way split as #794, just
working syntax.
Releasing v0.42.0-desktop.0 surfaced this: when an APPLE_* or
WINDOWS_CERTIFICATE secret is unset, GitHub Actions fills the env
var with an empty string, and tauri-action interprets "env defined"
as "try to sign". `security import` of an empty cert fails on macOS;
signtool fails the same way on Windows.
Splits the single Build Tauri bundle step into three mutually
exclusive variants gated on whether the certificate secret is
actually non-empty:
- unsigned (Linux always; Win/macOS when no cert)
- Windows signed (matrix.os == windows-latest && cert set)
- macOS signed + notarized (startsWith macos- && cert set)
Today only the Tauri updater key is configured, so every shard takes
the unsigned path. Wiring stays in place for when code-signing
secrets land.
README had no mention of the Tauri desktop bundle, so users wouldn't
know it exists. Adds a short section under Install: where to grab
installers, the prerelease caveat (unsigned bundles), and the two
one-line gotchas users hit on macOS (xattr) and Windows (SmartScreen).
The previous exit watcher took the Child by move and blocked on
child.wait(), with no way to interrupt it from outside. RpcHandle
stored only stdin, so the only thing keeping Node alive-or-not was
the stdin pipe closing on parent exit — fine in the common case but
leaks the child if Node is mid-tool-call when Tauri exits.
Replaces the watcher with a recv_timeout loop on a kill-signal mpsc:
RpcHandle holds the Sender, dropping the handle disconnects the
channel, the wait thread sees Disconnected and calls child.kill()
followed by wait() to reap. Natural exit (try_wait returns Some) is
detected on the 500 ms tick and clears RpcState so a future rpc_spawn
isn't blocked by stale state.
Tauri 2's process exit doesn't always run managed-state drops, so
RunEvent::ExitRequested also invokes rpc_kill explicitly — belt-and-
braces.
`rpc_kill` is exposed as a tauri command for a future UI affordance
(restart RPC button); not wired to a button yet.
Skills that runAs=subagent were hard-capped at the spawn default of
16 tool calls — no way to raise it from the frontmatter. Review /
exploration playbooks with bigger codebases run out and stop with
"Tool budget exhausted at 16 calls". The setup.ts run_skill bridge
ignored skill.maxToolIters because the field didn't exist.
Adds `max-iters` to the parsed frontmatter (clamped to [1, 32] to
match the spawn_subagent JSON-schema bounds), wires it through to
spawnSubagent, and documents it in docs/configuration.html plus the
/skill new stub. Invalid / out-of-range values fall back: junk text
→ undefined (default 16), >32 → 32, <1 → 1.
Closes#783
Two prerequisites for the desktop's first prerelease bundle.
- Cargo.toml + tauri.conf.json + desktop/package.json were all stuck
at 0.0.0. tauri-action doesn't auto-rewrite them from the tag, so
the artifact filenames would have been Reasonix_0.0.0_x64-setup.exe
and the updater's version compare would be broken. New
scripts/sync-desktop-version.mjs reads the tag (or GITHUB_REF_NAME /
TAG env var) and writes the SemVer to all three files. Wired into
release.yml between `npm ci` and the CLI build step.
- CSP was `null`. Switched to a minimum self-only policy with the
usual escapes for inline styles, fonts, and Tauri IPC origins
(`ipc:` + `http://ipc.localhost`). Only applied to the bundled
build, dev server is untouched.
Updater pubkey was already set on a previous pass; nothing to do
there. Code-signing certs (Windows EV, macOS Developer ID) are a
later step — first prerelease can ship unsigned with the usual
SmartScreen / Gatekeeper warnings.
* fix(desktop): wire path_access gate and scope right-panel to this session
Two desktop-side gaps from the same field report:
- path_access requests hung forever. desktop.ts's pauseGate listener
handled run_command / run_background / choice / plan_* but had no
case for path_access, so any outside-sandbox read (e.g. the model
trying `/tmp/foo` on a Windows workspace) parked the tool call with
no UI surface. Now emits `$path_access_required` and renders a
PathAccessApprovalCard (allow once / always allow prefix / deny).
Response reuses `confirm_response` since both gates return a
ConfirmationChoice.
- The right-panel Files tab was dumping the entire workspace tree
(up to 800 entries) overlaid with `git status` dots and polling
every 5s, against the mockup's intent. That mockup was a curated
"files in context" view — only files the agent has read or written
this session, status `c` for reads and `m` for writes. Rewrote
CtxFiles to consume the session-tracked list directly; dropped the
`list_workspace_tree` / `git_status` invokes (Rust commands left
in place but no longer called). Tree falls out naturally from the
small flat list via parent-dir grouping. Status `m` never downgrades
back to `c`.
multi_edit's per-edit paths are extracted so a batch refactor surfaces
all touched files.
* fix(desktop): rename global .caret → .stream-caret, drop dead tree rule
The streaming-text indicator's `.caret` was a global selector. The
old CtxFiles also used `<span className="caret">` for its expand
arrow, and `.tree .node .caret` only overrode width/height/display/
color/flex-shrink — `background: var(--accent)` and the 1Hz
`animation: caret` leaked through, painting a flashing accent square
next to every tree node. Renaming the streaming class breaks the
collision, and now-unused `.tree .node .caret` goes with it.
YOLO mode already auto-allows shell tools via setup.ts's `allowAll`
getter, but filesystem tools went through `safePath` → `path_access`
gate unconditionally, so an outside-sandbox read like `/tmp/foo` would
still pause the loop waiting for user approval. autoResolveVerdict
now returns run_once for path_access in yolo (run_once rather than
always_allow so a transient YOLO session can't pollute the on-disk
allowlist).
CLI TUI also routes path_access through autoResolveVerdict so the
three surfaces (CLI / ACP / desktop) all converge on the shared rule.
52 commits since 0.40.0. Headline is the ACP three-stage rollout
(NDJSON framing → tool_call streaming → request_permission bridge)
plus three flags that close the headless-caller story: --transcript
for cost-tracking, --yolo to skip plan checkpoints without config
mutation, --mcp + --mcp-prefix so downstream adapters can bridge
their own MCP servers without touching the user's config.
Other shipped lifts: flash → pro auto-escalation on consecutive
read-only tool calls (caps the dead-end fishing-trip cost), read_file
outline support for Python / Go / Rust / Markdown, a wait_for_job
exit-only mode that turns a 5-minute download into ONE tool call,
/btw for side questions that don't pollute context, user-defined
memory types with priority + expiry, status-bar field toggles, and
a wave of desktop UI surfaces gaining real data.
Field-reported fixes: /new now reloads REASONIX.md without a restart
(#778 bug 2), the dashboard search toggle no longer one-way-traps
users whose config lacks an explicit "search" field (#778 bug 1),
preset switches preserve persisted reasoningEffort (#775), markdown
emits OSC-8 hyperlinks, embed batch responses tolerate missing inputs,
@-mention paths handle CJK, jobs settle running state across the
Windows taskkill window, and more.
Full notes in CHANGELOG.md.
The dashboard's search toggle reads `cfg.search !== false` and treats
missing as on, so the button renders ON even when `~/.reasonix/config.json`
has no `"search"` field at all. A user who reads the config file first,
sees no entry, opens the dashboard expecting OFF, and clicks "to enable
it" actually goes `undefined → false` — which matches the report on
#778 (config still shows `"search": false` after the click).
GET now persists the resolved default (`true`) on first read when the
field is missing, so on-disk state always matches what the dashboard
displays. Subsequent clicks toggle a real boolean and the config
mirrors the button state from then on. Idempotent on configs that
already have an explicit search field.
Refs #778 (bug 1 of 2)
`reasonix acp` is missing the MCP-server bridging that `reasonix run` and
`reasonix chat` already have. Headless ACP clients (Paperclip's
reasonix-local adapter, etc.) need to plumb domain-specific tool servers
to the agent without forking config — same shape as #766/#767.
Lifts the MCP load loop from run.ts:81-142 into a `loadMcpServers` helper
and calls it inside `buildSession` so the tools are bridged into the
toolset registry BEFORE the prefix is computed (matters for the cache key).
Failures stay non-fatal — a broken side-concern server logs to stderr and
the session keeps running.
Disposes spawned MCP children when the ACP server's stdin closes.
Closes#779.
Editing REASONIX.md and running /new currently leaves the in-memory
system prompt pointing at the old content — applyMemoryStack runs once
at startup, gets baked into ImmutablePrefix.system, and clearLog()
doesn't touch the prefix to keep the prefix-cache warm.
Accept the cache miss when the user actually changed something. Add an
optional rebuildSystem closure on CacheFirstLoop; /new re-runs it,
compares against the current system, and only invalidates the cache
when the string changed. Closures captured at the chat / code entry
points point back at applyMemoryStack / codeSystemPrompt — same args,
fresh disk read.
A reload prints " · REASONIX.md / project memory reloaded" next to
the usual /new banner so the cache miss isn't surprising.
Refs #778 (bug 2 of 2)
waitForJob currently races closedPromise + outputPromise + timer, so
any new output (curl progress, install spinner, watcher tick) wakes
the wait and the model fires another round-trip. On a 90s download
that's 30+ tool calls.
Add `waitFor: 'exit' | 'output-or-exit'`, default `'exit'` — drop
outputPromise from the race in exit mode. Raise timeoutMs cap from
30_000 to 300_000 (server-side block costs no tokens, so one 5-min
wait_for_job covers an end-to-end download). Update run_background +
wait_for_job descriptions and the code-mode shell-tool prompt to
steer the model toward bg-jobs for one-shot long work (curl/wget,
big installs, big builds), not just dev servers.
Closes#776
#770 reported that reasoningEffort silently reverted to "max" after
updating, requiring the user to re-set it via the dashboard every
time. Tracing it: the update wasn't the cause — every preset-apply
path was overwriting the persisted effort with the preset's default
(all three canonical presets bundle `reasoningEffort: "max"`). Any
click on a preset card in the desktop UI, any `/preset` slash, and
the ModelPicker outcome handler all called
`saveReasoningEffort(p.reasoningEffort)` and stamped "max" over
whatever the user had stored.
Three call sites now only persist `savePreset`; the live
`loop.configure({ reasoningEffort })` stays so the in-session bundle
effect is preserved. Persistence of effort becomes user-driven only
(dashboard effort dropdown or future explicit slash). Next-launch
`loadReasoningEffort()` then returns the user's stored choice
instead of the silently-rewritten preset default.
Adjacent fix in src/cli/commands/desktop.ts:buildRuntimeFor —
loadReasoningEffort() was being read for `ctx` but never passed to
the `CacheFirstLoop` constructor, so the desktop runtime loop
always ran at the default "max" regardless of the persisted value.
Now passed through.
Regression test in tests/preset-effort-isolation.test.ts mocks
saveReasoningEffort / savePreset and verifies the slash handler
calls savePreset but never saveReasoningEffort, while the live loop
still gets the preset's bundle effort applied.
Per-invocation override of editMode for plan-checkpoint gates only.
Mirrors the existing editMode = "yolo" semantics in
src/core/pause-policy.ts — shell, edit, and any future gates still
bridge to the client via session/request_permission.
Headless callers should not have to write to ~/.reasonix/config.json
just to skip plan modals when running unattended.
Refs: #765
The old `esengine/reasonix` URL still resolves via the GitHub redirect
but star-history.com follows the canonical slug, so the chart was
quietly diverging from the real star series after the repo rename.
Updates the link + three picture sources in both READMEs to
`esengine/DeepSeek-Reasonix` and drops the `timeline&logscale` style
in favour of the simpler `date` projection.
Adds the three oosmetrics achievement badges (Top 2 in Agents, Top 3
in LLMs, Top 3 in CLI — all by 7-day velocity, as of 2026-05-12) to
both README.md and README.zh-CN.md, plus a scheduled GitHub Action
(weekly Monday 09:00 UTC + manual dispatch) that runs
oosmetrics/health-check-action@v1 to open a summary issue with rank
deltas + new achievements.
Workflow uses only the default GITHUB_TOKEN with issues:write — no
extra secrets to configure.
Three small UI surfaces were showing values that looked dynamic but
were actually frozen at build time or hardcoded — fine for a design
sketch, wrong for a live agent UI.
settings.tsx (preset cards):
Dropped `speed` ("180 t/s" / "84 t/s") and `bench` ("MMLU 88.5" /
"AIME 79.8") rows. These were build-time literals presented next
to the contractual `ctx` / `out` caps, so users read all four as
authoritative model metadata. ctx + out stay (those *are* contract).
Re-add speed / bench when we have a source of truth that updates
with the model, not as inline constants.
cards.tsx (PlanCardView badge):
The "运行中" pill rendered unconditionally — a plan with every
step `done` still flashed "running". Extracted `derivePlanBadge`
to fold items into one of err / warn / run / ok / run for failed
/ blocked / active / all-done / todo respectively, reusing the
existing `.pill-tag` color variants.
live.tsx (ToolRunningCard skeleton):
Three `skel-line` placeholders rendered above the real `live-log`
when both existed, so the user saw a fake gradient stack glued on
top of actual streaming output. Switched to else-branch — skeleton
only when there is nothing real to show.
* feat(acp): --transcript flag for headless cost capture
Tees raw LoopEvents through writeRecord/recordFromLoopEvent during
session/prompt so headless ACP callers can parse usage, cost, and
prefixHash without driving the TUI. Reuses the JSONL shape chat and
code already emit; zero changes to transcript helpers.
Single-session-per-process — mirrors chat/code behavior; the JSONL
stays cleanly seekable.
Adds tests/fixtures/acp-driver.ndjson as scaffolding for future
end-to-end ACP smoke tests, per maintainer ack on #765.
Refs: #765
* test(acp): assert fixture sessionId is a placeholder
Adversarial review noted that piping acp-driver.ndjson as-is into
the binary produces ERR_INVALID_PARAMS "unknown session" with no
hint about the substitution requirement. Lock in the placeholder
contract so anyone editing the fixture sees the test fail with a
clear comment instead of discovering the trap at runtime.
Auto-preview's symbol outline was TS-only. Any non-TS file longer
than 200 lines dropped into the preview path with no navigation map —
just head 80 + tail 40 and an opaque "N lines omitted" marker. The
model had nothing to range-read against, so for Python / Go / Rust /
Markdown files the "scope your read" workflow stopped working past
the threshold and the model either guessed or full-read.
Adds per-language regex extractors dispatched on extension:
- TS/JS/TSX/MJS/CJS — existing top-level export logic (parity preserved)
- Python — top-level def / class (indent-sensitive, skips methods)
- Go — top-level func / type / var / const, methods captured by name
- Rust — fn / struct / enum / trait / impl / mod / type / const / static,
impl block target type extracted (incl. impl<T>, impl Trait for X)
- Markdown — headings at all levels, fenced code blocks ignored
Outline module lives in src/tools/fs/outline.ts. Header wording goes
from "N top-level exports" to "N symbols" so it fits all languages;
elision text follows. Per-entry shape unchanged for TS — the kind +
name still appear after the line marker, just no longer hardcoded to
"export".
Picked regex per language over tree-sitter because the published WASM
parsers are 5-50MB each — too much install weight for "show me the
top-level symbols". Tree-sitter remains a viable upgrade if the regex
extractors start hitting precision limits in real use.
The existing flash→pro escalation only fires on "repair signals"
(SEARCH-mismatch / scavenged / truncated / repeat-loop). A model
stuck reading file after file without ever writing or producing a
final answer never trips that trigger — every read returns cleanly,
so from the harness's view the turn looks healthy while the user
watches the bill climb.
#681 hit this exact shape: 34 tool calls / 142 log messages, top-5
all `read_file`, ¥3.41 spent on flash before the user aborted. The
underlying issue is "flash too weak for this task"; the right fix is
to detect the stuck-in-reads pattern and switch to pro mid-step.
Adds `ReadOnlyLoopTracker` (default threshold 8, env-tunable via
`REASONIX_READONLY_LOOP_THRESHOLD`). Each successful tool result
either bumps the streak (read-only) or resets it (mutating). When
the streak crosses threshold, set `_escalateThisTurn = true` and
yield a one-shot warning — same escalation contract as the existing
failure-signal path. `autoEscalate=false` still blocks; the user
keeps that lever.
Threshold of 8 is on the conservative side — bursty read-heavy
tasks (e.g. "read these 5 files then edit one") still finish on
flash; the trigger only catches genuine unproductive loops.
Closes#681.
The picker's prefix regex was ASCII-only:
/(?:^|\s)@([a-zA-Z0-9_./\-]*)$/
So `@中文/` failed the `$` anchor on the first non-ASCII byte and
`detectAtPicker` returned null. The picker disappeared, Tab had
nothing to drill into, and the user couldn't enter a Chinese-named
folder via @.
Swap the inner char class for `[\p{L}\p{N}_./\-]` with the `u` flag.
Same change on `AT_MENTION_PATTERN` so the expander recognises the
completed mention too.
Closes#749.
#760 added the keystroke handler that lets users type blind while
scrolled up. It also added a `useChatScrollState((s) => s.pinned)`
subscription inside `AppInner`, which re-renders the whole subtree
every time scroll state ticks.
Move the handler into a leaf component the same way
`InputAreaWithHistoryHint` already isolates its `pinned` read. The
leaf renders `null` and registers `useKeystroke` against
`enabled && !pinned`; AppInner just hands it `input` / `setInput` /
`onReturnToBottom`. Behavior identical; AppInner now stays still on
scroll events again.
When the user scrolls up to read chat history, PromptInput is unmounted
and keystrokes are silently dropped. Add an App-level keystroke handler
that captures printable characters, backspace, and Enter (returns to
bottom) when pinned=false, so the user can type blind while reading
history and see their input when they scroll back — Claude Code parity.
Co-authored-by: rokyplay <[email protected]>
Extract `createMcpRuntime` from `chat.tsx` into a non-tsx module
`cli/commands/mcp-runtime.ts` and import from both `chat` and `desktop`.
chat.tsx re-exports the public types for backwards compat.
In `desktop.ts`:
- Each `Tab` now owns an optional `mcpRuntime` plus a `mcpStatuses` map.
`bridgeTabMcp` lazily constructs the runtime, wires a lifecycle sink
that updates the per-spec status, and calls `reloadFromConfig` against
the tab's loop so MCP tools register into the live prefix.
- `closeTab` calls `runtime.closeAll()` so MCP children exit cleanly.
- `mcp_specs_add` / `mcp_specs_remove` trigger `bridgeTabMcp` so live
config edits reach the runtime without restarting the tab.
- `$mcp_specs` now carries `status` + optional `statusReason` /
`toolCount` per spec. `bridged` stays as a coarse "all connected"
flag.
The right-panel Tools tab renders the per-spec dot — green for
connected, yellow pending for handshake / configured, grey for failed /
disabled — and the row text shows the live state (tool count, failure
reason).
Closes#753.
Lists project- and global-scope memory entries beside the chat. The
desktop command opens a `MemoryStore` per tab and emits the entries as
a new `$memory` event on tab open. Each row shows the scope badge +
description, matching the v4 mockup. Empty state keeps the existing
placeholder copy.
Refresh is currently tab-open only — when the agent writes a new
memory via `update_memory`, the panel reflects it on the next tab open
/ reload. Live refresh on tool result can come later if it bites.
Closes#754.
Modified files (yellow dot) and in-context files (green dot) now show
beside their row, matching the v4 mockup's `data-s="m"` / `data-s="c"`
hooks (CSS was already shipped).
- **Modified**: new Tauri command `git_status(root)` runs `git status
--porcelain -z`, parses index/worktree codes into coarse kinds. The
tab polls every 5s and on workspace switch; returns empty (silent)
outside a git repo or when `git` is missing.
- **In context**: reducer scans `tool.intent` events for the known
file-reading tools (`read_file`, `list_directory`, `directory_tree`,
`search_files`, `get_file_info`, `glob_files`) and accumulates each
path arg. `$session_loaded` rebuilds the set from loaded segments so
resumed sessions show their dots without re-reading anything.
Closes#756.
System prompt + tool specs are constant per tab. Compute their token
count via `countTokens` at tab open, emit as a new `$ctx_breakdown`
event (with `reservedTokens` field), and render the band on the right-
panel meter alongside cached / used / free.
Cache-hit/miss numbers from the API include the reserved prefix once
the cache warms up, so the visual subtracts `reserved` from those
buckets to keep the segments disjoint. With a cold cache, the
reserved tokens land in `cacheMiss`; subtract from `used` instead.
Off by at most one turn of arithmetic; not exact, but doesn't double-
count visually.
Closes#755.
The desktop runtime doesn't actually bridge MCP yet — the
`$mcp_specs` event is emitted with `bridged: false` indefinitely, so
the Tools tab was painting every server as perpetually "loading". Read
the absence of bridging as the truthful "configured but not active in
this tab" state. When desktop-side MCP bridging lands (separate scope),
the `bridged: true` path already maps to "ready" with no further UI
change.
Part of #744.
Click a directory row to fold or unfold its descendants. Tracks a
`collapsed` set of paths and walks each entry up the parent chain
(reconstructed from the flat depth-first list) to decide visibility.
File rows lose their pointer cursor since they're not interactive.
Adds a `.caret` slot with chev / chev-right icons so the affordance is
visible. Dirs default to expanded — collapsing is opt-in and resets
when the workspace switches.
Part of #744 — depth-2 fetch from the Tauri side stays the same; lazy
deeper fetch can come later if anyone hits the bottom.
The right context panel was a placeholder per #744. This first pass
wires the two tabs whose data is reachable without big new plumbing:
- Files: new Tauri command `list_workspace_tree(root, maxDepth)` walks
the workspace up to depth 2, skipping hidden + standard noise dirs
(`node_modules`, `target`, `dist`, `build`, `out`), capped at 800
entries. Front-end renders the design's `.tree` markup with depth
indentation, refetches on workspace switch.
- Tools: switched from the per-message tool-call histogram to the real
MCP server list using `state.mcpSpecs` + `state.mcpBridged`. Each row
shows transport + ready/loading + parse error if any.
- Memory: kept placeholder but pulled the inline styles into a shared
`.ctx-empty` class.
- Rules: still editMode-driven (no per-pattern allowlist exposed to the
desktop yet) but the items now reflect what each mode actually
permits, instead of two hardcoded rows.
- Meter: bumped the context max from 128K to 1M to match the V4
catalog.
Reserved-tokens bucket and a real file-tree expand interaction stay
deferred — both need event-shape / Tauri additions and were called out
as separate stages in #744.
The model picker still listed `deepseek-chat` / `deepseek-reasoner` with
128K / 64K context — both stale. The CLI canonicalized on
`deepseek-v4-flash` / `deepseek-v4-pro` (presets.ts) at 1M context
(telemetry/stats.ts) a while back; the desktop UI never caught up, so the
settings page contradicted the status-bar label ("DEEPSEEK-V4-FLASH").
Pull the model card metadata, composer preset labels, and the default
modelLabel fallback into line with the CLI source of truth.
Closes#745
When `request()` did `Promise.race([transport.send(), promise.then(() => undefined)])`,
the `.then()` derivative was a fresh promise whose rejection only chained
through Promise.race's internal subscriber. On Node 20 that subscriber doesn't
reliably suppress unhandledRejection once the race has already settled — so
when send wins the race and the pending request later times out, the derived
chain rejects with no live handler and the CLI crashes mid-session.
Use the two-arg form `promise.then(() => undefined, () => undefined)` so the
derivative is always fulfilled. The original rejection still propagates to the
caller via `await promise` below.
Adds a regression test using a silent-server transport where `send()` resolves
immediately and the response never arrives — exactly the shape of the crash
report. The `unhandledRejection` handler must not fire.
On Node ≥ 24, Windows child processes killed via `taskkill /T /F` often
never emit a `close` event — libuv's stdio handle lingers even though the
process is reaped. `JobRegistry.stop()` waited up to 5s on `closedPromise`,
gave up, then returned a snapshot with `running: true` even though we'd
just killed the process. Vitest then asserted on that ghost-running state
and the entire test (and pre-push verify) failed.
Two pieces:
- Settle the record on `exit` in addition to `close`. `exit` fires the
moment the OS reaps the process, well before stdio drains.
- If neither fires by the SIGKILL deadline, assume the kill landed and
mark the job dead anyway. We issued `taskkill /T /F`; trust it.
Same fallback in `shutdown()` for the multi-job case.
The bottom-bar folder indicator was display-only, while the model /
currency / theme / settings segs next to it are all clickable. Wire
the same WorkdirPop the title header uses so users can pick a recent
workspace (or browse for a new one) without scrolling back up.
Anchor the popover above the statusbar — extend the Anchor type with
`bottom`, and use `position: fixed; bottom: ...` when set so the
popover sits cleanly above the trigger instead of trying to render
below the viewport edge.
Picking "new" in the /session or launch picker called
`setActiveSession(undefined)`, propagating an undefined `session` to
`CacheFirstLoop`. `this.sessionName` became null, and every
`appendSessionMessage` short-circuited on the `if (this.sessionName)`
guard — the new chat never landed on disk.
Mint a fresh `${base}-${YYYYMMDDHHMMSS}` name at both pickers so the
loop has somewhere to write. Seconds-precision stamp avoids
back-to-back-click collisions; the base is the current session minus
any prior 12/14-digit timestamp suffix, falling back to `default`.
Closes#737
`stop()` and `shutdown()` legitimately need >5s on Windows because
`taskkill /T /F` is async and the SIGKILL race inside `stop()` waits
up to 5s for `close` to fire. Vitest's default 5s test timeout was
killing the test before `stop()` could return, masking the real
behavior with "Test timed out".
Bump the three affected tests to a 15s budget. The underlying paths
still complete in ~1-3s on healthy runs; the wider window only matters
when taskkill is slow to propagate.
Two follow-ups from the #734 merge that didn't justify another round
on the contributor's branch.
1. PlanConfirm.tsx — document what `EXPANDED_MODAL_OVERHEAD_ROWS = 12`
and `EXPANDED_DETAIL_CHROME_ROWS = 4` actually count. Both are
derived from the card chrome (header / step list / dividers /
footer hints / picker); without the comment, the next person who
reflows the modal won't know which constant to retune.
2. tests/plan-confirm.test.tsx — drop the inline
`text.replaceAll("\x1b", "").replace(/\[[0-9;]*m/g, "")` helper for
the `strip-ansi` package. The inline version only handled SGR
subset; `strip-ansi` covers OSC 8 hyperlinks (which #730 now emits
in plan markdown bodies) and CSI subparam edge cases. Promoted
`strip-ansi` from a transitive dep (via `string-width`) to an
explicit devDependency so the import doesn't break if the parent
chain shifts.
Lockfile changed because `npm install` resynced the existing 0.39.1
→ 0.40.0 version drift and dropped now-orphaned `patch-package`
transitive entries — both pre-existing maintenance debt, no upgrades
on this project's own deps.
* fix(plan): stabilize expanded approval modal layout
Keep the expanded plan confirmation view from clipping or jumping while scrolling, and document the new Ctrl+P summary/detail toggle.
* fix(tests): restore React value imports for JSX runtime
Keep JSX-based Ink tests using value imports so Vitest can execute them during verify and push hooks.
Requested in #725. Borrowed from Claude Code: while you're deep in a
coding turn, sometimes you want to ask the model a quick unrelated
question without breaking the conversation flow or eating turns of
context budget. `/btw` runs the question against a fresh blank-slate
message list, displays the answer inline, and never touches
`loop.messages` — the next normal turn sees the same context it would
have seen if `/btw` had never been typed.
Implementation lives in the same App.tsx submit branch as `/resource`
and `/prompt`: intercept the command before the synchronous slash
dispatcher, call `loop.client.chat()` with `[system, user]` only,
push the answer through `log.pushInfo` with a `≫ btw` header.
The system prompt instructs the model to answer concisely, in plain
prose, with no tool calls or follow-up questions. The command runs at
the loop's current model (so `/preset flash` before `/btw` still saves
money on side questions).
Registry entry in `SLASH_COMMANDS` (chat group, `<question>` argsHint)
means the command surfaces in `/help`, the slash-suggestions palette,
and the `+ N advanced` count.
i18n strings:
- `app.btwUsage` — shown when `/btw` is typed bare
- `app.btwHeader` — the `≫ btw` answer-card header
- `app.btwFailed` — title for the warning card on API failure
Closes#725
Reported in #728: after a single round of dialogue the blue cursor in
the composer disappears and the user can no longer tell where typed
characters will land. Regression from #672, which traded the
hardcoded `cursorVisible = true` for `useSlowTick() % 2 === 0`.
The slow-tick frame is driven by Ink's shared animation timer, which
the TUI suspends whenever the conversation is idle:
const tickerSuspended = modalOpen || (!busy && !isStreaming);
When the timer pauses, Ink's `useAnimation` stops advancing but keeps
returning the last frame value. If a streaming turn ran for an odd
number of seconds, the frame freezes on 1 (or 3, 5, …), so
`frame % 2 === 0` evaluates to `false` and the cursor stays blanked
indefinitely. The user only sees the cursor on the empty-input first
mount (frame 0) — every later idle state inherits whatever parity the
last active stretch happened to land on.
Add `useCursorBlink()` in `ticker.tsx` which combines the slow tick
with the ticker-active state: while suspended, force visible; while
active, blink each second as designed. Replace the single inline
expression in `PromptInput.tsx`.
Regression test in `tests/cursor-blink.test.tsx` mounts a probe inside
an active TickerProvider, advances fake timers past a slow tick so the
raw frame is odd, then rerenders with the provider suspended and
asserts the probe still reads `ON`. Without the active-guard it reads
`OFF` (the original bug).
Closes#728
Reported in #727: SiliconFlow's `Qwen/Qwen3-VL-Embedding-8B` model
sometimes returns fewer entries in `data[]` than the number of inputs
in the request. Hit by index-build at chunk 8 of 72, with
`OpenAI-compatible response missing embedding at index 8`, which
hard-aborted the whole index pass — the user lost 71 already-embedded
chunks and had to switch models. The pure-text sibling
`Qwen/Qwen3-Embedding-8B` does not exhibit this.
The OpenAI-compat client used to validate full coverage with:
for (let i = 0; i < out.length; i++) {
if (!out[i]) throw new EmbeddingError(`... missing embedding at index ${i}`);
}
That was correct against strict providers but wrong as a hard error
against providers that silently drop inputs. `embedAll`'s contract
already supports `Array<Float32Array | null>` and the index builder
already handles `null` slots by logging via `onError` and skipping
the chunk.
Change the OpenAI-compat path to match that contract:
- `requestOpenAICompatEmbeddings` now returns
`Array<Float32Array | null>` instead of throwing on partial
responses. Other validation (invalid index, non-array embedding,
HTTP errors) still throws.
- `embedAllOpenAICompat` walks the returned array and routes each
`null` slot through `opts.onError` so the index builder prints
`! skipped path:start-end: provider dropped input N from the batch`
for the dropped chunks and keeps going.
- `embedOpenAICompat` (single-text path) keeps the strict throw — if
the provider rejects a single input there is nothing else to return.
Regression tests in `tests/semantic-embed-tolerant.test.ts` cover
both the SiliconFlow VL case (partial batch → partial result + per-
slot onError) and the single-text refusal (still throws).
Closes#727
Reported in #724: when /user/balance returns both USD and CNY entries
(e.g. USD 4.99 top-up + dust CNY 0.47), the TUI status row, doctor
check, desktop kernel, and dashboard cockpit all rendered just the
first array entry — typically CNY in that order — making the account
look almost empty even though the user has real USD balance.
Five call sites were doing `balance_infos[0]!`:
- `src/cli/ui/useSessionInfo.ts` (initial fetch + refresh)
- `src/cli/commands/desktop.ts` (Tauri kernel `$balance` event)
- `src/cli/commands/doctor.ts` (api-reach check, both branches)
Add `pickPrimaryBalance(infos)` in `src/client.ts` that walks the array
and returns the entry with the largest `total_balance`. For the
common single-wallet account the behaviour is unchanged (the only
entry wins); for multi-wallet accounts the wallet the user actually
funded surfaces correctly.
`doctor`'s api-reach check additionally enumerates every wallet when
there are multiple, so a diagnostic now shows
`/user/balance ok — 4.99 USD + 0.47 CNY` instead of hiding one half.
The dashboard cockpit reads `stats.balance` which is constructed from
`balanceRef.current` (the primary surfaced by `useSessionInfo`), so
this fix propagates to the dashboard wire shape without separate
plumbing.
Unit tests in `tests/pick-primary-balance.test.ts` cover the empty
case, single-entry passthrough, the issue-#724 USD+CNY case, the
zero-USD fallback, and the tie-break invariant.
Closes#724
Reported in #723: assistant replies containing `[text](url)` render as
blue underlined text but aren't actually clickable on hover — supporting
terminals (kitty, iTerm2, Windows Terminal, VSCode) need the OSC 8
hyperlink escape sequence around the label.
The `osc8()` helper in `src/cli/ui/markdown.tsx` was already named for
this — it just never emitted the escape. The `_target` parameter was
prefixed with an underscore because the function ignored it.
Wire it up properly:
- `osc8()` now wraps its child in `<Transform>` that emits
`ESC ]8;; URL ESC \ ... ESC ]8;; ESC \` around the rendered text.
Accepts `React.ReactNode` so it can wrap an `<Inline>` subtree (links
with bold / em / codespan inside).
- The `case "link"` branch of `InlineToken` now routes through `osc8()`
with `l.href` instead of a styled-but-inert `<Text>`.
- `SpanText` in `src/cli/ui/markdown-view.tsx` (used by PlanConfirm /
PlanRefineInput) gets the same treatment so plan-modal links and
file refs are also clickable.
Frame renderer at `src/frame/ansi.ts:146` already emits OSC 8
unconditionally; this matches that convention — terminals that don't
support OSC 8 silently discard the sequence.
Closes#723
Reported in #721: typing in the dashboard composer feels laggy on long
sessions. Root cause is that every keystroke commits to `input` state,
which forces ChatPanel to walk its entire vnode tree on each frame.
ChatMessage was already wrapped in memo (#560), so historical bubbles
short-circuit individually — but Preact still has to map() over every
message, evaluate the per-row `Boolean(streaming && streaming.id === m.id)`
discriminator, and diff each ChatMessage element. For a session with
100+ messages the per-keystroke work is enough to drop frames.
Move the message-list render into a `<ChatFeed>` sub-component and wrap
it in memo. With `messages` and `streaming` refs both stable while the
user is typing, memo bails the whole feed out — keystrokes no longer
touch the feed at all. SideRail and ChatStatusBar get the same
treatment so /overview poll churn and input edits don't repaint the
right-rail progress bars and statusbar.
Closes#721
* feat(desktop): wire up stubbed UI surfaces, drop roadmap-only tabs
A pass over the desktop client looking for UI that *renders* without
actually doing anything. Found a fair amount of theater.
- context panel "工具" tab was showing a hardcoded list of fake MCP
servers (filesystem/shell/search/edit, made-up tool counts, fake
"ready" dots). Replace with real tool-call frequency from the
current session's assistant messages; empty state when there are
none yet.
- sidebar footer's "审批规则" and "设置" rows both invoked the same
onOpenSettings callback. Route 审批规则 to the rules page via a new
initialPage prop on SettingsModal; drop the stray ⌘, accelerator on
the rules row since it doesn't open settings any more.
- settings nav had three pages whose body was literally a "在路线图上 /
即将开放" card with no controls: MCP, Skills, and (kept) Memory.
Drop MCP and Skills from the nav. Memory page stays — its copy
about CLAUDE.md / AGENTS.md injection is at least true.
- add /export and /lang slash commands. The composer's slashIcon
table already had icons for both — they were just never wired.
/export reuses the existing exportConversation; /lang flips between
en / zh-CN via the existing i18n setLang.
- ⌘, toggle, command palette, title bar, and status bar now go
through a single openSettingsAt(page) helper so the modal opens on
the right tab from each entry point.
* feat(desktop): restore MCP + Skills settings pages, now wired to backend
The previous commit on this branch dropped the MCP and Skills tabs as
roadmap-only placeholders. That was wrong — the CLI has both features
and the design mockup keeps tabs for them. Bring them back, properly
hooked up this time.
Backend (src/cli/commands/desktop.ts):
- new RPC commands: mcp_specs_get / mcp_specs_add / mcp_specs_remove
/ skills_get
- new emitted events: $mcp_specs (parsed specs + bridged flag) and
$skills (project + global + builtin)
- specs are validated through parseMcpSpec before persisting; add /
remove round-trip through readConfig / writeConfig
- skills load via SkillStore({ projectRoot: tab.rootDir }), so they
follow the current workspace and re-emit on switchWorkspace
- both fire on initial $ready and on tab_open
MCP page (settings.tsx PageMCP):
- lists every configured spec with name + transport summary
- "移除" button → mcp_specs_remove
- input + 添加 button → mcp_specs_add (parser-validated)
- header notes that the desktop session doesn't itself bridge MCP
yet, so changes take effect in TUI sessions; once we add the
bridge in desktop.ts the bridged flag flips and the caveat
disappears
Skills page (settings.tsx PageSkills):
- one card per skill: /name, scope, runAs, model override, full
description, file path
- read-only — skills are markdown files on disk
* fix(desktop): settings body scrolls when content exceeds viewport
.settings is a grid (200px + 1fr) with fixed height; .settings-main is
flex column with .settings-head (intrinsic) + .settings-body (flex: 1,
overflow-y: auto). Skills page can render dozens of cards — once the
total exceeds the modal height, .settings-body wasn't scrolling
because .settings-main, a grid item with the default min-height: auto,
would let its content expand it past the grid track. The .settings
overflow:hidden then clipped the bottom instead of yielding a scroll
inside .settings-body.
Add min-height: 0 to .settings-main so the grid track bounds it, and
.settings-body's overflow-y:auto kicks in normally. All pages benefit;
Skills (variable count) and MCP (long URLs) are the visible wins.
The card-based UI rebuild had dropped the .palette-* styles, so Cmd+K
was rendering unstyled. Bring it back as .cmdk-* matching the mockup —
grouped (导航 / 动作 / 目录 / 设置), Search head icon, item-count footer.
While there: pull the rest of the mockup polish.
- splash intro on first launch (per session): plankton drift + whale
silhouette glide + Reasonix wordmark reveal, ~3.3s, skippable by
click / Esc / Enter / Space, sessionStorage-gated so HMR doesn't
re-trigger it.
- workdir popover anchored to the main-head breadcrumb (also Cmd+O),
lists Settings.recentWorkspaces, current dir checkmarked, falls back
to the existing pickWorkspace dialog from a "browse local…" button.
- move the transient flashToast from bottom-center to bottom-right so
it stops landing right on top of the Review/Auto/YOLO switch in the
composer foot.
i18n: palette.group{Nav,Action,Workspace,Settings} + palette.countSuffix
+ workdir.{title,searchPlaceholder,empty,browse} for both en and zh-CN.
Final ACP slice tracked in #103. Internal PauseGate requests
($confirm_required / $plan_required / $checkpoint_required /
$revision_required / choice) now surface to the ACP host as outbound
`session/request_permission` requests, and the host's response is
mapped back into the Reasonix verdict shape and resolved into the gate.
A Zed / JetBrains / AionUI host can now drive a real flow — including
shell command authorization forwarded to mobile via AionUI / Feishu —
end-to-end.
Mechanics:
- AcpServer gains sendRequest(method, params) with id tracking +
Promise-based resolution. Inbound responses (id + result|error,
no method) route to the matching pending entry. close() rejects
all in-flight outbound calls.
- src/acp/gates.ts maps each PauseGate kind to the right
PermissionOption list (allow_once / allow_always / reject_once)
and converts the optionId in the response back into the internal
verdict shape. Allow_always carries a command-prefix glob
(`{firstWord} *`) or the path_access allowPrefix so the same
decision auto-resolves next time via the existing pause-policy.
- acpCommand registers a global pauseGate.on listener that uses
AsyncLocalStorage to find the currently-running session and
forwards the gate request. Gates outside any active session
(rare — initialization races) get cancelled cleanly. The shared
auto-resolve policy (review/auto/yolo) still runs first, so
/run_command in yolo mode bypasses the host as expected.
13 new tests covering: outbound sendRequest happy-path and error
path, close() rejecting in-flight requests, permissionOptionsFor +
verdictFor mapping for shell / plan_proposed / plan_checkpoint /
plan_revision / choice, and an end-to-end requestPermissionForGate
round-trip via the live server.
Refs #103
Builds on the stage-1 NDJSON foundation from #714. Internal tool events
now surface to ACP hosts as the corresponding session/update variants,
so a Zed / JetBrains / AionUI client sees real-time tool execution
matching what the TUI / desktop already show.
Mapping (in src/acp/dispatch.ts):
- tool.preparing → tool_call (status=pending, kind classified from
name)
- tool.intent → tool_call_update (in_progress) + a follow-up
tool_call carrying rawInput (parsed from args JSON if valid, else
the raw string)
- tool.result → tool_call_update (completed | failed) with the
output wrapped as content[].content.text, clipped at 8000 chars
with a truncation suffix
`toolKindFor()` maps internal tool names to the ACP-spec kinds:
read (read_file, glob, list_directory, …), edit (write_file,
multi_edit, …), search (search_content, search_files), execute
(run_command, run_background), other (everything else).
7 new tests in tests/acp.test.ts covering each variant + the
classification table + the clip threshold.
Refs #103
First slice of the ACP (Agent Client Protocol — agentclientprotocol.com)
support tracked in #103. Spawns reasonix as an ACP agent on stdio
NDJSON JSON-RPC 2.0; the cache-first loop and prefix hashing are
untouched, only the IO layer changes.
What stage 1 covers:
- `reasonix acp` subcommand with --dir / --model / --preset / --budget
- src/acp/ — JsonRpc types + NDJSON `AcpServer` (one object per line,
no embedded newlines, per the transport spec)
- initialize handshake with capability negotiation
- session/new — builds a per-session CacheFirstLoop with its own
toolset rooted at cwd (or the cwd from the request)
- session/prompt — drives one turn, streaming `agent_message_chunk`
and `agent_thought_chunk` via session/update notifications; returns
`{ stopReason: end_turn | cancelled | error }` on completion
- session/cancel — notification aborts the in-flight turn cleanly,
leaving the session reusable for the next prompt
What's deferred to stage 2 / stage 3 (tracked in #103):
- tool_call / tool_call_update notifications (stage 2)
- session/request_permission for $confirm_required / $plan_required /
$checkpoint_required gates (stage 3)
- plan updates and authorize round-trips
- session/load (loadSession capability advertised as false for now)
Tests: 10 in tests/acp.test.ts covering framing, method/notification
dispatch, parse-error response, internal-error response, and the
initialize handshake contract.
Hardcoded four types (user / feedback / project / reference) didn't scale
for teams whose memory bucket actually wants distinct categories — non-
negotiable security rules, design-system conventions, deploy checklists,
etc. Without a real type they all collapse into `reference` and the model
treats a security constraint with the same weight as a style note.
Changes:
- MemoryEntry.type relaxed to `BuiltinMemoryType | (string & {})`; the
four built-ins stay in BUILTIN_MEMORY_TYPES for UI / docs.
- MemoryEntry gains optional `priority: low|medium|high` and
`expires: project_end`. Both round-trip through frontmatter.
- config.memory.customTypes — new ReasonixConfig field. Each entry can
set a default priority + expires for its type name.
loadMemoryTypeRegistry() merges built-ins with the config overlay
(rejecting bad names and built-in collisions).
- applyUserMemory now scans for high-priority entries (own field OR
the type's config default) and prepends a `# HIGH PRIORITY
constraints (must observe)` block with `!!! [scope/type/name]`
headings ahead of the regular memory index — so security-class rules
get the strongest framing the system prompt offers.
- `/memory list --type X` filters by type; list rows get `⚠` for high
and `·` for low priority.
- `/memory clear project confirm` additionally removes any global-scope
entry with `expires: project_end` (lifecycle tied to the project).
- The `remember` tool drops its hardcoded enum, surfaces the config-
declared custom types in its description, and accepts `priority` /
`expires` parameters.
Behavior is fully backward compatible: existing memory files without the
new fields parse and inject exactly as before; an empty config produces
zero behavior change.
Closes#709
Replace the ad-hoc components.tsx / toolRenderers.tsx tree with a card
system organized per kind (plan, reasoning, shell, tool, diff, error,
approval, etc.), each with a tone palette and built against the design
mock-ups in IBM Plex.
UI surface:
- Composer gains a Review / Auto / YOLO mode switch wired to
settings.editMode and a working preset dropdown (auto / flash / pro).
Paperclip and image buttons now open a file picker and insert the
pick as an @-mention. Narrow-width adaptation hides labels first,
then shrinks the model pill, before anything overflows.
- Title bar gets a real "more" menu (palette, export, clear, settings).
Status bar exposes currency toggle (CNY / USD) instead of a no-op
language toggle. ⌘B toggles the sidebar, ⌘⌥B the context panel.
- YOLO triggers a hatched red sub-header strip under main-head with a
one-click "back to Review" button, so the dangerous mode is never
silent.
- Toast styling that got lost in the stylesheet swap is restored.
Backend:
- emitSessions includes meta.summary, and runTurn writes a 60-char
summary on the first user input of a session, so the sidebar shows
real chat titles instead of `desktop-202605121013-1`. Main-head H1
falls back to the first user message of the in-flight session.
Everything is wired to the existing RPC contract (settings_save,
mention_query / preview / picked, session_load / delete, the five
pending kinds). No new transport.
- vary the right-side color per badge so they stop reading as one dark blob; keep labelColor 161b22 for cohesion. add npm/CI/node logos. drop the static color override on CI so the badge reflects real build status.
- point contrib.rocks at the canonical esengine/DeepSeek-Reasonix; the old esengine/reasonix worked via GitHub redirect but contrib.rocks served a stale 9-author snapshot. switching the cache key forces a regen with all 18.
npm-only release. The Tauri desktop source is in the repo and the CLI
subcommand works, but installer bundles for macOS / Windows / Linux
don't ship this round (separate release once signing's settled).
Highlights:
- Tauri desktop client with multi-tab concurrent runtimes (#689)
plus a near-full polish pass: wallet balance, version chip, active-
plan rail, abortable pause-gates, edit-gate pill, en + zh-CN i18n,
shared pause-policy module dedup'd with the CLI TUI (#701)
- checkpoint API + git-changes panel in the embedded dashboard (#682)
- outside-sandbox file access approval modal (#696)
- MCP loading pill + readiness gate on tool dispatch (#687)
- escalate-after flag for flash → pro threshold (#699)
Fixes:
- CardStream Maximum-update-depth crash, quantize window so boundary
cards stop oscillating (#700, #702)
- `reasonix code` bridges config key to env + lazy subagent client so
fresh installs can reach the setup wizard (#703)
- pinned-mode scroll shrinks coalesced (#666), generic CSI key decode
(#692), shell-confirm preview clamp (#691), frontmatter BOM/folded
lines (#690), MCP error classification (#688), and more
`reasonix code` crashed at boot with "DEEPSEEK_API_KEY is not set" for
two reasons stacked:
1. code.tsx never bridged ~/.reasonix/config.json → process.env the way
chat.tsx / desktop.ts / run.ts do. A key the user stored via
`reasonix setup` was invisible to `code`.
2. buildCodeToolset eagerly constructed a DeepSeekClient for the
subagent runner. With no env key, the constructor throws — before
chatCommand mounts the wizard that would prompt for one.
- code.tsx now calls loadDotenv() + bridges loadApiKey() into env at
the top of codeCommand, mirroring chatCommand's setup
- setup.ts defers the subagent DeepSeekClient to first dispatch so
toolset construction succeeds even when no key is configured yet
- new tests/code-setup-lazy-subagent.test.ts pins the invariant
Same shape as #549. In pinned mode scrollRows tracks maxScroll, and
maxScroll = inner.height - outer.height. The items useMemo depends on
both scrollRows and outer.height, so a sibling row toggling (ToastRail
appearing, ThinkingRow flipping) shifts outer.height by ±1 → window
moves → a card straddling the live↔spacer boundary flips → inner.height
changes by Δ → setMaxScroll → scrollRows changes → useMemo recomputes →
card flips back. With flash streaming compounding inside the same React
batch, the chain reaches MAX_NESTED_UPDATES and aborts inside ink's
useBoxMetrics (#700).
Quantize the window position to VISIBLE_BUFFER_ROWS buckets. Sub-bucket
scrollRows / outer.height wiggles now map to the same window, so items
is referentially-stable across them and the feedback loop dies on the
first re-render.
- extract computeCardStreamItems as a pure exported function for tests
- new tests/card-stream-items.test.ts asserts live-set stability across
every sub-bucket scrollRows delta and a range of outer.height values
Closes#700
* fix(i18n): point session banners + overflow error at /new and /sessions
The top-level /forget command was removed in the slash refactor, but
the resumed-session and new-session banners + the context-overflow
error still told users to type it. Point them at the surviving paths
instead: /new for a fresh start, /sessions ([d] to delete) for
manage / rename / drop.
Closes#697
* feat(desktop): surface version + wallet balance, fix ⌘K Settings
Tauri shell had no visible version or DeepSeek balance, and ⌘K's
Settings was a stub toast despite SettingsPanel being mounted.
- $settings now carries VERSION → version chip in Sidebar brand
- new $balance event polls /user/balance on startup, after each
turn, and after key/workspace changes → wallet card in Sidebar
- ⌘K Settings opens the existing panel; About shows real version
- ⌘K gains New/Close tab, Stop turn, Copy/Export reply, Pick workspace
* feat(desktop): localize UI strings (en + zh-CN) with live toggle
Tauri shell was a mix of English labels and Chinese hints with no
way to switch. Add a small React i18n module (localStorage + listener-
based re-render), seed en / zh-CN dictionaries, and surface a Language
picker in Settings.
- new desktop/src/i18n/{index,en,zh-CN}
- migrate ⌘K palette items, sidebar nav + wallet label, App toasts,
composer placeholder + kbd hints, plan/choice modal placeholders
- Settings grows a Language section; auto-detect from navigator.language
on first launch, sticky via reasonix.lang
* feat(desktop): active-plan rail + checkpoint card, abortable plan gates
Desktop dropped plan_checkpoint and plan_revision pause-gate requests on
the floor and abort only flipped the per-turn AbortController, so once
mark_step_complete fired the user was wedged with no UI response and no
way out.
- pause-gate: new cancel(id) using existing safeCancelVerdict
- desktop CLI: per-tab pendingGateIds + completedStepIds; abort now
drains gates via cancel(id), emits $plan_cleared
- desktop CLI: emit $plan_required steps, $checkpoint_required (with
done/total), $revision_required, $step_completed, $plan_cleared
- desktop UI: state grows activePlan, pendingCheckpoints,
pendingRevisions; reducer wires resolve_plan(approve) → activePlan,
resolve_revision(accepted) → swap remaining steps
- desktop UI: new ActivePlanRail above messages (collapsible, progress
bar, per-step risk + result), CheckpointCard (continue/revise/stop),
RevisionCard (accept/reject/cancel); Stop button in rail when busy
- i18n: plan / checkpoint / revision strings in en + zh-CN
* feat(desktop): localize Settings panel, drop ThinkingBar Stop button
Settings panel still rendered every section label, hint, and option
description in hardcoded English. Toggling the language picker did
nothing for the panel itself.
ThinkingBar had its own Stop pill on the right while the composer's
send button already turns into Stop when a turn is in flight. Two
buttons for the same action.
- migrate every SettingsSection label / hint / option name + desc
through t(); editor presets and api-key inline buttons too
- new settings.* keys in en + zh-CN
- ThinkingBar: drop onStop prop + button + .thinking-bar-stop CSS
- App.tsx: stop passing onStop={abort} to ThinkingBar
* fix(desktop): yolo + plan-rail bugs; dedupe auto-resolve policy
Two real bugs from the desktop diverging from CLI TUI behavior:
1. YOLO still asked at every plan_checkpoint. Two causes:
a. Desktop UI's editMode union used "default" but config.ts canonical
values are "review" | "auto" | "yolo". loadEditMode() coerces
anything else to "review", so picking "default" silently wrote
review and every checkpoint paused.
b. Even with the right wire value, the desktop's pauseGate.on listener
had no auto-resolve branch — only CLI TUI App.tsx did.
2. ActivePlanRail never cleared. No "plan done" signal existed; rail
lingered after the final mark_step_complete.
Fixes:
- new src/core/pause-policy.ts — one source of truth for editMode→gate
rules; CLI TUI App.tsx and desktop CLI listener both call
shouldAutoResolveCheckpoint / autoResolveVerdict instead of inlining
the same `mode === "auto" || mode === "yolo"` check
- desktop CLI listener auto-resolves plan_checkpoint via the shared
helper, still emitting $step_completed so the rail ticks
- desktop CLI emits $plan_cleared on turn_complete when all steps done
- desktop UI: editMode union retyped to "review" | "auto" | "yolo"
end-to-end (App, Header pill, SettingsPanel, protocol); CSS class
.edit-pill-default renamed to .edit-pill-auto
- ActivePlanRail: optional onDismiss × button for manual clear of plans
that arrive with no structured steps (and thus no turn_complete trigger)
The hardcoded threshold of 3 repair signals escalates too eagerly on long subagent runs where transient tool failures are expected and recoverable on flash. Exposing this via `escalation.failureThreshold` in config and `--escalate-after` on the CLI lets users tune escalation to their workload without forking the loop, while preserving the existing default and behaviour for everyone else.
The top-level /forget command was removed in the slash refactor, but
the resumed-session and new-session banners + the context-overflow
error still told users to type it. Point them at the surviving paths
instead: /new for a fresh start, /sessions ([d] to delete) for
manage / rename / drop.
Closes#697
Filesystem tools now route any absolute-system path that escapes the
project sandbox (`/Users/foo`, `/etc/...`, `C:\Users\...`) through a
new PathConfirm modal: allow once / always allow this directory / deny.
Mirrors the existing run_command flow — a shared PauseGate kind
`path_access`, a per-project `pathAllowed` list persisted in
~/.reasonix/config.json, and a session-scoped run-once cache so
follow-up reads under an approved directory don't re-prompt.
Closes#684
* feat: checkpoint API + git changes panel with zero external deps
* fix(changes): Cross-site scripting vulnerability as the output of this final HTML sanitizer step may contain double quotes when it reaches this attribute definition.
* fix(changes): The file may have changed since it was checked
* fix(comment): shorten block comment to comply with policy
* fix(file-read): TOCTOU race + path traversal guard
Reasonix enables xterm modifyOtherKeys=2 at startup. Under that mode,
terminals re-encode any printable key whose Ctrl variant would produce
a control byte — `@` (^@=NUL), `[` (^[=ESC), `\`, `]`, `^`, `_` — as
`\x1b[27;<mod>;<cp>~`. The parser only had hardcoded entries for the
Tab / Enter modifier sequences, so those printables hit lookupCsi,
returned null, and were dropped silently. Reported under ghostty on
Ubuntu 25.10; the same shape also affects any xterm-compatible host
that honors the mode.
Adds a generic decoder for both the xterm `27;mod;cp~` and Kitty
`cp;mod u` / `cp u` envelopes, mapping back to the keystroke that
would have arrived as a bare byte without the mode.
Closes#683
A 30-line python heredoc pushed the SingleSelect and footer past the
viewport so users couldn't see (or pick) "allow once / always / deny".
Clamp the preview to (totalRows - 18) lines with a "… N more lines
hidden" hint, leaving the action footer on screen at every terminal
height.
Closes#680
* fix(skills,memory): handle BOM, folded lines, and quoted values in frontmatter
The three local copies of the frontmatter parser all skipped files with a
UTF-8 BOM, dropped indented continuation lines, and left wrapping quotes
in description values. Consolidates them into one parser that strips the
BOM, folds indented continuations onto the preceding key, and unwraps
matching single/double quotes after folding.
Closes#678
* fix(frontmatter): guard against prototype-pollution keys
The KEY_RE regex matches `__proto__` / `constructor` / `prototype`, so a
bracket write `data[key] = value` could mutate Object.prototype. Switch
the accumulator to a Map (no prototype to pollute), filter forbidden
keys at both the set and materialization sites, and return a
null-prototype object. Resolves CodeQL js/prototype-pollution-utility.
Native shell that drives a new `reasonix desktop` JSON-RPC subcommand
over stdio. Each tab owns an independent CacheFirstLoop, workspace,
session, and file/symbol index so two projects can stream in parallel
without crossing context.
Extracts buildCodeToolset into src/code/setup.ts so the desktop and
the `code` command share an identical tool surface. While extracting,
wires up web (web_search / web_fetch) and skill (run_skill +
subagent runner) tools — they were exported but never registered.
pauseGate confirm / choice / plan requests route via AsyncLocalStorage
so concurrent turns can't cross approvals. CacheFirstLoop._turn now
advances past loaded assistant messages on resume — the frontend's
turn-keyed message map would otherwise treat a fresh streaming
response as a duplicate of an historical message.
Release workflow builds Tauri bundles for linux-x64, macos-arm64,
macos-x64, windows-x64 on tag push and uploads to GitHub Releases.
Signing keys flow through env (Apple notary, Windows Authenticode,
Tauri updater); see desktop/SIGNING.md.
Raw Node error codes and bare HTTP status lines from SSE/Streamable-HTTP transports leave users guessing at the next step. Mapping DNS/connection/TLS codes and 401/403/404/5xx responses to targeted `try:` hints turns `reasonix mcp inspect` output into something users can act on without reading the source.
Tool calls invoked during MCP handshake were surfacing transport errors because the bridge had no signal that the server was still connecting. A per-server readiness deferred lets dispatches wait (capped at 30s) instead of failing, and a status-bar pill makes the otherwise-invisible background load legible to the user.
#632 actionable-error work stopped at 429 + 403 — generic 5xx still
fell through to the catch-all "rephrase the query / switch engine"
message, which is the wrong advice for a transient server-side
failure. Add serverError5xx + fetchServerError5xx pointing the model
at a browser sanity-check and a 30s retry instead.
Existing webSearch 503 test tightened from `/web_search 503.*try:/`
to assert on the new `retry in 30s` substring; a parallel webFetch
502 test added in the same shape.
Credit to @MyPrototypeWhat — #671 surfaced the gap and the 503 test
case lands with this PR.
#670 landed with console.warn for the buggy-readOnlyCheck surface, but
the rest of the project writes diagnostics via process.stderr.write
(see commit.ts, the mcp-stdio dropped-line trace, etc.). Align the two
catch blocks to match. Test updated to spy on process.stderr.write
instead of console.warn.
No behavior change — both routes land on stderr; this is purely a
consistency fix so future grep-for-diagnostics stays one-shot.
Closes#629.
Two catch blocks treat a throwing readOnlyCheck as 'not read-only' and
move on:
- src/tools.ts isReadOnlyCall — used by plan-mode refusal
- src/loop.ts isMutating — used by the storm-breaker window
If the check itself has a bug, nobody sees it; the tool just silently
behaves as if it were mutating. Log the exception on console.warn at
each catch so the bug surfaces during development without changing
default-on-throw semantics.
* feat(mcp): add REASONIX_DEBUG_MCP env var to surface dropped stdio lines
Closes#630.
The MCP stdio transport silently discards lines that fail to parse as
JSON-RPC, since servers typically emit non-JSON banners during startup.
That hides real wire-level bugs — truncated or corrupted frames produce
empty tool results with no clue why.
Gate a stderr trace behind REASONIX_DEBUG_MCP=1 so the noise only shows
up when a developer opts in.
* test(mcp): wait on child exit instead of fixed 250ms sleep
Fixed-time waits flake under cold Node spawns on slow CI (Windows
runners routinely exceed 250ms). The messages() iterator returns when
the transport closes, and Node guarantees stdout 'data' events fire
before 'close', so by the time the iterator returns every malformed
line has already been routed through the synchronous catch.
Also added a '0' case to actually distinguish 'off' from 'on' (the
prior 'truthy non-1' case only covered 'true', which was redundant
with the empty-string case).
* feat(cards): polish user / reasoning / task to match design tokens
UserCard: drop accent stripe — user is a conversational anchor, not
status. Use neutral CARD.user (muted ◇ + bg-elev pill) and prefix the
body with a fg.sub ↳ anchor.
ReasoningCard: tighten the four-tier render. Streaming → tail-3 with a
⋮ overflow marker (was tail-4, no marker). Settled-short shows the
whole body with anchor; settled-medium splits head + tail with a mid
`⋯ N lines elided` row. XL (≥800 tok) drops the head and surfaces a
`⋯ N ¶ + ~T tok scrolled past · /reasoning last` line — the head at
that scale is almost always restating a prompt the model has moved
past. Empty reasoning (model skipped thinking) renders a grayed
PILL_SECTION.empty pill + italic "no thinking — direct answer" hint
so the absence is explained, not silently missing. Body anchor ↳
shows only when the absolute start is visible.
TaskCard: section pill with status-mapped tones (task / taskDone /
taskFailed) replaces the bare glyph + "step N/M" prefix. Subtitle
becomes "N / M Title". Step rows wrap the target in a PILL_PATH chip.
* feat(composer): blink the prompt cursor at 1Hz via slow tick
cursorVisible was hardcoded true. Drive it from useSlowTick() so the
block cursor toggles each second when the input is idle. During
typing, value/cursor changes already drive re-renders so the blink
doesn't interfere visibly.
* feat(shell-confirm): show cwd + timeout / wait info rows
The modal previewed the command but not where or for how long it would
run, leaving the user to infer cwd from session context and trust the
default 120s timeout silently. Surface both as faint info rows below
the `$ command` line — `cwd ~/projects/reasonix`, `timeout 120s` for
run_command, `wait 3s` for run_background when waitSec is set.
Threading: PausePayloadMap.run_command and run_background gain
optional cwd + timeoutSec / waitSec fields; shell.ts computes
effectiveTimeout before gate.ask so the modal sees the same number the
runtime will enforce; App.tsx pendingShell mirrors the wider payload.
Audit casts still see {command} — the extra fields are ignored at the
audit boundary on purpose.
tests/shell-tools.test.ts: the regression test now uses toMatchObject
to accept the wider payload while still asserting kind + command.
Two related UX failures landed together because users couldn't tell what
was actually controlling the model:
1. Users saw `● auto` in the StatusRow (which is the EDIT-GATE mode) and
assumed it was the preset. Running `/preset pro` left both visible
`auto` indicators (StatusRow + LiveRows ModePill) unchanged, because
neither rendered the preset — usePresetMode's React-state mirror was
never wired to the agent store, and the slash handler didn't call
setPreset / dispatch at all.
2. People reach for `/model <id>` instead of `/preset` to switch models.
`/model` only touched `loop.model`, leaving `autoEscalate` whatever
the active preset had set — so `/model deepseek-v4-flash` from the
default `auto` preset still let flash escalate to pro on hard turns.
And nothing wrote `cfg.preset`, so relaunch silently reverted.
Changes:
- StatusRow: prefix the edit-gate mode label with `edits:` (new i18n key
`statusBar.editsLabel`) and render a new `▴ <preset>` pill after it.
Pill falls back to the short model name when the user is on a model
outside the three presets. Hidden below 60 cols (same pattern as
WALLET_MIN_COLS).
- `StatusBar.preset` + new `session.preset.change` event, reducer entry,
and a mount-only useEffect in App that seeds the initial value from
loop state so the first paint is correct.
- `/preset` slash handler now dispatches the preset change and persists
via new `savePreset()` (mirrors saveReasoningEffort). `/model` does
the same: turns off `autoEscalate` (manual pick = explicit pin),
dispatches inferred preset (pro/flash/null), and persists when known.
- ModelPicker `kind:"select"` and `kind:"preset"` outcomes get the same
treatment, plus the dashboard's `applyPresetLive`.
After: switching to pro via `/preset` or `/model` shows `▴ pro` in the
status bar, sticks across the session (no silent escalate-back), and
survives relaunch.
When an Esc abort tears down multiple subagent cards at once, each card's re-measurement called setMaxScroll synchronously, snapping scrollRows N times and bouncing the viewport past one screen. Holding a trailing-edge target on a microtask flush collapses the burst into one settled transition while keeping grows immediate so streaming output stays pinned without latency.
A user pasted `D:\VS_project\...\GraspAnalysisCommand.cpp` inside the
workspace; the model hallucinated "I cannot access the filesystem"
and ran `web_search` for a private local cpp file instead of just
calling `read_file`. The Path-conventions block only documented
POSIX-absolute as accepted, leaving Windows drive-letter paths to
the model's imagination — which here defaulted to "refuse".
`safePath` already accepts any shape that resolves inside the sandbox
(src/tools/filesystem.ts), so this is purely a prompt clarification
plus an explicit ban on the refusal patterns we observed in the wild:
shape-based refusals, "no filesystem access" claims, and `web_search`
fallbacks for local paths.
Hotfix for 0.39.0 install failure: the `postinstall: patch-package`
hook + missing `patch-package` runtime dep + missing `patches/` in the
files array meant fresh `npm install` / `npx reasonix@latest` runs
crashed before the binary was usable. 0.39.0 has been deprecated on
npm and `latest` rolled back to 0.38.0.
Removes the patch-package machinery entirely — it can't work for a
published library since npm hoists `ink` out of reasonix's own
`node_modules`. The ink alt-screen render fix (#639) will return via
a forked ink + `npm:` alias (#663) in a later release.
Piggybacks three PRs that landed since 0.39.0:
- #632 fix(web): actionable web_search / web_fetch errors
- #661 feat(composer): Ctrl+X opens \$EDITOR
- #662 feat(composer): Ctrl+P / Ctrl+N picker navigation
When any of the three input-prefix pickers is active — slash command
(`/`), @-mention file picker, or slash-argument enum picker — Ctrl+P
and Ctrl+N now move the highlighted row up/down, matching what ↑/↓
already do. Falls through to prompt-history recall when no picker is
open, so single-key bash parity is preserved.
Previously Ctrl+P/N always handed off to history recall regardless of
picker state — reported as keymap inconsistency in issue #647 (the
external-editor change is its own PR; this is the keymap half).
Implementation: `App.tsx` wraps `recallPrev` / `recallNext` from
`useInputRecall` in two memoized callbacks that consult atState /
slashArgMatches / slashMatches first (priority matching the existing
↑/↓ handler's order), and routes them into `PromptInput` instead of
the raw recall functions.
Closes#647
Composes a long prompt in the user's preferred editor instead of
typing it inside the TUI. Match for opencode's `<C-x>e` and codex's
`<C-g>` (issue #647).
Editor resolution follows the standard Unix precedence: $GIT_EDITOR →
$VISUAL → $EDITOR. Picked an explicit GIT_EDITOR-style fallback over
hardcoding nano/notepad so the user's existing shell config carries
through. Missing-editor and non-zero-exit cases surface as a warning
card in the chat log; on success the buffer is replaced with whatever
the user saved (one trailing newline stripped, since most editors
auto-append one).
Implementation notes:
- New action flag in multiline-keys (`openExternalEditor: true`) so the
pure reducer stays testable and PromptInput just signals up.
- App.tsx flips raw-mode off around the spawn so the editor can use
cooked line-buffered input; bracketed-paste / alt-screen are managed
by the editor itself via DEC mode 1049.
- Spawn uses `shell: true` so $EDITOR strings like `nvim --noplugin`
or `code --wait` split correctly across platforms (same shape as the
existing `commit.ts` editor invocation).
Refs #647 (the picker-keymap half of that issue is a separate change).
* fix(web): make web_search and web_fetch errors actionable
Bare HTTP status codes and terse refusal messages gave the model no signal about what to do next, leading it to either retry blindly or abandon the tool. Each error now carries a short " — try: …" tail tailored to the failure mode (429 backoff, 403 client-block, timeout, oversize body, unreachable SearXNG, invalid URL) so the model can self-correct without a human in the loop.
* style(tests): reformat web-tools assertions for biome
Biome's formatter flagged the existing single-line `expect(...).rejects.toThrow(...)` calls as needing the multi-line layout. Reformat to satisfy the formatter so `npm run lint` is clean.
The reporter showed a JSON snippet rendered as
`{ "apiKey": "..." }` inside a code fence — the
model emitted literal HTML entities instead of `"`. marked passes the
entities through verbatim (its tokens carry the raw text, not HTML-
escaped output), and our renderer rightly hands that to the terminal
unchanged. Terminals don't render entities, so they leak as visible
`"` / `&` / `<` etc.
This is a known LLM artifact: models sometimes HTML-escape inside code
blocks, especially on JSON / HTML / XML output, because their training
saw a lot of HTML-encoded code in web posts and docs. Both Claude Code
and Cursor decode entities at the rendering boundary; doing the same
here.
Scope: only code blocks and inline code spans (the contexts where
models leak entities the most). Prose paragraphs are left alone — if
someone genuinely writes "use the `&` entity to escape ampersand"
in non-code text, the entity name stays visible. Numeric forms
(`"` / `"`) and the five common named forms (quot / apos /
amp / lt / gt / nbsp) decode; unknown names pass through so we don't
corrupt prose that quotes entity names.
Closes#657
UserCard ran every user message through `<Markdown>`, so pasting code
or stack traces into the composer caused the displayed card to silently
reinterpret markdown punctuation: `*foo*` rendered italic, `# title`
collapsed into an H1 (the `#` vanished), `[label](url)` rewrote to an
underlined link with the URL hidden, four-space-indented lines
restyled as a code block, etc. The model still received the full
verbatim text — but the user's visible round-trip (`what I sent` →
`what I see in history`) was wrong.
Render as a plain `<Text>` instead. Assistant turns keep Markdown
(that's the only place formatted output belongs).
Closes#655
In a real review session, the model called `read_file({})` (missing
required `path`), got the standard "missing required parameter ..."
error back, and the very next turn issued the *exact same* call — same
empty args, same tool. Same error came back. After the second rejection
it gave up tool-calling entirely and went to summary. The existing
StormBreaker uses a 6-call window with threshold=3 across all tools, so
the two-in-a-row malformed-args shape never tripped it.
ToolRegistry now tracks the per-tool fingerprint of the last call that
failed schema validation (JSON parse error or missing required param).
On the second consecutive identical malformed call to the same tool the
result switches to a sharper "same call just failed validation — DO NOT
retry with identical args" plus `consecutiveMalformed: true` so callers
can spot it programmatically. Any successful validation for that tool
clears its streak; per-tool tracking keeps interleaved unrelated tools
from interfering.
Closes#651
Node's built-in fetch is undici under the hood, but undici ignores the
standard proxy env vars unless you explicitly install a ProxyAgent on
its global dispatcher. Users behind a corporate or local proxy were
getting opaque connection failures from every network surface — DeepSeek
API, web search, model list refresh, version check — even with
HTTPS_PROXY set in their shell, because none of those calls ever saw the
env var.
src/net/proxy.ts reads HTTPS_PROXY → HTTP_PROXY → ALL_PROXY (upper-case
preferred, lower-case fallback — matches curl precedence) and installs
an undici ProxyAgent as the global dispatcher. Wired at the top of
src/cli/index.ts so every fetch closure constructed later (DeepSeek
client, web tools, doctor's reach check) inherits the dispatcher.
/doctor now reports the active proxy as a check row — username/password
in the URL are redacted before printing so the output is safe to paste
into bug reports.
Closes#646
EditMode is "review" | "auto" | "yolo", but loadEditMode's ternary only
recognized "auto" and dropped everything else — including yolo — to
"review". /mode yolo writes the right value to disk via saveEditMode,
but the next read silently downgrades it.
Downstream: src/cli/commands/code.tsx:111 registers the shell tool with
`allowAll: () => loadEditMode() === "yolo"`. Because that getter never
returns "yolo", the shell tool always falls through to the pauseGate,
and the user sees the approval modal even though they're "in yolo".
Same demotion bites the App's initial editMode state in
src/cli/ui/hooks/useEditGate.ts:38 on every relaunch.
Closes#644
Plan progress (the `N/M done` counter on the live card and the resume
banner) is only ever advanced by the model calling `mark_step_complete`
after each step. When the model skips that call — and DeepSeek doesn't
always make it — the counter stays at `0/N` even though the work is
finished, and on resume the user sees `0/9 done` next to a plan they
know they completed an hour ago. There was no escape valve.
Two changes:
1. New slash subcommand `/plans done <id>` (single step) and
`/plans done all` (every remaining step). Updates completedStepIds,
persists .plan.json, dispatches plan.step.complete so live UI ticks.
Wired through new SlashContext callbacks that App.tsx owns, so the
in-memory ref stays in sync with disk and the next mark_step_complete
call (if it ever comes) won't re-add a duplicate.
2. Strengthened MARK_STEP_COMPLETE_DESCRIPTION — explicit MANDATORY
marker, explanation of the visible failure mode (0/N on resume),
and explicit "late is still better than never" so the model can
recover at end-of-turn if it noticed it skipped earlier steps.
Closes#641
If the user has scrolled up in the chat history and a pauseGate request
arrives — shell command, plan proposal, plan checkpoint, plan revision,
or ask_choice — the modal mounts at the bottom of the chat area, which
is off-screen below the scroll position. The picker captures arrow
keys, so the user can't scroll back down to see the options either,
and looks stuck.
Calling chatScroll.jumpToBottom() once at the top of the pauseGate
listener flips pinned back on; the modal's useReserveRows triggers
setMaxScroll, which snaps scrollRows to the new bottom under the
existing pinned-mode invariant.
Closes#642
[email protected]'s log-update tracks previousLineCount as logical newlines, not
visual rows. When any rendered line wraps because its visual width
exceeds terminal columns — which happens on CJK / ambiguous-width
content under East Asian terminals — the clear region on the next frame
undershoots the actual on-screen footprint and the bottom of the
previous frame survives. The reported symptom on Windows Terminal at
120×30 with zh-CN content is a duplicated status bar (two horizontal
separators stacked) and stale residue creeping up from below.
shouldClearTerminalForFrame already handles the overflow case, but it
gates on Yoga's outputHeight — which can itself undercount visual rows
for the same width-misjudgment reason, so the fallback misses exactly
the cases that trigger the bug.
Fix: in alt-screen mode, take the clearTerminal path unconditionally.
Alt-screen has no scrollback, so per-frame clear costs nothing visible;
incrementalRendering is already off (chat.tsx:571) so we're paying the
full-frame stdout cost regardless. Patched via patch-package so the fix
survives reinstalls until the same shape lands upstream.
Closes#639
github/[email protected] compiles patterns with `new RegExp(str)`,
which doesn't accept the PCRE `(?i)` inline flag — it throws
`Invalid regular expression: Invalid group` on the first pattern
and the whole label job dies before tagging anything (run 25649833795).
Switch every entry to the `/pattern/i` literal form the action
parses out of slash-delimited strings. Behavior is unchanged
(still case-insensitive); the YAML just speaks JS regex now.
Validated locally: all 14 patterns compile, 17/17 realistic
issue fixtures match the expected labels.
The agents.md open spec (Linux Foundation, 60k+ projects, broad
ecosystem support — Codex, Cursor, Aider, Gemini CLI, JetBrains
Junie, etc.) is the convergence point for "single agent-instruction
file at project root." Forcing a separate REASONIX.md next to an
existing AGENTS.md fragments memory and adds to the file-proliferation
problem the spec was designed to fix.
readProjectMemory now walks REASONIX.md → AGENTS.md → AGENT.md and
takes the first that exists. Writes (# quick-add, dashboard editor)
target whichever file is already on disk, defaulting to REASONIX.md
for fresh projects. AGENT.md drops out of FOREIGN_PLATFORM_FILE_MARKERS
since we now read it instead of flagging it as a foreign workspace.
Closes#635
Two GitHub Actions that fire on `issues: [opened, edited]`:
- `issue-similarity.yml`: actions-cool/issues-similarity-analysis posts
a comment with the top related issues (threshold 0.7) so a reporter
notices duplicates like #633 → #624/#625 without us hand-replying
every time.
- `issue-labeler.yml`: github/issue-labeler applies area / kind labels
by regex on title + body. Config in `.github/issue-labeler.yml` covers
bug / enhancement / documentation / question / dashboard / rendering.
Both use the default GITHUB_TOKEN — no secrets to provision. Judgment
labels (good first issue / rfc / tracking / duplicate / wontfix) stay
maintainer-driven.
The catalog already declares `requiredEnv` (github → GITHUB_PERSONAL_ACCESS_TOKEN
and friends), and `StdioTransport` already accepts an env overlay — but the
bridge call sites never threaded one through. Users had to export the var in
their shell and relaunch.
Adds `mcpEnv: Record<serverName, Record<envName, string>>` to ReasonixConfig,
keyed off the `name=` prefix in the --mcp spec. Stdio specs merge the entry
over process.env at spawn; SSE / streamable-HTTP ignore it (no child process).
Empty-string values are dropped so a blank in config doesn't blank out a
real env var.
Also collapses the four duplicate `spec → transport` ternaries (chat, run,
mcp-inspect, reconnect) into one `buildTransportFromSpec` helper so future
transport additions land in a single place, and pipes the same env lookup
into `/mcp reconnect` so a respawn after a token rotation picks up the new
value.
`reasonix mcp install` now also prints the `mcpEnv.<name>` shape next to its
"needs:" line, pointing users at config.json directly instead of leaving
them to discover the key.
Closes#376
Stable SSH tunnels need a deterministic port. Adds `--dashboard-port`
on `chat` and `code`, plus a `dashboard.port` config key, so the
embedded server binds to the same port across restarts. Resolution
order: flag > config > ephemeral (current behavior). Out-of-range
values warn + fall back; pinned-port EADDRINUSE surfaces through the
existing auto-start failure toast so the user knows the port is
contended instead of silently rolling onto a different one.
Closes#624
* feat(doctor): add --json flag for structured machine-readable output
Enables programmatic consumption of doctor results by CI pipelines and tooling that need to parse health-check status without scraping human-formatted output. Each check now carries a stable `id` so downstream consumers can key off specific checks rather than brittle label strings, while exit-code semantics and the default text output remain unchanged.
* test(doctor): use vi.stubEnv for env isolation in --json tests
Vitest's `vi.stubEnv` and `vi.unstubAllEnvs` provide automatic restoration of environment variables between tests, eliminating the manual save/restore boilerplate that's easy to get wrong. Collapsing the multi-line import also keeps the test file consistent with single-line import style elsewhere.
* feat(ui): add /copy — vim-style copy mode for SSH-friendly chat copy
Drag-select can't extend past the alt-screen viewport in SSH / mosh / tmux,
because the alt-screen has nothing scrollable above it. /copy gives users a
keyboard-driven path to yank chat text without depending on terminal selection.
j/k or arrows move the cursor by line, v starts/cancels a selection, y or
Enter writes the selection through OSC 52 (with the existing temp-file
fallback for >75 KB or terminals that don't honour OSC 52). g/G jump to
top/bottom; q/Esc exits without yanking.
Snapshot is taken at mount (frozen view), spans user / streaming / reasoning
cards; tool / diff / etc. are skipped. Headers are navigable but excluded
from yank, so cross-card selections come out clean.
Closes#614
* docs: add CLI reference — every subcommand, slash, keybinding
Until now /help and /keys were the only way to discover the full surface.
Both READMEs now link to docs/CLI-REFERENCE.md, which mirrors the in-app
content so it's greppable from the repo and indexable on the website.
Includes a copy/paste section with the SSH-alt-screen explanation and
both escape hatches (/copy and --no-alt-screen).
* docs(site): link CLI reference from index footer + configuration CTA
Adds a "CLI reference" entry in the index.html footer's Docs column and
in the configuration page's outro CTA cluster, pointing to the new
docs/CLI-REFERENCE.md. Mirrored in i18n.js + guide-i18n.js for both EN
and zh dictionaries.
* feat(tools): add delete_file / delete_directory / copy_file
The model could only delete or copy files via run_command (rm/cp), but
neither rm nor cp is on BUILTIN_ALLOWLIST — every call hit the user
confirmation gate. Three new sandbox-scoped tools eliminate that
friction:
- delete_file(path) — fs.unlink, refuses directories
- delete_directory(path) — fs.rm recursive by default; recursive:false
falls back to fs.rmdir for empty-only
(Node's fs.rm without recursive rejects
every directory, so the empty-dir path
needs the rmdir variant)
- copy_file(source, dest) — fs.cp recursive, refuses overwrite
All three resolve through the existing safePath() check so paths
outside the sandbox are rejected the same way write_file / edit_file
already are. No description bloat — short single-line teaching plus
the parameter shapes are enough.
12 new tests cover happy paths, refusal conditions (directory /
file mismatch, non-empty refusal, overwrite refusal), parent-dir
auto-creation, sandbox escape rejection, and the read-only-mode skip
(allowWriting:false leaves all three out).
Also extend the plan-mode write-tool list in src/code/prompt.ts so
the model knows these will be bounced under /plan.
* perf(tools): compress run_command / run_background descriptions
Tool descriptions ship in every API request as part of the prefix.
run_command's description was the largest single contributor — six
bulleted constraint paragraphs spanning ~200 tokens, much of it
re-explaining the same shell semantics. run_background then claimed
"Same shell constraints as run_command" but proceeded to re-list a
subset of them anyway.
Compress without losing substance:
- run_command: lead with the one-line summary, then condense the six
constraint bullets into one paragraph that lists supported /
unsupported / cd-doesn't-persist with the same concrete examples
but no prose padding. Drops ~120 tokens per request without losing
any information the model needs.
- run_background: drop the duplicate constraint listing (still
inherits from run_command), keep the Vite gotcha (high-value pitfall
the model gets wrong) and the "use this for npm dev / uvicorn /
tsc --watch" guidance. Drops ~60 tokens.
Net per-request prefix saving: ~180 tokens. Across a typical 50-turn
session that's ~9000 tokens off the parent prompt.
The subagent loop has used a setResultAugmenter-driven budget tail since
0.36 — when within BUDGET_WARN_THRESHOLD of the per-spawn cap, every
tool result picks up `[budget: K of N tool calls left — wrap up soon]`,
and at 0 left a stronger finalize-NOW form. The parent CacheFirstLoop
exposed the same setResultAugmenter hook on the registry but never
wired a consumer, so the model running in the main session had zero
runtime visibility into its iter budget. The user-facing 70% warning
fires to the TUI, not to the model — when it hits iter 60 of 64 it
still has no signal it's about to be force-summarized.
Wire an analogous augmenter on the parent loop (threshold 5, slightly
wider than subagent's 3 since the parent's default 64-cap is 4× larger)
and reset the per-step counter at step entry so consecutive turns don't
accumulate. Constructor checks ToolRegistry.hasResultAugmenter first so
subagent's pre-installed child-registry augmenter survives — the
constructor must not clobber it.
Also flag wait_for_job as parallelSafe + stormExempt: concurrent waits
on different jobs are safe, and polling-loop is the intended pattern so
the storm breaker shouldn't trip on it.
* feat(prompt): add audit-mode rails for review/critique tasks
When the user asks Reasonix Code to audit its own architecture, the
existing "cite or shut up" rule covers absence claims but doesn't
catch the more common audit-mode failure: confident, well-structured
proposals built on factually wrong premises about runtime behavior,
fabricated quantities, or recommendations that contradict pinned
memory.
Adds a six-bullet section after "Cite or shut up": auto-preview is
for locating not auditing, flag→consumer trace before claiming
runtime behavior, no fabricated percentages, schema-cost accounting
for new-tool proposals, MEMORY.md as design constraint, and
user-facing ≠ model-facing as a category-error guardrail.
Closes#610.
* prompt: tighten rails #2 and #6 from real audit-session failure modes
Audit session run against the original 6-rail section (#610) showed
two failures the wording didn't catch:
1. **Inventory-claim hallucination.** Asked which tools have
`stormExempt: true`, the model enumerated 6 file-system tools as
having it — only 2 actually do. The rail said "trace flag to
consumer", which the model interpreted as "for one named tool",
not "for an inventory claim covering many tools." Add an explicit
inventory clause: grep the flag, don't enumerate from memory.
2. **Library API → dead-code mischaracterization.** The model
labeled `registerSubagentTool` "dead code from CLI perspective"
on the basis of a clean grep in `src/cli/`. It's a deliberate
library export consumed by embedders via `src/index.ts`. The
rail enumerated three surfaces (slash / tools / UI); add a fourth
(library) so library exports aren't mistaken for unused code.
Two-test bump on tests/code-prompt.test.ts so the tightened wording
can't silently regress.
* prompt: broaden rail #1 to cover doc / state claims, not just runtime
Second audit session run against the tightened rails (#611) showed
the same head-only-then-conclude failure mode again, this time on a
plan-doc file rather than runtime code: the model read the head of
docs/plans/architecture-refactoring-roadmap.md, saw "8 services
still use singletons", and asserted the plan was now stale —
without reading the rest of the doc to check for a "Status: done"
section that might have been there.
The original rail was scoped to "runtime behavior" because that was
the loop.ts dispatcher case from #610. The same blind spot applies
to any file: don't conclude what's in the elided middle off head +
tail. Broaden the wording to cover runtime behavior, current
architectural state, and doc freshness explicitly.
One test bump on tests/code-prompt.test.ts so the broader scope
can't silently regress to runtime-only.
The split-string approach (codeRooted + session + nativeTools as separate
t() calls) dropped the comma+space between rootDir and session in both
EN and zh-CN, and locked the word order across languages. Fold the four
fixed segments into a single codeRooted template with {rootDir} /
{session} / {tools} / {semantic} placeholders so each locale owns its
full sentence and translators can reorder freely.
Add tests/startup-banner-i18n.test.ts to lock both rendered banners.
* feat(i18n): localize confirmation modals, HintRow, and remaining cards with zh-CN
* feat(i18n): localize pickers (SessionPicker, ModelPicker, SlashSuggestions, AtMentionSuggestions) with zh-CN
* feat(i18n): localize StatsPanel, WelcomeBanner, ctx-breakdown with zh-CN
* fix: adjust zh-CN translations based on user feedback
* feat(i18n): localize web search errors, startup message, and doctor diagnostics with zh-CN
* fix: remove duplicate namespaces from rebase and reformat
The subagent sink mirrors every child LoopEvent (assistant_delta /
reasoning_delta / tool_call_delta) into useSubagent's inner branch.
The map callback always allocated a new array reference, so React
re-rendered App.tsx + SubagentLiveStack on every child delta — with
3 parallel subagents streaming, that was 90+ no-op re-renders/sec
each forcing a Yoga layout pass. Closes#554.
Pull the inner/progress/phase logic into a pure reducer that returns
prev by reference when no row would change, and also memoize
ToolCard's spawn_subagent JSON.parse so the inflight-context tick
doesn't re-parse 8 KB on every passing tool start/finish.
The always-visible composer hint row hardcoded English labels and omitted the `^U` clear chord, leaving it undiscoverable without reading source. It also referenced a non-existent `composer.hint` key that would leak the literal path to users when no abort hint was active. Routing the row through `HintRow` with proper i18n keys keeps the chord vocabulary discoverable in both locales and removes the broken key fallback.
Layer 1: rewrite the "Delegating to subagents" section in code/prompt.ts
and the spawn_subagent tool description from "when to delegate" to
"default: don't delegate". Lead with the two narrow exceptions where a
spawn pays for itself (parallel fan-out, >10-read context blow-up) and
name the anti-patterns explicitly (single grep, 1-3 file cross-ref,
"keep my context clean for one question").
Layer 2: track per-session spawn count + cumulative subagent tokens in
the registerSubagentTool closure. After each spawn, append a hint to
the JSON tool result. Soft note from spawn 2 onward, strong "justify
the next spawn" hint past 5 spawns or 50k tokens. The hint surfaces
on the model side via the same shape as the existing per-child iter
budget hint (subagent.ts:189), so the model already knows how to read
it.
Layer 3 (single-call refusal gate) deferred until we see whether 1+2
moves the storm pattern in #415 / #553.
Closes#553.
Rolling #594 into 0.37.0 since the version was bumped but not yet
tagged or published to npm. Tag will land on this commit so the
published 0.37.0 contains the fix, no 0.37.1 needed.
The empty-state guard checked !hasConversation && !busy && !isStreaming
but missed the slash-suggestions overlay. Pressing `/` from the home
screen left the bordered welcome card mounted in the flex column while
SlashSuggestions rendered below, producing interleaved frame output
where the card border drew through the menu rows.
ESCALATION_CONTRACT was a const with `deepseek-v4-flash` baked in,
interpolated into three system prompts at module load. A pro session
got told it was running on flash, so when the user asked "which model
are you?", pro answered "flash" — accurately reading what the prompt
told it.
- Convert ESCALATION_CONTRACT → escalationContract(modelId): pro tier
gets a short "you are the escalation tier" note (no <<<NEEDS_PRO>>>
ladder, since pro can't escalate to itself); other tiers get the
contract with the actual model id interpolated, plus an explicit
"if asked which model you are, answer `<id>`" line.
- DEFAULT_SYSTEM (cli/index.ts) → defaultSystemPrompt(modelId), called
per chat / run / bare-reasonix invocation against the resolved model.
- CODE_SYSTEM_PROMPT split: the public-API const stays at the
historical flash phrasing for backward compat; codeSystemPrompt now
takes opts.modelId and the code command threads in opts.model.
- DEFAULT_SUBAGENT_SYSTEM split into a memory-stable base + per-spawn
contract appended against the spawn's resolved model id.
Closes#582
A skill whose frontmatter omits `description:` was silently dropped
from the prefix index, but `/skill <name>` still ran it from disk —
so it worked in the install session and vanished in the next one,
with no diagnostic.
- POST /api/skills/<scope>/<name> now validates frontmatter via
validateSkillFrontmatter() and returns 400 instead of writing a
skill the model will never see.
- applySkillsIndex no longer filters out blank-description skills;
it injects them with a placeholder line that names them and tells
the model to flag the missing frontmatter to the user.
Closes#583
clearLog() truncated the live session jsonl in place, so users running
/new lost every previous turn — the dashboard's Sessions tab faithfully
reported one row because there was one file. Rotate the live jsonl plus
sidecars to <name>__archive_<ts> so the prior conversation survives in
Sessions. sessionName is unchanged, so the prefix cache stays warm.
The __archive_ infix sits outside the ${name}- resume-prefix matcher,
so archives don't get auto-resumed on next launch.
Closes#587
chatCommand used to `await runtime.addSpec(raw)` once per server
before render() — every handshake (100ms-2s) blocked the alt-screen
from coming up, so users with MCP configured saw a black screen
on startup.
Now mcpRuntime exposes a setLifecycleSink(sink) hook. chatCommand
hands the empty mcpServers array off to App immediately; App.tsx
swaps in a log-routing sink on mount and fires runtime.addSpec
(spec, loop) for each requested spec in the background. As each
server bridges, hot-add pushes its tools into loop.prefix and
setLiveMcpServers refreshes the /mcp panel live. Lifecycle events
(handshake / connected / failed / slow) flow into the in-app log
instead of stderr — stderr writes during alt-screen would corrupt
the UI.
UI now paints immediately even with N MCP servers configured.
Servers that fail to connect just stay unavailable; their tools
never bridge — same end state as before, just without the wait.
Adds src/cli/ui/BootSplash.tsx — a full-screen splash that AppInner
returns from before its first real paint, gated by a 1.4s timer
(one whale-spout cycle). Two purposes:
- Hides the brief alt-screen-blank gap on cold launch (heavy
AppInner first-paint cost stays under the splash).
- Brand mark always lands clean instead of flashing raw mount
state.
Splash content:
- ANSI Shadow REASONIX wordmark (6-row block letters, brand color)
- Three-tone shaded whale silhouette (░ outline / ▒ midtone /
▓ inner) with eye, mouth, tail flukes
- 7-frame spout animation cycling at 200ms (idle → rising →
peak with droplets → dispersing)
- Wave line below shifting one column per frame
- 'loading...' indicator with cycling dots
App.tsx wires bootReady state + setTimeout, returns <BootSplash />
until ready.
useLanguageReload() returns a counter that increments on
runtime language changes — same shape as before, just owns its
own useState + onLanguageChange subscription. Lets App.tsx drop
the onLanguageChange import.
Step 7/7 of #565 phase 1. App.tsx LOC unchanged (one import line
in, two hook lines out).
usePresetMode(model) bundles the three model-mode states:
- preset: "auto" | "flash" | "pro" (initial seeded from model)
- proArmed: /pro pending for next turn
- turnOnPro: current turn is on v4-pro (arming consumed or
⇧ pro auto-escalation fired)
App.tsx loses three useState calls plus the inline narratives.
The states and their setters are destructured back so handleSubmit
+ startDashboard's handlers stay structurally identical.
Step 6/7 of #565 phase 1. App.tsx 3701 -> 3695.
useHookList(initialProjectRoot) returns hookList + a reloadHooks
helper that bundles loadHooks() + state replacement. The two
slash callbacks (`/hooks reload`, `/cwd`) and the dashboard
mutation surface now call reloadHooks(projectRoot) instead of
duplicating the loadHooks + setHookList pattern.
App.tsx drops the loadHooks + ResolvedHook imports along with
the inline initial-load comment and the three duplicate
load-and-set blocks.
Step 5/7 of #565 phase 1. App.tsx 3715 -> 3701.
useWorkspaceRoot(launchRoot) returns currentRootDir +
setCurrentRootDir + currentRootDirRef and runs the ref-mirror
effect. App.tsx loses one useState, one useRef, one useEffect,
and the long inline narrative explaining what each
rootDir-dependent surface reads.
The /cwd slash handler still composes the swap (re-register
tools + reload hooks + re-bootstrap semantic) — only the state
+ ref ownership moves into the hook.
Step 4/7 of #565 phase 1. App.tsx 3723 -> 3715.
Bundles pendingEdits ref + pendingCount mirror + pendingTick +
syncPendingCount + editMode + editModeRef + saveEditMode
persistence + the 1.2s mode-flash effect into one hook in
src/cli/ui/hooks/. App.tsx loses three useState calls, two refs,
two effects, and several long inline narratives — those are now
single-line field docs on the EditGate interface.
Note: the tool interceptor stays in App.tsx for now — it's tangled
with review-modal state (pendingEditReview / editReviewResolveRef /
turnEditPolicyRef), which want their own hook in a follow-up.
Step 3/7 of #565 phase 1. App.tsx 3760 -> 3723.
Bundles ongoingTool / toolProgress / statusLine state + the
progressSink wiring + the turn-end clear() into one hook in
src/cli/ui/hooks/. Long inline narratives explaining the
pulse-spinner row / progress frame / silent-phase status line
move out of App.tsx; the hook's name carries the role.
Step 2/7 of #565 phase 1. App.tsx 3785 -> 3760.
DECSET 2004 / modifyOtherKeys / DECSET 1007 setup+cleanup moves
to its own hook in src/cli/ui/hooks/. App.tsx no longer owns the
escape-sequence dance; the long inline narrative collapses to one
line documenting the only non-obvious choice (1007 over full
mouse tracking).
Step 1/7 of #565 phase 1. App.tsx 3816 -> 3785.
After A+B (#573) the App-level render cost on scroll was gone, but
Yoga still had to lay out every card in CardStream's inner Box on
every frame — for a 50-card history, that's hundreds of rows
re-measured per scroll tick.
This PR adds card-level virtualization. Each card is wrapped in a
MeasuredCard that captures its row height via useBoxMetrics and
reports it to the chat-scroll store. CardStream then walks the cards
once per render, computes the cumulative offset of each, and decides:
- live render the card (it's inside the viewport ± 30-row buffer, OR
its height isn't cached yet so we need to measure it), or
- collapse it into a spacer Box of the cached height.
Adjacent collapsed cards merge into a single spacer, so the off-screen
ranges add up to one Yoga node above and one below the visible cards.
Total inner-Box height stays exact, so marginTop={-scrollRows} still
lands on the right rows and maxScroll is correct.
Edge cases:
- New cards (id not in heights map) always render live so the first
measurement happens. Once cached, they collapse next frame.
- Streaming cards re-measure on every render — their height changes
and the cache stays fresh through the same path.
- pruneCardHeights drops heights for cards that disappear from the
list (resumed sessions, /clear), so the map can't grow unbounded.
For a session with 50 cards and ~600 row total height, only the ~5-10
cards under the viewport go through Yoga per scroll. The off-screen
work that was making long sessions feel sluggish is now gone.
Wheel/arrow ticks were re-rendering all of AppInner — 3,800 lines and
122 hook calls — even though the actual UI delta was a single
marginTop change in CardStream. Each scroll paid the full hook-eval
tax before Yoga layout and Ink commit could even start.
The fix has two parts:
1. New chat-scroll store under src/cli/ui/state/. Same useSyncExternalStore
pattern as the agent store — selectors subscribe per-slice, actions
are stable refs. CardStream now reads scrollRows directly from it;
App.tsx only takes the action callbacks (which never change identity).
The "reading history" branch that depended on `pinned` moves into
InputAreaWithHistoryHint, a leaf that subscribes to pinned in
isolation. Net: scroll ticks no longer re-render App.tsx at all.
2. Visual polish.
- Wheel/PgUp/PgDn step from 8 to 5 rows. Smaller jumps read as
smoother continuous motion in a cell-based TUI.
- The "↑ earlier" line is now a live position indicator
("↑ N / M rows above — K more · PgUp / wheel / ↑").
- The indicator briefly switches to the accent color on every
applied delta (scrollVersion bump), so the user gets visual
confirmation the wheel registered before the new frame paints.
Removes the old src/cli/ui/hooks/useChatScroll.ts; nothing else used it.
Hotfix: the squash merge of #571 landed with a 5-line block comment
that violates tests/comment-policy.test.ts (cap is 3 lines). The
fixup commit was pushed to the branch after the auto-merge had
already fired, so it never made it onto main.
Wheel-up felt laggy because every tick paid a full 16 ms wait before
any visual feedback — schedule() was trailing-edge: first call started
a setTimeout, the actual setScrollRows didn't run until the timer
fired. With Ink's reconcile + Yoga layout on top of that, a single
wheel tick took 30-50 ms to land visibly.
Two changes:
1. Leading-edge schedule. First call applies the delta immediately
(instant feedback on first wheel tick), opens a 16 ms window during
which subsequent calls accumulate into pendingDelta, and lands one
trailing flush. Fast scrolls still produce only one re-render per
window, but the user no longer waits for a slow tick to feel.
2. Split arrow step from page/wheel step. SCROLL_ARROW_ROWS stays at
3 (fine-grained ↑/↓). New SCROLL_PAGE_ROWS = 8 covers PgUp/PgDn
and the wheel-via-DECSET-1007 path. Each wheel tick now travels
roughly a third of a typical viewport instead of three lines.
Vertical-jitter reports were tracing back to the 16ms (60Hz) flush
default — on winpty/MINTTY/ConEmu/tmux/high-latency-SSH the cursor-up
repaint can't atomically swap the frame at that rate, so users see
the old frame's bottom rows briefly through every redraw. 50ms (20Hz)
is still continuous-feeling for streaming text and stops the bobbing
on every terminal we've seen affected. Override via REASONIX_FLUSH_MS
when running on a terminal with atomic frame swap.
REASONIX_UI=plain is removed: it was the nuclear escape hatch for the
same problem, but it suppresses every live row (streaming text, tool
spinner, plan progress, undo banner, subagent stack, status line) —
i.e., most of what makes the TUI useful. The slower default flush
addresses the same terminals without that tradeoff.
Adds a dedicated configuration guide page (docs/configuration.html)
covering MCP, skills, memory, hooks, permissions, web search, and
the semantic index — bilingual (en/zh) with scrollspy TOC.
Landing page: hero gets a real-metric strip (counts up once when
scrolled into view), orbital SVG decoration, status pill. The
"Configure in five minutes" teaser block links into the guide.
README cleanup: pulls Configuration into prime real estate, collapses
the chat-vs-code / working-folder / first-skill detail into a
<details> block, drops the standalone Web Search section (now
covered by the guide), tightens install copy. Mirrored in zh-CN.
SEO: correct og:url (was pointing at the wrong repo path), canonical,
hreflang en/zh-CN/x-default, JSON-LD SoftwareApplication + WebSite
on landing, TechArticle + BreadcrumbList on guide, Twitter card
metadata. Adds docs/robots.txt and docs/sitemap.xml.
Perf: stripped scroll-reveal, card spotlight + 3D tilt, capability
marquee, backdrop-filter on metrics row, fractal-noise overlay,
content-visibility, gradient-text shimmer, and section-beam
animations after they made the page feel laggy. Background is now
fully static — dot grid, three glow blobs, horizon hairline.
Only one-shot animation left is the metric count-up; the brand
mark, status dot, and terminal caret keep their tiny scoped pulses.
Surfaces a SingleSelect modal for the terminal theme preference. Bare
\`/theme\` opens the picker; \`/theme <name>\` keeps its existing
"persist and report" behaviour. Moves the slash entry from the
advanced group to setup and adds high-contrast to the arg completer.
Adapted from J3y0r's PR — repointed onto current main (which had
since reformatted App.tsx around the InflightProvider wrap from
#566) and the count test in tests/ui-slash-suggestions.test.tsx
updated from 12 → 11 advanced commands now that /theme has moved
out of the advanced bucket.
Thanks @J3y0r for the contribution.
Closes#557
Tool spinners occasionally kept spinning after the underlying work had
finished. The cause: status was set imperatively from paired tool_start
/ tool events, and every code path that exits a dispatch had to
remember to emit the closing event — normal return, throw, abort,
storm-breaker, network drop. Miss one and the card was stuck.
Switch the running flag to a derived view:
- New InflightSet (src/core/inflight.ts) with add / delete / has /
subscribe + notify-on-mutation. Parallel finally-driven cleanup is
the contract: the language guarantees finally on every exit path,
so there's no closing event to forget.
- CacheFirstLoop holds one. runOneToolCall adds the call's id at
function entry and deletes it in finally; the chunk-loop pre-adds
before yielding tool_start so the very first card render already
reflects the running state. clearLog drains the set on /new.
- LoopEvent.tool_start / tool now carry callId — same id used as the
inflight key. TurnTranslator threads it into Scrollback.startTool,
which uses it as the card id so the card and the inflight key match.
- InflightProvider + useIsInflight (src/cli/ui/state/inflight-context.tsx)
expose the set as a React context backed by useSyncExternalStore.
ToolCard's toolStatus consults the hook for "running"; card.done is
no longer the spinner discriminator, only terminal flavor (ok /
rejected / aborted / error).
Tests:
- tests/inflight.test.ts — InflightSet contract: idempotent add,
notify-only-on-change, listener errors don't break the gate, clear,
finally-on-throw, finally-on-abort, parallel allSettled.
- tests/loop-inflight.test.ts — runOneToolCall finally clears the
set on success and on tool throw; tool_start carries callId
matching the inflight key; clearLog drains.
Out of scope (follow-up): subagent runId in the same set; deriving
streaming/reasoning running flags. Both are mentioned in the issue
but live behind different leak surfaces; the tool-card path is the
one users see most.
Chrome's "Page not responding" dialog fires on the dashboard chat tab
once a session accumulates enough messages. Repro condition: long
streaming turn or several concurrent jobs broadcasting at once.
Two cooperating bugs on the chat feed's hot path:
1. Every assistant_delta event hit setState synchronously. The model
streams ~20 deltas/sec; each one re-rendered ChatPanel, which
.map'd over every historical ChatMessage with no memoization, so
each one re-ran marked.parse + (for tool messages) hljs syntax
highlight on UNCHANGED content. Long sessions = N grows = main
thread starves.
2. The `streaming` prop fed to historical ChatMessage flipped between
`null` (no streaming) and `false` (streaming-but-not-this-message)
across turns, so even with memo, `null !== false` would force
every historical message to re-render every time streaming
started or stopped.
Fix:
- Wrap ChatMessage in `memo` from preact/compat so historical messages
with stable `msg` refs short-circuit re-renders.
- Cast the per-row streaming prop to a boolean so historical
messages get a stable `false` and memo's shallow compare actually
bails out across streaming-on/off transitions.
- Coalesce assistant_delta into a single rAF-batched setStreaming.
Multiple deltas in the same frame collapse into one state commit;
the streaming bubble's re-render rate is capped at the display
refresh rate. assistant_final + SSE reconnect + unmount each
cancel the pending flush so the buffer can't leak across turns.
Closes#551
When the sandbox root contained another product's data dir (Hermes
Agent's SOUL.md, skills/, memories/, etc.), the model would browse
those files and infer it was a sub-profile or runtime layered on top of
the host product. The system prompt defines the assistant as a
standalone coding assistant; the workspace contents shouldn't override
that.
Two layers:
- Top-of-prompt identity section names the failure mode explicitly:
workspace files describe the user's project, never what Reasonix is.
Calls out SOUL.md / AGENT.md / PERSONA.md / foreign skills+memories
trees / a foreign REASONIX.md as not-the-spec, and tells the model to
answer "who are you?" from the prompt instead of running ls.
- detectForeignAgentPlatform(rootDir) flags the workspace at launch if
one of those markers sits at the root, and the code-mode banner adds
a one-line warning suggesting --dir <real-project>. Conservative
signal: lone skills/ doesn't trigger (common in coding repos);
skills/ + memories/ pair does.
Closes#550
When a tool awaits pauseGate.ask (plan_checkpoint, plan_proposed, etc.),
the gate's promise ignores AbortSignal. Esc-during-busy fires
loop.abort(), but the awaiting tool fn never returns, so:
- busy stays true forever — PromptInput stays disabled.
- The pending modal (or its plan card) can't be dismissed.
- /new is silently dropped by handleSubmit's `if (busy) return`,
so the user can't even wipe the session to start over.
Add pauseGate.cancelAll() that resolves every outstanding request with
its kind's safe-cancel verdict (deny / cancel / stop / cancelled). Wire
it into a resetPendingModals helper that also clears every pending*
modal state, and call it from both Esc-during-busy and apply-slash-
result's clear branch. The awaiting tool fn now returns or throws
cleanly, busy clears, and the user can recover.
The "↑ earlier" hint was rendered conditionally on scrollRows > 0, as a
sibling of the measured outer Box. That tied outer.height to scrollRows:
toggling the hint changed outer.height by one row, which changed
maxScroll, which pinned-mode wrote back as scrollRows, which toggled
the hint again. With streaming content compounding inside the same
React batch, the chain reached MAX_NESTED_UPDATES = 50 and aborted with
"Maximum update depth exceeded" inside ink's useBoxMetrics.
Reserve the hint row unconditionally so outer.height is independent of
scrollRows. Trade is one row of permanent reservation; the loop is
gone.
The picker UI sorts suggestions by usage count (slashUsage) but the
Enter-time substitution recomputed the list without it, so the list
the user navigated and the list dispatch indexed into were ordered
differently. The shared slashSelected index then dereferenced a
different command than the highlighted row.
Pass slashUsage through so both calls produce identical orderings.
Rolling PR #538 into 0.36.0 since the version was tagged but not yet
published to npm. Tag will be moved to this commit so the published
0.36.0 contains the fix, no 0.36.1 needed.
SlashSuggestions called useColor / useStdout / useState before two
early-return branches (matches === null, matches.length === 0), then
useEffect afterward. When matches flipped from non-null/non-empty to
either of the early-return states and back, React saw 4 hooks one
render and 3 the next — "Rendered more hooks than during the previous
render" crash, killing the whole TUI.
Hoist windowStart computation + the useEffect above the early
returns. Compute against `matches ?? []` so the math is well-defined
when matches is null (windowStart resolves to 0, the effect no-ops
because state already equals 0). The early-return JSX branches stay
unchanged below.
Regression test rerenders the component through
non-empty → null → empty → non-empty and asserts no throw.
* chore(release): 0.36.0
* test(status-row): pin status-line version assertion to live VERSION import
Hardcoded "v0.35.0" string broke on every release bump. Reading from
src/version.js means future releases don't need a coordinated test
edit alongside the package.json bump.
* test(mcp): bump startup-summary timeout to 15s — chronic flake under suite load
captureStartupState dynamically imports chat.js + tools.js inside the
test, which can blow past Vitest's 5s default when the worker pool is
saturated (148 test files, lots of cold cache). Passes in isolation,
flakes under `npm test` parallel load. 15s adds headroom without
slowing the happy path.
Bracketed-paste markers (DECSET 2004) don't arrive on every host —
multiplexers strip them, some web-SSH gateways drop them, certain
Windows pipes never forward them. When they're missing, a multi-line
paste arrives as raw bytes; each \r in the chunk gets dispatched as
an Enter event; PromptInput submits the partial buffer; the loop
fires a fresh agent call per line. Reporter saw multi-line paste
trigger multiple submits in a row.
Heuristic rescue at the parser entry point: when a chunk in idle
state contains 2+ line breaks, OR a single line break with non-empty
text on both sides, AND no ESC bytes (would indicate a real key
sequence) AND no existing paste markers, wrap it in synthetic
\x1b[200~ … \x1b[201~ before processing. Routes through the existing
paste accumulator so it lands as ONE paste event with the whole blob.
Asymmetric tradeoff is intentional — a false-positive paste makes the
user re-press Enter; a false-negative paste fires N prompts and burns
N agent calls. The detector errs toward paste.
Bare \r and \r\n stay typed-Enter (terminal-converted CRLF is one
keystroke, not two breaks). "abc\r" stays typed-then-Enter, so a
fast typist's batched chunk still submits.
Updated the printable-coalescer split test to use \t since \r/\n now
route through the heuristic rescue when surrounded by text.
Closes#522
When the user picked Refine on PlanConfirm and typed their suggestion,
the model never saw the text. `handleStagedInputSubmit` built a rich
`synthetic` string with the feedback embedded but only resolved the
PauseGate with `{ type: "refine" }` — no payload. submit_plan threw
the bare `Error("user requested refinement")`, the model received
that as the tool result with zero context, and proposed a near-
identical plan, which fired PlanConfirm again. From the user's
perspective the suggestion was silently dropped.
The PlanVerdict union didn't even allow a feedback field, so the
omission was structural. The CheckpointVerdict pattern (already
shipping for revise-at-step) had the right shape; submit_plan just
never adopted it.
Pipe feedback through PlanVerdict for all three outcomes (refine /
approve / cancel) and surface it in the tool result string so the
model sees the user's exact words. Drop the dead `synthetic` that was
being built and discarded; keep `marker` and emit it via `pushInfo`
so the user gets a visible confirmation in chat scrollback right
after they hit Enter.
Closes#533
The /api/events endpoint snapshots only `busy-change` on (re)connect.
When the SSE connection drops mid-task — proxy timeout, browser
background-tab throttle, or Node event loop blocked past the 25s ping
window during heavy work — every assistant_delta / assistant_final /
tool / modal-up event fired during the disconnect window is lost.
EventSource auto-reconnects, but the new stream only carries new
events. If the disconnect happened before the end-of-turn
busy-change(false), the UI is wedged on "busy" forever and the
completed reply never appears. Reopening the dashboard URL was the
only escape, since fresh page load fetches /api/messages.
On reconnect (every onopen after the first), refetch /api/messages
and /api/modal to recover canonical state. Streaming + active-tool
slots reset since they're transient — the next delta will repopulate
streaming, the next tool_start will repopulate active-tool. First
open is skipped because the boot effect already fetched canonical
state.
Closes#521
* fix(tui): enable DECSET 1007 alternate-scroll so wheel scrolls on cloud/web terminals
Previously we relied on the implicit "terminal translates wheel→↑/↓ in
alt-screen" behavior. That only holds on local desktop terminals
(xterm/iTerm/Windows Terminal/Alacritty) where alt-scroll is on by
default. Web/cloud/SSH terminals (xterm.js, code-server, Cloud Shell,
mobile SSH clients, tmux without `mouse on`) don't ship with that
default, leaving the wheel as a dead key — the most common
"can't scroll" report.
Explicitly request the behavior via DECSET 1007 (alternate-scroll) on
mount, reset on unmount. Falls back silently on terminals that don't
recognize 1007. Native drag-select and right-click are untouched —
no Shift bypass needed.
`--no-mouse` opts out for the rare user who'd rather suppress the
sequence entirely.
* fix(tui): disable Ink incrementalRendering to drop render ghosting
Incremental render diffs against an internal "what's on screen"
snapshot. The diff drifts when:
- string-width misjudges CJK / emoji ZWJ cell width and Ink
miscomputes the affected region
- async terminal-event bytes (DA replies, mouse, focus) interleave
between Ink's cursor-positioning writes
- terminal resize races a flush
When the diff drifts, stale rows survive the redraw — the residual
"ghost" class users have been reporting on cloud/web terminals.
Full-frame redraws sidestep the snapshot. Cost: more stdout bytes per
flush. At 60Hz default flush, local terminals are unaffected; remote
SSH only feels it during sustained high-rate streaming, where the
existing REASONIX_FLUSH_MS escape hatch can drop to 30Hz.
Replace hardcoded English strings in 8 card components (Ctx, Error, Reasoning, Search, Streaming, SubAgent, Tool, Usage) with t() calls. Pluralization handled at the call site via singular/plural key pairs (Chinese maps both to one form). Adds cardTitles + cardLabels namespaces to EN.ts / zh-CN.ts / types.ts.
Levenshtein-rank registered command names against unknown slash input; surface up to three closest candidates inline in the dispatch response. Falls back to the existing "(try /help)" hint when nothing is within distance threshold. Closes#17.
Collapse case-variant PATH / PATHEXT keys (Path / PATH / path) into one normalized entry before passing env to child_process.spawn on Windows, and read PATH / PATHEXT case-insensitively in resolveExecutable so the spread env (which is a plain object, not the case-insensitive process.env Proxy) still resolves bins. Refs #520 — does not auto-close; awaiting reporter verification that Machine PATH inheritance is restored.
Slot a theme step between language and apiKey so the rest of the wizard renders in the chosen theme. Live preview updates as the user navigates the list; default highlight lands on the currently-resolved theme; commit writes through writeConfig. Sample tile exercises tone.accent / tone.info / tone.ok / tone.warn / tone.err + fg.meta. Closes#492.
Rework SlashSuggestions windowing so grouped headers are budgeted into the visible row count and selection moves through commands without skipping group rows. Wrap StatusRow children with flexShrink/height/wrap=truncate so the status bar no longer collapses under the suggestion popup. Surface /language as a visible setup command. Filter order in suggestSlashCommands now also exposes code-group commands in bare browsing — flagged for follow-up if undesired.
We write to stdout at the streaming flush rate, and the terminal has
to interleave those writes with its own native drag-select highlight
repaints. At 30Hz (33ms) the terminal can't keep up — selection
feedback visibly lags during model output. Now that mouse mode is
off (#514) and users actually use drag-to-select again, this is the
load-bearing perf knob.
50ms (20Hz) still feels smooth on every modern terminal we test on
(WT, WezTerm, iTerm2, Alacritty, Ghostty) and cuts the write rate by
33%, leaving terminal repaint enough budget to keep selection
highlights snappy. `REASONIX_FLUSH_MS=33` brings the old behavior
back for anyone who actively prefers it.
* fix(tui): drop xterm mouse tracking; ↑/↓ scroll chat, Ctrl+P/N owns prompt
Multiple users reported they can't copy text and can't scroll. Both
trace to the same root cause: we enabled DECSET 1000 + 1006 mouse
tracking so the wheel could route through `mouseScrollUp/Down`. The
side effect is that every terminal we know about then refuses to
start a native drag-select on click, blocks right-click, and on
ConPTY / multiplexer setups can drop the wheel events entirely (so
neither path scrolls).
Architecture flip:
- Don't enable mouse tracking. Bracketed paste + modifyOtherKeys stay.
- ↑/↓ at the App level always scroll chat, no buffer-state gating.
Terminals translate the wheel to ↑/↓ in alt-screen mode, so the
wheel still scrolls chat — for free, in every terminal.
- Ctrl+P / Ctrl+N take over what ↑/↓ used to do in PromptInput:
cursor up/down inside a multi-line draft, falling back to prompt
history when no cursor move is available (readline parity).
- /keys + tipMouseClipboard rewritten to reflect the new bindings;
the old "hold Shift to drag-select" workaround is gone — drag
works directly now.
Cost: power users who liked the wheel-scroll-while-typing affordance
have to switch to PgUp/PgDn or empty their prompt. Worth it given
how many users hit the copy-paste wall.
* fix(tui): update prompt hint row + stale comments to reflect ↑↓ scroll / Ctrl+P/N history binding
* fix(tui): don't scroll chat when a picker owns ↑/↓ (slash / @-mention / slash-arg / shell-confirm)
Two compounding bugs sent self-hosted DeepSeek users back to the
official endpoint regardless of how they configured the client:
1. config.baseUrl was a dead field. Every `new DeepSeekClient()` call
site (App.tsx, commit.ts, doctor.ts, run.ts) constructed the
client without passing baseUrl, so it always fell back to the
`DEEPSEEK_BASE_URL` env var or `https://api.deepseek.com`. The
dashboard settings panel saved the value but nothing read it.
2. isPlausibleKey enforced the `sk-` prefix, so the wizard / setup /
`/feedback` settings rejected any token that didn't look like an
official DeepSeek key — even when the user had pointed baseUrl at
their own deployment.
Adds `loadBaseUrl` (env > config > undefined) + `saveBaseUrl`, plumbs
the loader into all four client construction sites. Relaxes
isPlausibleKey to a generic typo guard (16+ chars, no whitespace) so
self-hosted token formats work; the real auth check is the first API
call against baseUrl.
Closes#502
The dashboard health card, overview cockpit, and /feedback diagnostic
all decided "up to date" via `latest === installed` string equality.
That fires false-positive "needs update" / "(latest: 0.31.0)" pills
whenever the cached latest is older than the installed version — for
example after publishing 0.35.0 while the 24h cache still holds the
prior latest.
Switch all three sites to `compareVersions(installed, latest) >= 0`.
Add a tiny dashboard/src/lib/version.ts so the browser bundle has the
same comparator the CLI uses (no cross-package import).
Closes#510
`reasonix update` previously always emitted `npm install -g`, which
clobbered bun/pnpm/yarn installs and was unpredictable under nvm/fnm
where ambient npm may resolve to a different node runtime than the one
running the binary.
Detection (`detectInstallSource`) reads argv[1] and matches each
manager's unique global path segment:
- `_npx/`, `.pnpm/...dlx/`, `npx/` UA → npx
- `.bun/`, `bun/install/` → bun
- `pnpm/global/` → pnpm
- `yarn/global/`, `.yarn/global/` → yarn
- `node_modules/reasonix/` → npm
- otherwise → unknown
Plan emits the matching command per source. For npm we additionally
pin `--prefix=<extracted-prefix>` so nvm/fnm runtime switches don't
redirect the install elsewhere. For unknown source we refuse with a
manual hint listing all four commands and exit 1 — no silent npm
fallback.
Closes#506
PATH refreshes per-shell on Windows, so a dashboard process started
before the Ollama install (or before a Terminal restart) inherits a
stale PATH and `where ollama` returns nothing — even when the daemon
the user launched from the tray icon is fully serving requests.
Two changes:
- findOllamaBinary falls back to %LOCALAPPDATA%\Programs\Ollama\
ollama.exe when `where` fails. spawn() for `serve` / `pull` now uses
the resolved path so those buttons survive a stale PATH too.
- ready no longer requires binaryFound. The embedding pipeline only
talks to the HTTP API; the binary is only needed for daemon-start
and model-pull, which have their own UI guards.
Closes#504
* chore(format): reuse fmtPct for cache-hit display; keep cachePct numeric
Drop the duplicate `formatCacheHitPct` helper added in #503 — `fmtPct`
in `dashboard/src/lib/format.ts` already does the same `(n*100).toFixed(1) + "%"`
shape and is the canonical formatter for the rest of the panels.
In `/status` (`observability.ts`), keep `cachePct` as a number through
`renderTinyBar` and only `.toFixed(1)` at the template-string boundary,
so we don't round-trip through string + `Number()`.
* chore(release): 0.35.0
* feat(ui): version badge in status row + /feedback opens issue with diagnostic clipboard
When a user hits a bug, the first question back is "what version" — and
the only way to find out today is to drop to the shell. Filing the
issue itself means leaving the TUI, finding the repo URL, then either
remembering or re-collecting version / OS / terminal / Node / locale /
model. Both papercuts are easy to fix from the prompt-input surface.
- StatusRow shows a `v<VERSION>` pill on the right cluster, gated to
cols ≥ 70 so it doesn't crowd narrow terminals.
- New `/feedback` slash: gathers version + platform + os release +
TERM_PROGRAM/TERM + Node + locale + model + sessionId, writes a
paste-ready Markdown block to the clipboard via the existing
`writeClipboard` helper, then opens the GitHub new-issue URL in the
default browser via a new cross-platform `openUrl` (win32 cmd /c
start, darwin open, linux xdg-open). No-ops under CI / when
REASONIX_NO_OPEN is set.
- Diagnostic body contains exactly the seven advertised fields and
nothing else — `tests/feedback.test.ts` pins the field set and asserts
no API keys / file paths / transcript content can leak through.
Closes#499
* feat(ui): pre-fill /feedback issue body via URL + surface chip in status row
Two follow-ups so the affordance actually gets discovered and used:
- The issue page now opens with the diagnostic block already in the
textarea via `?body=<urlencoded>`. Most users won't notice we copied
to clipboard; pre-filling the URL is the obvious path. Clipboard
stays as belt-and-suspenders for when the URL fails to open.
- StatusRow shows a `⚑ /feedback` hint after the version pill at
cols ≥ 100 so users see the command exists. Narrower terminals (70–99
cols) still get the version, just without the hint.
- Body length is capped at 6000 chars before encoding so a runaway
diagnostic can't blow past the URL limit.
* feat(ui): expand /feedback diagnostic with flicker-relevant fields
The original block had version + platform + TERM_PROGRAM + Node + locale
+ model + session — fine for "agent ran the wrong tool" reports, but
useless for the rendering / flicker reports we actually field. Adds the
fields that come up first when triaging those:
- terminal size (cols×rows) — lots of repaint bugs only repro at
specific widths
- env markers that change the rendering pipeline: COLORTERM,
WT_SESSION, TMUX, SSH_TTY, WSL_DISTRO_NAME — TERM_PROGRAM alone can't
distinguish cmd / WSL / SSH-tunnelled terminals
- theme name — different themes use different background fills, flicker
is often theme-dependent
- edit / plan mode — decides which surfaces are mounted, changes
repaint cadence
- latest version compare — surfaces "you're on an old build" without a
follow-up question
- reasoning effort + MCP server count — incidentally cheap, occasionally
load-bearing for cost / latency reports
Still no transcripts, paths, workspace name, or env outside the
hand-picked safe list. New tests pin the exact field set so future
fields can't sneak in unannounced.
The design-doc page chrome (`.toc` / `.section` / `.subsec`) was tuned
on a larger display and reads as too tight on a 13" laptop at 100%
zoom. Sidebar section headers at 10px with 0.14em tracking are the
worst offender — section labels also wrap mid-word in the 240px column.
- `.page` sidebar column: 240px → 260px so 2–3 word section labels fit.
- `.toc h1` 14 → 15px; `.toc .sub` 11 → 12px.
- `.toc-section` 10 → 12px and tracking 0.14em → 0.08em (lower so the
size bump doesn't fight the letter-spacing).
- `.toc li a` 12.5 → 14px with `line-height: 1.4` and
`overflow-wrap: anywhere` for graceful wraps on longer labels.
- `.section > .lede` 13 → 15px; `.subsec > p` 12.5 → 15px (line-height
1.6 already applied).
- `.subsec > h3 .desc` 12 → 13px.
- `.swatch .hex` 10.5 → 11.5px; `.scale-row .lbl` 10.5 → 11.5px (and
width 70 → 76px to keep the new monospace digits aligned).
Mirrored verbatim into `docs/design/agent-dashboard.html` per the
"keep CSS in lockstep with the mockup" comment at the top of app.css.
Closes#461
Two new agent-facing tools so "add a skill that does X" / "wire up a
postgres MCP server" work as normal chat requests instead of forcing the
user out to slash commands:
- `create_skill` — pre-fills frontmatter (description / runAs /
allowed-tools / model) from structured args and writes through a new
SkillStore.createWithContent that reuses the same path resolution +
collision check as `/skill new`.
- `add_mcp_server` — builds a `name=...` spec for stdio / sse /
streamable-http transports, optionally hydrates from MCP_CATALOG,
runs the existing preflight (filesystem sandbox-dir check), and
appends to cfg.mcp via writeConfig. Refuses name collisions.
Active on next launch — no live MCP client churn this session.
Both are registered alongside the existing native tools in
`reasonix code` so they're available wherever filesystem / shell are.
Closes#494
The banner already detected `Open Questions` / `Risks` / `Unknowns` headings
but the questions themselves were never shown — PlanConfirm rendered either
a step list or a 24-line body cap, both of which can hide the block. Refine
mode then reopened a blank input with no echo of the questions, so the user
either invented an answer or hit Enter and we asked the model to re-derive
its own questions on a follow-up turn.
- Extract the matching block (heading down to next same-or-shallower heading)
via `extractOpenQuestionsSection` and render it under the banner regardless
of steps / body cap.
- Forward the extracted block to `PlanRefineInput`, which now renders the
questions above the input on `mode === "refine"`.
- Replace the blank-refine synthetic that asks the model to re-derive
questions with one that tells it to pick safe defaults and call them out.
- Move all plan-flow strings (PlanConfirm / PlanRefineInput /
PlanCheckpointConfirm / PlanStepList counter line) through `t()` under a
new `planFlow` namespace in EN + zh-CN.
Closes#477
A single popular symbol could match 200+ lines in a big file (App.tsx,
loop.ts) and eat the entire byte budget before the walk reached any
other file. Truncation marker fired, every other matching file got
zero coverage, and the caller saw a wall of one file's hits with no
hint that distribution was wider than that.
Three knobs:
1. MAX_HITS_PER_FILE = 30. Beyond that, the per-file output ends with
"[rel: N more matches in this file — re-grep with a tighter
pattern or use read_file to see them]". One bullhorn file can no
longer dominate the byte budget.
2. After each file completes, if printed bytes have crossed 80% of
the byte budget, remaining files switch to histogram form
("rel: N matches"). A one-line notice marks the flip so the
caller knows distribution from this point on is summary-only.
3. New `summary_only:true` arg skips line content entirely and
returns just the histogram. Useful for "where does this exist at
all" before drilling in with a targeted read_file.
Closes#489
The child loop's tool-iter cap was enforced from the outside only;
the subagent's system prompt never said "you have N tool calls", and
the child had no way to know which iteration it was on. The visible
failure mode was an explore subagent burning all 20 iters mapping the
territory, then hitting the cap mid-thought and emitting a partial
summary the parent had to re-dispatch from.
Two pieces:
1. spawnSubagent now appends a one-paragraph budget notice to the
child's system prompt — literal "Tool budget: you have N tool calls"
with the resolved cap baked in. Applies to default, typed
(explore/verify), and caller-supplied system prompts uniformly.
2. ToolRegistry gains setResultAugmenter(), a final-stage post-hook
on dispatch. spawnSubagent installs one that counts dispatches and
appends "[budget: K of N tool calls left — wrap up soon]" once the
child is within 3 iters of the cap, escalating to "0 left —
finalize NOW" on the last call.
Static prompt + dynamic countdown together: prompt sets expectation,
countdown forces reckoning when the budget is actually tight.
Closes#488
When the auto-preview path fires (file > 200 lines, no head/tail/range
given), the head 80 + tail 40 slice rarely covers the full export list
of a real file. Callers had to follow up with a search_content grep to
locate "where is function AppInner defined" before they could pick a
useful range.
Now the auto-preview embeds a top-level outline between the head slice
and the omitted-marker — function / class / const / interface / type /
enum names with their line numbers, capped at 30 entries (first 25 +
last 5 + an elide marker). One round-trip, not three.
Closes#487
Each PgUp / PgDn / arrow / wheel tick used to call setScrollRows
synchronously, so a single mouse-wheel gesture (10-30 events) triggered
10-30 full Yoga layout passes over the entire card tree. Layout cost
scales linearly with history length, which is what made long sessions
feel laggy.
Accumulate the delta into a ref and flush once per ~16ms. Net effect:
one setState per scroll burst regardless of event volume. jumpToBottom
cancels any pending delta so End still feels instant.
Closes#482
The dashboard's initLangFromServer() had two branches when localStorage
disagreed with the server config:
1. If `rx.langExplicit` was set (user picked a language in dashboard
panel at some point) → POST localStorage value back to server
2. Otherwise → adopt the server value
Branch 1 silently clobbered CLI-side `/language` changes. Sequence:
- User picks zh-CN in dashboard once → rx.langExplicit=1, rx.lang=en
(or whichever)
- User later runs `/language zh-CN` in the CLI → server config is
now zh-CN
- User opens dashboard tab (or browser restores it from a previous
session) → init runs → POSTs localStorage's old value back, server
flips to en, CLI's choice is lost on next launch
Server config is the single source of truth. localStorage is purely a
render-cache to avoid first-paint flicker — never push it back.
Removes EXPLICIT_KEY / isExplicit / markExplicit entirely; the stale
key in existing users' localStorage is harmless dead data.
Two layers around the new TipCard:
1. /keys — make the slash command real
It was already referenced in the edit-gate tip's footer ("Run /keys
anytime for the full list") but no handler existed; typing /keys hit
the unknown-command branch. Add the spec under "info", a handler
that pushes a multi-section TipCard with the full reference, and a
`postKeys` callback on SlashContext wired to log.pushTip.
The reference is sectioned: keyboard / mouse / copy-paste /
edit-gate. Each section has its own subtitle and aligned key column.
2. First-run mouse + clipboard tip
SGR mouse tracking captures the wheel for chat scroll but also eats
the terminal's native right-click-paste — without explanation users
think the prompt is broken. Add a one-time tip mirroring the
edit-gate pattern: pushed on first launch, suppressed thereafter via
a `mouseClipboardHintShown` flag.
TipCard now supports multiple sections (single-section tips just have
one un-titled section). The previously-shipped tipEditBindings is
re-wrapped in a single section; behavior unchanged.
i18n: keysReference (4 sections, ~25 rows) + tipMouseClipboard (1
section, 3 rows) + handlers.basic.keysNeedsTui in EN.ts and zh-CN.ts;
matching shape in types.ts. The i18n /keys row already existed but its
description was outdated — refreshed in both languages.
The edit-gate one-time tip currently renders as raw multi-line text
inside a stepProgress LiveCard — `✓` glyph (success semantic, wrong
for educational content) plus a manually-inlined `▸ TIP:` prefix,
columns aligned with hand-counted spaces that wrap badly on narrow
terminals, and the "shown once" disclaimer crammed into the body
parenthetical.
Replace it with a dedicated `TipCard` kind:
- Single `ⓘ` glyph in accent color, no duplicated prefix
- Topic + "shown once" badge in a header row (justified)
- Each row is its own `<Text>` with real column alignment driven by
stringWidth (works for CJK widths too)
- Footer separated from body by a blank row, dim color
- No border — tips are scrollback content, not modal
i18n: `tipEditBindings` becomes a structured `{topic, rows, footer}`
object across types.ts / EN.ts / zh-CN.ts. New helper `tObj<T>(path)`
in i18n/index.ts for non-string entries; the existing `t()` is
unchanged. Adds a tiny `tipShownOnce` string for the badge.
Adds a `pushTip()` method on Scrollback alongside `pushInfo()`; the
new `tip.show` event flows through the same reducer / dispatch pipeline
as every other card kind.
* feat(at-picker): rebuild as file browser with streaming search
Empty / trailing-slash queries (`@`, `@src/`) browse one directory level
with a single readdir — folders selectable, drill via Tab. Any non-slash
filter (`@foo`, `@auth/log`) kicks off a cancelable streaming walk across
the full tree, batching matches into the popup as they're found, with a
`searching… N scanned` footer while in flight.
Replaces the upfront 500-file walk that was unusable on large repos —
on a 5k-file tree the cap evicted ~90% of paths before ranking, leaving
the picker effectively empty.
- walkFilesStream: cancelable streaming walker; powers search mode
- listDirectory: single-level browse, no recursion; powers browse mode
- parseAtQuery: splits `dir/filter` with trailing-slash awareness
- listFilesWithStatsAsync now delegates to walkFilesStream (no behavior
change for existing callers)
- expandAtUrls + helpers split into at-mentions-url.ts to keep
at-mentions.ts under the 800-line ceiling
Closes#478
* fix(scroll): route mouse wheel via SGR mouse tracking
Enable DECSET 1006 + 1000 at startup so the terminal reports wheel
events as `\x1b[<btn;col;row;M` mouse sequences instead of translating
them to ↑/↓ key presses. The chat-scroll handler routes the resulting
mouseScrollUp/Down events to scrollback, bypassing the arrow-key path
entirely — the wheel now scrolls chat regardless of buffer state, while
↑/↓ keys retain their existing PromptInput bindings (history recall on
empty buffer, cursor motion otherwise).
The SGR mouse parser already lived in stdin-reader.ts; this just
turns on the terminal-side feature so events actually flow.
Cost: terminal-native drag-to-select needs a modifier (Shift on Windows
Terminal / Alacritty / WezTerm, Option on iTerm2) — same trade-off as
tmux, Claude Code, Cursor's terminal.
Two bugs in one issue.
1. **↑/↓ stopped recalling history.** 9254d3a unbound history from
arrows because Windows Terminal + ConPTY can translate mouse-wheel
events to ↑/↓ keystrokes — wheel-up was clobbering the prompt with
a recalled message. The fix moved history to Ctrl+P / Ctrl+N.
That was the right call for legacy ConPTY users but broke the
universal CLI muscle memory for everyone else (bash / zsh / fish
all bind ↑ to history). Linux / macOS / modern Windows Terminal
users don't have the wheel-translation problem in the first place.
Restore ↑/↓ on empty buffer = history; keep Ctrl+P / Ctrl+N as
the wheel-immune fallback. The App-level keystroke handler still
routes ↑/↓ to chat-scroll once the user is unpinned (subsequent
wheel events keep scrolling), so the only regression for legacy
ConPTY is the FIRST wheel-up from a pinned position recalls a
prompt. Documented; ⌃P/N is one keystroke away.
Drops the now-dead `chatScrollHandoff` plumbing.
2. **Doctor reported "tokenizer not found" when it was installed.**
The tokenizer ships under `data/` in the npm tarball and the
runtime resolver in tokenizer.ts has three candidates including a
`createRequire("reasonix/package.json")` probe — finds it
reliably. The doctor had its own resolver that walked
`dist/cli/commands/doctor.js → ../../../data/`, which broke after
the lazy-import refactor in #467 emitted the doctor at
`dist/cli/doctor-HASH.js` (one level shallower). Walked above the
package root and reported missing.
Reuse the runtime resolver (now exported) so the two paths can
never disagree.
The status row was reading status.cost (turn) and status.cacheHit
but ignoring two fields the reducer already populates:
status.sessionCost (running USD total) and status.balance (DeepSeek
wallet, refreshed on every submit). balanceColor() with red/orange
thresholds even sat in tokens.ts unused.
New WalletPill segment renders right of the cache pill:
⛁ ¥1.20 spent / ¥45.32 left
with thresholded color on the balance number. Shown only when
the terminal is ≥90 cols and at least one of the two values is
known, so narrow sessions don't wrap.
PromptInput: friendlier placeholder copy ("ask anything") and the
hint footer now uses keycap/label spacing (⇧⏎ instead of
shift/alt+⏎) for a less command-line-jargon read.
The /tool slash command was removed in #453 but its supporting
plumbing was left behind: every tool result was still being pushed
into a useRef array, with no consumer ever reading it. Long-running
sessions accumulated full Read/Grep/Bash output indefinitely and ran
out of heap.
#465 reports a JS heap OOM after ~2.6 hours on v0.31.0; this leak
matches the failure shape (mark-compacts ineffective, 4GB ceiling).
#459 follow-up. When `/cwd` swaps the workspace root, FS/shell/memory
tools were re-registered against the new path but `semantic_search`
kept pointing at the OLD root — meaning queries silently searched
the previous project's index, or the tool stayed registered when
the new dir had no index at all.
Split semantic re-bootstrap from the sync `reregisterTools` callback:
- `reregisterTools` stays sync (FS/shell/memory must land before the
next tool dispatch).
- New `reBootstrapSemantic(root) => Promise<{ enabled }>` reads disk
to probe index compatibility, registers `semantic_search` if found,
unregisters it otherwise.
App.tsx fires the async tail with `void ...then(postInfo)` so the
slash dispatch returns synchronously (matches the codebase's
fire-and-forget pattern documented in slash/dispatch.ts). User sees:
▸ workspace switched to /new/path
▸ semantic_search re-pointed at /new/path ← if compatible
▸ semantic_search disabled (no compatible index in /new/path)
← if not
Same machinery handles the launch path — `code.tsx` now calls
`reBootstrapSemantic(rootDir)` instead of bootstrap directly so
the unregister-on-skip behavior is exercised on every entry path.
Stage 2 follow-up to #464. Continuing the profile-driven trims.
The dashboard server module (src/server/index.ts plus its ~4200 LOC
of transitive dashboard code) was being eagerly imported into App.tsx
even when --no-dashboard was set or auto-start hadn't fired. Move it
to a dynamic import inside startDashboard's startup IIFE — it's
already async, so the await import() is free in the structural
sense.
Measurable hot-path delta is small (~4ms within noise) but it shaves
real bytes off the first-paint module graph and removes a synchronous
dependency on the entire server tree. Cold paths benefit too.
Also adds two strategic marks (`app_render_start`, `app_inner_start`)
for future profiling. They're harmless when the env var is off and
expose the React-component-body boundary in the dump, which makes
the existing `first_paint` delta self-explanatory.
Findings from the deeper investigation (now reverted as noisy diagnostics):
- App's disk-hitting useState initializers (loadHooks, loadSlashUsage,
loadEditMode, hydrateCardsFromMessages) are all sub-ms each.
Deferring them buys nothing measurable.
- The 280-300ms gap between `app_inner_start` and `first_paint` is
React reconciliation + Ink's terminal commit + the first useEffect
flushing. Trimming further requires reducing initial render
complexity, not deferring side work.
Stage 3 (CI budget gate) remains deferred — the platform-dependent
nature of these numbers makes a hard threshold fragile. Profile
harness is already documented in-tree via the env-var hint
(`REASONIX_PROFILE_STARTUP=0 to silence`).
Stage 1 (#466) showed module-load was 57% of cold-start cost (436ms
of 764ms total on this Windows box). Every `reasonix <subcommand>`
invocation was eagerly loading every other command's module —
including chat.tsx → App.tsx → React/Ink. `reasonix version` paid
for the chat UI it doesn't need.
Move every `import { fooCommand } from "./commands/foo.js"` into a
dynamic `await import()` inside the relevant `.action()`. tsup
splits these into separate chunks automatically; Node only loads
them when the user invokes that subcommand.
Measured impact:
reasonix code (hot path, 5 runs avg): 778ms vs 764ms baseline
→ +14ms regression (within measurement noise; the 388ms that
used to live in `cli_module_loaded` now lives in
`code_command_enter` since code.tsx is dynamic-imported)
reasonix version: ~140ms vs ~440ms baseline → 290ms saved
reasonix --help: ~140ms vs ~440ms baseline → 290ms saved
Cold-path commands (version, --help, doctor, commit, sessions,
events, replay, diff, mcp *, update, index) all benefit. They
no longer pay the ink/react/dashboard import cost.
Hot path (`code` / `chat`) is roughly neutral. Real wins on hot
path will come from trimming first_paint (316ms, 41% of total) —
follow-up.
Test fix: bundle-smoke.test.ts asserted `from "ink"` lived in
dist/cli/index.js specifically; with code-splitting the import
moves to a chunk file. Updated assertion to scan all dist/cli/*.js.
The semantics are preserved — ink stays external (not bundled),
just no longer in the entry chunk.
#464 plan was profile-first; this lands Stage 1.
Adds src/cli/startup-profile.ts with markPhase/dumpStartupProfile
gated behind REASONIX_PROFILE_STARTUP=1. When unset (default), every
call is a no-op — zero cost in normal runs.
Marks placed at:
- cli_module_loaded — top of the bin entry, after all transitive imports
- chat_command_enter / config_loaded
- mcp_launch / mcp_connected_M_of_N (only when MCP specs exist)
- code_command_enter — top of `reasonix code`
- semantic_bootstrap_start / _done_(enabled|skipped)
- ink_render_call — just before `render(<Root/>)`
- first_paint — App's first useEffect after mount, also dumps the profile
Baseline collected on this Windows box (no MCP, semantic index already
built):
436ms cli_module_loaded (+436)
3ms code_command_enter (+3)
2ms semantic_bootstrap_start (+2)
2ms semantic_bootstrap_done_enabled (+2)
3ms chat_command_enter (+2)
0ms config_loaded (+0)
2ms ink_render_call (+1)
316ms first_paint (+316)
─── 764ms total
Read: module-load (Node + transitive imports) is 57% of total, first
paint (Ink render + React commit) is 41%. Everything else is noise.
Stage 2 should target lazy-loading heavy import dependencies that
land synchronously today (DeepSeek client, Ink, dashboard server,
embedding provider). MCP serial setup hypothesis from the issue
needs a real config to confirm — punted until we have a measured
multi-MCP run.
Stage 3 (CI budget assertion) deferred until Stage 2 trims have
landed and we have stable numbers to set thresholds against.
#459 is a meta-issue with three first-five-minutes UX papercuts.
This lands two of them; startup-perf (part 3) needs profiling
first and gets a separate issue.
## Part 1: at-mention picker — subsequence fallback
The picker rejected anything that wasn't a substring match, so
typing `atmnt` for `at-mentions` returned nothing. Adds a fuzzy-
subsequence scorer as a fallback after substring lookup misses.
Substring hits still win — class 0/1/2 cap at 29_999, subseq
starts at 30_000. Fuzzy scoring rewards consecutive runs and
basename-anchored matches, penalizes total path length.
Files walking + cap-aware UI hints already existed (the audit
showed them at useCompletionPickers.ts:102 and
AtMentionSuggestions.tsx:55–77). The missing piece was ranking.
## Part 2: /cwd slash command
The plumbing was already there: `codeMode.reregisterTools(root)`
exists in code.tsx, App.tsx already comments "/cwd mutates this
state to swap the workspace mid-session". The slash command
itself was just never wired.
Wires it end-to-end:
- SlashContext gets a `switchCwd(path) => { ok, info }` hook.
- App.tsx implements switchCwd: stat + isDirectory check,
reregisterTools(newPath), setCurrentRootDir, reload hooks.
- New `/cwd` (alias `/sandbox`) command in the code group.
- Handler in handlers/edits.ts.
- EN + zh-CN strings added.
Out of scope: semantic-index re-bootstrap on cwd swap (current
bootstrap runs once in code.tsx). Tracked as a follow-up.
## Part 3 (deferred)
Slow startup needs profiling before redesign. Will open a separate
issue with a concrete "mark phases, defer post-mount" plan.
Three quality polishes to the filesystem toolbelt, all small, all
addressing real friction the model hits often.
glob — new tool. Mtime-sorted file walk with picomatch glob syntax
(**/, *.{ts,tsx}, etc.). Default sort=mtime desc so "what did I
touch lately" works out of the box; sort=name for deterministic
listings. Skips deps by default, capped at 200 results (1000 max)
with overflow notice. Different from search_files (substring on
basename) and search_content (greps file bodies).
search_content — new `context: N` param mirroring `grep -C N`.
Output uses ripgrep convention: `:` after the line number on hits,
`-` on context lines, `--` separating non-adjacent windows.
Adjacent windows merge automatically so a hit at line 42 and 44
with context:1 produces one continuous block. Capped at 20 lines
on each side to keep the maxListBytes budget intact.
multi_edit — reshape from single-file `{ path, edits: [...] }` to
cross-file `{ edits: [{ path, search, replace }, ...] }`. Reads
each touched file once, applies edits in array order against an
in-memory buffer (so a later edit can match text inserted by an
earlier one), validates everything, then writes all touched files.
ANY validation failure → ZERO writes (true atomicity at the
validation layer; sequential disk writes after that). Output
header now reports both "N edits across M files".
This is a hard schema break for multi_edit, but it shipped
unreleased six hours ago — no consumers to migrate.
Test coverage: 24 new cases (glob: 6, context: 4, multi_edit: 8
covering single + cross + atomic + missing-file). 2243 pass on
verify.
submit_plan is the heavy gate (user approval, per-step checkpoints,
plan-mode toggle); ask_choice is the branching primitive. Neither
covers "I have 4 things to do, let me record them and tick them off
as I go" — that's prose-list territory today, which means lost
context the moment the loop folds history.
todo_write fills the gap: replace-set semantics, no approval pause,
no file writes. Validated: at most one in_progress, status enum,
non-empty content+activeForm. readOnly=true so it stays callable in
/plan mode (recording intent during planning is exactly when it's
most useful).
Wired into reasonix code with an onTodosUpdated callback hook for
future TUI surfacing (live progress strip, etc.). System prompt
gains a "When to track multi-step intent" section telling the model
to reach for it on 3+ step tasks instead of inlining "1. ... 2. ..."
in prose.
N edit_file calls for a single-file rename burns a tool round-trip
per site and isn't atomic — a mid-batch failure leaves the file half-
edited. multi_edit takes an array of {search, replace} entries,
applies them sequentially against an in-memory buffer, and only
writes once all succeed. Any failure (search not found, ambiguous
match, empty search) → no edits are written.
Per-edit rules match edit_file: exact whitespace-sensitive search,
must be unique at the moment that edit applies. Sequential semantics
mean edit N+1 can match text that edit N inserted.
Closes a concrete pain point flagged when surveying the toolbelt
against typical multi-site refactor flows.
Closes#451
UI flicker (section 3 of #451) is already tracked in #412.
1. expandAtMentions treated `@<dir>` as a `not-file` skip — the model
never saw what was in the directory. It now resolves the path, walks
the project root with the existing gitignore layers, filters to
entries under the directory, and inlines a `<directory>` block
capped at DEFAULT_AT_DIR_MAX_ENTRIES (200). `@docs/` and `@docs`
resolve to the same key, so trailing-slash typing doesn't double-fire.
2. listFilesWithStatsSync / listFilesWithStatsAsync called only
ent.isFile(), which returns false for symlinks. Symlinked source
files were silently dropped from the picker. Both walkers now stat
through symlinks; symlinks-to-files come back, symlinks-to-dirs
stay dropped (cycle risk), broken links stay dropped (nothing to
point at).
Two related plan-mode UX gaps.
1. PlanLiveRow had nothing to dock. `case "plan_proposed"` dropped the
gate payload's steps/summary, and the approve path never dispatched
plan.show — so no card with variant: "active" ever existed and the
filter in isActivePlanInFlight returned null. Stash steps/summary in
the existing refs on plan_proposed, materialize the active card on
approve, and drop+re-show on revise-accept so the dock tracks tail
rewrites instead of silently going stale.
2. "Checkpoint — step done" fired after every mark_step_complete even
in auto/yolo, defeating the whole point of those modes (shell and
edit-gate already self-skip). plan_checkpoint now checks editModeRef
and, in auto/yolo, resolves the gate with "continue" without UI.
Per-step rollback snapshot still runs so /restore granularity stays.
* slash: unified preset+model picker, grouped suggestions, kill 11 commands + harvest/branch
The slash surface was 58 commands deep with no organization, two confusable
options for "fresh start" (/clear vs /new), separate preset and model commands
that solved the same user question ("what AI am I using"), and two heavy
features that almost nobody opted into. Pulled all of that apart.
Picker
* ModelPicker now shows the 3 presets at the top with cost/headline copy and
the model catalog below; auto-detects which preset the loop currently matches
(model + effort + autoEscalate) so the cursor lands on the active row. Both
/preset (no arg) and /model (no arg) open it.
SlashSuggestions
* SlashCommandSpec gains a `group` field (chat / setup / info / session /
extend / code / jobs / advanced). Suggestion palette renders section headers
on a bare /; advanced rows hide behind a "+ N advanced · type to search"
footer until the user types a letter. /help walks the same registry, so
there's one source of truth.
Telemetry
* New ~/.reasonix/slash-usage.json counter (read-modify-write, atomic rename)
feeds suggestSlashCommands so frequent commands sort first within a prefix.
emitSlashInvoked is now wired to the events.jsonl sidecar.
Removals (commands)
* /models, /keys, /resume, /semantic — redundant with picker / /help / /doctor.
* /clear merged into /new (now an alias) — the visual-only clear was the most
common confusion source ("why does /clear keep my context?").
* /effort, /rename, /forget, /apply-plan, /think, /tool, /mcp browse — second
pass; either covered by other UI (sessions picker has rename/delete; preset
locks effort) or self-described as fallback / debug.
Removals (features)
* /harvest and the Pillar-2 plan-state extractor (src/harvest.ts).
* /branch and the parallel-sample selector (src/consistency.ts,
src/loop/branch.ts). Streaming/branching coupling, BranchCard,
branch_start/progress/done events, transcript planState/harvestedTurns,
--harvest/--branch CLI flags, all gone.
* benchmarks/harvest/ deleted; ARCHITECTURE.md collapsed from four pillars
to three; README + zh-CN + dashboard/PARITY updated.
i18n
* Cleared dead keys for every removed command (handlers.basic.helpHelp..helpExit,
keys*, semantic, resume*, models*, harvest*, branch*, effort*, think*, tool*,
apply-plan*, slash.harvest, slash.branch, ui.harvest*, ui.branch*).
Tests: 138 files / 2192 tests pass. Public API drops harvest, runBranches,
TypedPlanState, BranchSummary, etc.; consumers using those break intentionally.
* ci: drop harvest-bench dry-run step
Follows the harvest feature removal — benchmarks/harvest/ no longer exists,
so the CI step was breaking on ERR_MODULE_NOT_FOUND. τ-bench dry-run stays.
Configurable API URL / key / model / request body for embeddings, replacing the Ollama-only setup. Adds a provider abstraction in src/index/semantic/embedding.ts, index identity check + abort wiring through the builder, API-key redaction in dashboard/status output, and en-US + zh-CN strings for the new provider UI.
Most handler files were already 80%+ i18n'd from prior work, but
four files had drift:
- web-search-engine.ts — 0 t() calls, the entire help text plus
switch confirmation was hardcoded English. Whole new
handlers.webSearchEngine namespace (~12 keys).
- mcp.ts — 5 hardcoded usage / unknown-server / "(none)" /
reconnect-not-wired strings; added under handlers.mcp.
- plans.ts — the archive row template ("✓ {when} {N} steps · …"),
"complete" verb, and the /stop abort line. Added under
handlers.plans.
- semantic.ts — code-mode-only refusal + "checking…" status.
Added under handlers.semantic. Note this file uses two t()
instances side-by-side — the local @/index/semantic/i18n one
stays for the existing slashHeader/slashEnabled keys, and the
main @/i18n/index t (aliased as tMain) is added for the two new
strings.
zh-CN translations included for all ~22 new keys.
Test plan: full suite 2301 pass, tsc + biome clean.
Two patterns rolled into one PR:
1. Wire seven existing ui.* keys that had been defined in EN.ts /
zh-CN.ts but never actually called: ephemeralSession,
resumedSession, newSession, restoredEdits, resumedPlan,
tipEditBindings, dashboardAutoStartFailed. The keys had drifted
into dead code — same pattern that bit the loop.* namespace
before #445.
2. New app.* namespace (~24 keys) covering every other hardcoded
user-facing string in App.tsx:
- walk cancel (with / without remaining count)
- edit-mode cycle (review / auto / yolo)
- reject / auto-approve / flip-to-auto messages
- dashboard stopped, /restore code-mode-only
- hash-memory note (with translated scope + verb)
- bash-mode + memory-write failures
- hook headers (UserPromptSubmit, Stop)
- @mentions / @url expansion + failure
- shell confirm (deny / always-allow / running / starting)
- checkpoint saved
- plan continue / stop / revise
zh-CN translations for all 31 new keys.
Test plan: full suite 2301 pass, tsc + biome clean.
Two small follow-on batches after #445:
1. hooks.formatHookOutcomeMessage — was hardcoded
\`hook \${tag} \\`\${cmd}\\` \${decision}\${truncTag}\`. Pulls
the structural words (\"hook\", decision verb, \" (output truncated
at 256KB)\") into a new \`hooks.*\` namespace. The technical bits
(tag, cmd) stay verbatim — they're identifiers, not prose.
2. loop/force-summary.ts — three user-visible strings:
- \"summarizing what was gathered…\" (status during summary call)
- the fallback when the model emits hallucinated tool-call markup
instead of prose
- the error template when the fallback summary itself crashes
New \`summary.*\` namespace covers all three. zh-CN translations included.
Decision verbs (block / warn / timeout / error) are translated via a
small \`hooks.decision\${Capitalize}\` lookup so the formatter still
takes \`outcome.decision\` (the typed enum) as input.
Test plan: full suite 2301 pass; tsc + biome clean.
Yields like 'session budget exhausted', 'aborted at iter X/Y',
'preflight: request ~X/Y tokens', and the post-turn fold/forcing-
summary status lines were all hardcoded English. The loop.* i18n
namespace had 7 keys defined but never wired — placeholders from a
previous attempt that drifted away from the actual call sites.
This PR replaces the dead namespace with 20 keys that match the
actual yield shapes, wires t() at every site, and adds zh-CN
translations.
Categories covered:
- budget (exhausted / 80% warning)
- /pro armed
- aborted-at-iter / tool-budget-warning
- preflight (status + folded / no-fold-left)
- escalation (flash → pro / auto-escalation)
- storm-broken (stuck retry loop / suppressed-N-times)
- history compaction (status + folded / aggressively-folded)
- forcing summary (context-guard exit)
Behavior preserved: tests pin runtime to EN, so existing assertions
on the English text still pass. The dead loop.* keys (budgetWarning,
budgetRefusal, contextWarning, escalationWarning, toolFailure,
interrupted, loopStopped) had zero callers across src/ and tests/
and are removed as part of the namespace cleanup.
formatLoopError, reasonPrefixFor, and errorLabelFor were all
hardcoded English. A Chinese user hitting a 503 / 401 / context
overflow saw raw English (and on top of that, the new 5xx outage
notice from #440 was also English).
Move the strings to a new errors.* i18n namespace covering:
- context overflow (with V4/legacy limit mention)
- 401 auth / 402 balance / 422 param / 400 bad request
- 5xx head + reachable / unreachable / two action variants
- reason prefix and label for budget/aborted/context-guard/stuck
- "(no message)" fallback for empty error bodies
zh-CN translations included. Existing tests still cover EN (vitest
setupFile pins runtime to EN); two new tests flip to zh-CN to confirm
runtime switch actually translates.
Stacked on #440 — merge that first.
* fix(loop): friendly DeepSeek 5xx error with reachability probe
Raw `DeepSeek 503: <body>` was bubbling straight to the UI. Users on
flaky DS days couldn't tell if it was DS-side (their service was
overloaded) or Reasonix-side (we crashed). The header comment in
loop/errors.ts even claimed retry.ts swallowed all 5xx — but retry.ts
returns the last response instead of swallowing, so 5xx did reach the
formatter and just fell through to a passthrough branch.
Now formatLoopError takes an optional probe result. The catch in
step() detects 5xx, fires a 1.5s `/user/balance` probe, and passes
the result back. Three message variants:
- no probe → DS-side outage notice + retry hints
- probe reachable → "main API answered, /chat/completions failing"
- probe down → "DS unreachable from your network — check net"
All three include "this is a DeepSeek-side problem, not Reasonix" and
a status-page link so users know where to look.
* test: avoid CodeQL js/regex/missing-regexp-anchor on URL substring match
Use toContain('status.deepseek.com') instead of /status\.deepseek\.com/
— same assertion semantics, dodges CodeQL's high-severity false positive
on unanchored URL regex.
Plans whose completionRatio is 0 (submitted but no steps marked
complete yet) showed a hardcoded English "idle" pill — surrounding
"active" / "done" pills already used t().
Add plans.idle to en.ts ("idle") and zh-CN.ts ("未开始"), and route
the idle branch of statusPill() through t().
Two related fixes for non-English first-runs:
1. Add a language step at the very start of the setup wizard.
Cursor defaults to detectSystemLanguage() result. Selection saves
immediately, so all later wizard steps render in the chosen
language. Re-runs (`reasonix setup`) start there too — cursor
defaults to currently saved language so Enter is a no-op for
users who don't want to change it.
2. Localize every hardcoded string in the wizard via a new wizard.*
i18n namespace (~30 keys, EN + zh-CN). Previously a Chinese user
who hit /language partway through never saw zh-CN copy because
the wizard rendered raw English. Now language → applies → review
step renders in zh-CN.
Why this matters: Intl.DateTimeFormat().resolvedOptions().locale
isn't always correct (terminal env strips LANG, CI returns "C", etc.),
and the prior workflow only let users discover /language *after*
finishing setup in English.
Tests: ink-testing-library renders the Wizard and confirms the
language step is shown first with both options visible, in EN and
zh-CN. wizard.test.ts → wizard.test.tsx (now contains JSX).
Closing audit of the #369 split: every slash command tagged with how
the dashboard handles it (panel / chat-box / tui-only).
Findings after C + D:
* ~20 slashes have a dedicated panel or modal — Settings (presets,
effort, model, /pro, budget gauge, loop control, language), MCP,
Permissions, Hooks, Skills, Memory, Plans, Sessions, Usage, plus
the C-bucket pickers (SessionPicker, CheckpointPicker, MCP
marketplace, plan replay viewer).
* ~38 slashes work as-is via the chat box — short text outputs
(/help, /keys, /status, /cost, /context, /think, /retry, /compact,
/update, /doctor, /init, /semantic, …) plus admin / code-mode
niches (/walk-around, /resource, /prompt, …). No structured-output
gaps remain after C + D — the long-standing Memory / Permissions /
Hooks / Skills / Plans / Usage panels already cover every command
whose payload warranted a dedicated UI.
* Stays TUI-only by design: /exit (no live process to kill from web),
the raw keyboard shortcuts (Esc / Shift+Tab / Ctrl-L / Ctrl-O / u
/ space).
Bucket A and B turned out empty after the C/D work — no commands
need a chat-box rendering tweak, and no commands need a new
structured-output panel. PARITY.md is the source of truth going
forward; add a row when a new slash lands.
This wraps up #369 — the umbrella issue closes with this PR.
Final stage of #428. Adds a Loop section to SettingsPanel for the
auto-resubmit timer.
Design — two states from one component:
* Idle → 6 quick interval buttons (30s / 1m / 5m / 15m / 1h / 6h) plus
a custom field with s/m/h unit selector, a multi-line prompt
textarea, and a Start button. Cost hint reads "each iteration costs
~$X.XXXX (last turn)" pulled from /api/overview stats so the user
knows what an unattended overnight loop will run.
* Running → live countdown ("fires in 1m 24s"), iter counter, the
prompt verbatim (max 120px scroll for long prompts), and a Stop
button.
Implementation:
* dashboard/src/lib/loop-control.ts — pure helpers: INTERVAL_PRESETS_MS
table, parseCustomInterval (s/m/h → ms with 5s..6h clamp),
formatRemaining (5m 12s / 2h 45m / 0s for races past zero).
* SettingsPanel polls /api/loop/status every 5s; a separate 1s tick
interpolates the countdown locally between syncs (clamps to 0 if
the next-fire moment passes between polls).
* Page-reload mid-loop reads /api/loop/status and re-renders the
running panel from server state — no double-start risk because the
Start button only renders in idle state.
Wraps up bucket D — all four targeted slashes (/pro, /budget, /model,
/loop) are now panel-driven.
Fourth stage of #428. Replaces the read-only active-model code line
with a select driven by /api/models, plus an inline pricing line.
* New /api/models GET — returns the cached model catalog
(string[] | null), the live current model, and the DEEPSEEK_PRICING
table so the SPA can render input/output USD per 1M tok without a
second source.
* DashboardContext.getModels callback; App.tsx ref-mirrors useSessionInfo's
models so the dashboard server (frozen at boot time) sees fresh
catalog without re-mint.
* SettingsPanel ModelRow component: graceful fallback to the existing
read-only display when the catalog is null/empty (network failure
or in-flight). Live model is always selectable, even if the catalog
hasn't echoed it yet (preset overrides, custom IDs).
* Save flows through the existing D-1 applyModelLive path — same as
/model <id> slash.
Closes#432
Third stage of #428. Replaces a typed-input form with a state-driven
budget gauge that reads at a glance and turns the common bumps into
single clicks.
Design:
* Off → quick-cap row ($1 / $5 / $10 / $25 / $50) + custom field. No
number to type for the common case.
* Running (<80%) → spend / cap progress bar + bump suggestions
(1.5× / 2× / 4× current cap, snapped to a "nice" round number per
size bucket) + Clear.
* Approaching (≥80%) → amber tone + "loop will refuse past 100%" line
+ bump suggestions promoted to primary buttons.
* Exhausted (≥100%) → red tone + "next turn refused" line + same
bumps.
Implementation:
* dashboard/src/lib/budget.ts — pure helpers: BudgetState union,
deriveBudgetState, bumpSuggestions, budgetTone, QUICK_CAPS_USD.
niceUp() subtracts an FP epsilon before ceil so 0.4 × 1.5 doesn't
bump 0.6 to 0.7.
* SettingsPanel: BudgetSection consumes derived state and renders
off / running / warn / exhausted variants. Same gauge shape across
all three live states (just colour + helper text differ).
* Overview cockpit: budgetKpi reuses deriveBudgetState + budgetTone
so threshold logic lives in one place.
* /api/settings GET adds sessionSpendUsd from ctx.getStats so the
panel renders without a second /overview round-trip.
* 12 new unit tests for the derivation and bump rounding.
* feat(dashboard): server surface for /pro / /budget / /model / /loop (#429)
First stage of #428 (bucket-D of #369). Server-side plumbing for the
slash-only knobs the web should drive directly: /pro arming, /budget,
/model, and /loop. No SPA UI yet — D-2..D-5 each ship a panel section
against this surface.
* /api/settings GET exposes proNext / budgetUsd / model from live
loop state alongside the existing persisted fields.
* /api/settings POST validates and routes each new field to the
matching ctx.*Live callback. budgetUsd accepts null for "off".
* /api/loop/{status,start,stop} (new endpoint) drives the auto-resubmit
timer the same way the /loop slash does. start enforces 5s..6h range
and a non-empty prompt.
* DashboardContext gets matching callbacks: applyModelLive,
setProNextLive, setBudgetUsdLive, getLoopRunStatus, startAutoLoop,
stopAutoLoop.
* App.tsx wires each callback against existing live methods on
CacheFirstLoop and the useLoopMode hook. No new state.
/harvest and /branch are deletion-bound features and are deliberately
out of scope here — see #428 follow-up.
Closes#429
* feat(dashboard): compute panel section — /pro one-shot (#430)
Second stage of #428. Adds a Compute section to SettingsPanel for the
/pro one-shot toggle.
* Single-row section under the existing Defaults block: button toggles
arm / disarm — same path as the slash; auto-disarms after the next
turn fires.
* Section header lives even with one row so D-4 (model picker) and any
future compute knobs cluster here naturally.
* i18n: en + zh-CN strings for the section + row + helper note.
/harvest and /branch were originally bundled into this stage but
dropped — both are deletion-bound features.
Closes#430
First stage of #428 (bucket-D of #369). Server-side plumbing for the
slash-only knobs the web should drive directly: /pro arming, /budget,
/model, and /loop. No SPA UI yet — D-2..D-5 each ship a panel section
against this surface.
* /api/settings GET exposes proNext / budgetUsd / model from live
loop state alongside the existing persisted fields.
* /api/settings POST validates and routes each new field to the
matching ctx.*Live callback. budgetUsd accepts null for "off".
* /api/loop/{status,start,stop} (new endpoint) drives the auto-resubmit
timer the same way the /loop slash does. start enforces 5s..6h range
and a non-empty prompt.
* DashboardContext gets matching callbacks: applyModelLive,
setProNextLive, setBudgetUsdLive, getLoopRunStatus, startAutoLoop,
stopAutoLoop.
* App.tsx wires each callback against existing live methods on
CacheFirstLoop and the useLoopMode hook. No new state.
/harvest and /branch are deletion-bound features and are deliberately
out of scope here — see #428 follow-up.
Closes#429
Final stage of #416. /replay [N] now broadcasts a read-only viewer
modal to the web dashboard so the plan archive (summary + steps +
markdown body) is visible alongside the existing TUI scrollback card.
* New `viewer` member on the ActiveModal discriminated union — sibling
to `picker`, but read-only: only `close` flows back through
/api/modal/resolve. Splitting them keeps the picker schema clean
rather than carrying empty `actions: []` on every viewer payload.
* useViewerBroadcast helper alongside usePickerBroadcast.
* App.tsx intercepts result.replayPlan, packages a snapshot
(title with #idx/total · relative time, structured steps with
done/queued status, markdown body, archive basename as meta), and
feeds it to the hook. The existing log.showPlan call is unchanged
so the TUI scrollback card still renders.
* SPA ViewerModal renders the steps as a list (✓ for done, · for
queued) plus the markdown body and a single Close button.
* Server tests cover the dispatcher: close happy path, rejection of
non-close actions, 503 when the resolver is not wired.
Wraps up bucket-C of #369. All five originally TUI-only pickers
(/resume, /restore, /mcp browse) plus the read-only /replay viewer
are now drivable from the web with no TUI keyboard required.
* feat(dashboard): picker modal kind for web parity (#417)
First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.
* New `picker` member on the `ActiveModal` discriminated union plus
`PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
rename / new / install / uninstall / load-more / refine / cancel.
`refine` and `load-more` keep the picker open so the TUI's filter
state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
rows, action buttons gated on `modal.actions`, and rename / new
inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
C-2..C-5 picker components only need the hook to participate.
No picker is migrated yet — that arrives in C-2 (#418).
* feat(dashboard): wire SessionPicker through picker modal protocol (#418)
Second stage of #416. SessionPicker (the simplest existing TUI picker —
no pagination, no async, ~5 actions) now broadcasts modal-up snapshots
to the web dashboard and resolves pick / delete / rename / new / cancel
from /api/modal/resolve.
* SessionPicker.tsx accepts an optional `pickerPorts` prop bundle and
feeds usePickerBroadcast a snapshot mapped from the existing sessions
list (id=name, badge=branch, meta=turns/cost).
* App.tsx wires a memoized pickerPorts (broadcast + resolver/snapshot
refs from C-1) and passes it to the picker mount.
* TUI keystroke handling unchanged — broadcast is purely additive.
Validates the C-1 (#417) protocol foundation against a real picker with
no dashboard-side regressions.
* feat(dashboard): checkpoint picker for /restore (#419)
Third stage of #416. Bare /restore (no name argument) now opens an
interactive CheckpointPicker — covering both the TUI side (the command
was text-only before) and the web dashboard via the picker modal
protocol from C-1.
* New CheckpointPicker.tsx mirrors SessionPicker shape: arrow-key
navigation, ⏎ to restore, [d] to forget, esc to quit. Rows show
short id + name + relative age + file count / size.
* /restore handler returns openCheckpointPicker:true when called with
no argument; /restore <name|id> still resolves directly to keep the
one-shot path working.
* App.tsx mounts the picker, gates hotkeys behind it, and routes
outcome → restoreCheckpoint / deleteCheckpoint with a summary line
on success.
* usePickerBroadcast wires the same modal-up/down + resolvePicker
pipeline as C-2; web sees pick / delete / cancel actions.
* feat(dashboard): wire McpMarketplace through picker protocol (#420)
Fourth stage of #416. /mcp browse now broadcasts a picker snapshot to
the web dashboard with installed/source-tagged badges, popularity
meta, and the full action set: install / uninstall / refine /
load-more / cancel.
* installOrToggle split into doInstall + doUninstall so the web's
explicit `install` / `uninstall` actions don't accidentally toggle
on the wrong button (TUI Enter still toggles for keyboard
ergonomics).
* Snapshot builder extracted to a pure
`buildMarketplacePickerSnapshot` so the entry-to-item mapping can
be unit-tested without mounting Ink + the registry network call.
* refine and load-more keep the picker open (per C-1 design); cancel
closes it via the existing onClose hook.
* hasMore wired from `state.handle.cache.pagination.nextCursor` so
the dashboard's "Load more" button only shows when more pages exist.
* McpHub forwards pickerPorts from App.tsx to the marketplace tab;
the live tab is unchanged.
* feat(dashboard): picker modal kind for web parity (#417)
First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.
* New `picker` member on the `ActiveModal` discriminated union plus
`PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
rename / new / install / uninstall / load-more / refine / cancel.
`refine` and `load-more` keep the picker open so the TUI's filter
state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
rows, action buttons gated on `modal.actions`, and rename / new
inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
C-2..C-5 picker components only need the hook to participate.
No picker is migrated yet — that arrives in C-2 (#418).
* feat(dashboard): wire SessionPicker through picker modal protocol (#418)
Second stage of #416. SessionPicker (the simplest existing TUI picker —
no pagination, no async, ~5 actions) now broadcasts modal-up snapshots
to the web dashboard and resolves pick / delete / rename / new / cancel
from /api/modal/resolve.
* SessionPicker.tsx accepts an optional `pickerPorts` prop bundle and
feeds usePickerBroadcast a snapshot mapped from the existing sessions
list (id=name, badge=branch, meta=turns/cost).
* App.tsx wires a memoized pickerPorts (broadcast + resolver/snapshot
refs from C-1) and passes it to the picker mount.
* TUI keystroke handling unchanged — broadcast is purely additive.
Validates the C-1 (#417) protocol foundation against a real picker with
no dashboard-side regressions.
* feat(dashboard): checkpoint picker for /restore (#419)
Third stage of #416. Bare /restore (no name argument) now opens an
interactive CheckpointPicker — covering both the TUI side (the command
was text-only before) and the web dashboard via the picker modal
protocol from C-1.
* New CheckpointPicker.tsx mirrors SessionPicker shape: arrow-key
navigation, ⏎ to restore, [d] to forget, esc to quit. Rows show
short id + name + relative age + file count / size.
* /restore handler returns openCheckpointPicker:true when called with
no argument; /restore <name|id> still resolves directly to keep the
one-shot path working.
* App.tsx mounts the picker, gates hotkeys behind it, and routes
outcome → restoreCheckpoint / deleteCheckpoint with a summary line
on success.
* usePickerBroadcast wires the same modal-up/down + resolvePicker
pipeline as C-2; web sees pick / delete / cancel actions.
* feat(dashboard): picker modal kind for web parity (#417)
First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.
* New `picker` member on the `ActiveModal` discriminated union plus
`PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
rename / new / install / uninstall / load-more / refine / cancel.
`refine` and `load-more` keep the picker open so the TUI's filter
state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
rows, action buttons gated on `modal.actions`, and rename / new
inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
C-2..C-5 picker components only need the hook to participate.
No picker is migrated yet — that arrives in C-2 (#418).
* feat(dashboard): wire SessionPicker through picker modal protocol (#418)
Second stage of #416. SessionPicker (the simplest existing TUI picker —
no pagination, no async, ~5 actions) now broadcasts modal-up snapshots
to the web dashboard and resolves pick / delete / rename / new / cancel
from /api/modal/resolve.
* SessionPicker.tsx accepts an optional `pickerPorts` prop bundle and
feeds usePickerBroadcast a snapshot mapped from the existing sessions
list (id=name, badge=branch, meta=turns/cost).
* App.tsx wires a memoized pickerPorts (broadcast + resolver/snapshot
refs from C-1) and passes it to the picker mount.
* TUI keystroke handling unchanged — broadcast is purely additive.
Validates the C-1 (#417) protocol foundation against a real picker with
no dashboard-side regressions.
First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.
* New `picker` member on the `ActiveModal` discriminated union plus
`PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
rename / new / install / uninstall / load-more / refine / cancel.
`refine` and `load-more` keep the picker open so the TUI's filter
state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
rows, action buttons gated on `modal.actions`, and rename / new
inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
C-2..C-5 picker components only need the hook to participate.
No picker is migrated yet — that arrives in C-2 (#418).
Flicker reports keep landing without the one piece of info that
discriminates the bug — the terminal host (VSCode/Cursor xterm.js vs
standalone Windows Terminal / iTerm2 / etc.). The shell field on the
generic bug template was the wrong axis. New template asks for host +
version, env vars (TERM_PROGRAM/VSCODE_INJECTION/WT_SESSION), and ships
copy-paste diagnostic snippets so users do not have to know how to
introspect their own terminal.
Two stacked rules + five-segment status row + per-card breathing room
made history scroll read as scattered fragments. Tighten three things:
- Settled cards drop the marginTop the active form keeps, so scrollback
collapses to flat lines instead of one blank between every card.
- ModeStatusBar drops its dashed rule; StatusRow's solid rule already
separates the chat from bottom chrome.
- StatusRow drops session-cost + wallet segments (StatsPanel and
UsageCard already surface those); only turn cost + cache stay.
- Settled CardHeader filters faint string meta (1.2KB / 2.34s / exit N
on OK cards) and drops the right slot so spinners don't linger in
scrollback. Colored badges (rejected, retry) still render.
ui-status-row-balance reduced to the cells StatusRow now renders;
wallet/session currency coverage stays in ui-stats-panel-currency
and ui-usage-card-balance.
The Install block dropped readers at `npx reasonix code` with no
mention of the global-install path, and the README never named the
five subcommands a new user actually has to choose from. The website
already has a CLI panel but the section had no anchor, so the README
couldn't link to it.
- Name `npx` as the recommended path; point users at `reasonix update`
if they want the global install.
- Add a five-row cheatsheet (code / chat / run / doctor / update) so
newcomers don't have to guess. Defer the long tail (replay / diff /
events / stats / index / mcp / prune-sessions) to `--help` and the
CLI panel on the website.
- Mirror in zh-CN.
- Add `id="cli"` to the website's CLI section so the README link
resolves.
Bracketed-paste content was always converted to a `[paste #N · …]`
sentinel chip, even when the user pasted a single word or a number.
That made the composer feel hostile to common one-shot paste usage —
copying an identifier or a URL out of another window and dropping it
mid-sentence shouldn't leave a chip in the buffer.
Inline the content verbatim when it has no newline AND fits under
INLINE_PASTE_THRESHOLD (200 chars); fall back to the sentinel chip
for anything longer or multi-line. The model still receives the full
paste text either way — this is display-only.
projects[] is keyed by absolute rootDir, so on Windows two sessions
that resolve the same physical directory to different drive-letter or
component casing (PowerShell's `F:\Reasonix` vs bash/MINGW's
`f:\reasonix`) miss the persisted "always allow" entry from the prior
session and re-prompt every turn.
Add findProjectKey() that prefers the exact match and, on win32,
falls back to a case-insensitive scan. Use it in load / add / remove
/ clear so any-cased rootDir consolidates onto the existing key
instead of forking a duplicate. Non-Windows lookups remain
case-sensitive — Linux paths really are.
Two paths bypassed the cards' model snapshot:
- Dashboard preset change (POST /settings → applyPresetLive) reconfigured
the loop but never dispatched session.model.change, so subsequent
reasoning/streaming cards still rendered the old model badge.
- /pro consumed a single-turn escalation without telling the cards, so
the armed turn ran on v4-pro but the badge stayed on the base model.
applyPresetLive now dispatches session.model.change. reasoning.start /
streaming.start carry an optional model id; the loop's currentCallModel
getter feeds it through TurnTranslator.flushBuffers so the badge tracks
the model that actually produced the output.
Three contributor-led follow-ups: storm guard exempts safe inspector
reads (#388 by @ctharvey), wait_for_job replaces polling loops with
one blocking call (#390 by @ctharvey), and /skill new finally
provides the missing scaffold for user skills (#394).
* feat(skills): /skill new scaffolds a stub + README walkthrough (#366)
User feedback: wanted to install a frontend-writing skill, "no
discoverable entry point". The /skill list empty state told users
WHERE skills live but not HOW to author one — and there's no remote
registry to install from.
Adds the missing creation step:
- /skill new <name> → writes <project>/.reasonix/skills/<name>.md
- /skill new <name> --global → writes ~/.reasonix/skills/<name>.md
The stub carries the minimal frontmatter (name + description) plus
a comment block listing the optional knobs (runAs, allowed-tools,
model). Refuses to overwrite existing files; rejects invalid names
via the existing isValidSkillName regex.
Empty /skill list now surfaces the new scaffold + an explicit "no
remote registry yet" line so users don't keep hunting for a
marketplace that doesn't exist. Catalog + README in EN + zh-CN
gain the "author your first skill" path. The /skill list footer
mentions /skill new alongside show / run.
* fix(skills): atomic create with wx flag — close TOCTOU race CodeQL flagged
CodeQL flagged the existsSync→writeFileSync sequence as a potential
file-system race. Switch to writeFileSync with `flag: "wx"` so the
existence check IS the atomic write — if a parallel process landed
the file between our check and write, EEXIST surfaces and we report
the conflict instead of silently overwriting.
Keep the folder-form pre-check for a cleaner error message when the
collision is on the dir-style skill (`<name>/SKILL.md`).
Sweep of the 0.30.2 / 0.30.3 launch-day bug + onboarding queue:
resume now restores cache+context+cost (#364), model pill follows
/model + /preset switches (#372), bare /model opens an interactive
picker (#371), three more Shift+Tab encodings for PowerShell /
modifyOtherKeys / Kitty (#373), defensive stdin drain on exit kills
the fish/bash escape-leak (#365), and --dir / pinned workspace get
surfaced in the welcome banner, /status, sandbox errors, and the
README (#370).
Reporter saw `^[]11;rgb:...^[\^[[33;1R^[[?62;1;4c` printed by fish /
bash right after exiting reasonix. Those bytes are RESPONSES — OSC 11
bg-color, CPR cursor-position, DA1 device-attributes — sent by the
terminal in reply to queries the runtime / a dep emitted during
session startup. The dist bundle has none of those query bytes
itself, so the source is bun's tty feature-detection path or a
transitive dep doing color-scheme detection.
Whoever sent them, the responses sat in stdin's queue until reasonix
exited. The parent shell then read them and rendered the bytes as
input.
Add `drainTtyResponses(50ms)` and call it in chat.tsx's exit finally,
after `runtime.closeAll()`. Best-effort: sets raw mode, reads-and-
discards anything still queued for 50ms, restores cooked. No-op when
stdin isn't a TTY or raw mode isn't available.
0.30.3's alt-screen default is the upstream mitigation (DECSET 1049
flushes the input queue on most terminals); this is the program-side
mitigation that's independent of which terminal the user is in.
User feedback (multiple data points): beginners hit the default
cwd-scoped behavior and conclude Reasonix can't read folders other
than where they launched it. The capability already exists via
`reasonix code --dir <path>`, but nothing in the UI tells you so
until you read --help.
Three onboarding surfaces now make it discoverable:
- WelcomeBanner shows a "▸ workspace · /path (relaunch with --dir
<path> to switch)" line in code mode. Visible only on the empty
state, so it doesn't survive past the first turn.
- `/status` includes a workspace line:
workspace /path · pinned at launch (relaunch with --dir <path>
to switch)
- The filesystem sandbox-escape error now points the user at --dir
instead of just dropping a raw "path escapes sandbox root":
path escapes sandbox root (X): Y — workspace is pinned at
launch; quit and relaunch with `reasonix code --dir <path>` to
work in a different folder
Plus a Getting Started callout in both READMEs explaining --dir and
why mid-session switching isn't a thing (message log + memory paths
get tangled with stale roots, so the design pins at launch).
No new slash command, no /cwd. The agent's system prompt already
says mid-session switching was removed by design.
`/model <id>` required typing the model id by hand and `/models` was
a separate read-only listing. New users had no obvious way to switch
without prior knowledge of the catalog.
Bare `/model` now opens a modal picker that mirrors SessionPicker's
shape: arrow-key list, ⏎ confirm, [r] refresh the API catalog, esc
cancel, current model marked. The list seeds from the live DeepSeek
catalog (`useSessionInfo` already fetches it on mount); when the
catalog hasn't loaded yet the picker falls back to the four known
DeepSeek ids so it's never empty on first open. The current model
is always included even when the API didn't return it.
Confirming a row routes through `loop.configure({ model })` AND the
`session.model.change` event added in #372 — so the badge on the
NEXT card pill reflects the new selection.
`/model <id>` typed entry continues to work for power users.
Recognized only the bare xterm `\x1b[Z` back-tab. PowerShell 7.x on
some Windows hosts emits the modifier-encoded `\x1b[1;2Z`; modern
Windows Terminal in modifyOtherKeys mode (which we enable on
startup) emits `\x1b[27;2;9~`; the Kitty keyboard envelope is
`\x1b[9;2u`. None of these matched, so the edit-mode cycle was
silently dropped on PowerShell.
Add all three variants to `stdin-reader.ts` CSI_TAIL_MAP and to the
Ink-fallback `key-normalize.ts` recovery table. `/mode` slash command
remains as a typed fallback for any future terminal that emits a
form we haven't seen yet.
`state.session.model` was set once in `initialState()` and never
mutated. `/model <id>` and `/preset {auto,flash,pro}` only routed
through `loop.configure({ model })`, never into the agent store —
so the next `streaming.start` / `reasoning.start` / "thinking · X"
card snapshotted the launch-time model id, even when the model that
actually answered the turn was different.
Add a typed `session.model.change` event the model handlers dispatch
through `ctx.dispatch`. Reducer mutates `state.session.model` (with
referential identity preserved when the id is unchanged) and the
existing snapshot logic in `makeReasoningCard` / `makeStreamingCard`
picks up the new value automatically. Cards already opened keep
their captured model — that snapshot is intentional so mid-turn
escalation doesn't relabel completed reasoning.
`SessionMeta` only carried `totalCostUsd` and `turnCount`, so on every
resume `/status` showed:
- 0 context — `lastPromptTokens` came from `turns[0]?.usage`, and
`turns` is empty before the first live turn fires
- 0% cache hit — `aggregateCacheHitRatio` summed `turns[]` only
The next API call would still read the cached prefix and answer
correctly (turn 1 in the user's log shows 366,976 / 367,085 cache
hits), but the panel reported "no context" until that call landed.
Persist the missing fields after each turn (`patchSessionMeta`) and
seed them on resume (`stats.seedCarryover`). `aggregateCacheHitRatio`
and `summary().lastPromptTokens` now fall through to the carryover
when no live turn has run yet.
* feat(ui): row-precision virtual scroll on Ink 7 + React 19
Bump ink 5.2→7.0.2 + react 18.3→19.2; drop react-reconciler/yoga-layout.
Retire src/renderer/ (cell-diff + ink-compat shim) — Ink 7 ships native
equivalents for every motivation: alternateScreen, useAnimation,
useWindowSize, useBoxMetrics, synchronized output, incrementalRendering.
Default to alt-screen so the resize-ghost / scroll-yank class of bugs
disappears. `--no-alt-screen` opts back into scrollback for users who
need chat output preserved in shell history on exit.
Row-precision virtual scroll with reading mode: scrolling away from
bottom hides PromptInput and replaces it with a "📖 reading history —
End / PgDn to return" indicator. PgUp/PgDn/End owned by App; ↑/↓ on
an empty buffer hand off to chat scroll via PromptInput; App takes ↑/↓
directly when busy or in reading mode (PromptInput can't process them).
Wheel events translate to ↑/↓ in raw mode, so the same paths cover wheel.
Ctrl+P/N keeps the prompt-history binding (wheel-immune).
Drop <Static> — incompatible with alt-screen (no scrollback to shelter
committed cards across resize-reflow). React.memo on CardRenderer plus
the reducer's reference-stable card array skips reconciler cost on
unchanged cards. CardStream renders all cards inside an overflow:hidden
Box; inner Box's marginTop=-scrollRows shifts content; useBoxMetrics
reports inner/outer heights so App can clamp scroll bounds.
CardStream.isSettled covers task / plan / subagent kinds. PromptInput's
useReserveRows quantizes to 4-row buckets so per-keystroke layout doesn't
churn. TickerProvider migrated to Ink 7's useAnimation. Modal-open
condition collapsed from 14 OR'd checks into one reused boolean.
Migrate inline tests (markdown, plan-confirm) off the cell-diff renderer
to ink-testing-library. Remove dead alt-screen.ts; strip stale comments
referencing removed scrollback-mode workarounds.
* test(ui): provide fake stdin for Ink 7 raw-mode check in CI
Ink 7 calls setRawMode on stdin during render(); CI's process.stdin
isn't a TTY so it throws "Raw mode is not supported". Pass a minimal
EventEmitter-based fake stdin (setRawMode no-op, isTTY=true) alongside
the existing fake stdout. Affects four tests that import render directly
from ink for in-process render-and-assert: ui-session-picker-currency,
ui-stats-panel-currency, ui-usage-card-balance, ui-status-row-balance.
* test(ui): extract makeFakeStdin/Stdout to shared tests/helpers/ink-stdio
The official @modelcontextprotocol/server-filesystem refuses to start
when its sandbox directory is missing and prints a raw Node stack
trace, leaving the user without an actionable next step.
- preflightStdioSpec validates every positional path arg before
spawn and throws a one-line error: "create it with: mkdir -p '<path>'"
- The first-run / reconfigure wizard now stat()s the directory the
user typed for filesystem MCP and offers Y/Enter to mkdir -p,
N/Esc to enter a different path.
Adds SearXNG as an alternative web_search engine, switchable via /search-engine slash command or ~/.reasonix/config.json. Mojeek stays the default — zero risk for existing users.
CLI shows session cost in the wallet's currency (¥ for CNY wallets,
$ for USD), but the dashboard always used `fmtUsd()` which prints
the raw stored USD with a `$`. CNY users saw `$0.5190` in the
dashboard for the same session that read `¥0.024` in the CLI — both
the symbol AND the magnitude diverged because no conversion happened.
- New `fmtCost(usd, currency, fractionDigits?)` helper in
`dashboard/src/lib/format.ts`. Mirrors the CLI's `formatCost()` —
CNY converts via `USD_TO_CNY = 7.2`, USD passes through, undefined
defaults to CNY.
- `overview.ts` current-session cost + cost-trend day average now
thread `c.balance?.currency` into `fmtCost()`.
- `chat.ts` SideRail cost / budget rows and ChatStatusBar
turn / session cost rows pull currency from `stats.balance[0]`.
- Existing `fmtUsd()` kept as-is for places where USD is intentional
(Claude-equivalent comparisons in usage.ts) — those stay USD because
Claude's API is USD-priced regardless of the user's wallet.
Pain point @dacec354 raised twice: while the model writes a long plan
or todo list, the streaming card only shows the last 4 lines, so the
content scrolls past before you can read it. And once a long reply
settles, you may want to fold it back down — but `<Static>` already
flushed the bytes to scrollback so that half can't be unwound.
This collapses both requests into one keystroke: `ctrl-o` toggles
"expanded" mode on the live streaming card. Expanded shows the last
60 visual lines (capped so the card can't swallow the whole viewport)
plus a `⋯ N earlier lines above` hint when content overflows.
Collapses back to the 4-line preview. Auto-resets to collapsed at the
end of every turn so each new reply starts compact.
The same `(LIVE)` constraint covers #337's fold-toggle ask: only
not-yet-committed cards are addressable. Settled cards live in Ink's
`<Static>` which writes terminal scrollback once, no take-backs.
The `expanded ⌃o` / `preview ⌃o` pill in the card header advertises
the keybind so users discover it without reading docs.
`splitCardStream` only treated the LAST card as live; everything before
it was committed to Ink's `<Static>`. When the model streamed reasoning
THEN content (or kicked off a tool card), the reasoning card was
no longer last — so it got frozen into `<Static>` while still
`streaming: true`. `reasoning.end` later set `streaming: false` on
the cards array, but `<Static>` doesn't re-render frozen items, so the
"reasoning…" header kept its spinner indefinitely.
Fix: live-vs-committed split now scans for the FIRST unsettled card
and keeps everything from there onward in the live tree. Cards only
move into `<Static>` once they're settled AND every earlier card is
too — preserving the in-order append contract `<Static>` requires.
`suppressLive` semantic preserved: still hides the trailing live card
when the modal owns the screen.
Two new regression tests cover the reasoning + streaming case (must
stay live) and the all-settled case (must commit in order).
Same bug shape as the StatusRow / UsageCard / StatsPanel set that #272
already fixed — `SessionPicker` was still doing
`¥${totalCostUsd * USD_TO_CNY}` so USD-wallet users saw ¥-formatted
costs in the session list.
- `SessionMeta` gains `balanceCurrency?: string`. App.tsx writes the
live wallet currency alongside `totalCostUsd` on each turn save, so
every persisted session knows what currency its cost is denominated
in.
- `SessionPicker` accepts a `walletCurrency` prop and falls back to
each row's `meta.balanceCurrency`. Prop wins (live value > stored).
In-app picker (`/sessions`) gets the live ref from App; pre-mount
picker in `chat.tsx` doesn't have a balance fetched yet, so it
relies on the stored per-session value.
- Cost rendering routes through the shared `formatCost()` helper that
the rest of the cost UI already uses.
- Regression test asserts USD wallet → `$0.05`, CNY wallet → `¥0.36`,
no-prop + stored-USD → `$0.05`, neither → unchanged `¥0.36`.
- StreamingCard renders a `42 t/s` pill in the live header and a
`1.2k tok · 42 t/s` summary on the settled card. Computed via the
bundled DeepSeek tokenizer; gated below 4 tokens / 500 ms so the
pill never shows obviously-bogus rates while the first chunk lands.
Re-renders piggyback on the slow tick so the rate keeps updating
even when chunks stall briefly.
- The auto-mode undo banner now accepts a `space` keystroke to pause
the 5-second countdown indefinitely. While paused the bar freezes
at the captured fraction, the badge swaps to "Ns · paused", and
pressing space again resumes from where it stopped. The hint row
on edit-mode entry mentions both `u` and `space`.
The `u` and `space` keybinds share the same modal-and-prompt-empty
gating, so neither steals input while the user is typing.
Aliasing `from "ink"` → ink-compat in the CLI bundle made every
TUI bug invisible to `npx tsx` repros and forced cell-diff regressions
onto users only. Issue #346 (ShellConfirm ghost rendering) was a pure
cell-diff bug; the cleanest fix is to remove the alias and let
production take real Ink the same way source mode does.
- tsup: drop the `ink` alias and `noExternal` for ink/ink-text-input;
bundle keeps `from "ink"` external
- package.json: ink + ink-text-input move to runtime dependencies
- markdown-view: switch the only `inkCompat.*` namespace user back to
`import { Box, Text } from "ink"`
- bundle-smoke: invert the alias assertion to expect ink stays external
useCursor() in PromptInput keeps its cell-diff import; without a
CursorContext provider it no-ops, so it's harmless under real Ink.
Anonymized DeepSeek dashboard from a real Reasonix user
(2026-05-01, used with permission): 435M input tokens, 99.82%
cache hit, ~$12/day on v4-flash vs ~$61 the same workload would
cost without the cache.
Lives at benchmarks/real-world-cache/ alongside an explanation of
the four mechanisms (ImmutablePrefix + AppendOnlyLog +
VolatileScratch + auto-compact) that produce the hit rate. README
gets a NOTE callout pointing at it — answers the recurring "isn't
this just DeepSeek's prefix cache?" pushback with concrete numbers
instead of a re-derived napkin.
Switch the X-axis branch of `moveTo()` from CUF (relative cursor right,
`\x1b[NC`) to CHA (absolute column, `\x1b[N+1G`). Y-axis stays on
CUU/CUD since we don't track absolute terminal rows.
Relative column moves accumulate drift across frames: if any earlier
write miscounted cell width — wide-char disagreement (`▸` U+25B8 in
"narrow" fonts that render 2-cell), `▎` ambiguous-width on terminals
that font-detect East Asian width, OSC8 hyperlinks parsed as visible
chars, etc. — the cursor's actual column desyncs from what the
renderer thinks. The next CUF lands at the wrong column, ghost-rows
get written into hint lines, and the modal "shifts" as users navigate
(symptom in #346 issue screenshots).
Anthropic's Claude Code TUI hit the same class of bug
(anthropics/claude-code#14208) and the fix was the same: prefer CHA
over CUF/CUB so column targeting is immune to per-cell width
miscounts. Fix is invisible on terminals where our width math was
already correct; on terminals where it wasn't, no more accumulating
drift.
Add `aliases?: readonly string[]` to SlashCommandSpec so /quit + /q
resolve to /exit, /? to /help, /reset to /new, /lang to /language —
all from a single declaration on the spec instead of ad-hoc handler
mirrors scattered across handlers/basic.ts + handlers/language.ts.
dispatch, suggestSlashCommands and detectSlashArgContext all route
through one resolveSlashAlias() built from SLASH_COMMANDS at module
init. Suggestion rows surface aliases dimly (` · /quit /q`) so they
stay discoverable without polluting the autocomplete list with
duplicates. Dashboard /api/slash response now exposes the field too.
When a markdown table is too wide for the viewport, FallbackTable
flattens it into key/value lines. The previous implementation
iterated headers first, then rows-within-each-header — so a 3×N
table came out as N "Component:" lines, then N "What:" lines,
then N "Manual TCs:" lines. The user couldn't tell which value
belonged to which row.
Reproduction (issue #340): a planning table for 9 components
rendered as 9 grouped Component lines, 9 grouped What lines,
9 grouped Manual TCs lines — visually a list, not a table.
Swap loop order: iterate rows first, then write all columns
inside each row block, separated by a blank row between rows.
Output now reads top-to-bottom as one logical row at a time.
When the model called submit_plan with a markdown body but no
structured steps, the Approve plan modal showed only the
warning banner + the choice list — the actual plan content
was hidden behind the collapsed tool-call card in scrollback.
Users had no way to see what they were approving without
hunting up through the transcript.
- Render the plan body via MarkdownView when no steps are
supplied. Steps still take precedence when present (they
are the canonical structured view).
- Cap inline preview at 24 lines; surface "… N more lines
above in scrollback" when the body exceeds that. Reserve
budget grows with whichever body section is being shown.
Tests cover the three branches: body-only, steps-present,
and truncated-body-with-overflow-hint.
The TUI's session-cost figure ($X session) reset to $0 on every
resume because SessionStats was rebuilt empty even when the disk
meta still held the cumulative totalCostUsd from prior runs.
Reproduction (issue #333): hello → exit → resume → expense
accumulator displays 0 instead of the prior session total.
The persistence path was already correct — App.tsx writes
`{ totalCostUsd, turnCount }` into the session meta after every
turn. Only the read-back was missing.
- SessionStats gains a `seedCarryover()` once-at-construction hook
that adds prior totals to the in-memory totalCost / summary.turns
without polluting the live `turns[]` array (which intentionally
holds only this run's per-turn records).
- CacheFirstLoop now calls `loadSessionMeta()` on resume and seeds
the carryover when prior messages exist. Fresh sessions are
unaffected — undefined meta fields short-circuit the seed.
Tests cover the carryover math (telemetry.test.ts) and the
end-to-end loop wiring (session.test.ts).
* fix(markdown): stop linkifying "e.g" / "i.e" / drop OSC 8 garbage (#330)
Two coupled bugs in the markdown file-ref linkifier:
1. FILE_REF_RE matched English abbreviations because the extension
class was `{1,6}` — `e.g`, `i.e`, `a.m` all qualified.
2. `osc8()` baked OSC 8 escape bytes (\x1b]8;;...\x07) into Text
content. The cell-diff renderer's wrapLine strips zero-width chars
(ESC, BEL) but keeps the printable body, so terminals received
plain `]8;;file://e.ge.g]8;;` characters — visible garbage on
any terminal, with no working hyperlink anywhere.
The fix:
- Tighten FILE_REF_RE post-match: require either path-shape (slash),
line-number suffix, or extension >= 2 chars. `src/foo.ts`,
`package.json`, `util.c:42` still match; bare `util.c` no longer
does (acceptable — rare in prose).
- Strip the OSC 8 escape from `osc8()` — keep color + underline
styling so file refs stand out, but do not emit hyperlink bytes.
The renderer would need per-span hyperlink propagation through
nested HostText flattening to support real OSC 8; that's a
separate refactor. Until then, no link beats broken link.
- Plumb a `hyperlink` prop on ink-compat Text so the future
per-span fix has a place to land.
Regression test mounts Markdown through the reconciler and asserts
the byte stream never contains `]8;;` for `e.g` / `i.e` samples.
* fix(renderer): trail-clear shrunk rows in cell-diff (#330)
Defensive against terminal-state desync. The cell-diff renderer
skips cells where prev and next are byte-equal — including the
trailing EMPTY cells of a row that shrank. If the terminal's
actual state diverged from prev (e.g. a stray ESC body slipped
through earlier rendering), those skipped trailing cells retain
stale chars from prior frames.
This was the second half of issue #330: with the markdown OSC 8
garbage previously sourcing the desync, the option-list modal
rendered "allow always" + "mand, ask again next time" leftover
on rows that originally held a longer hint.
- New `clearToEOL` patch type → serializes to `\x1b[K`
- After diffEach, sweep rows: if next's row ends earlier than
prev's content extent, emit clearToEOL past the last visible
cell. Bounded — at most one clearToEOL per row that shrank.
- Two regression tests cover the modal-shrink case and verify
no clearToEOL is emitted for same-width swaps.
The .chip-f class has cursor:pointer + a hover style, so every chip
looked clickable. In skills, plans, and hooks the chips were laid out
as filter buttons (one hardcoded "active") but had no onClick — clicks
did nothing. Other panels reused chip-f for non-interactive count
indicators, which had the same misleading hover affordance.
Real filters wired:
- skills: All / Project / Global / Builtin filters the list by scope
- plans: All / Active / Done filters by completion status
- hooks: Resolved + each event filters the matrix to rows whose hooks
fire on the selected event (matrix columns still show all events)
Static indicators marked with the new `chip-f.static` modifier (cursor
default, no hover lift). Sessions count, permissions Project/Builtin
counts, usage records/log size, tools total + plan-mode flag, chat
mode label, semantic index status, and semantic config-tag chips all
no longer pretend to be clickable.
CSS: new `.chip-f.static` + `.chip-f.static:hover` rules disable the
interactive affordances without duplicating the chip styling.
Document the chunked-parallel dispatcher and the two knobs that govern
it (REASONIX_PARALLEL_MAX, REASONIX_TOOL_DISPATCH=serial), plus the
list of built-in tools that opt in via parallelSafe.
Closes the docs portion of #325. Observability-event work (chunk-start
in events.jsonl) is deferred — the existing test suite already validates
the timing, ordering, and barrier guarantees, and the kernel event log
is a heavier surface that can wait until a real ops need surfaces.
Replace the serial `for...of + await` tool dispatch with chunked
parallel scheduling: consecutive `parallelSafe` calls race together;
unsafe calls form serial barriers. Tool yields and history append
preserve declared order regardless of which call settles first.
- Loop dispatch chunks consecutive parallelSafe calls; unsafe call
ends the current chunk and runs alone
- runOneToolCall extracts per-call lifecycle (PreToolUse + dispatch +
PostToolUse) so chunks can fan out via Promise.allSettled while the
loop body keeps yielding events in declared order
- New env knobs: REASONIX_PARALLEL_MAX (cap, default 3, hard max 16)
and REASONIX_TOOL_DISPATCH=serial (escape hatch)
- SubagentEvent gains a stable runId per spawn; useSubagent keeps an
array of in-flight activities; SubagentLiveStack renders 1 → rich
card, 2..max → compact rows, >max → "+N more" fold
Tests cover the four guarantees: parallel timing, serial barrier on
mixed safe/unsafe, declared-order yields under racey completion, and
both env-knob overrides.
Two task shapes repeat often enough to warrant first-class support
without needing a skill:
- explore — wide-net read-only investigation (20-iter budget)
- verify — narrow yes/no check with evidence (8-iter budget)
Add an optional `type` field to the spawn_subagent schema. When set,
the type supplies the system prompt and default iter budget. Caller-
supplied `system` / `max_iters` override the type's defaults.
Prompts live in src/tools/subagent-types.ts so subagent.ts stays under
the 500-line target.
Closes#319
Subagents have always had a configurable maxToolIters internally, but
the public spawn_subagent schema exposed only task/system/model. Every
spawn paid the 16-iter default, even narrow verify-style tasks that
want fewer or broad explore tasks that want more.
Add an optional `max_iters` integer field to the schema, clamp at the
boundary to 1-32 so a stray prompt can't request thousands, and pipe
through to spawnSubagent. Non-numeric / missing values fall back to
the registration-time default (still 16).
Closes#318
Skill frontmatter `allowed-tools` was parsed but ignored — every subagent
inherited the parent's full registry minus spawn_subagent / submit_plan,
which gave skill authors no way to scope a child to read-only or
task-specific tools.
Plumb the parsed list through SpawnSubagentOptions; when present, fork
via new forkRegistryWithAllowList helper instead of forkRegistryExcluding.
NEVER_INHERITED still wins so spawn_subagent stays out even if the
skill's allow-list names it. Validate at spawn time — if the allow-list
names a tool the parent doesn't have, return a structured error result
naming the missing tool, no API call burned.
Direct (non-skill) spawn_subagent calls still see full inheritance —
the tool schema is unchanged.
Closes#317
No live render path — `App.tsx` mounts `StatsPanel`, which has its own
`ChromeRow` that diverged from `ChromeBar` and is the bar users actually
see. Only references are a CHANGELOG history line and one test
description string ("'w \$0.91' style").
The two formatter helpers `ChromeBar` once owned (`formatBalance` /
`formatBalanceLabel`) already live in `theme/tokens.ts` after #272 / #313.
After #272 fixed StatusRow / UsageCard / ChromeBar BalancePill, three
display sites still hardcoded `$` and ignored the wallet currency:
- StatsPanel.ChromeRow (the live top bar) — cost label `[$0.0058]`
- StatsPanel.ChromeRow — balance label inline-formatted, bypassing the
shared formatBalance helper from #272
- useSubagent end-event summary — ` · $0.0123` cost suffix
Now all three route through formatCost / formatBalance and follow the
live wallet symbol. Render tests added in ui-stats-panel-currency.test.tsx
covering USD / CNY / no-wallet variants.
useSubagent gets a `getWalletCurrency` thunk (not a snapshot value)
because subagent runs can outlive a balance refresh — the thunk reads
the latest currency at end-event time.
Out of scope: ChromeBar.tsx (orphan, no live render path), DiffApp.tsx
(dev tool comparing historical USD numbers), BudgetRow (USD by definition,
user sets `--budget` in USD). SessionPicker tracked separately in #312.
* fix: Currency for USD wrong afeter TUI redesign.
* red: tests for the currency bug
* Fix implementation
* fixup: collapse tokens helpers + fix UsageCard cost bug
Addresses the two review comments on this PR:
1. Undefined-currency fallback now defaults to CNY for all three helpers
(formatBalance, formatCost, balanceColor) — matches pre-fix unconditional ¥.
2. Seven helpers (formatCNY, formatBalance, formatBalanceLabel,
formatWalletDisplay, formatCost, balanceColorCny, balanceColorForBalance)
collapsed to three: formatBalance, formatCost, balanceColor.
Also fixes a separate bug surfaced while collapsing: UsageCard turn cost
(header) and session cost (body) used formatCNY, which was unconditional ¥
regardless of wallet currency. They now use formatCost(…, balanceCurrency)
and follow the wallet symbol like StatusRow does.
Render tests added for UsageCard turn/session cost in USD wallet mode.
---------
Co-authored-by: esengine <[email protected]>
PR2 under #307. Three more pieces that didn't depend on `this`:
- new `src/loop/types.ts` — `EventRole`, `BranchSummary`, `BranchProgress`,
`LoopEvent`. The public-API re-export from `loop.ts` is preserved
(`export type { ... } from "./loop/types.js"`), so consumers importing
from `reasonix` see no change.
- new `src/loop/branch.ts` — `summarizeBranch` lives next to the types
it produces.
- new `src/loop/hook-events.ts` — `safeParseToolArgs` + `hookWarnings`.
These format hook outcomes as `LoopEvent`s and were the only callers
of `formatHookOutcomeMessage` / `HookOutcome` from `./hooks.js`, so
those imports leave `loop.ts` too.
`loop.ts`: 1414 → 1332 lines. No public API change. `npm run verify`
green (2336 pass / 1 skip).
PR1 under #307. Six functions and three constants that don't touch
`this` had no business living inside the `CacheFirstLoop` class file.
- new `src/loop/escalation.ts` — `parseEscalationMarker`,
`isEscalationRequest`, `looksLikePartialEscalationMarker` plus
`NEEDS_PRO_MARKER_PREFIX` / `NEEDS_PRO_MARKER_RE` /
`NEEDS_PRO_BUFFER_CHARS`. The streaming chunk consumer + post-call
retry path call these as plain functions now.
- `src/loop/errors.ts` gains `reasonPrefixFor` + `errorLabelFor` next
to `formatLoopError`. They share the same `"budget" | "aborted" |
"context-guard" | "stuck"` reason union and were the only callers.
`loop.ts`: 1463 → 1414 lines. No public API change — these were all
private / file-local. `npm run verify` green (2336 pass / 1 skip).
The chain-of-regex approach was tripping CodeQL across three rules
(bad-tag-filter, incomplete-multi-character-sanitization,
polynomial-redos) on the same set of patterns:
- `<tag[\s\S]*?</tag>` misses `</tag >` (whitespace before `>`) and
re-exposes `<tag` after one removal pass on `<scr<tag>ipt>`-shaped
input.
- `<[^>]+>` doesn't handle attribute values containing `>` (rare but
legal in unquoted contexts) and is the canonical "incomplete
sanitization" footgun.
Replaces both with a `node-html-parser` walk:
- `htmlToText` parses the input, removes `script / style / noscript /
nav / footer / aside / svg` blocks via `querySelectorAll`, then
walks the surviving tree and emits text with `\n` breaks at the
block-level tags we care about (`p`, `div`, `br`, `h1-6`, `li`,
`tr`, `section`, `article`).
- `stripHtml` (used by `parseMojeekResults`) becomes `parseHtml(s).text`.
- `decodeHtmlEntities` stays — kept for the post-parser pass since
parser-decoded text can still contain numeric entities in edge
attribute contexts.
- 5 MB input cap retained.
`node-html-parser` 7.x: 25 KB gzip, zero deps, ~30k packages
depend on it, active maintenance. Lighter than `parse5` for our
use case (we don't need full HTML5 conformance — just the tree).
21 web-tools tests pass unchanged; 2336 total tests green.
- src/cli/ui/Wizard.tsx — quoteIfNeeded escaped `"` but not `\`. A
trailing backslash on the input would consume the closing quote
when a downstream parser un-escaped the result. Escape `\` first
(CodeQL js/incomplete-sanitization).
- src/cli/ui/clipboard.ts — temp filename was `reasonix-clip-${Date.now()}.txt`,
predictable + collides under sub-millisecond bursts. Switched to
`randomUUID()` (CodeQL js/insecure-temporary-file).
- tests/slash.test.ts — `/kb.example.com/` matched too broadly (`.`
matched any char, no anchors). Tightened to
`/\bkb\.example\.com\b/` (CodeQL js/incomplete-hostname-regexp +
js/regex/missing-regexp-anchor).
136 wizard + slash tests pass unchanged.
Drains the last 2 file-system-race warnings in code/edit-blocks.ts.
Replaces the existsSync precheck + separate read/write pair with a
single fd-scoped flow:
- Try `openSync(path, "r+")` first. ENOENT → file doesn't exist:
bail with `file-missing` (when SEARCH is non-empty) or fall through
to atomic create.
- Atomic create is `openSync(path, "wx")` — fails on EEXIST so a
concurrent writer that filled the slot between our `r+` ENOENT and
our create can't be silently clobbered.
- Modify path keeps one fd open through fstat → read → ftruncate →
write. ftruncate sets the new length first (so a shorter result
doesn't leave stale tail bytes), then we overwrite from offset 0.
The 22 edit-blocks tests pass unchanged.
1 file-system-race warning still open (`usage.ts:103` compaction);
needs temp-file + rename, separate PR.
Drains the last 2 file-system-race warnings in cli/ui that were
exists→write rather than stat→read.
The original `appendBulletToFile` had two races:
1. `existsSync(path)` then `writeFileSync(path, header)` — between the
check and the write a concurrent appender could create the file,
and our writeFileSync would clobber it with a fresh header (losing
their bullet).
2. `readFileSync(path)` then `appendFileSync(path, …)` — peeking the
trailing byte to decide whether we need a leading `\n`, then a
separate append. A concurrent writer that added their own newline
in between would cause us to insert a redundant blank line.
Fix:
- Atomic create-or-fail via `openSync(path, "ax")`. EEXIST means
another process won the race; we fall through to the append branch
rather than clobbering.
- For the append branch, open with `a+` once and do the trailing-byte
peek + write on the same fd. `O_APPEND` means each `writeSync`
atomically lands at end-of-file regardless of concurrent appenders.
20 hash-memory tests pass unchanged.
3 file-system-race warnings still open: edit-blocks.ts (×2) and
usage.ts:103. They need different surgery (`r+` + ftruncate /
read-modify-write or temp-file + rename); separate PR.
Same fix shape as #298 — open once, do the size check and the read
against the same fd. The read on filtered semantic indexes also gets
to enforce its size threshold against the actual bytes we're about
to load, not a stat result that could be stale by the time we look.
- src/index/semantic/chunker.ts:209 per-file read in the indexer —
re-checks `maxFileBytes` against `fh.stat()` before reading
- src/server/api/semantic.ts:200 `/api/semantic/status` index
summariser — was `statSync().size` then `readFileSync`
- src/cli/ui/slash/handlers/semantic.ts:78 `/semantic` slash status —
was `fs.stat` then `fs.readFile`; estimate fallback for >10MB stays
the same, just bound to the fd's stat
- src/telemetry/usage.ts:74 compactUsageLogIfLarge — folds the
separate stat / read try-blocks into one fd-scoped sequence
5 file-system-race warnings remain — those are exists→write or
read→write patterns (`hash-memory.ts`, `edit-blocks.ts`,
`usage.ts:103`); separate PR with `openSync(path, "ax" | "r+")`.
Same fix shape across three files: open once, use fstat + read against
the same fd. The fd binding pins the inode for the lifetime of the
operation so a concurrent rename / replace / unlink during the call
can't desync the size or mtime we just observed from the bytes we're
about to read.
- src/tools/filesystem.ts:127 read_file body — was `fs.stat` then
`fs.readFile`; switches to async `fs.open` + `fh.stat` + `fh.readFile`
- src/server/assets.ts:36 mtime-keyed asset cache — was `statSync`
then `readFileSync`; switches to `openSync` + `fstatSync` + chunked
`readSync`
- src/server/api/skills.ts:72 per-skill listing — same shape; also
drops the redundant `existsSync` precheck that was a separate race
in the same chain
9 file-system-race warnings remain — those are exists→write or
read→write patterns that need a different fix (open with `ax` / `r+`
flags); separate PR.
Phase-2 PR under #290 (start of the feature-cluster phase). The
/apply and /discard slash callbacks move into one hook (93 lines).
The hook owns the partition / snapshot / save / sync sequence and
returns thin string-builders that AppInner forwards to its log.
Drops `partitionEdits` (unused after extraction) and `savePendingEdits`
(only used by the extracted callbacks) from App.tsx's imports.
App.tsx: 3361 → 3304 lines.
Phase-1 PR under #290 — biggest single extraction so far. The /loop
slash command's entire lifecycle moves into one hook:
- the activeLoop state + the four refs (mirror, timer handle, firing
flag, and the timer scheduler effect itself)
- startLoop / stopLoop / getLoopStatus
- the timer scheduler useEffect (35 lines)
External consumers no longer poke at refs directly. The hook exposes:
- startLoop / stopLoop / getLoopStatus (forwarded to slash handlers)
- isLoopActive() — replaces all `activeLoopRef.current` checks (Esc
handlers, apply-slash-result)
- isLoopFiring() / clearFiringFlag() — replace the cross-component
`loopFiringRef.current` reads in handleSubmit's cancel guard
- activeLoop — reactive state for the LoopStatusRow render
apply-slash-result.ts's context shape switches `activeLoopRef:
MutableRefObject<...>` to `isLoopActive: () => boolean`. Cleaner —
slash handlers don't need to know about the ref shape.
App.tsx: 3499 → 3400 lines.
Phase-1 PR under #290. The Ctrl+C / SIGINT exit handler now lives in
its own hook: it returns the `quitProcess` callback and registers /
deregisters the SIGINT listener on its own. AppInner just calls
`useQuit(transcriptRef)` and forwards the returned function to the
slash dispatcher and Ctrl+C interceptor.
The "why process.exit, not Ink exit" rationale moves with the code
into the hook's docstring — that's the only place future callers
need to read it.
App.tsx: 3499 → 3483 lines.
Phase-1 PR under #290. The transcript writer becomes its own hook —
takes the transcript ref + the model/prefix metadata it needs to
stamp on each record, returns the LoopEvent writer that AppInner
forwards into stream subscribers and slash handlers.
Drops `recordFromLoopEvent` + `writeRecord` from App.tsx's import
block since the hook now owns those.
App.tsx: 3499 → 3493 lines.
First Phase-1 PR under #290. Lifts the bash-style ↑/↓ history recall
out of AppInner: the two `useRef`s (`promptHistory`, `historyCursor`)
and the two `useCallback`s (`recallPrev`, `recallNext`) are now
co-located in `src/cli/ui/hooks/useInputRecall.ts`.
The hook returns four functions — `recallPrev` / `recallNext` for
PromptInput, plus `pushHistory` (called on every successful turn) and
`resetCursor` (called once on submit). Existing callers that wrote
`promptHistory.current.push(text)` switch to `pushHistory(text)`;
`historyCursor.current = -1` becomes `resetCursor()`.
`apply-slash-result.ts` had the only out-of-component reference to
the ref — its context shape now accepts `pushHistory: (s: string)
=> void` instead of the raw `MutableRefObject`. Cleaner contract.
App.tsx: 3499 → 3479 lines.
* fix(redos): close polynomial backtracking in 4 regexes
CodeQL js/polynomial-redos flagged four regexes whose backtracking
shape is O(n²) on adversarial input. None are reachable from a real
attacker today (the inputs are model output / our own URL constants),
but the patterns are easy to fix and the alerts were noise.
- at-mentions.ts:319 — `/\.+$/` on path-like tokens. Loop-slice instead.
- client.ts:95 — `/\/+$/` on baseUrl. Loop-slice instead.
- scavenge.ts:67/75/86 — three DSML matchers (`<X>[\s\S]*?</X>` shape)
on reasoning_content. Adds a 100 KB input cap with an early-bail
note; the matchers themselves stay readable.
Per CodeQL's third remediation example, bounding the input length is
a valid fix when the regex is hard to rewrite — scavenge is best-effort
and the cap is well above any plausible legitimate reasoning_content.
* fix(web): drain CodeQL warnings on htmlToText
htmlToText leaned on a chain of regex replacements that CodeQL flagged
across six rules — bad-tag-filter, incomplete-multi-character-
sanitization, polynomial-redos (×2), double-escaping. None were
exploitable in our pipeline (output goes to the LLM, not a browser),
but the patterns had real correctness bugs visible to the model:
- `<script[\s\S]*?</script>` missed `</script >` (whitespace before
`>`) and could leave `<script` behind on the second pass when an
outer match revealed a previously-hidden inner opening.
- Chained `decodeHtmlEntities` replacements ran `&` before `<`,
so `&lt;` decoded to `<` instead of literal `<`.
Rewrites both:
- `stripTagBlock(s, tag)` — indexOf-based scan with explicit tag-
boundary check (avoids matching `<scriptfoo>`) and tolerant close
matching (`</tag …>` with whitespace).
- `decodeHtmlEntities` — single regex pass with an entity map plus
`&#nnn;` / `&#xHH;` numeric-entity handling. No more order bugs.
- 5 MB input cap on htmlToText so any residual quadratic patterns
(e.g. the kept `<[^>]+>` strip) stay bounded.
21 web-tools tests still pass.
* chore(tsconfig): add @/* path alias for src; migrate slash handlers
The 16 files under src/cli/ui/slash/handlers/ sit four levels deep, so
every import to a top-level module read "../../../../i18n/index.js" or
the equivalent. The depth was load-bearing for nothing — it just made
moves and reviews painful. Adds a single \`@/* → src/*\` alias to
tsconfig.json and mirrors it in vitest.config.ts (esbuild via tsup
already picks up tsconfig paths transparently).
Migrates only the four-level offenders for now. Three-level imports
(siblings within cli/ that resolve to "@/cli/...") are left alone —
the relative form is arguably clearer when the import target is a
neighbour. A follow-up can tighten that if it's worth the churn.
Build, typecheck, and full test suite all pass on the migrated paths.
* fix(jobs): wait for actual close event after SIGKILL, not a fixed timer
stop() had two timing races. Both manifested as the same flake — the
returned snapshot's `running` flag could still be true even though the
test (and the user) just told us to stop the job.
1. SIGKILL phase used a fixed 800ms timer, then returned regardless of
whether the OS had reaped the process tree. Under Windows scheduler
load, taskkill /T /F on a 3-level tree (npm → node → vite) can take
over a second to propagate before Node's `close` event fires.
2. SIGTERM phase awaited `readyPromise`, which is dual-purpose: it
fires on either a startup ready-signal regex match OR child exit.
If the job had already matched a ready signal, `readyPromise` was
already resolved, so the SIGTERM grace race short-circuited
immediately and we'd jump to SIGKILL with zero pause.
Adds `closedPromise` — fires only on close/error, never on ready
signal — and uses it for both the SIGTERM grace race and the post-
SIGKILL wait, with a 5s ceiling on the latter so a wedged kernel
can't hang us indefinitely.
* refactor(filesystem): extract edit + search bodies into src/tools/fs/
filesystem.ts had grown to 681 lines, with three of the registered
tools — edit_file, search_files, search_content — carrying most of
the weight in their inline `fn:` bodies. The diff helpers (renderEditDiff,
lineDiff) were also trailing the registration code with no good reason
to live in the same file.
- src/tools/fs/edit.ts — applyEdit + lineDiff + renderEditDiff (the LCS-based diff renderer is now in the same file as its only caller).
- src/tools/fs/search.ts — searchFiles + searchContent share a SearchContext shape so each tool's `fn:` becomes a one-line dispatch.
- src/tools/filesystem.ts — registration entries kept; bodies are now thin pass-throughs.
`lineDiff` is re-exported from filesystem.ts so the existing test import
(`tests/filesystem-tools.test.ts`) doesn't move.
No public API change. No behavior change. filesystem.ts: 681 → 486 lines.
* fix(filesystem): close stat→read race in search_content (CodeQL)
Replaces the separate `fs.stat(full)` + `fs.readFile(full)` pair with a
single `fs.open` → `fh.stat` → `fh.readFile` sequence so the size check
and the actual read bind to the same fd / inode. No TOCTOU window.
Functionally equivalent: oversized files still skip cheaply (we never
read past the size check), small files still read in one shot.
shell.ts had grown to 847 lines, mixing three unrelated concerns:
allowlist parsing (which is pure string work and the security gate),
process spawning (which carries all the Windows / PowerShell / GBK
workarounds), and tool registration with the ToolRegistry. Each lives
in its own file now:
- src/tools/shell/parse.ts — tokenizer, allowlist, RISKY_ARGS demotion
- src/tools/shell/exec.ts — runCommand, prepareSpawn, killProcessTree, all the Windows quirks
- src/tools/shell.ts — registerShellTools, NeedsConfirmationError, format helpers, plus re-exports
No public API change — every name still importable from ./shell.js.
No behavior change. shell.ts: 847 → 304 lines.
loop.ts had grown to 1724 lines, mixing the CacheFirstLoop streaming
class with a dozen helper functions across four unrelated concerns:
message healing, oversized-result shrinking, thinking-mode flags, and
DeepSeek error formatting. Each concern now lives in its own module
under src/loop/, and loop.ts re-exports every public name so external
callers don't move.
No behavior change. loop.ts: 1724 → 1459 lines.
* fix(benchmark): drop useless \$ escapes in tdd-eval prompt string
The h1 task description string used `\${file}::\${fullName}` inside a
regular `"..."` literal. The backslashes are no-ops (JS quietly drops
unrecognized escapes in regular strings) but trip CodeQL's
js/useless-regexp-character-escape rule. Identical resulting string,
cleaner source.
* fix(jobs): wait for actual close event after SIGKILL, not a fixed timer
stop() had two timing races. Both manifested as the same flake — the
returned snapshot's `running` flag could still be true even though the
test (and the user) just told us to stop the job.
1. SIGKILL phase used a fixed 800ms timer, then returned regardless of
whether the OS had reaped the process tree. Under Windows scheduler
load, taskkill /T /F on a 3-level tree (npm → node → vite) can take
over a second to propagate before Node's `close` event fires.
2. SIGTERM phase awaited `readyPromise`, which is dual-purpose: it
fires on either a startup ready-signal regex match OR child exit.
If the job had already matched a ready signal, `readyPromise` was
already resolved, so the SIGTERM grace race short-circuited
immediately and we'd jump to SIGKILL with zero pause.
Adds `closedPromise` — fires only on close/error, never on ready
signal — and uses it for both the SIGTERM grace race and the post-
SIGKILL wait, with a 5s ceiling on the latter so a wedged kernel
can't hang us indefinitely.
TODO/HACK markers without a (#nnn) issue anchor are debt leakage —
they accumulate without ever being tracked. Require the anchor; bare
markers fail the comment-policy gate.
FIXME is banned outright: either fix it now or open an issue and turn
it into a TODO(#nnn). The marker without follow-through is just noise.
Translator-note comments in i18n files ("english version", "中文版",
etc.) restate what the strings already say — i18n entries are
self-documenting.
src/ currently has zero violations of any of these rules, so this is a
floor-keeper, not a cleanup.
jobs.test.ts / loop.test.ts / bundle-smoke spawn real processes and
load the tokenizer cold; on Windows under load these intermittently
miss their wall-clock budget. One retry absorbs the scheduler
hiccup; a real failure still re-fails on the second run.
handleSettings read cfg once up front, then per-field either called a
self-contained helper (setLanguage / saveApiKey / saveReasoningEffort)
or mutated the snapshot and called writeConfig — so a combined POST
like { lang, baseUrl } would write lang via the helper, then clobber
it with the stale snapshot in the writeConfig branch.
Single read up top, all field updates accumulate into one cfg, single
writeConfig at the end. Runtime side-effects (setLanguage,
applyPresetLive, applyEffortLive) fire after the disk write succeeds
so disk + runtime state can't diverge mid-request.
Closes#274
The `glob` arg was always a `name.toLowerCase().includes(...)` substring
filter, so `*.ts` matched the literal three-char filename instead of
TypeScript files. Param name advertised glob, behavior didn't.
Now glob via picomatch when the value contains `*`, `?`, `{`, or `[`;
case-insensitive substring otherwise so existing `.ts` / `test` callers
keep working. Patterns containing `/` match against the rel-path
(enabling `src/**/*.tsx`), basename otherwise.
Closes#273
Aligns search_files with search_content + directory_tree: skip the
existing SKIP_DIR_NAMES set (node_modules / .git / dist / build /
.next / target / .venv) by default, accept include_deps:true to opt
back into walking them. Fixes the surprising mismatch where
search_content("foo") and search_files("foo") had different default
scopes.
Closes#267
Inside `"..."` the parser treated any `\X` as a generic escape and
dropped the backslash, so `dir /b "C:\Users\foo\.bar"` ran against
`C:\Users\foo.bar`. Restrict the escape to `\"` and `\` only —
everything else stays literal so Windows path separators survive.
Single `isDqEscape` helper now shared by `tokenizeCommand`,
`detectShellOperator`, `splitOnChainOps`, and `parseSegment`.
Closes#265
* feat(mcp): registry-backed marketplace + CLI/Ink/dashboard surfaces
Was: 5-entry hardcoded catalog. Now: live marketplace pulling from
registry.modelcontextprotocol.io (primary), smithery.ai (fallback),
bundled catalog (offline last-resort). 24h cache, schema v2, lazy
per-page loading so first list returns ~30 entries in ~1s.
CLI: `reasonix mcp {list,search,install,browse}` — browse is an Ink
TUI (type-to-filter, ↑↓ pick, Enter install, Tab load 5 more pages,
Esc quit).
Dashboard: MCP panel grows a "marketplace" chip beside all/live/
unbridged. New endpoints: GET /mcp/registry, POST /mcp/registry/install.
Install writes the spec to config.json (same path as manual /mcp/specs
POST).
Cache file moves to ~/.reasonix/mcp-registry-cache.json with a
schemaVersion gate; older blobs are silently rejected and refetched.
MCP_REGISTRY_PAGE_LIMIT env var caps how far an eager load walks
(rarely needed since pagination is now on demand).
* feat(mcp): smithery detail-fetch — install Smithery-only entries
Smithery's listing endpoint omits install metadata, so previously any
Smithery-sourced entry surfaced a "not yet supported" hint. Now `mcp install`
(CLI + dashboard) lazily fetches `/servers/<qualifiedName>` detail and
maps the connection to a runnable spec:
http → remote streamable-http with deploymentUrl
stdio → npx -y @smithery/cli run <qualifiedName> (via new extraArgs
field on RegistryInstall, threaded through specStringFor)
Verified live: `exa` → `exa=streamable+https://exa.run.tools`,
`hugeicons/mcp-server` → `mcp-server=npx -y @smithery/cli run hugeicons/mcp-server`.
Both CLI and dashboard install paths share the same lazy-detail fall-
through. 6 new tests cover http/stdio mapping, 404 fallback, and
extraArgs spec generation.
* test(shell): SpyGate denies instead of approving — kills 5s flake
The "passes the correct kind to the gate" test only asserts what the
gate received; it doesn't care whether the command runs. The old
SpyGate returned `run_once`, so the dispatch went on to spawn `npm i`
in an empty tmp dir. On Windows under concurrent load (full suite +
antivirus + npm cold start) the spawn could exceed the 5s test
timeout, then the afterEach `rmSync` hit EPERM because npm still had
the dir open.
Switching the gate's response to `deny` short-circuits the dispatch
before any spawn. Test runs in ~50ms instead of 1-5s, and the EPERM
failure mode goes away. The assertion (kind + payload were forwarded
correctly) is unchanged.
* test(mcp): anchor mock-URL prefixes with trailing slash
CodeQL flagged `url.startsWith("https://registry.modelcontextprotocol.io")`
in the test's inline fetch mock — without a trailing `/`, an attacker-
controlled URL like `https://registry.modelcontextprotocol.io.evil/`
would also match. Not actually exploitable since the URL is generated
by our own fetcher (the test mock just routes calls), but the rule is
correct in principle and trivial to satisfy.
Adds the trailing slash to every mockFetch host key plus the inline
matcher. All 34 tests still pass.
* feat(mcp): /mcp browse slash + dashboard cards/uninstall + iconUrl
Three improvements driven by user feedback after the marketplace v1:
1. **/mcp browse slash command** — opens an Ink marketplace modal inside
the chat session. Type to filter, ↑↓ pick, Enter installs (or
uninstalls if already present), Tab loads 5 more pages, Esc closes.
No more "exit chat to run external `reasonix mcp` command" friction.
2. **Dashboard cards now show icons + installed-state badge**, and the
detail pane gets: full description (no truncation), runtime/transport
meta line + actual on-disk spec when installed, required-env card,
homepage link, and an explicit "restart required" hint. Lift iconUrl
out of the official registry's `icons[]` and Smithery's `iconUrl`.
3. **Uninstall button** — a marketplace entry whose spec already lives
in config.mcp[] swaps Install → Uninstall (calls existing DELETE
/mcp/specs). Detail pane carries the matching badge.
NOT in this PR: live hot-reload after install. `ctx.reloadMcp` was
declared but never wired in `chat.tsx`, so install/uninstall still
needs a `reasonix code` restart. Both UIs say so honestly. Real
hot-reload is a separate refactor.
* feat(mcp): hot-reload — install / uninstall now bridges live without restart
Closes the last gap in the marketplace flow: previously the user
installed an MCP server through the slash modal or dashboard, the spec
got written to config.json, and we had to tell them "restart `reasonix
code`". `ctx.reloadMcp` was declared on DashboardContext but never
wired in chat.tsx, so it was always undefined.
Refactor: chatCommand's inline MCP-init loop becomes an `McpRuntime`
object (createMcpRuntime in chat.tsx) with addSpec/removeSpec/
reloadFromConfig methods. The runtime owns:
- clients, summaries, registered-tool-names per spec
- hot-add path that calls loop.prefix.addTool for every newly
bridged tool
- hot-remove path that closes the client + unregisters tools +
calls loop.prefix.removeTool
New on the supporting types:
- ToolRegistry.unregister(name)
- ImmutablePrefix.removeTool(name) — same cache-miss cost as addTool
Wiring:
- chat.tsx passes runtime → Root → App → both modal/dashboard surfaces
- SlashContext gets a `reloadMcp` field (for future slash handlers)
- DashboardContext.reloadMcp is set by App.tsx
- /mcp browse modal calls reloadMcp after install/uninstall;
failure falls back to the old "restart required" message
- POST /mcp/registry/install and POST/DELETE /mcp/specs all call
ctx.reloadMcp() and surface bridged: true/false in the response
- Dashboard panel shows "installed + bridged → spec" when hot-reload
succeeded, falls back to plain "installed" otherwise
CLI `reasonix mcp install` still says "restart required" — it runs
in a separate process from any active chat session, so it can't reach
into a different process's runtime. The slash + dashboard surfaces
inside the same session do hot-reload.
* feat(mcp): unify /mcp into a single tabbed hub + cap dashboard list height
User feedback after the marketplace landed: the McpBrowser ("/mcp")
and the new McpMarketplace ("/mcp browse") felt like the same feature
because the visual style overlapped and the verb "browse" collided
with the existing component name "Browser".
Fix: wrap both in a single McpHub modal with two tabs.
- `/mcp` → opens the hub on Live (or Marketplace if no servers attached)
- `/mcp browse` (also `/mcp install`, `/mcp marketplace`) → opens on Marketplace
- Tab key cycles tabs; the previously Tab-bound load-more in
Marketplace moves to PgDn so the wrapper owns Tab cleanly
- Slash result loses openMcpBrowser/openMcpMarketplace; gains
openMcpHub: { tab: "live" | "marketplace" }
- Tests in tests/slash.test.ts updated to match the new shape
Dashboard list height: `.sessions-grid` had `min-height: 540px` but
no ceiling, so a long marketplace list pushed the right detail pane
off-screen. Adds `max-height: calc(100vh - 140px)` so the list scrolls
internally (`.ssl-rows` already has overflow-y: auto). Affects all
panels using the grid (sessions, mcp, etc.); same UX win for any
long left-column list.
* fix(mcp): /mcp opens hub even with native tools (code mode)
In `reasonix code` mode, `tools` is seeded with native filesystem /
shell / memory / plan / choice tools, so `loop.prefix.toolSpecs` is
never empty. My earlier guard required all three (servers + specs +
toolSpecs) to be empty before opening the hub on the marketplace tab,
which meant `/mcp` in code mode silently fell through to the printed
fallback text dump — exactly what the user reported.
Simplified: interactive `/mcp` always opens the hub. Live tab when at
least one server is bridged, Marketplace tab otherwise. The text dump
is only reachable via `/mcp text` (replay / non-TTY scenarios).
Tests: renamed two assertions to `/mcp text`, added a new case that
exercises the code-mode regression directly (mcpSpecs present but
servers empty → opens hub on marketplace).
* fix(dashboard): cap marketplace list height — was still scrolling the page
The previous attempt added `max-height: calc(100vh - 140px)` to the
grid container, but CSS Grid items default to `min-height: auto` (which
means "content size"), so the children — `.sessions-list` (with the long
registry list) and `.sessions-detail` — grew past the grid's max-height
and dragged `.app-body`'s overflow-y along, pushing the right detail
pane below the fold. Symptom user reported: "I scroll to the bottom
and the right detail pane is gone."
Fix is the standard CSS Grid + inner-overflow recipe:
- Add `grid-template-rows: minmax(0, 1fr)` so the row resolves to the
grid's available height (capped by max-height) rather than to
children's content size.
- Add `min-height: 0; min-width: 0` to both grid items so they
actually shrink to fit the track. With min-height: 0, their inner
`.ssl-rows { overflow-y: auto }` and `.sessions-detail { overflow:
auto }` rules finally take effect — list scrolls internally, detail
pane stays visible at all viewport sizes.
Affects every panel using `.sessions-grid` (sessions, mcp, …) — same
UX win for any long left-column list.
* fix(mcp): load-more button — distinct exhausted state + lift hardcoded caps
Two bugs the user reported in the dashboard marketplace:
1. Click "load more" → no visible response. Cause: dashboard sent
`limit=50` hardcoded, so even after the server walked more registry
pages the response was sliced to the same top 50. Fix: track
`displayLimit` in panel state, bump by 50 on each click, send as
query param.
2. Server-side hardcoded caps (`pages` / `maxPages` clamped to 50,
`limit` clamped to 200) hit a wall after a few clicks regardless
of cache depth. Lifted to 200 / 200 / 1000.
3. When the registry is genuinely exhausted, the old footer just
showed dim "all pages loaded" text — visually indistinguishable
from a disabled button, so the user thought clicks weren't
registering. New footer:
- active: primary button with "load 50 more · showing X / Y"
label so the count visibly grows after each click
- exhausted: distinct success-tinted card with ✓ marker
Side effect: `q`-search now also benefits from raised caps. With
matchTarget early-stop the server still returns fast even when caps
are higher.
* fix(server): asset cache uses mtime, not "once per process"
Caused real friction during dashboard development: change panels source,
run `npm run build`, refresh browser → still see old UI because the
running reasonix server cached `dashboard/dist/app.js` in memory at
first read and never re-reads. Required a full restart to pick up any
dashboard rebuild.
Switched to mtime-keyed cache: re-stat each request, re-read body if
mtime advanced. `dashboard/dist/app.js` is ~800KB so the stat-then-
hit-cache path is microseconds. The previous "ONE read per process"
optimisation was guarding against ~zero cost.
Show what the badge looks like before anyone has earned it, so
prospective advocates can see the target. Uses the for-the-badge
shields.io style in the project's lavender brand colour; metadata
badges at the top stay flat-square for information density.
Point active users at the Show and tell discussion category and
preview a forthcoming Reasonix Advocate badge for sustained advocates.
Word of mouth is the only growth channel for a zero-marketing-budget
project, so make the ask explicit.
* fix(shell): demote destructive flags on allowlisted commands (#257)
Allowlist matched on leading tokens only, so `git branch -D`,
`find -delete`, `git diff --output=...`, `npx eslint --fix`, etc.
flowed through without confirmation. Add a per-prefix RISKY_ARGS
table that demotes specific tail tokens back to the confirm gate;
both `--flag value` and `--flag=value` forms are caught. Chains
inherit via the existing per-segment isAllowed call.
* fix(shell): also demote tree -o and find -fprint0 (#257)
Follow-up audit caught two more write-anywhere paths on otherwise-
allowlisted inspection tools: `tree -o FILE` writes the tree output,
and `find -fprint0 FILE` writes NUL-separated paths. Same risk class
as the `git diff --output=` family already covered.
The /svg?type=Date endpoint was returning empty for this repo (likely
because the cumulative-by-day shape needs more data points). /chart with
type=timeline + logscale renders correctly from day one and reads better
when the y-axis range is small.
The post-stop/shutdown asserts were racing Windows taskkill /T tree
propagation, occasionally catching a transient `runningCount === 1`
right after the stop promise resolved. Poll up to 2s for the value to
settle to 0 — distinguishes "persistently wrong" (real bug) from
"momentary race during reap" (not a bug).
Add custom OG social card (1280×640), star-history chart in both READMEs,
FUNDING.yml so the Sponsor button shows up. Goal: when someone lands here
from a shared link or GitHub explore, the first impression and signal of
seriousness should be higher than a default-rendered repo page.
The marketing site had drifted from the project. Bring it back in line with
the post-0.26 README:
- Hero: drop "Ink TUI" / "No LangChain" / "DeepSeek V4" pin; replace the
three hardcoded-number stats (90.2% / ~98% / 100%) with qualitative tags
- Why Reasonix: reorganize the six cards as four architectural pillars
(matching ARCHITECTURE.md) plus two community/positioning cards
- In the box: expand from six to twelve capabilities, matching the README's
feature-grid.svg — adds plan mode, permissions, dashboard, sessions,
semantic search, auto-checkpoints, /effort, replay, event log
- Benchmarks: remove the hardcoded-numbers table; keep methodology + repro
command + link to the harness directory
- CLI: refresh command list and flags to current 0.26 surface
- New Community section with contrib.rocks wall + good-first-issue /
discussions / contributing links
- Footer: drop Changelog (we don't keep one), add Releases / Benchmarks /
Contributors links
i18n.js: rewrite both dicts; 118 keys × 2 with verified 1:1 parity. CSS:
new .community styles, .stat-num resized for qualitative tags, .feat-grid
responsive breakpoints expanded for the wider 12-card layout.
GitHub strips CSS from HTML tables, so the previous <table>-based pillar
and capability sections rendered as plain rows. Move both to custom SVG
assets that match the existing hero-terminal.svg design language —
dark cards (#0a0c10), gradient icons (teal/blue/purple), Inter + JetBrains
Mono typography.
- pillars.svg / pillars.zh-CN.svg: new 2x2 grid of the four architectural
pillars from ARCHITECTURE.md, with deep-link anchors below
- feature-grid.svg / feature-grid.zh-CN.svg: rewritten as a 3x4 grid of
twelve concrete capabilities (was 6 cards with hardcoded "94% live cache
hit" copy that violated the no-hardcoded-numbers rule)
README drops the HTML <table> markup, halving its line count.
\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.
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.
/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.
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`).
- 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]>
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.
- 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]>
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.
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.
* 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
`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`).
* 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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%".
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.
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.
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.
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.
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.
Marked v12's tokenizer ran inline text through HTML escape (& → &,
< → <, " → "), 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 (`<`) and clipped
content past the wrap edge.
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.
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).
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.
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).
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).
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]>
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.
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.).
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.
* 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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
- 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]>
* 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.
* 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.
* 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.
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.
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.
* 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.
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.
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.
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.
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.
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]>
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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
#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.
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.
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.
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
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
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).
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.
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.
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]>
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).
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.
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.
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.
@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.
* 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.
* 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.
* 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.
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.
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.
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.
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.
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.
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.
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.
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.
Stage C2a of #105.
Per-server ring-buffered latency tracker; emits a one-line warn
toast (design §32) on p95 threshold cross. Idempotent within a
"slow window" — fires once when p95 transitions over the
threshold, again only after p95 dips below and crosses back.
Touch:
- New `src/mcp/latency.ts` — `LatencyTracker` with size-5 ring
buffer + p95 helper. Tracks `wasOverThreshold` boolean so
emission is gated on the transition, not on every over-cap call.
- `src/mcp/registry.ts` — `BridgeOptions` gains `serverName`,
`slowThresholdMs`, `onSlow`. The bridged tool's `fn` records
per-call elapsed time when a tracker is configured. Default
threshold 4000ms.
- New `src/cli/ui/mcp-toast.ts` exporting `formatMcpSlowToast`
that prints `⚠ MCP `<name>` slow · 8.4s p95 over the last 5
calls` per design §32.
- `src/cli/commands/chat.tsx` + `src/cli/commands/run.ts` — wire
`serverName` and `onSlow` callback so the warn line lands on
stderr.
- `tests/mcp-latency.test.ts` — 9 cases covering buffer fill
threshold, single-fire on cross, re-fire after dip-and-cross,
default threshold, p95 math edges, and toast formatting.
Stage C2b (`/mcp reconnect <name>` with cache-prefix invariant
handling) is split out into a separate RFC — the live tool-list
swap raises a non-trivial design question (what if the
reconnected server's tool surface changed? cache prefix breaks).
Closes part of #105.
Stage C1 of #105 (Stage C split into C1 = persistence side here, C2
= live reconnect + slow toast next).
Add a config-persisted disable list and the corresponding `○ disabled`
lifecycle line so users can keep a flaky server in their config but
skip it on launch.
Touch:
- `src/config.ts` — new `mcpDisabled?: string[]` on ReasonixConfig.
Backwards-compatible: existing configs ignore it.
- `src/cli/ui/mcp-lifecycle.ts` — `disabled` state added to the
formatter, prints `○ disabled via /mcp disable <name>`.
- `src/cli/commands/chat.tsx` + `src/cli/commands/run.ts` — read the
disabled set on startup; skip the bridge for matching named
servers and emit the `disabled` lifecycle line in their place.
Anonymous servers (no `name=`) are not toggleable, by design.
- `src/cli/ui/slash/handlers/mcp.ts` — first-arg dispatch:
- `disable <name>` writes the name into `mcpDisabled`, idempotent
- `enable <name>` removes from the array; deletes the field
entirely when the last entry clears (keeps configs tidy)
- `text` / no-arg paths unchanged
Unknown names produce a "Known: …" hint listing the valid set
(joined from live mcpServers labels + parsed config specs).
- `tests/mcp-lifecycle.test.ts` — disabled-state snapshot
- `tests/slash.test.ts` — six cases: persistence, idempotent
disable, enable that empties the array, enable that clears the
field, unknown-name rejection, missing-arg usage line. All
isolated through `HOME=tmp` per the existing pattern.
Stage C2 (next PR): `/mcp reconnect <name>` (live teardown +
re-handshake), p95 latency tracker, slow-server warn toast.
Closes part of #105.
Stage B of #105.
Replace the `/mcp` text-dump with a keyboard-driven modal matching
`docs/design/agent-tui-terminal.html` §24. The text-dump path is kept
as `/mcp text` for non-TTY / replay contexts.
Modal shape per design:
◈ MCP browser · ~/.reasonix/config.json · 4 servers
▸ notion ● healthy · 142ms 12 tools · 8 resources · 0 prompts
tools/list tools/call resources/list prompts/list
linear ◌ slow · 4.2s 7 tools · 3 resources · 0 prompts
...
↑↓ pick · [r] reconnect (Stage C) · [d] disable (Stage C) · esc quit
Touch:
- New `src/cli/ui/McpBrowser.tsx` — the modal component, manual row
rendering (not Select.tsx) so we can put the per-row health badge
in the right color and show a second-row capability list under
the active server.
- `src/cli/ui/slash/types.ts` — add `openMcpBrowser?: boolean` to
the SlashResult union, mirroring `openSessionsPicker`.
- `src/cli/ui/slash/handlers/mcp.ts` — return `{ openMcpBrowser: true }`
in the rich-data path; `/mcp text` keeps the printed-card output.
- `src/cli/ui/App.tsx` — `pendingMcpBrowser` state, modal slot in the
render tree, gates added to the eight conditional chains that
already suppress prompt input while a modal is open.
- `tests/slash.test.ts` — split the existing `/mcp` test into one
case asserting the modal flag fires and one asserting `/mcp text`
still prints the card view.
Stage C will activate the `r` and `d` keybinds (currently labelled
"Stage C" in the footer).
Closes part of #105.
* feat(readme): hero terminal SVG matches design-doc aesthetic
Replace the plaintext code-fence demo of `reasonix code` with a
self-contained SVG that mirrors the design-doc terminal mockup
(`design/agent-tui-terminal.html`) and the website palette: dark
chrome, traffic-light dots, JetBrains Mono, ANSI-style color
roles (cyan prompt, purple `assistant`, amber path, coral SEARCH,
green REPLACE).
Bilingual: a separate zh-CN variant carries the Chinese user
message and the localized pending-edit footer.
* fix(readme): hero terminal shows unified diff, not raw SEARCH/REPLACE
The previous SVG painted the model's raw `<<<<<<< SEARCH` / `=======` /
`>>>>>>> REPLACE` markers, but those are an internal protocol — the TUI
actually renders pending edits via `formatPendingPreview` from
`src/cli/ui/edit-history.ts`, which produces a unified diff with `-`/`+`
prefixed lines and a `path (-N +M lines)` file header.
Match that format faithfully; shrink the canvas to 880x360 since the
diff is more compact than the marker block was.
* docs(readme): tighten prose, replace feature wall with SVG grid
Two new design-token SVGs continue the hero-terminal aesthetic so the
README has consistent visual rhythm instead of a wall of `### heading`
subsections.
- Add `docs/hero-stats.svg` (+ zh): three gradient numbers (94% live
cache hit · ~30× cheaper / task · MIT) below the hero tagline.
- Add `docs/feature-grid.svg` (+ zh): 6-card 3x2 grid replacing the
eight `###` subsections that ran 25+ lines of wall text.
Prose cleanup:
- Drop the `--system-append` subsection; it's documented in
`reasonix code --help`, doesn't belong in the hero quickstart.
- Drop the "Edits stay in memory..." line redundant with the
terminal SVG that already shows the /apply gate.
- Drop the stale "1665 tests" count from the contributor snippet —
the number drifts; "tests" alone is enough.
Net: 175 → 132 lines per README, four anchored visual blocks
(logo · stats · terminal · features).
* docs: publish design mockups under docs/design/ so links render
The README points at the dashboard and TUI design mockups, but the
links resolved to repo paths — GitHub serves `.html` files in repos
as syntax-highlighted source, never as a rendered page. Anyone
clicking through hit a wall of HTML instead of the intended preview.
Move the two mockups into `docs/design/` (already published via
GitHub Pages) and switch the README links to absolute
`https://esengine.github.io/reasonix/design/...` URLs. Now click-
throughs land on the rendered mockup, and the links work the same
on github.com, on the npm registry, and anywhere else the README
gets reposted.
`dashboard/app.css`'s "anchored to ..." comment updated to track
the new location.
* docs(readme): trim comparison table to differentiating rows only
Drop the 7 universally-yes rows (plan mode, edit review, MCP, skills,
hooks, sandbox, surface) and keep the 6 where Reasonix is actually
different from peers: backend, cost, license, cache-hit %, dashboard,
sessions.
Add a one-line note pointing at the feature grid for the rest, so the
information isn't lost — just reordered into the section that's
already explaining each feature in detail.
* docs(readme): unify hero block to a single centered column
Designer-pass cleanup. The hero used to fracture between centered
(logo, tagline, lang) and left-aligned (H1, badges, description),
making the eye jump as it scanned downward.
- Drop the redundant `# Reasonix` H1 — the wordmark in `logo.svg`
already says it; the H1 was duplication, not hierarchy. Astro,
Bun, Tailwind and similar polished READMEs do logo OR title,
not both.
- Drop the `<em>` tagline; the description paragraph below
conveyed 90% the same info more concretely. Pick one, not two.
- Center the badges and the description paragraph inside
`<p align="center">` so logo → langs → badges → description →
stats SVG all share one vertical axis.
- Quick start: drop the "First run: paste a key…" paragraph
(the wizard prompts the user when they run it; pre-explaining
was reading-overhead). Compact note inline as a `# comment`
on the `npx reasonix code` line, plus an API-key link in the
trailing requirements line.
- Contributing: drop the trailing `git clone … npm install …`
snippet that duplicated CONTRIBUTING.md's setup section. The
link above already says "read CONTRIBUTING.md" — trust it.
Net: 132 → 115 lines per README. Hero feels like one block.
* docs: drop "free credit on signup" — DeepSeek no longer offers it
Three places referenced free signup credit:
- README.md / README.zh-CN.md "Non-goals" bullet — rephrased as
"needs a paid DeepSeek API key" so the air-gapped redirect to
Aider+Ollama / Continue still makes sense
- docs/index.html + docs/i18n.js Quick start step 1 — "Sign up at
... and create a key" / "到 ... 注册并创建 Key"
- src/cli/ui/Setup.tsx + src/cli/ui/Wizard.tsx — drop "free credit
on signup" hints from the key-paste prompt
* docs: contributor avatars, more badges, COC + SECURITY
README polish bundle:
- Add 2 badges: GitHub stars + Discussions count. Brings the row
from 5 → 7 (still under the badge-spam threshold).
- Add a contrib.rocks contributor-avatar grid at the bottom of the
Contributing section. Auto-updates from `git log` — no bot, no
config file. Single `<img>`, fresh forever.
- Reference Code of Conduct + SECURITY.md from the Contributing
blurb so first-time PR authors land on the right pages.
Project hygiene files:
- `CODE_OF_CONDUCT.md` — Contributor Covenant 2.1, fetched
verbatim from the canonical EthicalSource repo, with the
`[INSERT CONTACT METHOD]` placeholder filled in. GitHub's
Insights → Community will now show the green check, and the
repo nameplate gains a "Code of Conduct" link.
- `SECURITY.md` — private-disclosure policy, scope (in: package,
dashboard, sandbox; out: third-party MCP servers, upstream
Node, the user's own key handling), supported-versions note,
and hardening reminders for users.
- `CONTRIBUTING.md` "Reporting security issues" reduced to a
one-line pointer at SECURITY.md, eliminating the duplicate
email address.
* docs: move README image assets into docs/assets/
The `docs/` directory was a mixed bag: GitHub Pages site source
(index.html, styles.css, i18n.js, term-anim.js, logo.svg, favicon.svg),
documentation pages (ARCHITECTURE.md), README image assets (six
hero / feature-grid / stats SVGs at root), and design mockups
(design/). Six SVGs cluttering the listing made it hard to tell
website-source from README-only-fixtures at a glance.
Move the README-only SVGs into `docs/assets/`:
- hero-stats.svg + .zh-CN.svg
- hero-terminal.svg + .zh-CN.svg
- feature-grid.svg + .zh-CN.svg
Update all 6 image references in README.md and README.zh-CN.md.
`logo.svg` stays at `docs/` root because it's used by both the
website (`docs/index.html` includes it) and the README — it's
genuinely a top-level brand asset, not an asset-folder fixture.
The hardcoded list (#15-#18) drifted: #18 closed but stayed listed, and
every closed ticket required a manual README edit. Point at the label
filter URL instead — always fresh, zero maintenance.
The line that already existed at the bottom ("Browse all good first
issue") was the better signal anyway; just promoted it.
* fix(mcp): allow hyphens in MCP spec name prefix regex
The NAME_PREFIX regex excluded hyphens, so kebab-case server names like sage-wiki failed the prefix match. The entire string (including the =) was treated as a raw command path. One character added to the character class.
* test(mcp): cover kebab-case names in parseMcpSpec
---------
Co-authored-by: Charles H <[email protected]>
Co-authored-by: esengine <[email protected]>
Node 20 reached end-of-life on 2026-04-30. The CI matrix kept it green
for users on the prior LTS; with EOL passed, the verification cost is
no longer paying back.
- engines.node: ">=20.10" -> ">=22"
- CI matrix: ["20", "22"] -> ["22"]
- tsup target: node20 -> node22
- README / README.zh-CN / CONTRIBUTING / REASONIX / docs: Node >= 22
reasonix code now reads the mcp array from ~/.reasonix/config.json and passes it to chatCommand, which parses each spec and bridges the MCP server tools into the session. Previously only reasonix chat read config.mcp — reasonix code silently ignored it.
Co-authored-by: Charles H <[email protected]>
Three coupled changes:
- CONTRIBUTING.md: replace 'update CHANGELOG.md under [Unreleased]'
with 'don't touch CHANGELOG.md'. Releasing section now says the
maintainer writes the notes from git log at release time.
- PULL_REQUEST_TEMPLATE.md: replace the 'CHANGELOG updated' checkbox
with the inverse — 'no edits to CHANGELOG.md'.
- CHANGELOG.md: drop the lingering [Unreleased] section. The
--system-append feature it described will land in the next
versioned section, written by the maintainer.
Why: PR-time CHANGELOG entries had two failure modes — they piled up
in [Unreleased] when releases didn't roll them forward, and they
created soft conflicts between concurrent PRs. PR descriptions are
the authoritative record while work is in flight; release notes are
better written once with full context than in pieces during review.
Locks the npm package's exported names to a recorded snapshot. When src/index.ts
gains or loses an export, this test fails with a clean diff and the maintainer
explicitly updates PUBLIC_API in the test file. Catches accidental ABI breakage
before a release ships.
Snapshot derived from the current 263-name surface. Future intentional changes
land via the same PR that touches src/index.ts: see test failure → update
PUBLIC_API → review the diff → merge.
The comment-policy gate previously only walked src/. Tests, benchmarks,
scripts, and dashboard/src were left to convention — which meant that
multi-paragraph module-essay headers and stale phase-narrative comments
silently accumulated. Expand the test's roots to cover every code dir,
clean the 146 violations that surfaced, and gate them at pre-push.
The new tests/architecture-invariants.test.ts promotes two properties
from spike #87 (Exp 1) into permanent regression:
- reducer projection determinism (identical events → byte-identical
messages, regardless of timestamp / id / counter state)
- message-level append-only across turn boundaries (every cut is a
strict prefix of any later cut)
These are the load-bearing properties for the v0.14 event kernel and the
forkable-sessions RFC. Encoding them as tests means any reducer / event
schema change that violates them fails CI, not a future spike.
No behavior change in src/. Comment-policy expansion + invariants test
add about 18 new test assertions; full verify is unchanged at ~23s.
Followup to #86. The ▲ prefix has no precedent in other stderr writes
(run.ts / commit.ts / index.ts use plain text), and the empty-catch
note restates what the empty body already conveys.
Add two CLI options to reasonix code that let users layer personal workflow rules on top of the default Reasonix Code system prompt without replacing or weakening it.
--system-append <prompt> inline string appended after the base prompt
--system-append-file <path> UTF-8 file contents appended after the base prompt
Both may be used together. Inline text appears first, then file contents. Both are placed after the .gitignore section under a # User System Append heading. File read errors surface with the OS error code and exit cleanly.
Tests cover: absent by default, inline-only, file-only, combined ordering, placement relative to .gitignore, and base prompt preservation.
Co-authored-by: Charles H <[email protected]>
The Excludes section had its own ad-hoc layout with a toggle expander,
"excludes-card" / "excludes-grid" / "excludes-options" / "excludes-actions"
classes — none of which were in the design.
Restyled to match design §12's `index config` card:
- `.card` + `.card-h` with title and reset link in the header
- `.form-row` per category (lbl above, chip row below)
- Optional sub-label (e.g. "· glob") rendered dim
- `.checkbox-row` with `.box.on ✓` instead of native checkbox for gitignore
- `.input.mono` for max bytes; help text shows MiB equivalent
- `.btn.ghost` Preview + `.btn.primary` Save side-by-side, flex:1 each
Always visible — drops the toggle so the config is discoverable.
ChipExcludesField → ChipFormRow with the new design markup.
Server: /api/semantic GET now returns index meta when an index
exists — chunks, files (distinct paths), dim, sizeBytes, lastBuiltMs,
model. Reads index.meta.json + index.jsonl from .reasonix/semantic/.
UI: restructured the panel to design §12's 2-col layout:
- Left: chips + search section + ollama setup cards (when not ready) + job view
- Right (280px sidebar): "index status" card with the new rail-kv stack
+ Re-index/Rebuild/Stop buttons inline; "ollama" card with binary/daemon/model
pills; existing "Excludes" card
Setup checklist (install / daemon / model pull) restyled as proper
.card blocks with .card-h headers instead of ad-hoc sections.
Closes#82.
Adds the floating popover from design §4 above the chat composer.
- **Slash popover** — fires when input matches `^/(\w*)$`. Filters
the SLASH_COMMANDS catalog (fetched once via new GET /api/slash)
by prefix, shows name + summary per row. Tab inserts; Enter
inserts and submits. ↑/↓ navigate, Esc closes.
- **@ mention popover** — fires when input ends with `(?:^|\s)@(\S*)$`
in attached mode. New POST /api/files walks cwd up to depth 4,
caps at 50 results, skips node_modules / .git / common binary
extensions. Tab inserts the relative path; Esc closes.
The popover degrades to no-op when slash commands fail to load or
in standalone mode (no cwd).
Closes#81.
- Skills: + create button could be pushed off-screen because the new-name
input had default min-width:auto. Added min-width:0 + flex-wrap so the
controls stack at narrow widths instead of clipping.
- Sessions: detail header only had a "back" button — no way to actually
resume a session from the dashboard. Added a copy-friendly card that
shows the `reasonix chat --session <name>` command, matching how /resume
surfaces it in the TUI (mid-session swap needs a restart).
Adds the search functionality from design §12. Renders a search
input above the existing index admin sections (only when an index
is built). On Enter, POST /api/semantic/search → result cards with
path, line range, cosine score, snippet (capped at 8 lines).
Server-side: new POST /api/semantic/search endpoint reuses the
existing querySemantic() entry. Validates topK (1..16) + minScore
(0..1). Returns 503 in standalone mode, 404 when no index exists.
Closes#78.
User-reported bugs:
- Builtin skills (explore / research) were marked cursor:default with
no click handler — clicking did nothing. Now opens a read-only
detail card with description + a hint that custom skills override.
- MCP unbridged config rows were also non-clickable, and the row
preview showed the raw spec ("filesystem=npx -y @modelcontextprotocol/...")
with no explanation. Now: rows show parsed `<label>` + `<command>`,
click opens an explanation card noting that MCP attaches on
reasonix-code start (the dashboard alone can't spawn the child).
Replaces the textarea-per-category excludes UI with the design's
chip editor — each entry renders as .chip-f with × delete, a
dashed-border input handles + add (Enter or blur to commit, dedupes
existing entries).
Drops the newline-serialize / line-split conversion in favor of
native arrays end-to-end (toDraft / fromDraft now identity-pass).
Closes#69.
Adds the "runs" column from the design's inventories pattern. Counts
subagent rows in the cross-session usage log filtered to last 7 days,
keys by `subagent.skillName`. Surfaces as `runs7d: number` per skill
on /api/skills, rendered in the skill list row meta only when > 0.
Closes part of #69.
Surfaces the design's "Recent runs" section at the bottom of the
Hooks panel. Reads `hook.fired` events from up to 8 most-recent
session events.jsonl files, returns the 12 newest with phase /
outcome / hook name / when. Renders as a compact table with
ok/warn/err pill per row.
Refactored `recentEventFiles` out of cockpit-events.ts into
`adapters/event-source-jsonl.ts` for shared use across cockpit
+ hooks aggregators.
Closes part of #69.
Adds all / live / unbridged filter chips to the MCP panel header.
Live = bridged into the session, unbridged = in config but not yet
loaded. The chips drive a single setState filter that toggles which
groups render in the list.
(Errored / uptime tracking from the design left for later — needs
new server-side state.)
Closes part of #69.
Adds the third rail card from design §4 — Active plan. Reads
cockpit.recentPlans (already shipping on /api/overview), picks the
most recent plan with status === 'active', renders a step-dot
header (1 → N) plus title + progress count. Hides when no plan
is active.
Closes part of #69.
* feat(dashboard): chat side rail — Session + Tool budget (Stage 2a of #69)
Wraps the chat composer + feed in a `.chat-body` grid with a 280px
right column for the design's chat-rail card stack. Two cards in v1:
- **Session** — turns, last-turn prompt tokens, total cost, cache
hit ratio progress bar (tinted ok / warn by threshold). Reads
from the existing `stats` poll.
- **Tool budget** — only renders when `loop.budgetUsd` is set;
shows spent / cap as a single progress bar that turns warn at
80%, err at 100%. Surfaced `budgetUsd` on `/api/overview`.
Active plan card + slash command popover follow in 2b.
Closes part of #69.
* chore: drop unrelated RFC #25 spike draft accidentally committed
`.app { height: 640px }` was a leftover from the design mockup's
fixed-height display box. At runtime it caused a page-level
scrollbar on viewports below 640px and dead space above. Switch
to `100vh` so the dashboard fills the viewport.
`.chat-shell` height was wrong by the chrome chrome — it was
`100vh - 56px` instead of subtracting the actual top (44) +
status (26) + body padding (24×2). Pin the math precisely so the
composer stays in view and only `.chat-feed` scrolls.
Add `min-height: 0` to `.chat-feed` for the flex shrink-to-zero
gotcha — without it `flex: 1` can't actually shrink to allow
internal overflow:auto to take effect.
Adds the events-derived half of the design §5 cockpit:
toolCalls·24h with prior-window delta, recentPlans (4 most recent
with completion ratio + done/active status), toolActivity (6 most
recent tool calls with ok/warn/err level).
Reads up to 8 most-recently-modified `*.events.jsonl` files from
the sessions dir, skips files whose mtime is older than 30 days.
Plugs into the existing 30s TTL cache shared with Stage 1A.
Adds `sessionsDir?` to DashboardContext so tests can isolate from
the user's real `~/.reasonix/sessions`.
Closes part of #64.
The catch-all `button:not(.primary):not(.danger):not(.btn)` rule had
specificity (0,3,1) — higher than `.mode-btn.active` (0,2,0) — so
the active sky-blue background was getting overridden by the generic
fallback's bg-elev-2. Result: every mode button looked identical
regardless of which was selected. Excluded the panel-specific button
classes from the catch-all instead of bumping selectors everywhere.
Also added a thin themed scrollbar so dark-mode panels don't fall
back to the default OS chrome.
Adds the usage-log derived half of the design §5 cockpit:
balance, tokens·7d (with prior-week deltaPct), cache hit·7d (deltaPp),
14-day cost sparkline, current-session detail. Hot fields refresh
per-poll; warm (disk-read) fields are 30s-cached behind a TTL keyed
on usageLogPath so the 2.5s overview poll doesn't burn disk I/O.
Stage 1B (events.jsonl-derived: toolCalls·24h, recentPlans, toolActivity)
lands in a follow-up. Stage 2 wires the UI rows.
Closes part of #64.
Closes the budget loop with /budget. Bare /cost still shows the last
turn's spend. With text args, tokenize the prospective prompt
(system + tools + log + msg), price it both worst-case (full miss)
and likely (apply session's running cache-hit ratio), and surface
output cost using the session's average completion length.
Type the last bulk-migration escape hatch — useState generics,
api<T> calls, modal/event/setting handler signatures, helper props.
Also strip multi-paragraph essay comments per CLAUDE.md (default
is none, one line max if WHY is non-obvious).
Adds the design §13 event matrix above the JSON editors.
Flattens hooks from `{ event: [{ command, matcher? }] }` into per-script
rows; cells render '✓' (or matcher glob in warning color) when the
script fires for that event, '—' otherwise.
Each row is keyed by (scope, command) so the same script in project
+ global show as separate rows with a small scope tag.
Implementation:
- buildMatrix(data) helper produces the 2D grid from the nested
hook config.
- Inline grid-template-columns string scales with the event count
(220px label + N event columns).
- Reuses the design's .matrix / .row / .cell.on/.off styles from
app.css.
JSON editors below remain the source of truth for editing —
matrix is read-only at this point. Click-to-edit cells (design §13
mentions it) is a follow-up.
The PR #44 Foundation replaced app.css wholesale with the design
mockup's <style>. That dropped ~1100 lines of chat-specific CSS
(chat-shell / chat-feed / chat-msg / mode-picker / composer /
modal-card / toast / tool-card / markdown blocks) which Chat,
Sessions, modal popups, and toast/error overlays all depend on.
This PR:
- Restores the chat-related CSS sections from pre-foundation
app.css as a 'Chat-panel legacy CSS' block at the tail of
app.css (~1100 LoC).
- Remaps all old token references inside that block to design
tokens: --primary → --c-brand, --bg-2 → --bg-elev-2, --mono →
--font-mono, --border → --bd, etc. So the visual still aligns
with the design palette, just keeps the working selectors.
- Migrates the Chat panel's outer header from .panel-header /
.panel-title to a small .chips badge.
What's deferred:
- Deep restyle of chat-feed / chat-msg / composer to match the
design's §4 Chat mockup pixel-for-pixel. Currently functional
with the same look as before the foundation flip, just retoned.
- Drop the @ts-nocheck pragma on chat.ts (700 LoC of useState +
SSE handler typing). Tracked as a follow-up.
Light migration: textarea editors stay (matrix UI from design §13
needs more than the current API exposes — script-level editing,
glob filters, per-event toggles). What changes:
- Header chips show resolved count + each event name as separate chips
- Section h3 helper consistent with Settings/Semantic
- Cards wrap each scope's textarea (project / global)
- .btn / .btn.primary / .btn.ghost replace legacy primary buttons
- Info / error use .pill ok / .card.accent-err
Deferred: full event matrix UI (script × LoopEvent grid, click-to-edit
cells). Tracked as a follow-up.
- Pill modifiers swap to design tokens: pill-ok/warn/err/active/dim
→ pill ok / warn / err / info / pill (no modifier).
- Header becomes .chips with index status + ready/setup-needed
badge.
- Section headers use the inline h3 sectionH3 helper (font-mono
uppercase + spacing) consistent with Settings/System.
- Loading / error / not-attached states use .card / .card.accent-err
/ .card-h structure instead of legacy .boot/.notice/.empty.
- .muted spans replaced with inline color:var(--fg-3).
- Adds .kv-key to legacy panel utilities to keep the existing
kv block rendering until the deeper Semantic redesign (sidebar
index status + index-config card per design §12) lands.
- Header chips replace panel-header — record count + log size.
- Chart sits in a .card with .card-h title.
- Tables get .tbl class, td.num for numeric cells, td.dim for the
bucket-label column. Headers no longer use legacy 'numeric' class
(drops the right-align since .tbl handles it via .num).
.sessions-grid layout. Left list shows live-bridged servers + any
config-only specs (with inline remove button) merged into one
.ssl-rows feed. Add-spec form sits in the list head. Detail view
on the right has spec card + optional instructions + tools /
resources / prompts tables.
Form-based panel — three .card sections (DeepSeek API / Defaults /
Runtime), each with rows: 110px label gutter + control + optional
right-aligned note. Uses .btn / .btn.primary plus design's input /
select tokens. Saved feedback shown as a .pill.ok.
.sessions-grid layout. Filter input + scope chips + create form
in the left list head. Builtin items render with cursor:default
since they're read-only. Editor on the right with save / delete /
back actions.
Same .sessions-grid pattern: file list on the left (project REASONIX.md
+ global + project-private all merged into one .ssl-rows feed with
scope tag in meta), editor on the right with .sessions-detail-h
title bar + Save button + char count.
Same .sessions-grid pattern as Plans (#48). Filter input + .ssl-row
list on the left, transcript detail on the right with .sessions-detail-h
title bar and back button.
Adopts the design's two-column .sessions-grid layout:
- Left: .sessions-list with filter input, status chips, .ssl-row
per plan (name + status pill + preview + meta).
- Right: .sessions-detail with title bar + horizontal
.plan-timeline / .plan-step cards (done / active / pending
variants).
Plus a filter input that searches session id and summary.
- chips show project / builtin counts
- add prefix moves into a .card with title + meta + form row
- feedback rendered as a .pill (ok / err / warn) instead of a notice
- project allowlist becomes a .tbl inside .card
- builtin section becomes a .card with grouped verb pills
- YOLO banner becomes a .card.accent-warn
No behavior change — all CRUD paths preserved.
Replaces the metric-grid + .card paths layout with the design's
.health-grid + .health-item pattern. Each health check is a
labeled card with state pill + value + meta line. The paths card
becomes a .card with a .tbl inside.
Skipped from the design mockup (need new data sources):
- Per-MCP-server / API health checks (need /api/mcp + ping data)
- Environment table (process.platform / node version / terminal)
- log-tail event stream (would need SSE)
Tools panel migrated to the design's class structure:
- .chips + .chip-f filter row (just `all` for now — category filtering
is a follow-up that needs new API fields).
- .tbl inside a .card for the tools table; pill.ok / pill.acc /
pill (default) for the read-only / write / flat flags.
- card.accent-warn / card.accent-err for error states; .card with
muted fg for loading / empty.
The 13 panels that haven't been migrated yet still reference
class names from the old CSS that no longer exist (.panel-header,
.empty, .notice, .pill-ok, .metric-grid, etc.). Added a `Legacy
panel utilities` block at the tail of app.css mapping them to
design tokens so those panels keep rendering passably until each
gets its own design-aligned migration. Block gets removed in the
final cleanup PR.
PR 1 of the visual catch-up. Replaces dashboard/app.css wholesale
with the design mockup's CSS (extracted verbatim from the <style>
block in design/agent-dashboard.html), and rewrites the App
component's sidebar/shell HTML to use the new class structure.
What changes visually:
- Sidebar adopts the design's three-section grouping (workspace /
observe / configure) with the new .app-side / .side-tab markup,
proper glyph + label slots, brand block with version badge.
- Top bar (.app-top) and status bar (.app-status) frames added —
empty placeholders for now; will fill with breadcrumbs / live
meters in panel migrations.
- Whole layout grids on .app (sidebar | top / body / status).
What stays broken (intentionally, per the migration plan):
- Each panel's interior still uses the old class names. Until the
per-panel migration PRs land, panel content will look unstyled
inside the new shell. That's the visible cost of doing this in
reviewable chunks instead of one giant PR.
Token rename map (current → design):
--primary, --accent, --grad-1..8 → --c-brand, --c-accent,
--s1..6, --fg-0..4, --bg / --bg-elev / --bg-elev-2 / --bg-input
/ --bg-code / --bg-hover, --bd / --bd-strong.
Live-mode override at the tail of app.css forces .app to fill
viewport (the mockup constrains it to a 640px tile inside the
docs page).
Build / typecheck / 1682 tests still green.
PR #39 (Chat migration) extracted ChatPanel into panels/chat.ts
with a `@ts-nocheck` pragma. Four references the original
function had via global lexical scope in app.js were silently
missed at extraction time:
- MODE — used in the placeholder text at line 448
- TOKEN — used to build the SSE EventSource URL at line 126
- appBus — used in a navigate-tab dispatch at line 545
- parseToolArgs — used in summarizeActiveTool at line 641
@ts-nocheck masked all four ("cannot find name" errors are
suppressed by the pragma), and tests don't load the bundled
dashboard, so it shipped. The runtime symptom is the error
overlay reproduced in the user's bug report:
ReferenceError: MODE is not defined
at ChatPanel ...
Restored as named imports from `../lib/api.js`, `../lib/bus.js`,
and `../components/chat-internals.js`. parseToolArgs was
previously a private helper inside chat-internals.ts; promoted
to a named export so panels/chat.ts can reach it.
Verified by temporarily removing the @ts-nocheck and running
typecheck — zero "Cannot find name" errors after this fix.
1682 tests still pass.
Removes `@ts-nocheck` from `dashboard/src/components/chat-internals.ts`
(541 → 692 LoC after annotations). Adds:
- ChatRole / ChatMsg / OnResolve types exported for re-use.
- Per-modal payload interfaces (ShellModalSpec, ChoiceModalSpec,
PlanModalSpec, EditReviewSpec, WorkspaceSpec, CheckpointSpec,
RevisionSpec, plus ChoiceOption / RevisionStep) — every modal's
props now have proper shape.
- DiffEntry / DiffPair for the LCS diff helpers; lineDiff and
pairDiffRows now strict-typed end to end (noUncheckedIndexedAccess
satisfied without `any`).
- ToolCard's `args` narrows from `Record<string, unknown> | null`
via runtime `typeof` guards; the few cross-cuts where TS can't
follow the narrowing use `as string` casts on already-validated
fields.
`panels/chat.ts` keeps its `@ts-nocheck` for now — ChatPanel is
700+ LoC of interleaved useState / SSE handlers / refs, type
tightening tracked as a follow-up in #28. Annotated the pragma
with a one-liner so readers know it's intentional and where it's
tracked.
Build / typecheck / 1682 tests still green.
Stage 2 (#31) removed the dashboard's editor surface — the
CodeMirror integration that was its only consumer. The 20
@codemirror/* packages have been dead weight in package-lock
since then.
Removed:
@codemirror/autocomplete, commands, language, search, state,
theme-one-dark, view, plus 13 lang-* grammars.
Build / typecheck / 1682 tests still green.
Until now the dashboard's runtime imports pointed at esm.sh URLs
(preact, htm, marked, highlight.js, uplot). Tsup kept them
external so the browser fetched them on every cold load. Three
real risks:
- esm.sh outage / route change → dashboard breaks.
- CSP-locked environments → dashboard can't load at all.
- First-paint latency on flaky networks.
Bundle everything locally instead. tsup already exists; this is
just removing the external escape hatch.
Changes:
- All `https://esm.sh/<pkg>@<ver>` imports across `dashboard/`
(19 files, .ts/.tsx/.js) become bare specifiers (`preact`,
`preact/hooks`, `htm`, `marked`, `highlight.js/lib/common`,
`uplot`).
- `dashboard/src/types.d.ts` deleted — the URL module shims it
contained are no longer needed; TS resolves bare specifiers
against the npm packages directly.
- tsup config: drop `external: [/^https:\/\//]`, set
`noExternal: [/.*/]` and `splitting: false`. Result is a
single self-contained `dashboard/dist/app.js` (696 KB —
was 123 KB at runtime + ~3 MB live-fetched from esm.sh).
- `dashboard/index.html` references local `/assets/vendor-uplot.css`
and `/assets/vendor-hljs.css` (was esm.sh URLs).
- `scripts/copy-dashboard-vendor-css.mjs` (new) copies those two
CSS files from `node_modules/{uplot,highlight.js}/...` into
`dashboard/dist/` after each build.
- `package.json` `build` chains the copy step.
- `src/server/assets.ts` adds a vendor-CSS branch so the asset
server can serve `/assets/vendor-{hljs,uplot}.css` from
`dashboard/dist/`.
- `uplot` added to devDependencies.
Bundle output verified: zero `esm.sh` references in
`dashboard/dist/app.js`. 1682 tests pass.
Stage 4 PR 4.6 from #28. The largest single migration: ChatPanel +
SessionsPanel + all 7 modals + ToolCard + ChatMessage + diff helpers
move out of app.js into typed modules.
- components/chat-internals.ts (541 LoC) — ROLE_GLYPH, ToolCard,
ChatMessage, ModalCard, 7 modal components (ShellModal,
ChoiceModal, PlanModal, EditReviewModal, WorkspaceModal,
CheckpointModal, RevisionModal), plus lineDiff/pairDiffRows
helpers used by EditReviewModal. Carries `// @ts-nocheck` for
bulk migration; type tightening is a follow-up.
- panels/chat.ts (784 LoC) — ChatPanel + summarizeActiveTool +
InFlightRow + ChatStatusBar. Same @ts-nocheck rationale.
- panels/sessions.ts (128 LoC) — SessionsPanel; depends on
ChatMessage from chat-internals. Properly typed.
Bug fix: ROLE_GLYPH was accidentally dropped during PR 4.1 (small
panels) when the strip cut its definition along with the chat
banner comment. ChatMessage would have crashed at runtime with
ReferenceError on any chat / sessions render. Tests didn't catch
it because no test loads the bundled dashboard. Restored in
chat-internals.ts.
Cleanup: dashboard/app.js trimmed to a 125-line shell — imports +
TABS array + the App component (sidebar + tab routing + error
boundary + toast stack). The @ts-nocheck pragmas in chat-related
files are explicitly tagged "tighten in follow-up".
Bundle: 122 → 123 KB (ROLE_GLYPH restoration). 1682 tests pass.
Stage 4 PR 4.3 from #28. Usage panel pulls out with its uPlot
chart loader and the chart subcomponent.
- panels/usage.ts (231 LoC) — UsagePanel (renamed from
UsageWithChart), UsageChart subcomponent, loadUPlot helper
(private). Daily series chart, rolling-window table, top
models — same as before.
- dashboard/app.js — drops the live UsageWithChart + UsageChart
+ loadUPlot (~210 LoC) AND the dead-code original UsagePanel
(~85 LoC) that hadn't been wired since the chart rewrite.
TABS entry points at the new UsagePanel symbol.
Net dashboard/app.js loses 295 LoC; bundle still ~122 KB. uPlot
import stays external (esm.sh URL preserved through tsup).
1682 tests still pass.
Stage 4 PR 4.1 from #28. Five panels move out of dashboard/app.js:
- panels/overview.ts (53 LoC) — Live Cockpit metric grid
- panels/tools.ts (71 LoC) — registered-tools table
- panels/permissions.ts (169 LoC) — allowlist CRUD + builtin
groupings; private groupByVerb helper folded in
- panels/plans.ts (104 LoC) — archived-plan browser + step view
- panels/hooks.ts (105 LoC) — JSON editor for project + global hooks
Plus shared pieces these panels need:
- components/metric-card.ts (23 LoC) — used by overview now and
by system in a later PR
- lib/html.ts (4 LoC) — single htm.bind(h) export so panels
don't each rebind
dashboard/app.js loses 419 LoC. Bundle holds at ~122 KB; CDN
imports stay external. Typecheck + lint + 1682 tests still
pass. No behavior change.
Stage 3 PR (consolidated). Originally split across PRs 3.2–3.5 in #28
but each was a 30–60 line leaf extraction — not enough review value
for the PR overhead. Folded the four into one architectural slice.
New files under dashboard/src/lib/:
- use-poll.ts (45 LoC) — typed `usePoll<T>` hook over the api() wrapper.
- bus.ts (65 LoC) — appBus, toastBus, showToast, ToastStack, plus
reportAppError and the two window error listeners (registered on
module load, same as before).
- error-boundary.ts (159 LoC) — ErrorOverlay component, ErrorBoundary
class, buildIssueBody helper. Both consumers of bus.ts.
- markdown.ts (169 LoC) — escapeHtml, SEARCH_REPLACE_RE,
renderSearchReplace, renderUnifiedDiff, the marked renderer
customisation, renderMarkdownToString (was inline in
renderMessageBody), LANG_BY_EXT, langFromPath,
renderHighlightedBlock, hlLine. Drops the unused previewMarked
(was only for the Editor that #31 removed).
Other moves:
- types.d.ts — module shims so TypeScript resolves the CDN URL
imports against npm types. Specific shims for preact, htm,
marked, highlight.js; wildcard fallback for anything else.
- package.json — preact, htm, marked, highlight.js added as
devDependencies (types only — runtime still loads from esm.sh,
tsup keeps them external).
- dashboard/app.js — drops ~500 LoC of moved blocks. renderMessageBody
stays as a thin wrapper around renderMarkdownToString since it
needs the Preact-bound `html` template literal.
Bundle output verified: dashboard/dist/app.js still 121 KB, CDN
imports preserved external. 1682/1682 tests pass.
Stage 3 of #28, PR 3.1. The fetch wrapper (token-on-url for reads,
header-too for mutations, JSON parsing, structured ApiError) was
the next leaf-y piece after the formatters. Used by every panel,
no Preact dependency, easy to type.
- dashboard/src/lib/api.ts (new) — typed exports: TOKEN, MODE
("standalone" | "attached"), ApiOptions, ApiError, api<T>().
- dashboard/app.js — drops the inline definitions (~30 lines),
imports the named exports.
Bundle still passes through tsup unchanged at the byte level
(esbuild inlines the lib module into a single file as before).
1682/1682 tests still pass.
The design mockup deleted §7 Editor in #26 — Reasonix's value is the
agent loop, not a VSCode-in-a-tab. The code follows. Net −1535 LoC
across nine files; the dashboard bundle shrinks from 137 KB to 121 KB.
Removed:
- dashboard/app.js — EditorPanel + the lazy CodeMirror loader (~540
lines), the editor drawer overlay in App, the `editor` entry in
TABS, the `openFileInEditor` helper, the `open-file` event-bus
path, and the four tool-card path-link click handlers (now plain
code spans).
- dashboard/app.css — 590 lines of editor-drawer / file-tree /
CodeMirror skin. The `.tool-card-path-link` hover treatment goes
with the click handler.
- dashboard/codemirror.js — 36-line CDN loader stub, gone.
- scripts/bundle-codemirror.mjs — the build-time CodeMirror bundler,
no longer needed.
- src/server/api/file.ts — the `/api/files` + `/api/file/<path>`
endpoints had no consumer outside the editor panel.
- src/server/router.ts — drops the `files` / `file` route cases.
- src/server/assets.ts — drops the `codemirror.js` serving branch.
- package.json — drops `dashboard/codemirror.js` from the npm
files list and removes the `build:cm` script.
Out of scope: the new §7 Edit review surface (Stage 4 PR 4.15)
will live in `dashboard/src/panels/edit-review.tsx` and replaces
this slot in the IA conceptually, but that's later in the rollout.
First real TS module after the build-infra PR. Moves the five pure
helpers (fmtUsd, fmtPct, fmtNum, fmtBytes, fmtRelativeTime) out of
the 4768-line god file and into a typed leaf module. They had no
dependencies and ~6 panel call-sites, so this validates the
extraction pattern without touching state, polling, or buses.
- dashboard/src/lib/format.ts (new) — five exports, fully typed.
- dashboard/app.js — drops 35 lines of inline definitions, imports
from "./src/lib/format". File-header comment shrunk to one line
and corrected (no longer claims "no build step").
- tests/dashboard-format.test.ts (new) — 17 cases covering the
null/undefined branches, locale separators, byte-unit boundaries,
and the time-band edges; mocks Date.now where needed.
Bundle output verified: format functions appear once each in
dashboard/dist/app.js, CDN imports stay external. 1682/1682 tests
pass (was 1665; +17 from this PR).
The dashboard refactor (#28) needs to extract panels into typed
modules. Plain ESM-from-CDN can't follow `import` paths to local
sibling files at request time, so app.js has to go through a
bundler before it lands on the browser. Reusing the existing tsup
toolchain keeps build infra consistent with src/.
- tsup.config.ts adds a third entry: `dashboard/app.js` →
`dashboard/dist/app.js`. Browser target, externals match
`^https://` so esm.sh imports stay as live URLs in the output.
- dashboard/tsconfig.json extends the root config, swaps Node
types for DOM, allowJs so the legacy app.js compiles unmodified
while new TS modules under dashboard/src/ get strict checks.
- src/server/assets.ts reads app.js from `dashboard/dist/`; new
branch serves the sourcemap.
- typecheck script chains both root + dashboard projects; verify
now runs build first (matches the bundle-smoke pattern that
already assumes CI builds before tests).
- package.json files: ship `dashboard/dist/` instead of the raw
source app.js for npm consumers.
- Asset test that touches /assets/app.js skips when
`dashboard/dist/app.js` is missing — same convention as the
existing tests/bundle-smoke.test.ts.
No behavioral change at the dashboard level — esbuild passes the
source through; CDN imports stay external. First real TS module
extraction follows in a separate PR.
The four feasibility experiments for the kernel-level red-green
TDD invariant (RFC #25) produced reports, raw data, and reproducer
scripts. The RFC body and its summary comment cite paths under
benchmarks/spike-tdd-kernel/; without these files the references
are dead links.
Contents:
- latency.md / latency.json / bench-latency.mjs (Exp 4)
- test-id-spec.md (Exp 2)
- tdd-eval.md / tdd-eval.json / tdd-eval.mjs (Exp 3)
- cost-results.md / cost-results.json / cost.mjs (Exp 1)
- work-estimate.md (3-stage plan)
All reports include their own pass thresholds, decisions, and
RFC-text-change implications. Reproducer scripts read the project
.env and run against deepseek-v4-flash / deepseek-chat; total
cost was ~$0.001 for the original spike pass.
Local-only tracking-issue-draft.md is intentionally excluded —
it gets posted as a real GitHub issue once the FCP closes.
Mockup prep ahead of the dashboard code refactor — current
dashboard/app.js is a 4768-line single-file Preact SPA with no
clear state boundaries, and the refactor needs an updated target.
- Remove §7 Editor entirely. Reasonix's value is the agent loop,
not a VSCode-in-a-tab. Sidebar mockups (11 pages + collapsed
variant) and the glyph palette drop the corresponding entries.
- Add §7 Edit review (reclaiming the slot). GitHub-style
multi-file diff: aggregator header with stat + mode toggle +
bulk apply, per-file collapsible cards with approve/reject,
expand-context chevrons, intra-line word diff, unified ↔ split
modes, plus empty / applied / test-failed states. §3 inline
diff picks up syntax highlighting and a word-rem demo.
- §12 Semantic gains a real config card. The backend exposes
6 fields (excludeDirs / excludeFiles / excludeExts /
excludePatterns / respectGitignore / maxFileBytes); the mockup
previously showed one as a read-only list. New card has
editable chip lists, toggle, number input, and a Preview
action, plus a Config preview subsec demonstrating the dry-run
output of /api/index-config/preview.
CLAUDE.md is local-only project guidance — never committed. The
public-facing rules entry is CONTRIBUTING.md (added in 4bf0abe). My
README rewrite (#23) linked to CLAUDE.md, which 404s for anyone
viewing the repo on GitHub.
Both English and Chinese READMEs updated to point at CONTRIBUTING.md
with a slightly fuller description (the rules cover comments, error
handling, and libraries-over-hand-rolled, not just comments).
The previous README accumulated three years of "Risks", "Notes for
Reasonix", deep CLI reference, and library-usage walkthroughs that
belong on the website / in dedicated docs. Trim to the surface a new
visitor actually needs in 60 seconds.
Changes
- Single comparison table (was duplicated as "At a glance" + "Why Reasonix?")
- Drop stale `change_workspace` / `/cwd` row — both removed in 0.18
- Add per-workspace sessions row (new in 0.18)
- Cache-economics section condensed and tucked under <details>
- Feature highlights compressed to one paragraph each, link out for depth
- Contributing section front-and-centre with all four good-first-issues + the three open Discussions
- Non-goals retained (project-defining)
- Cut: long Risks essay, "Notes for Reasonix" prose, deep CLI reference,
library-usage walkthrough, MCP transport tutorial, web-search internals
- Link-only references to architecture doc, design mockups, benchmarks dir
Stats updated to 1665 tests (was 1482).
`debug:true` does NOT force full-frame writes — Ink's docs are explicit that
each update is rendered as a SEPARATE output without overwriting the previous
one. Every keystroke triggered a React rerender → a fresh frame appended to
scrollback. After a session, dozens of stale PromptInput frames remained
above; relaunching reasonix made the new session's typing look like it was
"syncing" with the ghost frames above.
The original justification ("log-update drops frames on Windows ConPTY") was
my speculative misread — never seen in practice. Default log-update diff
mode is correct here.
- chat.tsx: SessionPicker outcomes now drive state, parent re-renders App with `key={session}` so the new session gets a fresh transcript / scrollback / store; ink `debug:true` forces full-frame writes (log-update's diff dropped frames on Windows ConPTY)
- App.tsx: hydrate cards from `loadSessionMessages` on mount so resumed sessions render their history; expose `onSwitchSession` so the picker actually switches instead of printing a "quit and rerun" hint; conditional render of SlashSuggestions / AtMentionSuggestions only when matches !== null
- composer Esc: dismiss slash / @ / slash-arg pickers by clearing input — picker footers already advertise "esc cancel"
- state/{provider,state,store}: thread an optional `initialCards` through createStore; provider captures it in a ref so re-renders don't reset the store
- SessionPicker: rename starts with empty buffer (was pre-filled with old name — typo-prone)
- PromptInput: placeholder uses words "slash"/"at-sign" instead of `/`/`@` glyphs (read as residual typed input on dim-poor terminals)
- hydrate: new module rebuilds Card[] from ChatMessage[] (user → UserCard, assistant text → StreamingCard, reasoning_content → ReasoningCard, tool_calls + tool messages → ToolCard pairs)
- listSessions: filter out *.events.jsonl — they share the .jsonl suffix and were polluting the picker as phantom sessions
- listSessionsForWorkspace: strict equality on meta.workspace; legacy untagged sessions no longer leak into every workspace's picker (resume-by-name still works)
- rename / delete: also move/remove the .events.jsonl sidecar so /forget and /rename leave no orphans
- JsonlEventSink: skip model.delta — recoverable from model.final.text and would balloon the sidecar with token-by-token frames
Mid-session re-rooting was a footgun: the message log still referenced old paths after a switch, and any tool call dispatched in the same parallel batch as `change_workspace` ran against the pre-switch sandbox before the user had approved. Both the deferred-batch workaround (loop.ts) and the modal/UI plumbing exist only to paper over those races. Cheaper to pin workspace at launch and tell the user to relaunch.
- delete src/tools/workspace.ts and tests/workspace-tool.test.ts
- delete src/cli/ui/WorkspaceConfirm.tsx
- loop: drop workspaceSwitchPending gate (no batch can target a pending switch anymore)
- server: drop "workspace" ActiveModal kind + resolveWorkspaceConfirm + the modal route
- slash: drop /cwd command, handler, and setCwd context callback
- code/prompt: rewrite the "switch project" section to tell the model the workspace is pinned
- tests/loop + tests/server-dashboard: drop the corresponding cases
- shell: kill the whole process tree on timeout/abort (Windows taskkill /T, Unix process-group SIGKILL with leader fallback) — long-running shells were leaking children when the parent loop aborted
- shell + jobs: synchronously check signal.aborted before attaching the listener; AbortSignal addEventListener with `once:true` never fires if the signal already aborted, so child ran unbounded
- subagent: turn on streaming + emit `inner` and `phase` SubagentEvent variants so the parent UI can render child loop activity and flip "summarising" the moment the model starts the final answer
- skills: thread parent abort signal through SubagentRunner so subagent skill invocations cancel cleanly
- tests/subagent: extend fake fetch to serve SSE frames when stream:true
- App.tsx: drop legacy workspace-switch modal + registerWorkspaceTool wiring; surface active PlanCard via useAgentState selector
- handle-tool-event: remove change_workspace branch (the tool itself leaves in a follow-up)
- chat.tsx: pin session listing to the launch workspace via listSessionsForWorkspace
- PlanConfirm: route through ApprovalCard with metaRightColor; drop unused summary prop
- PromptInput: mirror value/cursor in refs so multi-event stdin chunks see the latest state (fixes a fast `/`+Backspace race that left the slash stuck)
- LiveRows / CardStream / BarRow / cards/{Approval,SubAgent}: layout polish for the card stream
- useSubagent: child-event subscription for the new SubAgent card
CLAUDE.md forbids conversation history / incident narrative / stream-of-
consciousness debug traces in committed code. Cleanups on the just-merged
PR #12 contributions:
- session.ts: drop bogus "Priority order in description.md" reference;
replace with a concise dispatch summary on resolveSession. Trim
findSessionsByPrefix JSDoc to a single line.
- tests/session.test.ts: replace the 17-line "Wait — let's trace..."
inner-monologue with one explanatory line. Trim 6-line ASCII-sort
essay to 2 lines. Drop "Regression:" incident narrative and a few
inline play-by-play comments on test setup.
- tests/plan-store.test.ts: replace the 8-line "Bug:" narrative with
a test name that documents the invariant directly.
Integrates PR #12 onto feat/tui-card-stream:
- Use resolveSession() in chatCommand for --session paths so --new
generates a timestamped name instead of truncating, and --resume
picks the latest prefixed session. The full-list SessionPicker
(this branch) covers the no-session launch path; the legacy
resume/new modal from PR #12 is dropped (full-list is strictly
more capable).
- Drop the baseSession Root prop and effectiveSession state — only
used by the dropped legacy modal.
- session.ts deleteSession sidecar list keeps .meta.json (this
branch had it; PR #12 didn't).
- App.tsx loop.resumedMessageCount > 0 guard from PR #12 lands as-is
(auto-merged).
* fix(ui) Rendering inline formating deletes prefixed spaces.
* Add falling unit tests for missing space before inline bold, code and others.
* Fix implementation
CodeMirror injects DOM into its container; the markdown preview uses
dangerouslySetInnerHTML. Toggling Edit / Split / Preview re-shaped the
DOM around both, so Preact tried to insertBefore against anchors that
were never its own children — observed as "render: Failed to execute
'insertBefore' on 'Node'" in the dashboard error overlay.
The editor stage now keeps both panes rendered at stable vnode
positions; data-mode on one wrapper drives CSS visibility instead of
restructuring the tree. CM stays mounted across toggles and gets a
requestMeasure when it returns from display:none.
Minor bump. New feature surface: ReasonixConfig.index block fully
replaces the previously-hardcoded skip lists in chunker.ts (and the
duplicated copy in directory_tree). .gitignore is honoured by default,
nested per-dir. Dashboard Semantic tab grows an Excludes card with
Save / Preview / Reset that round-trips through GET/POST
/api/index-config and POST /api/index-config/preview.
Defaults are the union superset of the previous two lists, so existing
installs keep current behaviour without touching config.
Landed via PR #10 (closes#9).
Earlier change used inline styles + abused .section-title for the
toggle header, leaving the card visually inconsistent with the rest of
the dashboard: bare textareas with no border, an unstyled number
input that fell back to browser defaults against the dark background,
and details/summary blocks rendered as raw HTML.
This adds:
- input[type="number"] grouped with text/search so it picks up the
same bg-2 / border / padding / font as the other inputs.
- textarea gets the missing border / radius / padding / font-size /
resize:vertical (was background+color+font-family only).
- New .excludes-* classes for the toggle header, two-column field
grid, options row, action row, and the dry-walk preview drilldown.
The JS swaps every inline style on the Excludes card for a class.
GET /api/index-config returns user, resolved, and defaults so the SPA
can render a "reset" affordance without re-implementing them. POST
persists into ~/.reasonix/config.json via the existing writeConfig
path. POST /api/index-config/preview dry-walks the project root with
a draft config (without saving) and returns sample included paths
plus per-reason skip buckets — lets users see the impact before
committing the change.
Dashboard Semantic tab gets a collapsible "Excludes" card with
editable lists, gitignore toggle, max-file-size input, and Save /
Preview / Reset buttons. The job result panel now shows per-reason
skip bucket counts when a build finishes.
semantic.ts is wired to load the resolved config so dashboard-
triggered indexing honours the same excludes as the CLI.
Pulls SKIP_DIRS / SKIP_FILES / BINARY_EXTS / maxFileBytes out of
chunker.ts (and the duplicate copy in directory_tree) into a single
src/index/config.ts. ReasonixConfig gains an optional `index` block
where any field present fully replaces the default for that field.
walkChunks now takes a ResolvedIndexConfig and an onSkip callback,
honours .gitignore by default (nested per-dir, scoped to the dir the
file lives in), and supports picomatch globs via excludePatterns.
buildIndex aggregates the callback into a per-reason skipBuckets map
that the CLI surfaces in its success line.
directory_tree no longer carries its own list — both code paths share
DEFAULT_INDEX_EXCLUDES, eliminating the drift the comment at
chunker.ts:29 had been warning about.
scripts/smoke-index-config.mjs is a tsx one-shot for verifying the
walker + .gitignore + glob behaviour against a real repo without
needing Ollama.
Patch release. 0.16.0 has a real production-affecting bug: any tool
loop on the default deepseek-chat model 400s on the second turn with
"reasoning_content in the thinking mode must be passed back to the
API." DeepSeek's V4 rollout means deepseek-chat now emits non-empty
reasoning_content even with thinking disabled, and the whitelist-by-
model logic in assistantMessage() was dropping it.
Fixed in a27d46f, regression test in a5ffa0b, full τ-bench re-run
(100% pass · 90.2% cache hit) in f77e8f2.
Re-ran the full τ-bench-lite suite (8 tasks × 3 repeats × 2 modes = 48
runs) on v0.16.0 against deepseek-chat. Numbers vs the v0.2.1 snapshot:
| metric | v0.2.1 reasonix | v0.16 reasonix | delta |
|---|---:|---:|---:|
| pass rate | 100% (24/24) | 100% (24/24) | — |
| cache hit | 94.4% | 90.2% | -4.2pp |
| mean cost/task | $0.001579 | $0.000593 | -62% |
Cost drop is mostly DeepSeek's price moves; cache-hit dip is small and
within run-to-run variance — the loop is still operating in the
prefix-stable regime (vs baseline's 32.8%, +57.4pp delta).
Also: runner.ts now reads VERSION live from src/index.ts instead of
the hardcoded 0.2.2 — every future re-run stamps the right version.
Refreshed transcripts (committed) carry per-turn usage/cost/prefixHash
so anyone can re-render the report locally without burning API credit.
New case alongside the existing R1 round-trip tests: when deepseek-chat
returns a non-empty reasoning_content (V4-era behavior), the next
request's assistant message must carry it back. Without the loop fix
in a27d46f the API 400s on the round-trip.
V4-era deepseek-chat now returns non-empty `reasoning_content` even
with `extra_body.thinking.type = "disabled"`. The API then rejects
round-trips that drop the field with "reasoning_content in the thinking
mode must be passed back".
The whitelist in `isThinkingModeModel` was too narrow — it only tagged
deepseek-reasoner / v4-flash / v4-pro. `assistantMessage()` now also
preserves reasoning_content whenever the producer emitted any non-empty
content, regardless of model name. The whitelist still applies to
synthetic messages where reasoningContent is empty (so they get an
empty string stamp for thinking-mode endpoints).
Caught by tau-bench (24/24 reasonix runs were failing on the kernel
HEAD; same test on v0.2.1 passed 100%). Single-task verify now hits
92.3% cache and passes.
README and zh-CN README: wrap four reference-heavy sections in
<details>/<summary> blocks so the visible flow on GitHub stays around
half its previous height while keeping every word findable via Ctrl-F
and clickable expansion.
- Why-Reasonix tail (Pick something else / DeepSeek-Anthropic-compat /
Aider-Cline-Continue): collapsed
- Slash-command reference inside "Commands inside the session": collapsed
- CLI reference (commands + flags + env vars): collapsed
- Library usage: collapsed
Comparison table, walkthroughs, plan mode, and benchmarks remain
visible — those are the parts a new reader actually reads.
README / README.zh: pull a focused 7-row comparison table to right
after Quick start (was buried inside the 'Why' prose section). Headline
numbers + "see full comparison below" pointer. Trim a couple casual
asides ("watch your bill not happen") and remove version-specific tags
that aged out (`(new in 0.12)`, "since 0.5.14").
docs/: bump VERSION_FALLBACK and the static hero badge from 0.6/0.12
to 0.16. The site fetches latest from npm at runtime; the fallback
just covers offline-first-visit.
CONTRIBUTING.md is the human-facing rules entry on GitHub (CLAUDE.md
stays as the AI-agent entry). Code rules previously only in CLAUDE.md
are now inlined here so contributors actually see them.
REASONIX.md layout table catches up to the recent structure refactor —
adds core/, ports/, adapters/, frame/, memory/, transcript/, telemetry/,
server/, code/ which had drifted off the doc.
feat(ui): plain mouse drag in the log now paints a reverse-video
selection, dragging past the viewport edge auto-scrolls the log, and
releasing copies the selected text to the system clipboard via OSC 52
+ tempfile fallback. Shift+drag still bypasses tracking for native
terminal selection.
chore(ui): the old /copy slash command, copyMode lifecycle, and
mouse-tracking helpers are gone — the new flow stays inside
alt-screen so there's no main-buffer dump to manage.
The old mouseToAbsRow assumed log content always started at the top of
the box. Two cases broke that:
1. ChromeBar is 2 rows (pills + ChromeRule), not 1 — log starts at row 3.
2. At logScrollOffset=0, the inner Box uses justifyContent="flex-end",
so when totalRows < available the content is bottom-anchored and the
top of the box is empty — clicks there were mapping to row 0.
Now the geometry IIFE computes contentTopRow / contentBottomRow per
render based on the actual layout (scrolled vs latest, BottomHint
present vs not), and mouseToAbsRow uses those instead of guessing from
logTopRow. Auto-scroll edge triggers use the real content edges too.
App now owns mouse selection. Plain drag in the log paints a reverse-
video selection highlight; dragging past the top/bottom edge of the
viewport auto-scrolls one row every 60ms; releasing copies the selected
text via OSC 52 to the system clipboard plus a tempfile fallback for
terminals that don't honor it. Shift+drag still bypasses tracking for
native terminal selection.
stdin-reader surfaces mouseDrag (SGR btn=32) and mouseRelease (tail='m')
events; alt-screen switches from mode 1000 (press only) to 1002
(button-event tracking with drag motion); log-frame extends AtomViewport
with firstRowAbs and adds extractSelection() to pull plain text out of
the selected absolute-row range.
Old /copy slash command, copyMode lifecycle, and the
isMouseTrackingOn / setMouseTracking helpers are removed — the new
flow stays inside alt-screen the whole time so there's no main-buffer
dump to manage.
The structure refactor (3b0dd73) moved src/transcript.ts under
src/transcript/, but the two benchmark runners kept the old import
path and tripped CI's tau-bench dry-run.
read(jobId) test fired fixed 300ms sleeps after child spawn; under
parallel-suite contention the child hadn't printed yet and the
"contains 'a'" assertion failed. Replace fixed waits with a 100ms × 20
poll loop. Same shape as the `since` test below it.
The root of src/ had 25 top-level *.ts files mixed with subdirs, including
several that map directly to architectural layers in design/architecture.md.
- memory pyramid → src/memory/{runtime,session,project,user}.ts
- telemetry → src/telemetry/{stats,usage}.ts
- transcript → src/transcript/{log,replay,diff}.ts
git mv preserves history. Internal cross-imports updated (siblings drop
the prefix; references to non-moved root files gain `../`). Public barrel
in src/index.ts and all consumers (~50 sites in src + 18 test files)
retargeted. Behavior is unchanged; verify (lint + typecheck + tests) green.
feat(core): replay() reads events.jsonl sidecar and runs the same
pure reducers as in-process apply() — first deterministic proof of
the v0.14 projection layer.
feat(cli): reasonix events <name> for inspecting any session's event
stream from the command line.
feat(ui): deny-with-context shipped via PR #1 (@wviana) — Tab on a
tool-confirm modal opens inline reason entry, forwarded to the model
so it knows *why* the user refused.
chore: tests/comment-policy.test.ts enforces CLAUDE.md rules under
npm run verify; companion sweep removed 6.3k LoC of dead-weight
comments across 148 files.
tests/comment-policy.test.ts pins six rules: ≤2-line module headers, no
Phase-N narrative, no version refs in comments, no incident history, no
banner separators, ≤3-line block comments. Runs under `npm run verify`
so pre-push catches new violations.
148 src files touched: 116 module-essay headers compressed to one line,
577 over-long block comments distilled or deleted, 44 banner separators
stripped, all v0.x / Phase-N / "user reported" / "fix for #N" narrative
removed. Net -6367 LoC of dead-weight comments. No behavior change;
1759/1759 tests, lint, typecheck pass.
Pressing Tab on a Deny item (or n on edit-review) opens an inline input so the user can tell the model *why* they refused. Context is forwarded into the synthetic message and the historical log.
Also: stdin-reader.ts now probes setRawMode directly so bun (where isTTY is undefined) can still go interactive; useKeystroke falls back to Ink useInput when no KeystrokeProvider is mounted.
Closes#1
reasonix events <name> pretty-prints the event-log sidecar — the first
user-facing consumer of events.jsonl. Renders one line per event with
per-type detail synopses; --type / --since / --tail filters; --json
for jq pipelines; --projection dumps the reduced ProjectionSet. Closes
the v0.14 kernel loop: events get written by every session, and now
there's a tool to read them.
Sweep pass: trimmed verbose jsdoc / restated-the-code comments off
eventize.ts, event-sink-jsonl.ts, event-source-jsonl.ts, and the
tests. ~80 lines of comment cruft gone, no logic changed.
- src/cli/commands/events.ts: command formatter + per-event detail
table covering all 25 Event variants
- src/cli/index.ts: command registration with commander, help text
- tests/events-command.test.ts: 6 tests pinning the formatter + each
flag (type filter, tail, json passthrough, projection, missing
session error path)
1753 tests pass (was 1747 + 6 new).
Closes the loop on the v0.14 kernel architecture: the events.jsonl
sidecar from the prior commit is now demonstrably reduceable into a
useful projection. Synthetic LoopEvents → Eventizer → JsonlEventSink
→ disk → JsonlEventSource → reducers.replay() → ProjectionSet round-
trips correctly, conversation messages reconstructed in order, tool
result correlation preserved, replay() deterministic across runs.
This is the architecture-value tipping point: events are no longer
just write-only artifacts, they're the source of truth a consumer
can rebuild state from. Future work — UI re-rendering from a
projection, time-travel, multi-agent event trees — has a working
foundation.
- src/adapters/event-source-jsonl.ts: EventSource port impl. Pure
read side: parses jsonl, skips malformed lines silently (best-
effort replay over a possibly-truncated live writer).
- tests/event-sink-jsonl.test.ts: 5 tests pinning the sink mechanics
(append-per-line round-trip, re-open on existing file, parent dir
creation, flush no-op, port-shape conformance).
- tests/event-replay.test.ts: 5 tests pinning the architecture
promise — synthetic LoopEvents reduce to expected projections,
error-shaped tool results land with ok=false, replay determinism,
missing-file safety, malformed-line tolerance.
1747 tests pass (was 1737 + 10 new). Zero touches to existing
production code.
Adds a new durable artifact: every session now writes a typed Event
log to ~/.reasonix/sessions/<name>.events.jsonl as a sidecar to the
existing ChatMessage / transcript files. Foundation for future
replay / projection / multi-agent consumers reading kernel events
instead of LoopEvent.
Architecturally a pure addition: no edits to loop.ts, transcript.ts,
EventLog, log-frame, replay, dashboard server, or any existing test.
LoopEvent stays as the internal protocol between loop and immediate
consumers — events.jsonl is a parallel kernel artifact, not a
migration target.
- src/core/eventize.ts: pure stateful translator. Holds monotonic
event id seq, last-turn tracker (synthesizes model.turn.started),
and a callId stack (correlates tool.intent → tool.dispatched →
tool.result chains since LoopEvent.tool_start doesn't carry
call.id).
- src/adapters/event-sink-jsonl.ts: concrete EventSink port impl —
append-only JSONL with append/flush/close lifecycle. eventLogPath
helper derives the sidecar path from a session name (mirrors
src/session.ts:sessionPath).
- src/cli/ui/App.tsx: ~30 lines additive — refs for sink + eventizer
opened on session mount (skipped for ephemeral sessions), pipe
attached inside the existing for-await consumer alongside
writeTranscript, sink.close on unmount, session.opened emitted at
open time.
- tests/eventize.test.ts: 11 unit tests pinning the mapper —
turn-start synthesis, delta channel split, tool callId
correlation, error detection, warning categorization, control-
marker passthrough.
1737 tests pass (was 1726 + 11 new). Zero existing-test edits.
fix(loop): streaming-abort path resets _turnAbort before returning,
so a queued-submit triggered by ShellConfirm "run once" no longer
trips a spurious "aborted at iter 0/64" on the next user message.
fix(tui): edit_file interceptor reads root via currentRootDirRef so
post-workspace-switch writes don't go to the stale root while
read_file looks at the new one.
feat(tui): /copy exits alt-screen and dumps the rendered log to
main screen, returning on any keystroke — native scrollback + drag
select work on the dump.
feat(tui): always-on context-pressure footer above the prompt
(`ctx ▰▱… 14K/977K · 1% · sys 5.8K · tools 6.1K · log 0`); /context
toggles visibility, full breakdown panel still pushed to scrollback
for headless / replay.
feat(tui): chrome bar drops the cols<120 hard cutoff in favor of
width-aware shed by priority (balance > cache > session > update);
cache pill default-on with cold-start dim treatment.
refactor(ui): Bar / formatTokens / ChromeRule / ContextCell promoted
to primitives.tsx; CtxBreakdownBlock + computeCtxBreakdown share a
single compute path; StatsPanel shrunk 769 → ~280 lines (dead
chrome-redesign helpers removed).
feat(core): v0.14 architecture scaffold — Event log + pure-reducer
projections (core/) and 6 ports (ports/). Types only, zero behavior
change. 19 new reducer tests pin the projections + prove replay
determinism.
Three places were computing 'rows the log can use' with subtly
different formulas:
· slicer: max(8, rows - 10)
· scrollbar bar: max(5, rows - 9)
· scrollbar math: max(8, rows - 10)
Bar height (the cell count) and thumb math (the divisor) didn't
match — thumb was computed for a 20-row viewport but rendered into
21 cells, so thumb position drifted vs. the actually-rendered log
slice. User reported visual oddness consistent with this drift.
Unify on (the parent log column's true height)
for both bar and thumb math. Slicer subtracts 1 when BottomHint
is active so the slicer doesn't claim the row the hint occupies —
the bar mirrors the same conditional so position stays in sync.
Tests: 1732/1732 pass.
Two reverts after the user reported chrome truncating worse than
before (only `[$` visible) and scrollbar display issues:
· The Phase 6a chrome migration removed the legacy
`paddingX={1}` from the StatsPanel outer Box but didn't
restore the equivalent inner-width budget. Inner content
rendered at full `cols` width, where on terminals that
reserve their last column for cursor/scrollbar (Windows
Terminal in some configs, ConPTY) the rightmost pill got
clipped mid-glyph. Restore: build chrome at `width - 2` and
wrap with 1-cell SPACE padding on each side so the visual
matches the legacy chrome and the right-edge pill is safely
inside the visible area.
· The Phase 8 kitty keyboard protocol push (`\x1b[>1u`) was
too aggressive — terminals without protocol support sometimes
displayed the unrecognized CSI as visible chars, distorting
the chrome layout. Revert until we wire feature detection
(DA1/DA2 query response) before pushing the flag. The
setImmediate-based ESC ambiguity timer in stdin-reader keeps
handling the bogus-Esc bug class for now.
The earlier 1-cell safety margin (`width - 1` in App.tsx) is
removed since the new `paddingX`-equivalent already provides
the right-edge buffer.
Tests: 1732/1732 pass. Lint clean. Typecheck clean.
User reported wallet pill still clipped at "[w" even after the
appendCells / composeRow fixes. Reproduction confirmed our Frame
output is correct (full 120-col row, all cells styled, ANSI bytes
intact) — the clipping happens at the Ink/terminal layer.
Most likely culprit: terminals that reserve their rightmost column
for the cursor or a scrollbar (some Windows Terminal / ConPTY
configurations report 120 cols but only render 119 visibly), or
Ink miscounting our SGR-rich row width.
Cheapest fix: build chrome at stdout.columns - 1, leaving a 1-cell
safety margin. The cost is one column of empty space at the right
edge; the gain is the wallet / cache pills survive on every
terminal we've seen.
Tests: 1732/1732 still pass.
User reported the wallet pill at the top wasn't displaying fully.
Two bugs in `chrome-frame.ts`:
1. `appendCells` was padding to a generous width then stripping
trailing-space-with-no-style cells. That stripped REAL spaces
the caller had explicitly added as inter-pill separators
(`appendCells(right, " ")`), collapsing pills into each other
visually. Fix: pass the EXACT visual width of the input string
to `text()` so no padding is added in the first place.
2. `composeRow` only handled "left+right combined exceeds width"
by truncating left. When `right alone` exceeded width, cells
were appended past the row budget — Frame width invariant
violated, terminal showed pills cut off mid-glyph. Fix: add a
case-3 branch that truncates from the LEFT EDGE of the right
group (drop update / mode / pro pills first; cost / balance /
cache live at the rightmost end and survive longest), so the
wallet pill stays visible even on terminals where every
optional pill is active.
Three new tests:
· wallet preserved when right side overflows (case 2)
· width invariant holds when right alone exceeds width (case 3)
· inter-pill spacer is NOT collapsed (the appendCells regression)
Tests: 1732/1732 pass (1729 prior + 3 new). Lint clean.
Chrome row + horizontal rule + optional budget row now compile to
a single Frame via `chromeFrame()` in `src/cli/ui/chrome-frame.ts`.
App.tsx renders it via the new generic `renderFrame(f, keyPrefix)`
helper in `src/cli/ui/frame-render.tsx`, which wraps each Frame
row in `<Box height={1}><Text>{ansi}</Text></Box>` — same
single-row-Box translation the log path uses.
· `chromeFrame(props)` composes:
· brand wordmark + project crumb (left)
· status pills — update, mode, pro, cost, balance, cache —
(right, with truncate-on-narrow rules)
· 1-row dim ─ rule
· optional budget row (`budget $X / $Y (Z%)` with amber
at 80% / red at 100%)
· `renderFrame(f, keyPrefix)` is generic — log atoms, chrome,
and future modals/prompt all flow through it. Phase 7's
direct-stdout paint layer will replace this helper without
touching call sites.
· App.tsx no longer imports `<StatsPanel>`. The legacy file is
untouched (tests/observability still reference some helpers)
and can be deleted in a follow-up once the dashboard panel
confirms it's unused too.
Tests: 1729/1729 pass (1714 prior + 15 new chrome-frame tests
covering brand / project crumb / narrow truncation / cost / mode /
pro / update / balance / cold-start cache / rule / budget / row-
width invariant under all configurations). Lint clean. Typecheck clean.
Phase 6 progress:
· 6a chrome ← this commit
· 6b modals (next: ModalCard + EditConfirm + ShellConfirm + …)
· 6c prompt (PromptInput + suggestion area)
Reuses the existing block-level parser (`parseBlocks` from
markdown.tsx) and adds a per-block Frame compiler in
`src/cli/ui/markdown-frame.ts`. Closes the visual regression
introduced in Phase 4 where assistant body / plan body fell back
to plain text in exchange for row-level scrolling.
Coverage in this first pass — most common 90% of model output:
· paragraphs with inline markup (bold, italic, code, link, strike)
· headings (H1–H6, bold + tone keys off level)
· bullet lists (`- ` / `* ` / `1. `) including GFM task items
with `[x]` / `[ ]` indicators
· fenced code blocks with bg tint per line
· blockquotes (left-border + dim text, recursive on children)
· horizontal rule
Inline parser:
· regex shared with `markdown.tsx`'s INLINE_RE so styling
matches the legacy renderer for the same input
· soft-wrap at last whitespace; hard-wrap as fallback when a
single token exceeds line budget
· 2-wide CJK / emoji handled via the Phase-1 width module
Wiring:
· `simpleAssistantFrame` and `complexAssistantFrame` body now
flow through `markdownToFrame()`; empty body still falls back
to the dim "(empty body — likely tool-call only)" placeholder
· `planFrame` body is markdown-compiled
Deferred (still plain-text fall-back inside the markdown pipeline):
· tables → header row + dim body rows for now
· Aider edit-blocks → SEARCH/REPLACE summary as plain text
· citation validation → URL passes through unchanged
Also tweaks `markdown.tsx` to export the `Block` AST union so the
Frame compiler can consume it without re-defining the type.
Tests: 1714/1714 pass (1699 prior + 15 new markdown-frame tests
covering paragraphs / inline / headings / lists / task items /
code / blockquote / hr / wrap / row-width invariant / links /
strike-through). Lint clean. Typecheck clean.
Migrate the remaining "complex" event roles off the ink-atom
fallback. Each sub-block has been ported from its Ink component to
a Frame builder using Phase-1 primitives, then composed into the
parent role's frame.
· reasoningFrame "R1 ↯ reasoning · ~Nk tok · /think for full"
header + violet-bordered preview body (last
260 chars of reasoning, italic dim).
· branchFrame "⎇ BRANCH ×N picked #M" pill + per-branch
uncertainty list with the chosen one called
out in cyan bold.
· planStateFrame One row per non-empty TypedPlanState field
(subgoals / hypotheses / uncertainties /
rejected) with its bold colored label,
count, and items joined by " · ".
· ctxBreakdownFrame `/context` 4-color stacked char-bar across
48 cells + legend with token counts. Used
to be `<CtxBreakdownBlock>`.
· complexAssistantFrame Composes branch / reasoning / planState /
body / stats / repair into one
assistant-accent bordered column. Body
is plain-text for now (markdown→Frame
is deferred to a future phase) — code
blocks / bold spans render unstyled but
scrolling works row-by-row.
· planFrame "📋 plan proposed" header + plain-text body.
Markdown rendering deferred (same as
complex assistant body).
Dispatch updated:
· plan / ctx-breakdown / assistant-with-reasoning|branch|planState
now produce frame atoms
· ink fallback shrinks to: streaming assistant (transient),
plan-replay, plan-resumed (rare turn-state events)
Tests: 1699/1699 pass (1696 prior + 3 new). Lint clean. Typecheck clean.
Visible regressions on the migrated paths:
· markdown formatting (bold / italic / code spans / lists / code
blocks) is rendered as plain text. The original formatted text
still lives in `~/.reasonix/sessions/<name>.jsonl`. This is the
last remaining trade-off; closing it requires a markdown→Frame
compiler which is the next phase.
What's next:
· markdown → Frame (preserves bold / code / lists in frames)
· frame-based ScrollBar / BottomHint (sibling components) so the
log-rows.tsx file can be deleted entirely
· streaming assistant migration (live atomic frame updates as
chunks arrive)
Three more roles migrated off the ink-atom fallback. Each is now
composed from Frame primitives — no Ink layout, no flex-engine
quirks, deterministic row count.
· userFrame — `◇ ` glyph header + cyan accent-bar body. Wraps
long text across rows, accent bar continues down
every row. Conditional turn-separator (gradient
rule with centered `◆` brand mark) above when
`event.leadSeparator` is set.
· toolCompactFrame — `[bar] ▣ name [duration] [summary] /tool N`,
single-row, color tone keys off whether the
result starts with `ERROR:` (red pill +
accent vs. cyan pill + tool-yellow accent).
· editFileDiffFrame — multi-row block:
1) `▣ edit_file diff:` header
2) status header line (`edited X (A→B chars)`)
3) magenta-pill hunk header (`@@ -N,M +N,M @@`)
4) body — each line gutter-glyphed and
tinted (`−` red for removals, `+` green
for additions, ` ` dim for context)
· turnSeparatorFrame — gradient `─` rule with centered `◆` mark,
composed from `gradientCells()` cells.
· rowFrame helper — concat-cells-and-pad-to-width for layouts
conceptually one line of mixed-style segments
(tool pills, header rows). Truncates if too
wide, right-pads if too narrow.
Tests: 1696/1696 pass (1690 prior + 6 new). Lint clean. Typecheck clean.
Remaining ink-atom escape hatch (next):
· plan / plan-replay / plan-resumed (uses Markdown renderer —
either render markdown to
Frame OR keep markdown as
ink for now)
· ctx-breakdown (4-color stacked char-bar)
· assistant with branch / reasoning /
non-empty planState (rich sub-blocks)
Migrate the log rendering path off the hand-rolled `log-rows.tsx`
LogRow/LogBlock pipeline onto the Frame primitives from Phase 1.
· src/cli/ui/log-frame.tsx — new module:
· `eventToAtom(e, projectRoot, width): LogAtom` — produces
a `frame` atom for migrated roles (info, warning, error,
step-progress, simple finished assistant turns) and an
`ink` atom (legacy `<EventRow>` + estimated row count) for
roles still pending migration (user, tool, plan / replay /
resumed, ctx-breakdown, assistant-with-reasoning/branch).
· `viewportLog(atoms, scrollOffset, available)` — slicer that
operates on cumulative-row coordinates and returns
`{ atoms, topSkip, bottomSkip, totalRows, maxScrollRows }`.
Frame atoms support row-precise clip via `topSkip`/
`bottomSkip`; ink atoms snap (no partial rendering).
· `renderViewport(v)` — emits each visible row of a frame
atom as `<Box height={1}><Text>{ansi}</Text></Box>`, and
each ink atom as its legacy ReactElement directly.
· App.tsx wiring:
· imports `eventsToAtoms` / `viewportLog` / `renderViewport`
from log-frame; keeps `ScrollBar` / `BottomHint` from
log-rows (they're orthogonal to the slicer)
· the renderer's IIFE replaces `eventToItems` + `sliceLogItems`
+ `slice.items.map(renderLogItem)` with the new pipeline;
`scrollMaxRowsRef` / `lastTotalRowsRef` are filled the same
way so the keystroke handler + scrollbar still work
· the append-anchor effect (`historical` grows while user is
scrolled up) sums `frame.rows.length` for frame atoms and
`atom.rows` for ink atoms — exact for migrated roles.
· Frame composition for these 5 roles uses primitives:
· info / warning / error → accentFrame() = vstack(per-line
rows of indent+body) → borderLeft for the colored bar
· step-progress → vstack(spacer, header, optional body /
note rows). Pill is bg-styled cells via `text()`.
· simple assistant → vstack(spacer, header w/ optional model
badge, borderLeft+padded body, optional repair / stats
lines)
The OLD log-rows.tsx is no longer imported for slicing; only
ScrollBar / BottomHint remain in use. It can be deleted in a
follow-up once we're confident the new path covers every scenario.
Why this is the right shape:
· Width invariant of every Frame is asserted by the Phase-1
tests, so cross-event row arithmetic CAN'T drift
· Topmost / bottommost frame atom in the viewport gets row-
precise clip — a long summary you've scrolled past now still
contributes its lower rows correctly, no more "long entry
disappears when scrolling up" (user complaint that originally
motivated this whole migration)
· Frame data is pure → tests like log-frame.test.ts (17 cases,
added this commit) can assert exact slice behaviour without
spinning up Ink
Tests: 1690/1690 pass (1673 prior + 17 new). Lint clean. Typecheck clean.
Phase 3 next: migrate user / tool / plan / ctx-breakdown to
Frame builders, shrinking the ink-atom escape hatch toward zero.
Once it's empty the entire log becomes one big composable Frame.
Phase 1 of the long-term Frame-compiler architecture. New
`src/frame/` module replaces the runtime dependency on Ink's
layout engine for the log region (Phase 2 next). All pure
functions over a single immutable `Frame` data type — no React,
no Yoga, no estimates.
· types.ts Cell + Frame types. Each Cell carries its own
visual width (1 or 2) and an optional `tail`
marker for the second half of CJK / emoji /
fullwidth graphemes. The row-width invariant
(sum of non-tail widths == Frame.width) is
what every primitive guarantees.
· width.ts Grapheme cluster aware via `Intl.Segmenter`,
so ZWJ emoji like 👨👩👧 count as one cell.
Custom char-width tables for East Asian Wide
ranges (Hangul, CJK Unified Ideographs A-G,
Hiragana, Katakana, Fullwidth, common emoji
blocks). Replaces the `string-width` npm
dependency, which Ink uses but which was the
cause of the dashboard-pill OSC-8 width bug.
· frame.ts Primitives: empty, blank, text, vstack, hstack,
pad, borderLeft, slice, bottom, viewport,
overlay, fitWidth. All composable, all
deterministic. `viewport(stack, offset, height)`
is the slicer that future log rendering will
use — clamps offset, never returns empty for
non-empty input.
· ansi.ts Frame → ANSI string. Style-run batching so we
emit ONE SGR escape per consecutive same-style
run instead of per-cell. Plain-text mode for
snapshot tests; OSC-8 hyperlink open/close
bracketed around linked cells.
· index.ts Public surface for downstream phases.
48 new tests in `tests/frame.test.ts` covering:
· grapheme width for ASCII / CJK / emoji / combining marks / ZWJ
· text wrapping at width boundary, hard-break on \n,
style propagation to every cell
· vstack / hstack with mixed widths and heights
· pad / borderLeft / slice / viewport / overlay / fitWidth
· the row-width invariant, asserted on every composition output
· ANSI serialization: style runs, OSC-8 hyperlinks, plain mode
· CJK split-clip handling in fitWidth (replace orphan head with
space when truncation would split a 2-wide grapheme)
Tests: 1673/1673 pass (1625 prior + 48 new). Lint clean. Typecheck clean.
Phase 2 (next): convert one EventLog role at a time to produce
Frames instead of JSX, replace `log-rows.tsx`'s row pipeline with
the Frame compiler. The current `LogRow`/`LogBlock` distinction
goes away — every event compiles to a Frame, slicer is just
`viewport(vstack(...frames), offset, height)`.
Phase 0 of the long-term Frame-compiler architecture migration:
foundation infrastructure to make sure the rest of the migration
can't accidentally ship broken.
· pre-commit → npm run lint (fast, enforces format + style
before staging)
· pre-push → npm run verify (lint + typecheck + test, full
gate before anything reaches
origin)
`simple-git-hooks` chosen over husky for zero runtime overhead and
no shell-script generation magic — the hooks live as 2-line shell
files in .git/hooks/, installed by `prepare` on every npm install
so a fresh clone gets them automatically.
`verify` script added so CI / contributors can run the same gate
locally without remembering the three sub-commands.
This replaces "remember to run lint before push", which 0.13.0
demonstrated is unreliable (CI failed on 23 Biome diagnostics
because it was forgotten). Foundation for Phase 1 (Frame primitives)
which will land next.
Tests: 1625/1625 pass. Lint clean. Typecheck clean.
Three significant fixes / additions on top of 0.13.1:
1. **Row-granular scrolling.** `sliceVisibleEvents` is replaced by a
pre-flattened row pipeline in `log-rows.tsx`. Each migrated event
role decomposes into one or more `LogRow`s (each ≈ one terminal
line); unmigrated roles fall back to a multi-row `LogBlock` that
wraps the legacy `<EventRow>` component. Migrated this commit:
· info / warning / error / step-progress
· finished assistant turns (header + body lines + stats line)
The slicer picks items by ROW range, the renderer wraps each item
in `<Box height={1}>`, and `overflow="hidden"` + `justifyContent`
handle clipping. Wheel = 3 rows / tick, PgUp/Dn = ~viewport.
Append-anchor sums row counts (not event counts) so the user's
logical scroll position is preserved exactly when content arrives.
The earlier negative-marginTop attempt is gone — Ink's overflow=
hidden does NOT reliably clip negative-margin children (verified
empirically), which let log content bleed up into the chrome and
hide the cost / cache pills. The pre-flatten approach avoids the
layout fight entirely.
2. **Vertical scrollbar + bottom-hint.** A 1-cell column on the
right of the log viewport renders a brand-colored thumb whose
position and size track the visible row range. Hidden when
`totalRows <= viewportRows`. The scrollbar component clamps its
own offset internally so a momentarily-stale `logScrollOffset`
can't make the thumb shrink toward zero in "scrolling into
emptiness" territory. Paired with a `BottomHint` row that surfaces
"↓ N rows below — End to jump" whenever the user is scrolled up,
so newly-arrived content at the bottom is never silently missed.
3. **No more bogus "aborted by user (Esc)".** When the event loop
was blocked >250ms (heavy Ink render on a long log), a
multi-byte sequence like `\x1b` + `[A` (Up arrow) split across
chunks would dispatch as `escape` THEN `upArrow` because the
`setTimeout`-based ESC ambiguity timer fires in the timers phase
ahead of the poll phase where stdin data events queue. The
spurious `escape` triggered `loop.abort()`, killing the running
turn — the same thing the PR #1 author reported as "sometimes
it's saying the user had aborted by pressing esc when I didn't".
Fix: defer the timer's dispatch via `setImmediate`, which runs in
the CHECK phase after POLL — giving any queued data events a
chance to consume the rest of the sequence first. The chunk
handler's `cancelEscTimer` already cancels both the timeout and
the immediate, so a real follow-up byte still wins.
Other polish:
· `maxScrollRows = totalRows - viewportRows` (was `totalRows - 1`)
so Home / max scroll lands on a fully-populated viewport showing
the start of the log instead of one row visible and the rest
empty.
· `useEffect` clamp on `logScrollOffset` snaps it back to
`scrollMaxRowsRef.current` when role-rendering height drifts
mid-stream — keeps the thumb in sync with reality.
Tests: 1625/1625 pass. Lint clean. Typecheck clean.
Three issues from 0.13.0:
· Mouse wheel didn't scroll at all — `useAltScreen` enabled the alt
buffer without enabling mouse tracking, so SGR wheel events from
`stdin-reader` were never produced. The `mouseScrollUp/Down`
handlers in App.tsx were dead.
· A tall LATEST event clipped its bottom rows behind
`overflow="hidden"`, so the user couldn't see the end of long
assistant replies / big diffs. The earlier attempt used negative
`marginTop` for row-granular scrolling, but Ink's overflow=hidden
doesn't reliably clip negative-margin children — content bled up
into the chrome region, hiding the cost / cache / balance pills.
· 0.13.0 was pushed without `npm run lint`, so CI failed on 23
Biome diagnostics (format / organizeImports / useImportType / a
missing useCallback dep).
Mouse tracking:
· `useAltScreen` now turns on mode 1000 + 1006 (basic button + SGR
coords) on mount and disables on unmount / SIGINT / SIGTERM.
Mode 1000 captures press/release only — wheel arrives as buttons
64/65 — without intercepting drag, so terminals that honor
`Shift + drag` for native cell selection (Windows Terminal,
iTerm2, WezTerm, gnome-terminal, kitty, alacritty, VS Code) still
let the user copy/paste cleanly. `/mouse off` is the escape hatch
for terminals that don't bypass on shift.
Long-event bottom-anchoring:
· The middle-region Box now sets `justifyContent="flex-end"` when
`logScrollOffset === 0` so the latest event's BOTTOM aligns with
the bottom of the viewport. A tall final entry's overflow then
clips at the TOP — the user sees the END of the just-produced
content, which is what they want at the "newest" anchor.
· Scrolling up (offset > 0) flips back to `flex-start` (top-anchored)
so reading older content starts from the slice's top edge —
natural "scrolling back through history" mode.
· Row-level scrolling within a single tall event is deferred — it
needs every event role to expose a row-list representation, which
is a larger refactor tracked separately. Until then, offset=0 +
flex-end gives both ends of long content via offset-mode switching.
Lint/typecheck cleanup (none change behavior):
· `import type React` reverted to `import React` (with biome-ignore)
in `SplitDiff.tsx` and `char-bar.tsx` — JSX in classic-transform
mode needs React in value scope.
· `App.tsx` adds `touchedPaths` to handleSubmit's dep array.
· `WelcomeBanner` drops a stale biome-ignore + uses `letter` as
React.Fragment key on the wordmark (REASONIX letters are unique
+ array is fixed, so no array-index-key concern).
· Test teardown for `process.env.HOME` keeps `delete` with a scoped
biome-ignore — assigning `undefined` would set the literal string.
· 16 files auto-fixed by `biome check --write` (format + import order).
Tests: 1625/1625 pass. Lint clean. Typecheck clean.
Breaking: TUI now takes over the alternate screen buffer (\x1b[?1049h),
which means session output is no longer captured in the user's terminal
scrollback after exit. The transcript file (~/.reasonix/sessions/<name>.jsonl)
is the durable record. Trade-off accepted in exchange for a real fixed-
header / scrollable-middle / fixed-footer layout.
Visual:
· single-row chrome: brand + project crumb + pills (mode, cost, balance, cache)
· WelcomeBanner: gradient REASONIX wordmark + 5 quick-start cards + live
web-UI URL when the embedded dashboard is up
· EventLog: ▎ accent bar on every role; ToolPill / ReasoningBlock /
StreamingAssistant rebuilt as bracket text with phase verbs and a
trailing ▌ blinking cursor while streaming
· PlanStepList: tree-style ┣/┗ rows with status icons + char progress bar
· ModalCard: full borderStyle="round" + header rule + footer slot;
every confirm modal (Shell / Plan / Choice / Workspace / Walk / Refine)
inherits the bordered card
· /context now renders a 4-color stacked char-bar via a new
ctx-breakdown DisplayRole
Behavior:
· /checkpoint <name> + /restore — Cursor-style session-scoped snapshot
store at ~/.reasonix/sessions/<root>/checkpoints/, replaces the
rejected auto-commit feature
· EditConfirm uses side-by-side diff (left old / right new)
· /mouse [on|off] runtime toggle; mouse tracking OFF by default so
native shift-drag selection still works
· Idle ticker gate — when nothing is streaming or busy, the 8Hz/1Hz
heartbeats pause so terminal text selection survives
· Dashboard: auto-starts on launch (configurable via --no-dashboard);
URL surfaces on the WelcomeBanner instead of a chrome pill that was
unreliable across terminals; concurrent startDashboard() calls now
de-dupe via an in-flight Promise ref so we don't leak listeners
· /jobs: 5-col table with port detection from job stdout
· /status enriched with cost / cache / budget / dashboard rows
New components:
· SplitDiff.tsx — side-by-side diff renderer with paired cells
· alt-screen.ts — useAltScreen hook with SIGINT/SIGTERM/exit restore
· char-bar.tsx — CharBar / StackedCharBar reusable progress bars
· src/code/checkpoints.ts — snapshot CRUD (15 tests)
Tests: 1625/1625 pass. Build + typecheck clean.
Reads `git diff --staged`, falls back to working-tree diff (with a
warning + refuses to actually commit when source is working tree),
samples the last 10 commits as a style reference, and asks DeepSeek
v4-flash to draft a message that matches the project's existing
voice. The diff IS the spec; the log is the voice.
UX:
- Print draft inside ─── separators
- [a]ccept / [r]egenerate / [e]dit (in $EDITOR) / [c]ancel prompt
- `-y / --yes` skips the prompt (CI / scripted use)
- Multi-line bodies survive: `git commit -F -` reads the message
from stdin, no shell quoting concerns
- Pre-commit hook output / git's confirmation are inherited so the
user sees the same final commit screen they'd see from `git commit`
Safety:
- Fails fast when not in a git repo
- Refuses to commit a working-tree-derived draft (staging area is
empty so `git commit` would fail anyway) — prints draft for the
user to copy after `git add`
- Caps diff at 80KB (head + tail with truncation marker) so a giant
refactor doesn't blow the model's prompt budget; warns the user
the resulting draft will likely be vague
Default model is v4-flash — drafting a commit message doesn't need
pro. `-m` overrides for cases where flash undercooks the message.
When a user reports "Reasonix is broken", the support flow has been:
"check API key, try a chat, look at config.json, check Ollama if you
use semantic, …" — now `reasonix doctor` runs all of that in one go.
8 checks, run in parallel (api-reach has an 8s timeout, the rest are
local + sub-millisecond). Each returns ok / warn / fail; the summary
line counts them. Exit 1 on any fail so CI / install scripts can
fast-fail on misconfiguration; warn → exit 0.
Checks:
- api key env DEEPSEEK_API_KEY → config.apiKey → fail
- config ~/.reasonix/config.json present + parseable + key fields
- api reach /user/balance reachable + balance reported
- tokenizer data/deepseek-tokenizer.json.gz on disk + readable
- sessions session count + total bytes + flag stale ≥90d
- hooks global + project hook count, parse-clean
- ollama skipped when no semantic index built; otherwise
binary on PATH + daemon up + embed model pulled
- project cwd has any of .git / REASONIX.md / package.json / pyproject.toml /
Cargo.toml / go.mod — heuristic for "is this a project root?"
Plain text output (no Ink) so it works even when Ink can't mount —
the case this command is most useful in. ANSI color when stdout is
TTY, gracefully bare on TERM=dumb / piped.
Off by default — Reasonix's cost story is 'cheap by design,' adding a
silent cap at install would just confuse new users.
Opt in via:
- CLI flag: `reasonix chat --budget 5`, same on `code` / `run`
- Slash mid-session: `/budget 5` to set, `/budget off` to clear,
`/budget` alone to show current spend / cap / percentage
- Config-file equivalent: not added yet; per-session override is the
primary surface
Loop semantics (src/loop.ts):
- step() opens with a budget gate that runs BEFORE any state mutation,
so a refusal leaves the loop unchanged — user corrects the cap and
re-issues the same prompt cleanly.
- spent ≥ cap → yields an `error` event with a clear hint about
/budget, returns immediately. Turn counter doesn't advance.
- spent crosses 80% of cap (one-shot, sticky via _budgetWarned) →
yields a `warning` event noting how close the next turn is.
- setBudget(usd|null) is the mutator that resets the sticky flag so a
user who bumps the cap mid-session sees a fresh threshold message.
UI (src/cli/ui/StatsPanel.tsx):
- One-row `budget .XXXX / .YY (Z%)` indicator below the metrics
block, hidden when `budgetUsd === null`. Color: dim under 80%,
amber 80-99%, red ≥100%.
Tests: 6 new cases in tests/loop.test.ts covering default off-state,
80% one-shot warn, no-repeat warn, refusal at cap, setBudget(null)
unblocks, setBudget(usd) re-arms warning. 1610 pass.
jobs.ts:
- ready-signal regex used to test against the FULL job.output buffer
on every chunk, then ALSO against the chunk. With 9 regexes ×
growing buffer × per-chunk dispatch, that's quadratic CPU during
startup of a chatty dev server. Replace with a 1KB sliding window
for cross-chunk matching — bounded cost regardless of total output.
web.ts:
- webFetch had no upper bound on response body size. `await resp.text()`
pulls the entire body into memory before applying the 32K char cap;
pointing the model at a 50MB changelog or a runaway server with no
Content-Length pegged the heap. Now:
- 10MB hard cap on raw body bytes
- pre-flight check against Content-Length when the server provides it
- streaming reader for chunked / undeclared-length responses, aborts
cleanly once total bytes cross the cap
Tests: +2 web cases (declared-length refusal, mid-stream cap). 1604 pass.
The default spawner appended every chunk into a JS string with no
upper bound. A buggy or runaway hook (`cat largefile`, infinite
`yes`, etc.) accumulated unbounded into Reasonix's heap until its
timeout fired — 5s for blocking events, 30s for logging hooks, plenty
to push the heap past comfortable limits.
Now:
- per-stream byte cap of 256KB (matches what hooks are actually for —
short error messages, validator stderr, `git status --short`)
- raw Buffer collection + decode-once-at-close, mirroring shell.ts —
protects against multi-byte UTF-8 sequences split across chunks
- HookSpawnResult / HookOutcome carry an optional `truncated` flag
- formatHookOutcomeMessage suffixes "(output truncated at 256KB)"
so users know the loop didn't see the full output
Tests:
- truncation flag propagates from spawner → outcome
- format message surfaces the truncation tag
- existing 26 hook tests all pass unchanged
1602 tests pass (+3).
CI failed on lint after the 0.12.17 push:
- src/memory.ts: collapse multi-line string concat into one template
literal (lint/style/useTemplate)
- src/usage.ts, tests/memory.test.ts, tests/session.test.ts: biome
formatter line-width preferences (auto-fixed via npm run lint:fix)
No behavior change. 1599 tests still pass.
P0 — true bugs:
- mcp/client: clientInfo.version was hardcoded "0.3.0-dev"; now imports
VERSION so MCP servers see the real client version
P1 — user-facing improvements:
- at-mentions: new listFilesWithStatsAsync — TUI mount no longer blocks
on hundreds of synchronous statSync calls; picker fills in once the
async walk completes (typically <200ms)
- usage.jsonl: auto-compaction past 5MB drops records older than 365d
so heavy users don't accumulate unbounded telemetry on disk
- session: pruneStaleSessions() helper + new /prune-sessions slash
command; /sessions listing flags entries idle ≥90d
- ImmutablePrefix: fingerprint is now cached + invalidated only by
addTool. Cuts the per-render JSON.stringify+sha256 cost AND adds
a verifyFingerprint() drift detector for catching future mutations
that bypass addTool — Reasonix's prefix-cache hit ratio is the
central KPI; silent prefix churn was the largest unguarded risk
UX polish:
- streaming row: "(no content)" → "(empty body — likely tool-call only)"
Tests:
- memory: fingerprint cache + dedup behavior + drift detection (5 new)
- at-mentions: listFilesWithStatsAsync mirrors sync contract (5 new)
- usage: compaction triggers past threshold, drops only old records
- session: pruneStaleSessions semantics + cutoff arg
- new tests/event-log-streaming.test.ts: lastLine bounded slicing
Total: 1599 tests pass (+20).
- FLUSH_INTERVAL_MS 100→33ms (≈30Hz) + REASONIX_FLUSH_MS env override
- lastLine bounded to tail*4 chars (was O(N) regex on full streaming buffer)
- phase pill padEnd(8) so WAITING/THINKING/DISPATCH/WRITING transitions
don't reflow the row
- ticker: split fast(120ms) + slow(1000ms) contexts; useElapsedSeconds /
UndoBanner countdown / ModeStatusBar jobs poller move to slow tick
- streaming row: drop the ◆/◇ pulse animation, single braille spinner
carries the liveness signal — one less Text node + one less fast-tick
subscriber
- citation validateCitation: mtime-keyed lineCount cache (256 LRU) so
repeated cites of the same file skip readFileSync
Every user-facing string that still said fast/smart/max now says
auto/flash/pro — the canonical names presets have used since the
autoEscalate split. Touches CLI flag descriptions (chat/run/code),
/help's preset table, /preset's argHint/completer, the slash
handler's usage line.
Old config.json files keep working: resolvePreset still maps
fast → flash·effort=high, smart → auto, max → pro. What changed
is the interactive surface — /preset fast now prints usage instead
of silently doing the right thing, so the in-chat vocabulary
matches what's documented.
Three TUI confirmations the dashboard couldn't see — change_workspace,
plan checkpoints, plan revisions — now mirror to the web modal layer
with the same Switch/Deny/Continue/Revise/Stop/Accept/Reject choices
the terminal exposes.
Loop fix: when DeepSeek emitted change_workspace + write_file in one
parallel batch, the write was firing against the OLD sandbox before
the user could approve the modal — silent data loss into the wrong
project. Subsequent calls in the same batch now get a synthetic
"deferred — re-issue next turn" result; tool_call ↔ tool pairing stays
valid for DeepSeek's next-turn validator. Test in tests/loop.test.ts.
Dashboard polish:
- In-flight row shows the active tool + key args (path / command /
char count) once tool_start fires, so write_file no longer feels hung.
- ErrorBoundary stops auto-recovering after 3 catches and renders a
manual "Try again" button — no more silent flickering loop.
- .modal-cmd gets overflow + max-height + word-break so a pathological
multi-kilobyte command can't push the rest of the panel offscreen.
Two stacked bugs let the auto-scroll keep yanking the user back
to bottom on every delta:
1. The "are they scrolled up?" listener attached via
document.querySelector(".chat-feed") on mount — but the feed
was conditionally rendered (only after the first message), so
on a fresh session the listener never attached and the
shouldAutoScroll flag was never flipped to false.
2. The auto-scroll's own scrollTop = scrollHeight write triggers
a scroll event, which the listener was treating as a user
scroll and snapping back to "at bottom".
Fixes:
- .chat-feed always rendered (empty state moved inside) + ref
attaches the scroll listener on first paint.
- autoScrollInFlight ref gates the listener so only genuine
user wheel/drag flips the guard.
Two questions from the user:
- "after index ends, does it auto-register so chat can use it?"
- "no index → put a dismissible warning at top of Chat?"
Both yes now.
Loop / prefix
- ImmutablePrefix.addTool(spec) appends to a (now-mutable) backing
array, exposed through a readonly getter. Cost: one cache miss
on the next turn after a tool's added; cheaper than restart.
- DashboardContext.addToolToPrefix wired from App.tsx.
Server
- runIndex on success: registerSemanticSearchTool + addToolToPrefix
- /api/overview returns semanticIndexExists (cheap stat)
Dashboard
- Top-of-Chat banner when no index, with "Build it →" (navigates
to Semantic tab via appBus) + dismiss × (persists in localStorage)
Previously the panel just said "not reachable" with a copy-paste
command list. Now it distinguishes the three failure modes and
offers a one-click action for the two that we can resolve:
- binary missing → Install Ollama card (macOS / Windows / Linux)
- daemon down → "Start daemon" button (ollama serve, detached)
- model missing → "Pull <model>" button with live progress
- all ready → Index buttons enable
Server adds:
- GET /api/semantic returns the full checkOllamaStatus shape
- POST /api/semantic/ollama/start
- POST /api/semantic/ollama/pull (fire-and-forget; PULLS map
carries status + last log line; SPA polls /api/semantic)
The "turn in flight" row used to sit at the top of the chat panel,
far from the user's eyes (which are at the input). Move it to a
proper InFlightRow above the ChatStatusBar, and fill it with the
live signals the TUI showed but the web didn't:
⠋ thinking · 2.3s · reasoning 1,204 ch · out 0 ch · [Abort]
- Phase: thinking / streaming / waiting based on which streaming
channel is growing
- Elapsed seconds tick every 500ms so motion is visible even
through long deltas
- Character counts derived from the existing `streaming` state
Previously building the index meant exiting the TUI to run
`reasonix index`. Now the dashboard has a Semantic tab that
kicks off `buildIndex` in-process and streams progress to the
SPA so users can keep coding while it runs.
Server
- src/server/api/semantic.ts — GET status / POST start / POST stop
- Per-root JobRecord captures BuildProgress via onProgress
- Wired into the /api router
Dashboard
- New Semantic sidebar tab; polls every 1.2s while running
- Shows Ollama reachability, index existence, live phase + counters
+ percentage bar + elapsed time
- Index / Rebuild / Stop buttons with appropriate disabled states
- Standalone (non-attached) dashboards explain why the panel is empty
0.12.7 put the URL + description on the same Ink row. On terminals
that hide the OSC 8 escape, Ink miscounts the escape bytes as visible
width — the description wrapped right through the middle of the URL.
Two stacked rows now:
◇ web open the dashboard in a browser (chat · files · stats · settings)
http://127.0.0.1:NNNN/?token=...
The URL is the only content on its line, so even a bad width
measurement can't collide with anything.
Most users never discovered /dashboard existed. Now the URL is in the
status panel from the first turn, on its own row with a description.
- App auto-calls startDashboard() on mount; --no-dashboard opts out
- StatsPanel renders a dedicated row:
◇ web http://127.0.0.1:NNNN/?token=... open the dashboard
in a browser (chat · files · stats · settings)
- URL wrapped in an OSC 8 hyperlink — clickable in iTerm2 / WezTerm /
Windows Terminal / VS Code / recent gnome-terminal; copy-pasteable
in older ones
- noDashboard prop threaded through App + chatCommand + codeCommand
Site
- Hero badge + term-anim header now read the live npm version. i18n.js
fetches https://registry.npmjs.org/reasonix/latest on init, caches
it in localStorage, exposes Reasonix.version() / onVersionChange().
- term-anim subscribes and patches the .tw-ver pill in place when the
fetch resolves, so we don't have to rerun the whole animation.
- Hardcoded "v0.6" / "v0.6.0" replaced with a {version} token in the
translation strings; only fallback constant left to bump on major
cuts (and the npm fetch overrides it on every visit).
README (en + zh)
- New Web dashboard section right after Quick start (0.12 headline).
- /preset and --preset references switched from the dropped legacy
fast/smart/max vocabulary to the current auto/flash/pro.
- Stale `Reasonix v0.5.21 · ...` example refreshed to the 0.12-era
panel header.
Without this, a Windows checkout with autocrlf=true lands the working
tree with CRLF even though the repo stores LF. Biome rejects CRLF, so
prepublishOnly's `npm run lint` step fails on tests/resolve.test.ts.
Pinning eol=lf for all text files makes the working copy match what
Biome expects and what the repo stores, on every platform.
Editor
- Side-by-side diff in the edit-pending-review modal (red/green tint,
hljs syntax highlighting, paired LCS rows). Modal payload gained
`search`/`replace` fields (the truncated `preview` stays for old
clients).
- Local CodeMirror bundle (`dashboard/codemirror.js`, ~937 KB) via
scripts/bundle-codemirror.mjs — replaces 21 esm.sh imports. Server
serves it through `serveAsset`.
- Markdown view modes: Edit / Split / Preview segmented control;
separate Marked instance for preview so chat-renderer customizations
don't run on user files.
- Sidebar collapses to icons (52px), persisted in localStorage.
CI / regression fixes
- Restore legacy preset migration (fast → flash+high, smart → auto,
max → pro) so `tests/resolve.test.ts` passes again.
- Storm breaker no longer hardcodes a mutating-tools list. It accepts
an `isMutating` predicate; `loop.ts` wires it from the existing
ToolRegistry `readOnly` / `readOnlyCheck` flags. Buffer entries are
tagged read-only vs mutating: a mutating call drops prior reads
(read→edit→verify cycles no longer trip), but identical mutator
calls still suppress on the threshold.
1571/1571 tests pass.
- Pin @lezer/highlight and @lezer/common in esm.sh ?deps= so all
CodeMirror packages share one copy. Previously each pack pulled
its own, so highlight tags compared by identity stopped matching
and oneDark silently produced no colors.
- Add markdown preview button (Edit/Preview toggle, only on .md tabs)
- Use a separate Marked instance for the preview so chat-specific
diff/SEARCH-REPLACE code handling doesn't run on user files
- New Editor tab in the sidebar, mounts full-width inside .main
- main-editor modifier strips panel padding so editor fills viewport
- Drawer entry still works for "click path in chat" deep-link
- Tabs lifted out of editor-main into a full-width bar (VS Code style)
- oneDark + defaultHighlightStyle reorder so colors actually show
- Gutter restyled (dark bg, dim numbers, active-line highlight)
- foldGutter + highlightActiveLineGutter added
- autocompletion(activateOnTyping: true) + completionKeymap
- Autocomplete popup styled to dark theme
Split /init into its own patch release. /init landed after the
0.11.1 commit, and it's a small but distinct addition (no fix /
no behavioral change to existing flows), so a separate version
makes the changelog story cleaner: 0.11.1 is the workspace-switching
release, 0.11.2 is the project-init release.
Two CHANGELOG fixes ahead of publishing 0.11.1:
1. Add a bullet for /init under 0.11.1 Added. /init was committed
after the 0.11.1 version bump but before publication, so the
shipped 0.11.1 actually includes it. Update the headline to
acknowledge the addition.
2. Restore the '## [0.11.0] — 2026-04-27' header that was clobbered
when the 0.11.1 entry was inserted earlier — the 0.11.0 content
was orphaned without a heading.
New slash command that asks the model to scan the project and write a
concise REASONIX.md baseline, removing the friction of having to
hand-author one. The file is auto-pinned into the system prompt every
launch, so a good baseline pays back on every subsequent turn.
Mechanism: handler emits a structured user-turn prompt via `resubmit`
that hard-constrains the model to a fact-only document with sections
for Stack / Layout / Commands / Conventions / Watch out for. The
"output ≤ 80 lines / 3KB" cap and "STOP after writing" line are
load-bearing — without the cap REASONIX.md would burn cache budget
every turn; without STOP flash chains follow-up suggestions and
wastes tokens.
Reuses existing filesystem tools (read_file / directory_tree /
edit_file / write_file) — no new tool, no new pipeline. The
generated content lands as a pending edit in the normal review queue,
so the user audits it via /apply before disk writes.
Edge cases:
- Outside code mode: handler returns "/init only works in code mode"
with the `reasonix code` invocation hint.
- REASONIX.md already exists: refused, points at `/init force` to
regenerate. Force matching is case-insensitive.
Five tests covering: refuse outside code mode, fresh-init resubmit
shape (verifies length cap + STOP marker survive future tightenings),
existing-file refusal, force override, force case-insensitivity.
1487 tests passing.
DeepSeek now ships an official Anthropic-compatible endpoint at
api.deepseek.com/anthropic, so the previous 'Claude Code can't run
DeepSeek' framing is factually wrong: Claude Code talks to it
unmodified.
The defense moves from 'protocol incompatible' to 'cache mechanic
incompatible':
- Anthropic native cache is marker-based: cache_control on a message
caches up-to-this-marker as a content-addressed unit. Claude Code's
loop is designed around this — markers compensate for an otherwise
non-stable prefix.
- DeepSeek's auto-cache is byte-stable: it fingerprints the literal
byte stream from 0. No markers.
- DeepSeek's compat endpoint IGNORES cache_control. Claude Code's
main caching strategy disappears; auto-cache misses because the
prefix wasn't byte-stable to begin with.
Reasonix's loop was designed around byte-stable prefix from line one
(append-only invariant). That's why 94.4% on the same workload
where a cache-hostile baseline lands at 46.6%.
Restructure the section into two subheaders:
- 'But DeepSeek now has an Anthropic-compatible API...' — handles
the Claude Code case head-on with DeepSeek's compat table and the
marker-vs-byte-stable contrast
- 'What about Aider / Cline / Continue?' — handles the natively-
DeepSeek tools, keeps the existing 5-row DeepSeek-specific quirks
table (R1 thinking leak, schema flatten, repair, effort, tail-only
compaction)
Mirror everything in README.zh-CN.md.
The 'Why Reasonix?' section explained why we beat generic competitors,
but didn't cover the sharper rebuttal: 'I'll just point Claude Code
(or Aider, Cline, Continue) at DeepSeek and get the same economics
without your tool.' Without an answer prospects bounce silently.
Add a third subsection to 'Why Reasonix?' that handles it head-on:
- Claude Code: not really. It's hard-bound to Anthropic's API —
auth, tool-schema shape, <thinking> parsing all assume Claude.
A translation proxy (claude-code-router) gets you protocol
compatibility but every Anthropic-tuning becomes overhead and
every DeepSeek-tuning is unreachable.
- Aider / Cline / Continue: yes, they support DeepSeek and you get
the cheap token price. What you don't get is the DeepSeek-
specific loop work, captured in a 6-row table contrasting how
each layer (cache markers, reasoning blocks, tool schemas,
malformed JSON, reasoning-effort, compaction) differs between
Anthropic/OpenAI assumptions and DeepSeek reality, with what
Reasonix does about each.
Then drive the cache-stability claim home with concrete numbers:
generic harnesses land at 40-60% cache hit on DeepSeek vs 94.4% for
Reasonix on the same workload, which at DeepSeek's pricing is ~2.5×
on input cost alone.
Mirror in README.zh-CN.md.
The README read like a feature manual — "here's everything we have"
without ever telling a new visitor why they'd pick Reasonix over
Cursor / Claude Code / Cline / Aider. Most prospects bounce because
the unique value (DeepSeek's price × cache-first prefix engineering)
isn't visible above the fold.
Insert a "Why Reasonix?" section between Quick start and the code-
mode walkthrough, with three pieces:
1. Three short pitches: cost economics that actually land in your
bill (~30× cheaper than Claude Sonnet, with 94% live cache hit
verified in benchmarks/), terminal-native (no Electron / IDE
plugin), MIT-licensed and hackable end-to-end.
2. A side-by-side comparison table — Reasonix vs the four
alternatives, on backend / cost / runtime / license /
cache-hit / MCP / plan mode / skills / edit review / workspace
switch / cost dashboard / sandbox enforcement.
3. An honest "Pick something else when" section pointing at Aider,
Cline, Cursor, and Claude Code's IDE mode for the cases where
Reasonix's tradeoffs don't fit (multi-provider, IDE integration,
PhD-level reasoning benchmarks, fully-local).
Also tighten the subtitle under # Reasonix to lead with the cost
angle instead of "no LangChain" (audience-correct, but doesn't
help conversion). Mirror everything in README.zh-CN.md. Bump the
test-count claim in Development from 1007 to 1482.
Add two ways to pivot to another project mid-session:
- /cwd <path> — user-typed slash; validates target, applies via
applyCwdChange (re-registers filesystem/shell/memory tools,
reloads hooks, syncs loop.hookCwd, re-registers run_skill).
MCP servers stay on the launch root (no reconnect handshake).
- change_workspace tool — model-callable, gated on a
WorkspaceConfirm modal. Tool fn always throws
WorkspaceConfirmationError; App detects the marker, mounts
Switch/Deny modal; approval drives the same applyCwdChange path.
No always-allow option — switches are per-target.
Fixes that surfaced from real-use workspace-switching attempts:
- loop: reset _turnAbort after Esc-abort branch returns. Prior
carry-abort logic re-aborted at iter 0 on every subsequent
step(), poisoning the session until restart.
- shell: collect Buffer chunks instead of decoding per-chunk;
smartDecodeOutput tries strict UTF-8, falls back to GB18030 on
Windows when invalid sequences detected. Fixes mojibake on
Chinese-Windows cmd.exe error messages (chcp 65001 doesn't
cover them — they come from a localized resource DLL).
- markdown: gate stripMath pipeline on a math-marker pre-check.
The catch-all \[a-zA-Z]+ → "" had been wiping \TEST out of
Windows paths like F:\TEST1, rendering them as F:1.
- prompt: tell the model to call change_workspace (or surface
/cwd) when the user asks to change projects, instead of
fumbling with cd /d / pushd / 2>&1 shell hacks.
Bump 0.11.0 → 0.11.1, CHANGELOG entry covers all four fixes plus
the two new entry points. 1482 tests passing.
Pillar 1 — semantic search (opt-in, local):
- src/index/semantic/{embedding,chunker,store,builder,tool,preflight,
ollama-launcher,i18n}.ts — Ollama-backed local embedding index for
the project. Cosine search over Float32 JSONL store, mtime-based
incremental rebuild, fault-tolerant per-chunk embedding so a single
oversized file doesn't kill the whole build.
- New CLI: `reasonix index [--rebuild --model --ollama-url --yes]`
with TTY-aware Braille spinner + elapsed-time + phase labels (no
more "stuck on building…"). Non-TTY path still emits one line per
phase for CI logs.
- Preflight checks Ollama binary / daemon / model and prompts (or
--yes auto) to fix what's missing. All user-facing strings route
through src/index/semantic/i18n.ts (zh/en, system-locale auto-detect
via REASONIX_LANG → LANG/LC_ALL → Intl.DateTimeFormat).
- `/semantic` slash inside reasonix code shows status + how to enable.
No startup auto-prompt — opt-in via the explicit shell command,
same pattern /setup and /update use.
- semantic_search tool registers only when an index exists.
- code-mode system prompt gets a routing fragment when the tool is
registered, telling the model to prefer semantic_search for
descriptive queries and fall back to grep for exact tokens.
Pillar 2 — fix subagent Esc race:
- DOM addEventListener("abort", …) doesn't fire for already-aborted
signals. If the parent aborted before the listener attached, the
child ran free until iter budget. Sync-check .aborted at attach.
- loop.ts step() reassigning _turnAbort lost prior aborted state.
Forward the carry-over so abort() called before step() runs still
kills it at iter 0.
- subagent treated forcedSummary assistant_final events as success,
so /skill claimed an aborted run finished normally. Now surfaces
forcedSummary as an error → success: false.
Tests (+27): chunker (incl. window-split + hard-truncate-overlong-line),
store roundtrip, embedAll null-slot fault tolerance, i18n locale
detection + EN/ZH dicts, /semantic slash status renderer, bootstrap
contract (no startup prompt), prompt routing fragment, and a regression
test for subagent already-aborted signal handling.
- docs/ landing page for GitHub Pages with i18n auto-switch (en/zh
via navigator.language → localStorage), terminal-themed dark UI,
hero animation that mirrors the real TUI rendering primitives
(◇/◆ role glyphs, yellow tool pills, rounded cyan EditBlockRow
with - red / + green diff lines, info-row pending/applied status)
- README.zh-CN.md mirroring the English README structure
- Language switcher header on README.md → zh-CN + website
- /loop <interval> <prompt> repeats the prompt every <interval> (5s..6h
bounds, fractional + s/m/h units). One active loop per session — re-
issuing replaces it. Cancellation: /loop stop, Esc, /clear, /new, exit,
any user-typed prompt (loop-fired submits set a ref-flag so the timer's
own re-submit doesn't self-cancel). LoopStatusRow ticks the countdown
every second under the modeline. Skips a tick (re-arm in 1s) when busy
rather than queueing duplicate submits.
- /walk steps through the pending-edits queue one block at a time using
the existing EditConfirm modal (per-block scrollable diff). y apply ·
n reject · a apply rest · A flip AUTO · Esc cancels (keeps remaining
queued). Each pick mutates pendingEdits via the existing /apply [N]
partial-apply path, then advances to the new "first" block.
- `/security-review` and `/test` ship as new built-in skills. Security-review
is a subagent (read-only, severity-tagged); /test is INLINE (parent must
see proposed edits) and runs npm/pnpm/yarn/pytest/go/cargo, fixes failures,
re-runs, stops after 2 failed attempts on the same line.
- `#g <note>` writes to ~/.reasonix/REASONIX.md (global, never committed),
symmetric to the existing project `#note`. New applyGlobalReasonixMemory
loader pins the file into every session's prefix. `\#g foo` escape lets
users send "#g foo" verbatim to the model.
- `@https://...` URL mentions: fetch via existing webFetch (HTML strip,
truncate to fit), inject under [Referenced URLs]. In-memory per-session
cache so the same URL twice fetches once. Trailing-punctuation strip
preserves query strings while peeling off sentence dots and unmatched
brackets.
- YOLO edit-mode (third stop on the Shift+Tab cycle): apply edits AND
auto-approve every shell command. Wired via a getter on registerShellTools'
allowAll so flipping the mode mid-session takes effect on the next dispatch
with no re-registration. Red modeline pill warns the user it's hot.
- `#note` prompt prefix appends a one-liner to <root>/REASONIX.md (auto-creates
with header). `\#literal` escape passes a real `#text` to the model; `##`
headings always pass through.
- `reasonix -c` / `reasonix chat -c` resume the most-recently-touched session
without the picker. Falls back gracefully + warns when no sessions exist.
Helper extracted to src/cli/resolve.ts so the lookup is testable without fs.
- Built-in `review` skill (subagent runAs) — reviews current branch diff,
reports verdict + per-issue file:line citations, read-only contract.
- `/apply 1` / `/apply 1,3` / `/apply 1-4` (and `/discard` likewise) — pending
preview labels each block `[N]` when 2+ are pending; partial apply leaves
the rest in the queue. Pure parseEditIndices + partitionEdits helpers.
User confirmed wheel-up still doesn't scroll in VSCode integrated
terminal even after 0.7.11 dropped the resize listener and the
\x1b[3J scrollback erase. The startup \x1b[2J was the remaining
suspect: xterm.js (VSCode's terminal) implements 2J in a way that
appears to disrupt scrollback anchoring even when scrollback bytes
themselves are preserved.
Fix: don't write any clear escapes at all. Mount Ink directly. The
user's previous shell prompt stays visible above the launch point
and wheel-up scrolls naturally. Trade-off: the launch isn't a
'clean canvas' anymore. /clear inside the TUI still works for an
explicit reset.
This stacks on 0.7.10's Ctrl+P/N history-recall binding and 0.7.11's
resize-listener removal. Together: wheel scroll works, history
recall doesn't get clobbered by wheel-as-arrow events, and chat
history survives terminal resize.
User reported on VSCode integrated terminal: resizing the window
loses chat history and mouse wheel can no longer scroll up. Two
related symptoms, one cause:
- VSCode's terminal interprets \x1b[3J (xterm scrollback erase)
aggressively — wipes everything, not just the saved-off
history. Combined with my prepended resize listener that wrote
\x1b[2J on every resize, every drag was wiping scrollback. With
nothing in scrollback, wheel-up has nothing to scroll to.
- Even \x1b[2J (visible-only erase) on each resize tick takes
the chat history with it on terminals where the spec is
interpreted loosely.
Fix: drop the resize listener entirely; drop \x1b[3J from the
startup clear. Startup now only erases the visible viewport so the
previous shell prompt scrolls up into scrollback rather than
vanishing. Resize ghosts (Ink's eraseLines miscount on wrap)
return as a known limitation; `/clear` is the documented manual
reset.
History recall stays on Ctrl+P/N (0.7.10) so wheel-as-arrow events
don't clobber the prompt.
Mouse wheel on Windows Terminal + ConPTY translates to up/down
arrow key events for raw-mode child processes. Indistinguishable
from keyboard arrows at the byte level. With history recall bound
to up/down on empty buffer, every wheel-scroll on the prompt was
clobbering it with a recalled prior message.
Fix: rebind history recall to Ctrl+P (prev) / Ctrl+N (next), the
bash readline convention. Up/down arrows now no-op on a single-
line buffer and only move the cursor across lines in a multi-line
draft. Wheel scrolls again belong entirely to the terminal.
Tests updated to reflect the new binding. Placeholder hint mentions
Ctrl+P/N alongside the Ctrl+J newline hint.
Alt-screen fixed the resize ghost stacking but cost the user wheel
scrollback — terminals translate wheel to up/down arrow keystrokes
for alt-screen apps, and those land in PromptInput's history recall
instead of scrolling chat history. Trade-off the user rejected.
Reverted to main-screen mode:
- Restored startup viewport+scrollback clear (\x1b[2J\x1b[3J\x1b[H).
- Restored prepended resize listener that writes \x1b[2J\x1b[H
before Ink's own resize handler runs.
- Added REASONIX_DEBUG_RESIZE env-gated stderr diagnostic so we
can verify the listener fires on the user's specific terminal +
host (Windows Terminal + PowerShell suspected of not
surfacing the 'resize' event consistently).
Resize ghost stacking returns as a known limitation; `/clear` resets
the screen state. This is the trade-off for keeping wheel scrollback
working.
Two unrelated fixes shipping together as 0.7.8:
1. Resize ghost stacking on chat.tsx: previous attempts (stdout 2J
listener, ticker pause, killing animations) all reduced the
symptom but couldn't fix it — Ink's eraseLines fundamentally
miscounts logical vs visible rows on wrap, and resize re-renders
pile up stale frames in scrollback.
Fix: enter the terminal's alternate screen buffer (\x1b[?1049h)
on Ink mount, leave it (\x1b[?1049l) on unmount. This is what
vim, less, htop, lazygit, etc. do. Inside alt-screen the
terminal owns the entire viewport; resize is handled natively
and there's no scrollback to leak ghosts into. Trade-off: chat
scrollback above the live region is gone after exit (returns
to the user's pre-launch shell view). /history still dumps
prior turns on demand.
Removed: the previous \x1b[2J\x1b[3J\x1b[H startup clear and
the prepended resize listener — both made redundant by alt-
screen.
2. Citation validator was reporting / as
'file not found' even when the source is /
. Models routinely cite the wrong extension when
they remember the file. Added a sibling-extensions probe in
validateCitation: when the literal path fails, try common
siblings (.ts↔.tsx, .js↔.jsx↔.mjs↔.cjs, .ts↔.mts↔.cts).
Genuinely missing paths still flag.
0.7.6 tried to mitigate ghost stacking on resize via stdout-clear
listener + ticker pause. User confirmed those still produce 3-4
stacked panels when the window is shrunk and re-expanded.
Root cause: Ink's eraseLines(N) counts LOGICAL lines, not VISUAL
rows after wrap. The 100+ char top/bottom gradient bars on the
StatsPanel always wrap on narrow widths; the per-tick wordmark
animation and per-tick prompt-bar gradient flow re-render every
120 ms; together they layer ghost frames on every resize event.
Real fix:
- Remove the top/bottom GradientRule entirely from StatsPanel.
Those were the dominant wrap source — wide bars on a narrow
terminal were the eraseLines miscount's main payload.
- Wordmark drops its useTick subscription. Sweep is now a
static teal→fuchsia gradient computed once per render. Brand
mark ◈ stays bold but no longer pulse-blinks.
- PromptInput drops its useTick subscription. Left-bar gets a
static row-indexed gradient color, cursor is a solid block
with no blink.
Net effect: no per-tick re-render anywhere in the live region
except the existing spinners (StatusRow, OngoingToolRow,
SubagentRow) — those are short single-row strings that don't
wrap. Ink's eraseLines now matches visible row count because
nothing in the panel wraps. Resize produces at most one
state-change re-render, which the chat.tsx 2J listener catches.
Visual loss: brand wordmark no longer flows colors over time, the
prompt cursor doesn't blink. Visual structure (pills, color, role
bands, full-height left bars on assistant messages) is unchanged.
Bumps to 0.7.7.
User reported StatsPanel rendering 3-4 stacked ghost copies when the
terminal is resized. Two-prong fix:
- chat.tsx — prepended stdout 'resize' listener writes \x1b[2J\x1b[H
on every resize event so Ink's next re-render starts at cursor
home, neutralizing eraseLines's stale storedHeight count.
- App.tsx — new isResizing state debounced from stdout 'resize'
events (400 ms tail). While the resize burst is in flight, the
TickerProvider's disabled flag is set, which kills the 120 ms
tick. With the tick frozen the per-frame animations (wordmark
gradient flow, gradient rule flow, prompt left-bar flow, cursor
blink) stop firing — they were the multiplier turning a single
resize event into a stack of N ghost frames. After 400 ms with
no further resize the ticker resumes and one clean render
catches up.
Together: each resize event is followed by exactly one Ink re-render
on a freshly-cleared viewport, with no animation re-renders piggy-
backing on top.
Bumps package version to 0.7.6.
Before Ink mounts, write \x1b[2J\x1b[3J\x1b[H so the user lands on a
fresh canvas — no leftover shell prompt, last command output, or
unrelated terminal history bleeding into the first frame. Same
sequence the /clear slash command already uses. TTY-gated so CI /
piped runs don't get raw escapes in their captured stdout.
Root cause: at narrow widths the StatsPanel header (wordmark +
version + model + N pills) and the PromptInput's typed line both
wrap to multiple visual rows. Ink's eraseLines counts logical rows,
not visible rows, so each tick (~120 ms re-render driven by the
wordmark / gradient bar / cursor blink animations) miscounts the
erase and leaves ghost rows in scrollback. Several seconds in the
screen looks like it's continuously scrolling — the user-reported
'screen flashing' symptom.
Fix:
- StatsPanel — added `animate = columns >= 100` gate. Below the
threshold the gradient rules + wordmark freeze (no per-tick
color shift), and the secondary pills (harvest / branch×N /
reasoning effort) hide so the header always fits one row. The
primary pills (PLAN / AUTO / REVIEW / ⇧ PRO) and metrics row
stay; only the optional decorations are dropped.
- PromptInput — same gate on the prompt. Below 100 cols the
left-bar gradient freezes and the cursor stops blinking. Above
100 cols nothing changes.
- 100-col threshold matches NARROW_BREAKPOINT closely (120) but is
a hair tighter — the panel can survive 80–100 cols without
wrapping if we drop the secondary content.
The bordered Boxes added recently (assistant left band, user left
band, edit-file diff band) live inside `<Static>`, render once per
event, never re-render, so they don't contribute to the per-tick
miscount.
User reported H3 was showing the literal sigils ('### 📖 代码探索')
inside assistant output, which defeats the heading semantic. Fixed:
- H1 cyan pill, H2 violet pill, H3 fuchsia pill, H4+ bold accent
with a leading ▸ marker.
- Sigils (#, ##, ###) are stripped at the pill — the level chooses
the bg color, not the title text. Three tiers walk down the
brand gradient so the heading tree reads at a glance.
- H4+ kept as bold-only (no bg) so deeply nested sections don't
visually overpower body content.
- EditFileDiff — hunk header is now a violet bg-pill (` @@ -10,3
+10,5 @@ `) instead of a plain cyan-bold one-liner. Body lines
have a colored gutter glyph (− for removed, + for added)
followed by tinted body text, so add/remove rows scan as
distinct lanes rather than colored prose.
- Markdown blockquote — left bar now uses the brand violet
(#c4b5fd) instead of dim gray, so quoted content carries
visual weight that matches the rest of the palette.
- Paste sentinel — was a magenta bold token (`[paste #1 · 12l ·
1.4KB]`); now a solid fuchsia bg-pill so the collapsed paste
block is unambiguous. Matches the mode/tool/badge pill idiom
used everywhere else.
- PromptInput cursor — was a static ▌ block; now toggles ▌↔space
every 4 ticks (~480 ms half-period) via the same ticker that
flows the bar gradient. Inverse-char cursor (mid-line) and
paste-sentinel cursor toggle their `inverse` prop in lockstep
so the character stays legible during the cursor's "off"
half-cycle. Disabled state freezes the cursor solid so the
busy-turn prompt reads as "frozen" not "dead".
- PlanRefineInput — wrapped in the shared ModalCard frame with
mode-specific accent: cyan for approve, amber for refine /
checkpoint-revise, fuchsia for choice-custom. Each accent
matches the related confirm modal so users learn "amber =
plan adjustment", "fuchsia = choice flow" by sight. Inline
cursor blinks too, on the same tick.
- Docstring on PromptInput updated — the old "no blink" comment
is no longer accurate.
- step-progress event row — replaced the green ✓ glyph with a
solid-bg ` ✓ STEP ` pill plus colored counter, body and notes
indented under for visual nesting.
- plan-resumed event row — opens with a ` ↻ RESUMED PLAN ` cyan
pill + bold counter; summary + step list flow underneath.
- plan-replay event row — slate ` ⏪ REPLAY ` pill mirroring the
resumed shape, so live and archived plans use the same idiom.
- error / warning event rows — now use the same pill idiom
(` ✦ ERROR ` rose, ` ▲ WARN ` amber) instead of one colored
glyph + colored body.
- PlanCheckpointConfirm + PlanReviseConfirm modals — wrapped in
the shared ModalCard frame (green ✓ checkpoint, amber ✏
revision). All four confirm-style modals now share the same
top/bottom rule + bg-pill title visual language: choice
(magenta), plan (cyan), shell (red), edit (yellow / green NEW),
checkpoint (green), revision (amber). User learns the modal
type by accent before reading the title.
- PlanStateBlock — labels are now solid-bg pills (` subgoals 3 `,
` hypotheses 2 `, ` uncertainties 1 `, ` rejected 4 `) with
truecolor hex backgrounds matching the role palette (cyan /
green / amber / slate). Items render to the right of the pill.
- BranchBlock — replaced the dim blue one-liner with a stacked
layout: blue ` ⎇ BRANCH ×N ` pill on the header row, then
one row per sample beneath with the chosen sample bolded and
arrow-marked.
- StatsLine (assistant footer) — was a flat dim row; now uses
threshold-colored cache % (green/amber/rose), cyan/violet for
in/out token counts, green for cost, with mid-dot separators.
- Info rows — auto-detect tone from the leading glyph: ▲/⚠ →
warn (amber), ✓ → ok (green), ✗/✖ → err (rose), ↻ → reload
(cyan), default ▸ → info (slate). The glyph is colored-bold,
body stays dim. Existing info messages with embedded prefixes
pick up their semantic without callers changing anything.
- PlanStepList — replaced the colored ✓/▶/—/space glyph column
with solid-bg status pills: ` ✓ DONE ` (green) / ` ▶ RUN `
(cyan) / ` — SKIP ` (slate) / ` ☐ PEND ` (slate dim). Header
row now shows percent done. Focus row gets bold + accent
arrow + bold title. Reads at a glance from across the screen.
- StreamingAssistant — phase header is now a solid-bg pill
(` WAITING ` amber, ` THINKING ` violet, ` DISPATCH ` fuchsia,
` WRITING ` green) instead of a long colored sentence. Pre-
first-byte / reasoning-only / tool-call-only hints get
paddingLeft so they sit visually under the pill. Same info
density, far better visual hierarchy.
- UndoBanner — replaced the magenta-text version with a violet
bg-pill header (` ✓ AUTO-APPLIED N/M `) + a cyan key-pill on
the `u` shortcut. Countdown turns red bold in the last second.
- SubagentRow — violet bg-pill for the ⌬ subagent label,
paddingLeft={3} so it visually nests under the parent
OngoingToolRow when both are visible.
Five surfaces touched, all visible during normal coding:
- Markdown H1 → solid cyan-bg pill (` # title `).
- Markdown H2 → solid violet-bg pill (` ## title `).
- Markdown H3 → bold fuchsia ### with bold body, no bg (avoids
visual overpower at the third nest level).
- Modals — ChoiceConfirm, PlanConfirm, ShellConfirm, EditConfirm
all wrap in a new <ModalCard> primitive: top accent rule, bg-pill
title row with optional icon + dim subtitle, content area, bottom
accent rule. Each modal keeps its own accent color so the user
learns by sight: magenta=choice, cyan=plan, red=shell, yellow=edit.
- Info rows in scrollback get a slate `▸ ` prefix so they read as
structured "system note" lines instead of dim continuation text.
ModalCard is plain Text for the rules + a bg-pill title — no Ink
borderStyle, so it stays compatible with the live region's eraseLines
constraint. EditConfirm's diff slicing budget is unchanged
(MODAL_OVERHEAD_ROWS still accounts for ~3 rows of frame).
Five more visual upgrades across the most-touched surfaces:
- PromptInput left bar — each row's ▎ picks a color from the
brand gradient with a tick offset, so the bar visually flows
vertically in sync with the StatsPanel's wordmark + rules.
When the prompt is disabled (busy turn), the gradient is
suppressed and the bar reverts to dim gray so the screen
calms down for the active spinner above it.
- User message — wrapped in a cyan left-only border Box matching
the assistant treatment, so both sides of the conversation
have the Discord-style avatar bar. Continuation lines align
under the band.
- ReasoningBlock — was a flat dim italic line, now opens with a
solid violet pill (` ⋯ thinking `) and the body in violet
italic. Reads as its own surface instead of blending into the
rest of the message.
- SlashSuggestions selected row — solid cyan-bg highlight (the
whole row, like an editor's autocomplete focus row) instead
of just colored text.
- AtMentionSuggestions selected row — same solid cyan-bg
treatment, basename + dir on one line for a tighter VS Code
Quick Open feel.
Tick is ~120 ms. Wordmark shifts the gradient one step every 4 ticks
idle / 2 ticks busy, so the teal→cyan→blue→purple→fuchsia sweep
visibly travels across REASONIX like a neon sign. Top/bottom
GradientRule bars share the flow logic (slower — every 6 ticks) so
the whole panel feels alive without being twitchy. Brand mark ◈ keeps
its existing bold-pulse so 'app is thinking' stays distinct from
'colors are flowing.'
Big visual upgrades on the surfaces with the most pixels:
- Assistant message — Box with left-only border in role color
(COLOR.assistant green) running the FULL height of the message,
Discord-style avatar bar. Reasoning, branch, plan-state, body
Markdown, stats footer, repair note all sit inside the band.
- Tool result for edit_file — same left-band treatment in
COLOR.tool yellow so the diff reads as a continuation of the
pill above.
- Markdown code blocks — round-bordered card in cyan, with the
language label as a solid-bg pill in the top-left and amber
body text. Fenced code now feels like a code block, not a
bare yellow-on-default text dump.
- OngoingToolRow — solid amber pill on the tool name, gradient
progress line, paddingX so the row sits in its own column zone.
- StatusRow — violet accent + paddingX + middle-dot separator
instead of a grey one-liner.
- ModeStatusBar — wrapped in a top dotted rule so the modeline
reads as its own zone, separate from the prompt above. Helix /
vim modeline feel.
Border usage notes: the assistant + tool left-only borders live
inside `<Static>` (scrollback) so Ink's eraseLines miscount that
banned bordered Boxes from the LIVE region doesn't apply. The live
region (StatsPanel, OngoingToolRow, ModeStatusBar, PromptInput)
still uses Text-only rules and pills, so the Windows ghost-row
class of regression stays out.
Centralised palette/glyphs in theme.ts so the TUI reads as one
designed surface instead of fifteen components inventing their own
color choices. Reuses the brand teal→cyan→blue→purple→fuchsia
gradient that the wordmark already establishes.
- StatsPanel: top + bottom gradient rules frame the header band;
progress bar redesigned with ▰/▱ glyphs and threshold colors
(green/amber/rose) using truecolor hex; metric cells now lead
with a dim icon (▣ ctx, ⌬ cache, ◴ cost, ◐ balance) and the
inline layout always shows the bar.
- TurnSeparator: gradient rule on both sides of the brand mark
instead of a flat dim minus row, so turn boundaries read as
designed accents.
- WelcomeBanner: gradient top/bottom rules + brand-color left bar
+ accent-color hint tokens. Card now feels like a card.
- theme.ts: GRADIENT array, semantic COLOR map, GLYPH set,
`gradientCells(width, glyph)` helper that other components
consume to render colored rules without duplicating the
interpolation logic.
Three high-frequency surfaces redesigned with solid-bg pills + card
framing so the TUI reads as a designed product instead of a wall of
glyphs:
- WelcomeBanner — left-bar card frame; sectioned 'welcome / quick
start / tip' rows; first thing on screen now has visual weight
instead of looking like a one-liner list.
- ModeStatusBar — solid-bg pills (AUTO / REVIEW / PLAN MODE) like
a vim/helix modeline so the bottom bar reads at a glance.
- Tool result rows — bg pill on the tool name (yellow ✓ / red ✗)
so a session full of dispatches has visible status hierarchy.
- Assistant header — model name now a solid-green pill next to the
◆ glyph, matching the visual language of the other pills.
No new abstractions, no border boxes (still avoiding Ink's Windows
eraseLines miscount). Just pills + bars + paddingX consistently
applied to the surfaces the user sees most.
historical always has at least one info row at startup (session state
banner, edit-mode hint, restored plan, etc.), so historical.length
=== 0 never holds and the welcome card never showed. Switch the gate
to 'no user/assistant message yet' so the card greets the empty
conversation as intended.
The 49d4648 stdin-reader refactor moved the KeystrokeProvider INSIDE
App's render but kept App-body `useKeystroke` calls — `useContext`
runs at hook-call time, so the provider wasn't mounted yet and the
returned bus was always null. Every global hotkey (Ctrl+C exit, Esc
abort, Shift+Tab edit-mode cycle, @-mention picker nav, slash
suggestion nav) silently never subscribed; PromptInput worked because
it lives in the provider subtree.
Fixes:
- chat.tsx wraps <App> in <KeystrokeProvider> from outside; remove
the inner one in App.tsx.
- stdin-reader splits \r vs \n: \r → Enter (return:true),
\n → Ctrl+J ({ctrl:true, input:"j"}). Was conflating both as
Enter, so Ctrl+J fired submit instead of newline.
- stdin-reader recognises modifyOtherKeys + kitty Enter sequences
(27;2;13~ / 13;2u and shift/ctrl variants) so terminals that
enable those protocols can distinguish Shift+Enter / Ctrl+Enter.
On Windows + ConPTY the bytes get stripped before reaching us, so
Shift+Enter still falls back to Enter there — Ctrl+J remains the
universal newline.
- App.tsx writes \x1b[>4;2m at startup (paired disable on unmount)
to opt into modifyOtherKeys for terminals that honor it.
- code.tsx drops the SIGINT/SIGTERM `once` handler that ran
jobs.shutdown without exiting (it overrode Node's default
"exit on Ctrl+C" with a silent no-op). Job cleanup moves to the
`exit` event so any termination path drains the registry.
- App.tsx: SIGINT and \x03 byte both call process.exit(0). Using
Ink's exit() left the singleton stdin-reader's data listener
attached and the event loop alive, so the terminal would hang.
Hint text updated to lead with [Ctrl+J] since Shift+Enter is
unreliable on the most common Windows host. Two diagnostic probe
scripts added under scripts/ for future input regressions.
Visual structure tightened along the way: a left-bar (▎) anchor
running down PromptInput, a thin rule under the StatsPanel, the
existing TurnSeparator now actually rendered between user turns,
StatsPanel pills/wordmark restored from the in-flight working tree.
When the user opens reasonix and nothing has happened yet, the screen
showed StatsPanel + the bare prompt — no signpost for what to type.
Add a small Welcome card with three or four hand-picked hints
(/help, /skill, @path / !cmd in code mode, /exit). Disappears the
moment the first event lands so it never gets in the way during a
real session.
Tight on purpose. Full reference is /help; this is just the friction-
removing first impression.
The 0.7.x bug parade (paste markers leaking, arrows not crossing
newlines, Shift+Tab broken, CJK ghost rows) traced back to two upstream
limitations we couldn't patch around forever:
1. Ink's `parse-keypress` uses a 100 ms intra-CSI timeout that is too
short for Windows ConPTY. Sequences like `\x1b[A` arrive split
across reads with > 100 ms gaps, so the lone `\x1b` fires as
`key.escape:true` and `[A` lands in `input` as plain text.
2. Ink/Yoga measures cell width with `string-width`, but on CJK
terminals some glyphs render at a different cell count than that
library reports. The terminal wraps to a 2nd visual row that
Ink's `eraseLines` doesn't account for, so each render leaks a
row into permanent scrollback.
Patching consumers one at a time was a Whac-A-Mole. This change
replaces the entire input layer:
- **`stdin-reader.ts`** — owns `process.stdin`, parses bytes with
our own state machine. ESC ambiguity timer is 250 ms (vs. Ink's
100). ESC-stripped CSI tails (`[A`, `[5~`, `[Z`, `[200~`) are
recognised at idle-state lookahead. SS3 (`\x1bOA`) supported. Drops
unknown CSI silently rather than inserting bytes as text.
- **`keystroke-context.tsx`** — React Context that owns the singleton
StdinReader and fans events out to subscribers via `useKeystroke`.
Replaces every `useInput` import in our tree.
- **`prompt-viewport.ts`** — pure helpers that slice each logical
prompt line into exactly one visual row. The cursor's window
slides so it stays visible; `‹` / `›` markers indicate clipped
content. CJK cell widths handled explicitly so our math matches
the terminal grid (no more `string-width` disagreement with the
real renderer).
- **PromptInput v2** — rewritten on top of these. No `useTick` (no
cursor blink — the 8 Hz repaint was amplifying the eraseLines
leak). One Box row per logical line, fixed visual height, viewport
clipping for content longer than the terminal width.
- **App / Select / EditConfirm / PlanRefineInput** migrated to
`useKeystroke`. Wizard / DiffApp / ReplayApp keep Ink's `useInput`
— separate render calls, no provider in their tree, no conflict.
SessionPicker (which uses our migrated SingleSelect) gets its own
KeystrokeProvider wrapper in chat.tsx.
- As long as no `useInput` is called inside the Ink tree, Ink itself
never attaches a stdin listener, so our reader is the sole consumer
of stdin. No race with parse-keypress.
41 new tests covering every CSI tail, paste accumulator across chunks,
ConPTY ESC-stripping, viewport clipping for CJK / paste sentinels.
1283 → 1324 tests, lint + typecheck clean.
Audit context. We've shipped three patches in two days for the same
class of bug:
1. paste markers `[201~` leaking into the prompt buffer
2. arrow keys not advancing the cursor across newlines on Windows
3. (foreseeable) Shift+Tab / PgUp / PgDn / Delete next, since they
all share the root cause.
Root cause is upstream: Ink's parse-keypress uses a 100ms timeout
to assemble CSI sequences from stdin. On Windows PowerShell + ConPTY
the bytes of `\x1b [ A` arrive split across reads with > 100ms
gaps. The standalone `\x1b` fires as `key.escape:true`, the trailing
`[A` fires as a regular character event with `input:"[A", upArrow:
undefined`. Every useInput consumer that reads structured key flags
silently misses the keystroke and the bare bytes get inserted into
the buffer as text.
Each individual patch was correct but localised — multiline-keys had
its own arrow recovery, PromptInput had its own paste-marker recovery,
App.tsx / Select / EditConfirm didn't recover anything at all and
would have been the next bugs found.
Fix is a single boundary. `src/cli/ui/key-normalize.ts` exposes:
- `recoverCsiTail(input, existingFlags?)` — the canonical mapping
from bare-or-prefixed CSI tails to structured Ink key flags.
Covers `[A`/`[B`/`[C`/`[D` (arrows), `[5~`/`[6~` (PgUp/PgDn),
`[3~` (Delete), `[Z` (Shift+Tab). Bracketed-paste markers
intentionally excluded — they have collect-between-markers
semantics and live in PromptInput's accumulator.
- `stripCsiFragments(input)` — defensive scrub for the edge case
where a fragment slips past structured-key recovery (e.g. arrived
embedded inside a paste burst). Replaces the inline replaceAll
chains we'd grown in multiline-keys.
Wired into every useInput call site that reads structured key flags:
multiline-keys (PromptInput's reducer), App's global hotkey handler
(Esc / Shift+Tab), Select's SingleSelect + MultiSelect (modal
navigation), EditConfirm's scroll/decision handler. DiffApp /
ReplayApp left for follow-up — separate subcommands, lower blast
radius.
+14 tests covering every supported tail, the pass-through path, the
already-structured-event short-circuit, and the literal `[A](url)`
non-rewrite. 1267 → 1283 tests.
User reported pressing right-arrow at end of line 1 would not advance
the cursor to line 2. Same root cause as the recent [201~ paste-marker
fix: Windows PowerShell + ConPTY consumes the leading \x1b of the
arrow's CSI sequence and routes the remaining '[C' through useInput
as plain text. Our rewriteRawArrowEscape only matched the full
'\x1b[C' form, so the keystroke landed on the printable-char branch
and inserted literal '[C' into the buffer instead of moving the
cursor.
Add fallbacks for the bare '[A'/'[B'/'[C'/'[D' input strings. +1 test
covering the cross-newline rightArrow case directly.
Windows PowerShell + ConPTY + Ink's parse-keypress consumes the
leading \x1b of \x1b[200~ / \x1b[201~ and routes the rest into
useInput as plain text. Our markers were the full sequence, so
indexOf missed them and the literal '[201~' ended up inserted into
the user's prompt buffer.
PromptInput now searches for both the full marker and the bare
'[200~'/'[201~' fallback. multiline-keys.ts strips both forms
defensively too. +1 test.
User reported repeating ghost top-borders accumulating in scrollback
on Windows + CJK input — every render leaked one row, so 17+ ghost
`╭──...─╮` lines stacked at the top within seconds. Root cause: Ink's
eraseLines counts logical rows, not post-wrap visual rows. Bordered
Boxes were both the most common wrap source AND the most visually
obvious thing to duplicate.
Fix: remove `borderStyle="round"` from every component in the live
region — StatsPanel, PromptInput, all *Confirm modals, UndoBanner,
EventLog plan/plan-resumed/plan-replay rows. Visual hierarchy now
comes from bold colored headers + indentation + marginY breathing.
Also pillify the active mode tag in ModeStatusBar — `▸ AUTO` becomes a
solid colored background block ` AUTO ` so the current mode reads at
a glance and the focus animation (briefly inserting a ◆) is more
distinct than `inverse` toggling.
No content lost; same affordances, less paint surface for Ink to get
wrong on fragile terminals.
User reported ghost top borders stacking up in scrollback after typing
two lines of CJK content, plus apparent cursor-stuck-on-line-1. Same
class of Ink eraseLines miscount that StatsPanel solved with explicit
width={cols} — long Chinese input (2 cells per char) overflows the
auto-flexed Box, every ticker tick leaves a ~1 row residual, and after
~3s the user sees 20+ ghost border tops.
Two changes:
- Pin the bordered Box to `width={cols}` so Ink's measurement matches
reality (same fix StatsPanel applies).
- Fold the disabled-state [Esc] hint back inside the bordered Box. The
`<>`-wrapped sibling Box from 0.7.2 was a structural variable with no
layout benefit. Continuation-indented row inside the box matches the
visual hierarchy without changing the live-region shape.
The cursor-stuck symptom was rendering corruption — once the live
region stops accumulating ghost rows, useInput delivery + setCursor
land where they should.
Same fix as EventLog ate earlier. RecordView is the read-only viewer
shared by reasonix replay and reasonix diff — multi-line transcripts
were wrapping under col 0 instead of under the body text. Continuation
indent of 6 spaces matches the 'you › ' prefix width.
LiveRows.tsx already used `name === s || name.endsWith("_" + s)` so MCP
tools like `filesystem_read_file` picked up the same per-tool argument
summary as the bare local `read_file`. tool-summary.ts used exact-name
match only, so bridged tools fell through to the generic "first line +
size hint" path in the compact scrollback row. Switch to the same
suffix predicate; add a write_file branch while there. +3 tests
covering the bridged path + a non-underscore-prefix non-match.
Bracket-style `[↑↓] navigate · [Enter] X · [Esc] Y` matches the Confirm
modals; Wizard and SessionPicker were the last surfaces using the older
free-form `↑/↓ move · enter X · esc Y` style. Doc-comment examples in
Select.tsx updated to match.
Three runtime fixes that all surfaced from a single user trace
(model looped on a broken read_file, the chat ended without
explanation, embedded GBK encoding errors, plus a separate
"PDF report on global economy" turn that wrote a 2024 report
from training memory instead of searching).
Storm-break no longer dead-ends the turn
- When the storm-breaker suppressed every tool call in a turn,
the loop yielded `done` with empty assistant content. The user
saw a one-line warning then silence and didn't know what to do.
Now routes through `forceSummaryAfterIterLimit` with a new
`"stuck"` reason: the model gets one no-tools call to explain
what it tried, what blocked, and what would unblock — turning
the silent stop into actionable feedback the user can act on.
PYTHONUTF8 / PYTHONIOENCODING for spawned shells
- run_command's spawn env now sets PYTHONIOENCODING=utf-8 and
PYTHONUTF8=1. On Chinese Windows, Python's default stdout
encoder is GBK; emoji / non-GBK output raises UnicodeEncodeError
and the model sees a Python traceback instead of the script's
real result, then loops trying to fix the wrong problem.
These env vars force UTF-8 unconditionally. Harmless on
non-Python processes (env vars they don't read).
Recency rule in default chat system prompt
- New short section in DEFAULT_SYSTEM telling the model that
when an answer's correctness depends on something that
changes over time (the user is asking what's *happening*,
not what's *true*) and a search tool is available, search
before composing. Phrased as a principle ("if I'm wrong
about this, is it because reality moved on?") rather than
a topic list, so it doesn't go stale or over-prescribe.
- web_search description rewritten in matching language —
emphasis on "current state" rather than enumerating
topics like markets / news / releases, which tied the
description to a particular moment in time.
Tests: loop +1 (storm→summary regression). 1264 tests total,
lint + tsc + build clean.
Several long-standing input-box and TUI annoyances fixed in one batch.
Paste handling
- Big pastes (3000-line error logs, etc.) used to be inlined into
the buffer verbatim — surrounding typed text drowned, every
keystroke re-rendered hundreds of rows. Replace with a sentinel
scheme: each paste blob becomes ONE PUA codepoint in the buffer
(`\uE100..\uE1FF`), full content lives in a side registry,
rendered as `[paste #N · 33l · 1.0KB]` magenta block. Buffer
stays small, cursor steps over the placeholder as one unit, a
single Backspace removes the whole paste. On submit the
sentinels expand back to full content for the model.
- Bracketed-paste mode (DECSET 2004) enabled at app start so
cooperating terminals deliver one marker pair per paste action.
- For terminals where the markers don't reach Ink (PowerShell +
ConPTY parses them out), a sub-30ms time-window + position-guard
fallback collapses chunks of one paste into a single sentinel.
30ms is well below human reaction for double-pasting (~100ms+),
so two deliberate pastes never falsely merge.
- Critical fix: PowerShell+Ink fires useInput TWICE per stdin
chunk, both with stale React closure over `value` / `cursor`.
The merge guard read stale state and never matched the previous
sentinel — one Ctrl+V kept producing four `[paste #N]`
placeholders. registerPaste now reads from refs we update
synchronously inside the function, so the second fire sees the
first's insert.
- Pasted CR/CRLF normalize to LF; bracketed-paste markers are
stripped if they leak through.
Multi-line cursor
- ↑/↓ at the buffer boundary (line 0 / last line) used to be
silent NOOP — felt stuck. Now hands off to the parent's history
recall, so users can escape into history from a multi-line
draft without first emptying it.
- Raw-escape fallback: terminals that don't set `key.upArrow`
and instead leak `\x1b[A` into `input` (older Windows configs)
now get the escape rewritten into the structured key event,
preventing the literal escape bytes from being inserted.
Buffer-wide shortcuts
- PageUp / PageDown jump to top / bottom of the WHOLE buffer
(was NOOP).
- Ctrl+U clears the entire buffer (readline-style; necessary
given the renderer can collapse the buffer to a few visible
rows after a paste — backspacing N times wasn't ergonomic).
- Ctrl+W deletes the word before the cursor (eats trailing
whitespace first, spans newlines).
- Hint row appears under the input when buffer has > 20 lines:
`[N lines · PageUp/PageDown jump to top/bottom · Ctrl+U clear ·
Ctrl+W del word]` so users discover the shortcuts in the
exact moment they need them.
Visual stability
- StatsPanel pinned to `width={columns}` so each render's frame
is exactly terminal-width — reduces (doesn't eliminate) the
resize ghost-frame stacking from Ink's eraseLines miscount on
re-wrapped lines.
- /help gains a "Known limitation" section about the resize
artifact so users aren't blindsided.
`/clear` actually clears
- Used to only `setHistorical([])` (React state). Terminal
scrollback was untouched — user kept seeing prior turns until
they scrolled past them. Now writes CSI 2J + 3J + H so the
viewport AND scrollback buffer are nuked. Ink's next render
paints the TUI on the fresh screen.
Tests: paste-sentinels (new file, 18 tests), multiline-keys +57.
Total 1264 tests, lint + tsc + build clean.
Substantial expansion of the chat-output Markdown renderer.
Block-level
- Blockquote `>` with proper recursion: nested quotes (`> >`) render as
adjacent left bars, lists / code fences / tables INSIDE a quote
parse via the same `parseBlocks` recursively (instead of being
flattened to text), GFM-style.
- Task lists (`- [ ]` / `- [x]`) — item text gains `task: "todo" |
"done"`, rendered as `☐` / `☒` with strikethrough on done items.
- Diagram code blocks (mermaid / dot / graphviz / plantuml / puml /
flowchart / sequencediagram / gantt / erdiagram) render with a
distinct magenta double-line frame + `◇ <lang> diagram (source)`
header + viewer-URL hint. Terminal can't draw the graph, but the
user knows it's source-of-a-diagram and where to paste it.
- Hard line break: trailing ` ` (two-or-more spaces) on a line now
inserts a real `\n` in the rendered paragraph instead of being
silently collapsed into a space.
Inline
- `***bold-italic***` (added as the first INLINE_RE alternative
before the bold and italic checks).
- `~~strikethrough~~` (with proper guards so subscript / strike
don't fight).
- Pandoc-style `^x^` superscript and `~x~` subscript — only
fire when every char is in the Unicode SUPERSCRIPT/SUBSCRIPT
table; otherwise leave the markers literal so we don't drop the
user's intent.
- Math: `$inline$` and `$$block$$` delimiters are stripped
(delimiters only — content still flows through the existing
LaTeX → Unicode pipeline).
- Emoji shortcodes: ~70-entry curated table covering the common
faces / hearts / gestures / signals (`:smile:`, `:fire:`, `:+1:`,
`:white_check_mark:`, etc.). Unknown names pass through literal.
- Autolinks: `<http://…>`, `<https://…>`, `<mailto:…>`, `<ftp://…>`
rewrite to `[url](url)` so the existing link path renders them.
- Backslash escapes: `\*` / `\` ` ` / `\~` / `\[` / `\]` / `\` etc.
emit literal characters via a final INLINE_RE branch — the
surrounding markup parsers don't get to consume the escaped
punctuation. `stripInlineMarkup` rebuilt around a single-pass
INLINE_RE walk so escape precedence matches the runtime.
Citation guard
- `collectCitations` now skips URLs that obviously aren't repo
paths: anchor-only (`#foo`), bare `/`, and short placeholder
words with no `/` `\` or `.` in them. Eliminates the false
"broken citation" red-strikethrough on demo / non-citation
links.
Bug fixes uncovered along the way
- `\sum_{i=1}^n` and friends were being eaten by the catch-all
LaTeX command stripper because `\b` doesn't match between `m`
and `_` (both are word chars). Switched the relevant rules to
`(?![a-zA-Z])` so the specific Σ / Π / ∫ / etc. substitutions
fire even when followed by a subscript.
Tests: markdown 60 → 173 (+113).
deepseek-chat and deepseek-reasoner are now just compat aliases for
v4-flash's non-thinking and thinking modes (same underlying model,
same bill per telemetry.ts). Presets already all point at
deepseek-v4-flash / deepseek-v4-pro. Retire the old names everywhere
they were still surfacing as the default or discoverable surface:
- harvest.ts default model: deepseek-chat → deepseek-v4-flash
(behaviorally identical — both route to v4-flash non-thinking)
- subagent tool enum: drop deepseek-chat/-reasoner; users pick
flash vs pro now, no legacy names to distract the model
- subagent JSDoc: default was documented as pro but the actual
constant is flash; fix the docs
- /model empty-arg hint: suggest v4 names instead of legacy aliases
- /think empty-reasoning hint: explain "thinking-mode models"
generically instead of pinning to deepseek-reasoner
Kept legacy names in telemetry.ts (DEEPSEEK_PRICING,
DEEPSEEK_CONTEXT_TOKENS) because historical usage.jsonl rows still
reference them — the table is for pricing old sessions, not routing
new requests. Runtime `--model deepseek-chat` still works; the
isThinkingModeModel() abstraction is semantic (thinking vs
non-thinking), not version-bound, so it stays correct.
Prior fixes (0.5.15, 0.5.18) progressively unscoped the stamp but kept
a reasoning.length > 0 guard that silently dropped the field whenever
the model happened to return empty reasoning — legitimate on flash
thinking-mode turns with zero reasoning deltas, forced-summary paths
whose resp.reasoningContent is null, and non-streaming responses
returning reasoning_content: null. The next API call then 400'd with
"The reasoning_content in the thinking mode must be passed back."
Architectural smell: assistantMessage gated on reasoning-content
presence, while syntheticAssistantMessage gated on model type — two
different encodings of the same invariant.
Unify both around isThinkingModeModel(producingModel): the field is
present on the persisted assistant turn iff the model that generated
it runs in thinking mode, using the captured reasoning (or empty
string) as the value. Call sites pass the real producing model — not
this.model — so escalation (pro) and forced-summary (flash)
round-trip correctly.
Session-load heal: stampMissingReasoningForThinkingMode back-fills
empty reasoning_content on assistant turns from pre-fix session
files, so resuming an older session on a thinking-mode model no
longer 400s on the first request.
Tests: +5 (null-reasoning stamping on v4-flash, chat stays clean,
session-load heal for reasoner/v4-pro/chat). 1150 tests, tsc clean.
The agent's live-run refactor (2c8... in the local log) correctly
split plan.ts into plan-core + plan-errors and preserved the barrel,
but stopped short of three things worth doing:
1. plan-errors.ts was mis-named — it also held the value types
(PlanStep, PlanStepRisk, StepCompletion). Extracted those to
a new plan-types.ts so file names match contents. Dependency
direction is now plan-core → plan-errors → plan-types.
2. Barrel used \`export *\` from both modules, which would silently
shadow on any future name collision. Replaced with explicit named
re-exports so TS catches duplicates the moment they appear.
3. plan-core.ts was still ~240 lines, mostly a single
registerPlanTool body with three inline tool-description strings.
Split into registerSubmitPlan / registerMarkStepComplete /
registerRevisePlan (one per screen) with descriptions hoisted to
SCREAMING_SNAKE constants at the top and the duplicated step-item
schema extracted to STEP_ITEM_SCHEMA. Function bodies now read as
control flow, not prose. Public API unchanged.
1145 tests still green, typecheck + lint clean. Zero behavior change.
Previous pass at tightening ask_choice guidance leaned on specific
anti-patterns — "方案 A:" headers, "你选哪个?" trailers, markdown
comparison tables. Ugly and brittle: next time the model adopts a
slightly different phrasing, we'd be patching yet another bullet.
Reframe as a single principle in both the tool description and the
code system prompt: "if the user is supposed to pick, the tool
picks — you don't enumerate the choices as prose." The model can
generalize from that.
Behavior contract is unchanged; the guidance is just cleaner and
easier to maintain. Prompt-engineering change only, no code logic.
Atlas W2 wave 2: load an archived plan as a read-only snapshot.
'/replay' defaults to the newest archive; '/replay 2' jumps to the
second-newest; '/plans' enumerates the full set.
- SlashResult grows replayPlan field so the handler can push a
structured payload — App.tsx mounts it as a plan-replay event
rather than flattening to info text. Keeps the bordered box +
step list + markdown body styling consistent with plan-resumed.
- New plan-replay DisplayRole + EventRow branch: gray border, ⏪
icon, dim header (completed time, N/total nav, archive filename),
markdown body rendered through the full pipeline, PlanStepList
with every step marked done, footer hint for jumping archives.
- /replay handler in plans.ts looks up listPlanArchives(session)
by 1-based index, validates range, carries the payload through.
Per-session only — same project-isolation as /plans.
- /replay added to commands.ts with argsHint=[N] so slash
autocomplete / hint surface picks it up.
Tests: 6 new slash tests cover default-newest, indexed lookup,
out-of-range rejection, empty-archive state, no-session guard, and
/plans summary label surfacing. Full suite 1145 green.
Two schema additions that unblock Time Travel and make /plans
listings useful.
- submit_plan accepts optional \`summary\`: one-line title. Surfaces
in the PlanConfirm header, the resume banner, and /plans so users
identify plans by intent ('Refactor auth into signed tokens')
rather than by filename.
- plan.json now stores the markdown \`body\` that came in with
submit_plan. Replay will read this; previously the body only
lived in the JSONL log, which is fine for the active session but
hard to surface in a closed archive without re-parsing tool-call
JSON.
Both fields are optional. Older plans without them still load and
render cleanly; /plans falls back to filename when no summary is set.
PlanProposedError carries summary through toToolResult. plan-store's
savePlanState grows an extras bag so callers don't have to care
about field proliferation. listPlanArchives surfaces both fields
on the PlanArchiveSummary type.
Tests: body+summary roundtrip, omission default, submit_plan
summary trim behavior, blank-rejection. Total: 1139 tests green.
Adds a per-session history view. Active plan (from plan.json) +
archived completed plans (.done.json), newest-first. Project-local
by design — cd to another project to see its plans, no cross-project
listing.
Output:
▸ active plan: 2/5 steps done · last touched 1h ago
Archived (3):
✓ 3d ago 5 steps · complete code-foo.plan.2026-04-21-...done.json
✓ 2026-04-15 8 steps · complete code-foo.plan.2026-04-15-...done.json
✓ 2026-04-10 3 steps · complete code-foo.plan.2026-04-10-...done.json
- listPlanArchives scans sessionsDir() for the session-prefixed
.done.json files. Sorts by stored updatedAt (with mtime fallback
for hand-edited archives). Skips corrupt JSON / wrong-version /
zero-steps archives instead of failing the whole list.
- /plans handler renders both views; falls back to a discovery hint
when no plans exist yet.
- Tests: 6 new — empty state, ordering, active-only ignored,
cross-session isolation, corrupt-resilience, mtime fallback.
Foundation for upcoming /replay <archive> + Time Travel canvas —
both will read these summaries to find replayable artifacts.
When the model marks the final step done, the active plan.json moves
to a timestamped .done.json archive instead of lingering. Two reasons
this matters: (1) the next session starts with a clean slate — no
stale resume banner for work that's actually finished; (2) the
archive is the foundation Time Travel replay will read from in W2
wave 2 to show "what the model actually did vs what was planned".
- archivePlanState renames plan.json → plan.<ISO-stamp>-<rand>.done.json
in sessionsDir(). Random 4-char suffix dodges within-millisecond
collisions if two plans finalize back-to-back. Returns the archive
path, or null when there's no active plan / rename fails.
- App.tsx mark_step_complete handler: after the progress row pushes,
if total > 0 && completed >= total, archive and post a
'▸ plan complete — all 5 steps done · archived' info row.
- Tests: 4 new — null-return on missing, rename verification,
payload preservation through archive, collision-resistance.
Auto-escalation (flash → pro) was the only truly automatic per-turn
decision the user couldn't see into. The warning fired but said only
'flash requested escalation' or 'flash hit N edit failure(s)' — no
WHY. Two changes surface the rationale.
1. Self-report marker now carries an optional reason:
<<<NEEDS_PRO>>> ← bare, still works
<<<NEEDS_PRO: <reason>>>> ← preferred, surfaces in warning
parseEscalationMarker pulls the reason out, the warning becomes
'⇧ flash requested escalation — <reason>'. Buffer bumped to 256
chars so reasons aren't truncated mid-stream. The streaming
look-ahead now uses looksLikePartialEscalationMarker so multi-
line / colon-form markers don't flush prematurely.
2. Failure-threshold escalation tracks PER-TYPE counts (search-
mismatch, scavenged, truncated, storm-broken). The warning now
says 'flash hit 2× search-mismatch, 1× truncated' instead of
'3 repair/error signals'. Same FAILURE_ESCALATION_THRESHOLD
semantics; just better attribution.
ESCALATION_CONTRACT prompt fragment teaches both forms with examples.
Three new tests cover the reason-carrying marker, empty-reason edge,
and the unclosed-marker fallthrough (still treats as content, no
silent retry on a malformed signal).
The W2 resume banner was a single info row — '▸ resumed plan: 2/5
steps done · last touched 3h ago'. Useful but minimal. Users had no
way to see WHICH steps were done or what's coming next without
scrolling back through the prior session's log.
New plan-resumed display role mounts a bordered box at the top of
the new session: header (badge + counter + relative time) plus
the full PlanStepList — same component used in PlanConfirm and the
checkpoint picker, with done steps dimmed + ✓, the next pending
step focused with the › cursor, and the risk gutter color-coded.
Carries the structured plan data through DisplayEvent.resumedPlan
so the renderer doesn't need access to the live planStepsRef. Pure
render layer; no new logic, no new tests needed (plan-store tests
already cover the data side).
Atlas W2 wave 1: the plan the model submits via submit_plan (and
mutates via mark_step_complete / revise_plan) now survives terminal
close. Without this, all the structured-step / risk / checkpoint /
revise UX evaporated whenever you took a coffee break.
- New src/code/plan-store.ts: loadPlanState / savePlanState /
clearPlanState / relativeTime. Storage path mirrors the JSONL
convention: ~/.reasonix/sessions/<sanitized>.plan.json. Format is
versioned (v1) with defensive parsing — corrupt files load as
null, malformed step entries are filtered, invalid risk values
are stripped, the rest of the plan still loads.
- App.tsx: load on mount, save after every plan-state change
(submit_plan, mark_step_complete, revise_plan accept), clear on
PlanConfirm cancel. The persistPlanState callback is threaded
through all the relevant useCallback deps so React's exhaustive-
deps rule stays clean.
- Resume banner: when an existing plan loads on startup, push
'▸ resumed plan: 2/5 steps done · last touched 3h ago' into the
scrollback so the user immediately sees the picked-up state.
- Tests: 15 covering save/load roundtrip, malformed-JSON recovery,
version mismatch, partial step sanitization, completedStepIds
filtering, path safety, and relativeTime branches.
The plan markdown body itself is NOT persisted here — it lives in
the session JSONL (it was a tool result), so resuming the session
replays it naturally. We carry forward only the live state needed
to keep mark_step_complete and revise_plan meaningful.
Compact tool rows now annotate with timing and a navigation hint:
▣ run_command (1.2s) → exit 0 · ✓ tests passed /tool 12
▣ read_file → import { foo } · 234 lines · 4.5KB /tool 13
▣ search_content (8.5s) → 5 matches · src/foo.ts:12 /tool 14
Duration is suppressed under 100ms (every read_file would scream
'47ms' otherwise — noise). Above that, formatDuration picks a tight
representation: ms → s.s → s → m+s as the magnitude grows.
The /tool N suffix makes the existing slash command discoverable
without scrolling — users can jump straight to full content via
`/tool 14` instead of guessing the position. toolIndex is captured
at push time as the 1-based length of the tool history.
App.tsx: toolStartedAtRef captures Date.now() on tool_start and
diffs at result. Single ref is enough — tools dispatch serially.
Old tool rows were 6–8 vertical lines each (glyph row + blank + 400-
char body block). 10 tool calls in a session = ~70 lines of
mostly-noise content drowning the actually-interesting events
(checkpoint pickers, plan submissions, edit diffs).
New rendering: one line per tool call.
▣ read_file → import { foo } from 'bar' · 234 lines · 4.5KB
▣ list_directory → 17 entries
▣ search_content → 5 matches · src/foo.ts:12: const x = 1
▣ run_command → exit 0 · ✓ 17 tests passed
▥ run_command ✗ exit 1 · TypeError: Cannot read property
▣ submit_plan → PlanProposedError — STOP, picker shown to user.
edit_file keeps its multi-line colored diff renderer (the diff IS the
value). Plan / Choice control-flow signals (PlanProposedError etc.)
render in non-error yellow even though they technically come through
the error envelope — they're picker triggers, not failures.
The summarizer is a pure function in tool-summary.ts so it tests
without Ink and can be reused by replay / transcript export later.
Full content remains accessible via `/tool N`.
Phase 2 Revise was just text-forwarding: user typed feedback, model
got a synthetic, model adjusted however it wanted with no structured
contract. Add revise_plan as the structured counterpart — the model
proposes new remainingSteps + a one-sentence reason, the TUI shows
a step-level diff, user accepts or rejects.
- New revise_plan tool (readOnly, throws PlanRevisionProposedError).
Sanitization reuses sanitizeSteps so risk levels and malformed
entries are handled the same as submit_plan.
- New PlanReviseConfirm modal: amber border, reason header, diff
rows (-removed/red+strikethrough, +added/green, kept/dim), counter
badge -N +M (K kept), Accept/Reject picker.
- App.tsx: pendingRevision state + handler. Accept splices the new
steps onto the done-step prefix in planStepsRef (done work never
undone), pushes an info row with -N+M counts, sends a continue
synthetic. Reject sends a 'keep original' synthetic. Picker takes
priority over checkpoint picker so a checkpoint-revise → revision-
proposal flow chains naturally.
- Checkpoint Revise synthetic now nudges the model toward revise_plan
for structural changes vs submit_plan for full reset.
Tests cover the error roundtrip, sanitization, risk preservation,
empty-input rejection, and the readOnly flag.
Phase 1 structured steps were only used for post-approval progress
tallying — the user never saw them at decision time. Add risk-coded
step list to both PlanConfirm (approval) and PlanCheckpointConfirm
(mid-execution) so the plan shape is visible where it matters.
- New PlanStep.risk: "low"|"med"|"high" (optional). submit_plan
description guides the model: high = hard-to-undo / prod / API
changes; med = non-trivial but reversible; low = safe local.
- PlanStepList renders a compact list with 1–3 colored dots per step
(●/●●/●●● green/yellow/red) + a ✓/▶/— glyph, a legend row, and
a '3 steps · 1 done' counter. Steps without risk render a blank
gutter, so pure-markdown plans degrade cleanly.
- PlanConfirm mounts the list above the approve/refine/cancel picker
when steps are supplied.
- PlanCheckpointConfirm mounts the same list with the current step
highlighted via a › cursor and completed steps dimmed, so the user
can see what just finished and what's next before picking
continue/revise/stop.
Result: a structured plan with risks looks like a real plan, not a
markdown blob. Pure-markdown plans keep working unchanged.
Phase 1 ask_choice was technically working but models rarely called it
— the description leaned defensive ('don't misuse') with only a light
'use when genuinely user's call' nudge, so DeepSeek Flash kept writing
prose comparisons that ended with '你选哪个?' (no picker rendered).
Two-layer fix:
- Tool description leads with 'CALL THIS WHENEVER your next reply
would end with A/B/C — 你选哪个?'. Spells out the self-detect
triggers and the failure mode of text menus. 'When in doubt, call
the tool' as the tiebreaker.
- Code system prompt gains a dedicated '# When to ask the user to
pick (ask_choice)' section sibling to the submit_plan one, plus an
inline warning in the submit_plan section against option-menu
plans cross-referencing ask_choice.
Costs one prefix-cache miss on first turn after the update; hit rate
re-stabilizes after that. No test changes (the behavior under test
was already correct — this is pure prompt-engineering).
New tool gives the model a proper home for branching questions —
submit_plan was getting misused as a route-picker and leaving users
stuck at approve/refine/cancel with no way to choose.
Tool throws ChoiceRequestedError (same toToolResult protocol as
PlanProposedError), TUI mounts ChoiceConfirm — a magenta-bordered
modal with the question, the option rows (title + dim summary), an
optional "Let me type my own answer" escape hatch, and cancel.
Picking routes a synthetic 'user picked <id>' back to the model;
custom ships whatever the user typed verbatim.
Registered in both code and chat modes so branching works anywhere.
Sanitizes malformed option arrays (DeepSeek V3/R1 occasionally drops
fields even with Pillar 3 auto-flatten) and caps at 6 options so the
model can't drown the user in choices. submit_plan's description now
cross-references ask_choice so the model learns the dispatch.
Foundation for the Atlas redesign — Fork Nodes in W2 will render
pending choices inline in the plan canvas instead of as a separate
modal.
Tool description now explicitly tells the model not to use submit_plan
as a "pick one of these routes" menu. The approve/refine/cancel picker
has no branch selector, so a menu plan strands the user — hit in the
wild where the model used submit_plan to offer three project directions.
Branches belong in plain assistant text with a question; submit_plan
stays reserved for a single actionable plan.
mark_step_complete now throws PlanCheckpointError so the loop pauses
after each step. A new PlanCheckpointConfirm picker drives what happens
next: Continue resumes the plan, Revise opens a feedback box whose
text is threaded into the next turn's context, Stop ends cleanly with
a summary.
Revise reuses PlanRefineInput's single-line UX with a new
"checkpoint-revise" mode label. Esc on the feedback input restores the
picker. The ✓ progress row from Phase 1 still renders before the
picker mounts, so the scrollback always records what was just done.
Ports the useful half of @imlingdu/reasonix-tools' dynamic-plan loop
into Reasonix's submit-plan / approval-gate model — Phase 3 will add
an LLM-driven revise helper on top.
submit_plan now accepts an optional steps:[{id,title,action}] array;
new mark_step_complete tool ticks them off during execution so the
scrollback shows `✓ step-1 · title — result (2/5)` instead of leaving
the user to infer progress from tool noise.
Pure-markdown plans keep working unchanged — steps and progress
rows only render when the model opted into the structured form.
Cost control promoted to Pillar 4. Breaking behavior: default model
flipped from v4-pro to v4-flash; smart (default) preset no longer
auto-enables harvest; max preset no longer auto-enables branch 3.
New: /pro one-shot arming, failure-triggered auto-escalate, model
self-report <<<NEEDS_PRO>>>, turn-end auto-compaction, per-turn cost
badges. UI refactor: App.tsx -33%, slash.ts split into slash/ with
13 focused modules. See CHANGELOG for the full matrix.
Two small papercuts from a 70-turn live run surfaced:
1. Every edit_file tool call showed the apply result TWICE — once
as a dim info row (pushed by applyNow in the edit-mode
interceptor), then again as a full `▣ edit_file → …` tool row
yielded by the loop. Both with identical text. Wasted rows, made
long sessions harder to skim.
Fix: drop the info-row push inside applyNow. The returned string
still becomes the tool result AND the model sees it via the tool
event; the user sees it once via the tool row with its
identifying header. The auto-text branch at turn-end (for
text-form SEARCH/REPLACE blocks parsed from assistant prose)
still pushes its own info row — there's no tool event to back
it up.
2. The model repeatedly tried `cd dir && cmd`, `cmd1 | cmd2`,
`cmd 2>&1`, learning only from the error reply. run_command's
top-level description didn't spell the constraints upfront.
Fix: front-load a "Constraints (read these before the first
call):" block in both run_command and run_background
descriptions. Explicit list of rejected operators, cd-doesn't-
persist, and concrete alternatives (`npm --prefix`, `cargo -C`,
`git -C`, `pytest tests/…` instead of `cd && …`). Also warns
against unbounded-output commands like `netstat -ano` /
`find /` that balloon context for no reason, with filtered
alternatives.
Both are tool/UI changes only; 1054 tests green, typecheck + biome
clean.
User bug: "submit_plan" proposals were being truncated inside the
PlanConfirm modal with "(25 more lines truncated — resize the terminal
to see more)". The whole point of a plan review gate is that the user
can read the full thing before approving; the old design cut it off
at roughly 11 source lines to keep the picker on-screen.
Root cause: PlanConfirm rendered both the plan body (via Markdown)
AND the 3-option picker inside one Ink modal, with a hard line clamp
so total height never exceeded the TTY. The clamp fired unavoidably
on any non-trivial plan.
Fix: push the plan body to Static scrollback as a new display role
"plan" the moment submit_plan fires. The Static component renders
once into the terminal's permanent buffer (users can scroll back
through the terminal itself), and the PlanConfirm modal below
shrinks to a tight picker header + choice list. No truncation ever.
Changes:
- EventLog.tsx: new DisplayRole "plan" renders the plan body through
the full Markdown pipeline inside a cyan-bordered box with a 📋
header. Goes into <Static> so it's render-once + scrollable.
- App.tsx: on submit_plan detection, setHistorical pushes a "plan"
row BEFORE setPendingPlan so the body is in scrollback by the
time the modal mounts.
- PlanConfirm.tsx: dropped the embedded Markdown render, the line-
clamp helper (clampBodyByLines), maxRenderedChars / terminalRows
props, and the two constants that drove them. The modal is now
just a header + open-questions hint + SingleSelect.
- tests/plan-confirm.test.ts deleted — its 5 tests were all for
the removed clampBodyByLines helper.
Everything else (approve/refine/cancel semantics, staged-input
handoff, hasOpenQuestions hint toggle) unchanged. 1054 tests green.
Users hit \`run_skill({"name":"🧬 explore"}) → {"error":"unknown skill: \"🧬 explore\""}\`.
The Skills index wrote entries like \`- 🧬 explore — …\`, with the marker
LEADING the name. Models copied the whole thing verbatim into the
\`name\` argument and the lookup failed (VALID_SKILL_NAME regex rejects
emoji + spaces).
Two fixes, defense in depth:
1. Prompt format (primary fix). Rewrite skillIndexLine so the
subagent marker trails the name, bracketed and labeled:
old: \`- 🧬 explore — …\`
new: \`- explore [🧬 subagent] — …\`
Name comes first, unambiguous. The index intro + tool descriptions
+ CODE_SYSTEM_PROMPT all explicitly spell out "the \`name\` is ONLY
the identifier before the tag."
2. run_skill normalization (belt-and-suspenders). If the model still
passes a decorated name, strip \`[...]\` bracketed tags and pick
the first whitespace-delimited token that starts with a word
character. Handles every shape observed in the wild:
"🧬 explore", "[🧬 subagent] explore", "[🧬] explore",
"explore [🧬 subagent]", " explore " → all resolve to "explore"
Tests:
- tests/skills.test.ts: updated to expect the trailing-tag format,
explicit regression assertion against the old \`- 🧬 name\` pattern.
- tests/tools-skills.test.ts: new "normalizes decorated names" case
exercising each decoration shape through run_skill dispatch.
All 1059 tests green.
Reactive-only escalation (wait for flash to rack up 3+ errors before
bumping to pro) burns tokens and time on tasks flash itself could
recognize as too hard upfront. Add a prompt-level contract: on flash,
the model can output `<<<NEEDS_PRO>>>` as the FIRST line of its
response to abort the current call and retry this turn on v4-pro,
one shot. Pro never self-escalates (the check short-circuits when
modelForCurrentCall === ESCALATION_MODEL).
This matters because non-expert users can't reliably predict which
tasks need the frontier tier. Letting the model self-assess catches
hard tasks upfront — design tradeoffs, architecture refactors, subtle
invariants — without auto-upgrading every prompt (which would destroy
the cost savings from flash-first defaults).
Implementation:
- loop.ts: NEEDS_PRO_MARKER constant, isEscalationRequest() helper,
post-call retry check that sets _escalateThisTurn and re-enters
the iter with `iter--; continue` on match. Streaming path buffers
the first 80 chars / first line before yielding assistant_delta
events so the marker never flickers on-screen before retry fires.
Guarded against infinite retries by checking modelForCurrentCall
against ESCALATION_MODEL — users who already chose /preset max
see the marker as normal content.
- prompt-fragments.ts: new ESCALATION_CONTRACT fragment spells out
when to use the marker (cross-file refactors, subtle correctness
invariants, design tradeoffs) and when NOT to (small edits, clear
bug fixes). Embedded into CODE_SYSTEM_PROMPT, DEFAULT_SYSTEM, and
DEFAULT_SUBAGENT_SYSTEM — subagents default to flash+high too,
so they benefit from the same escape hatch.
Tests (3 new in loop.test.ts):
- flash emits marker → retry on pro, final content is pro's response
- marker mid-text (not lead-in) → no retry
- pro emits marker → no infinite-retry loop
All 1058 tests green.
The previous ARCHITECTURE.md stopped at v0.3 (MCP + session persistence)
and read three-pillar (cache loop, harvest, tool-call repair) with a
roadmap that predates everything from v0.4 onward. After six months
of cost and refactor work the codebase is fundamentally different:
file layout reorganized, defaults flipped flash-first, branch + harvest
removed from every preset, /pro arming and failure-triggered
auto-escalation added.
New sections:
- Pillar 4 — Cost Control as a first-class subsystem: tiered defaults,
turn-end auto-compaction, /pro one-shot arming, failure-signal
auto-escalation, cost transparency thresholds.
- Module layout refreshed — reflects the slash/ + handlers/ split,
the six hooks under cli/ui/, prompt-fragments.ts, and actual LOC
counts (App.tsx 2931 → 1984).
- Design evolution replaces the stale roadmap — covers v0.0 through
v0.6 with a line each so readers orient without reading six months
of CHANGELOG.
- Non-goals updated to call out "automatic cost escalation without
user-visible announcement" as explicitly rejected.
Pillar 2 (harvest) and Pillar 3 (tool-call repair) content kept intact
and marked as before. Pillar 1 unchanged.
Pure docs change — no code touched.
Cost transparency is the last piece of the cost-control design —
users can now see at a glance how much the current turn cost and
which model it ran on, without opening /stats.
StatsPanel header picks up two new pills:
- ⇧ pro armed (yellow) — /pro queued, next turn will run on v4-pro
- ⇧ pro escalated (red) — current turn is on v4-pro (either /pro
armed was consumed at turn start, or the failure threshold
tripped mid-turn auto-escalation)
The cost cell now splits into two readings:
- turn $0.0042 — last turn's cost, colored by threshold
(green <$0.05, yellow $0.05-0.20, red ≥$0.20)
- session $0.1234 — cumulative, same color scale 10× up
(green <$0.50, yellow $0.50-5, red ≥$5)
No hard circuit-breaker that blocks turns — a mid-session pop-up
gate would be annoying. The colored thresholds are the signal;
users who notice yellow/red can /preset fast or /compact before
shipping the next message.
Plumbing:
- telemetry.ts: SessionSummary.lastTurnCostUsd added. Populated by
SessionStats.summary() from the most recent TurnStats.cost.
- replay.ts + ReplayApp.tsx: summary-shape call sites updated.
- StatsPanel.tsx: proArmed/escalated props; CostCell refactor;
turnCostColor/sessionCostColor threshold helpers.
- slash types: armPro / disarmPro ctx callbacks so the /pro handler
can update App's mirror state synchronously.
- App.tsx: proArmed + turnOnPro state mirrors, turn-start/end
transitions, warning-event sniff for "⇧" prefix flips turnOnPro.
Tests: 1055 green, typecheck + biome clean.
Two cost-aware escalation paths join the loop, keeping flash-first
as the default but letting the system (or the user) bump to v4-pro
when flash is visibly struggling — without requiring a persistent
preset switch.
1. `/pro` slash command arms pro for the NEXT turn only. Consumed
at turn start, auto-disarms after the turn ends. Use case: the
user knows the upcoming ask is hard and wants one-shot strength
without typing /preset max + remembering to revert. Separate from
/preset max (persistent, changes this.model) — armed state is
strictly single-turn.
2. Auto-escalation on failure. The loop tracks visible "flash is
struggling" signals per turn:
- edit_file / write_file SEARCH-not-found errors
- ToolCallRepair fires: scavenge, truncation-fix, storm-break
Once the count hits FAILURE_ESCALATION_THRESHOLD (3) in one
turn, the remainder of that turn's model calls upgrade to
v4-pro. Announced via a yellow warning row — no silent cost
surprises. Counter + escalation flag reset at every turn start.
Wiring:
- loop.ts: `_proArmedForNextTurn`, `_escalateThisTurn`,
`_turnFailureCount` private state. Public `armProForNextTurn`,
`disarmPro`, `proArmed`, `escalatedThisTurn` getters for UI.
`modelForCurrentCall()` returns the effective model (escalated
or this.model). `noteToolFailureSignal()` centralizes the
increment+threshold logic.
- All three chat call sites (branch path, streaming, non-streaming)
use `modelForCurrentCall()` instead of `this.model` directly.
- stats.record uses the actual model for cost attribution.
- Library-mode default model: v4-pro → v4-flash (aligned with CLI).
- slash/handlers/model.ts: new `pro` handler with /pro, /pro off.
- slash/commands.ts: /pro registered in SLASH_COMMANDS + /help text.
Tests: 1055 green, typecheck + biome clean.
Context bloat was the real cost driver, not model tier. A single
read_file returning 12K tokens rides every subsequent turn's prompt
at the cache-hit rate; 10 reads accumulate to 100K+ carry-cost
that each turn pays until the 60% reactive threshold kicks in.
By then the user has already paid for 20-40 turns of inflated
context.
Two changes shift us from reactive to preventive:
1. autoCompactToolResultsOnTurnEnd — fires at every `done` event
(normal completion, abort, forced summary). Shrinks every tool
result in the log over 3000 tokens to a tight cap. The model
can re-read the file if it needs fresh detail — one extra
read_file call is far cheaper than dragging 12KB through every
future turn.
2. Proactive in-turn threshold lowered from 60% → 40%. The turn-end
compact already handles the common case; this threshold now
only catches multi-iter turns where one tool returned a huge
payload mid-turn, before the turn ends. 40% triggers earlier
without waiting for context to get tight.
Net impact on long sessions: per-turn prompt tokens stop compounding.
Expected monthly cost reduction for active users: ~3-5× on long
projects where tool results accumulate.
Constants:
- TURN_END_RESULT_CAP_TOKENS = 3000 (new)
- ARGS_COMPACT_THRESHOLD_TOKENS = 800 (unchanged; per-response args shrink)
Tests: 1055 green, typecheck + biome clean.
Overhauls the cost model so `reasonix code` doesn't burn pro-tier
tokens by default. Three principles:
1. The default turn runs on v4-flash, not v4-pro. Pro is a ~12× tier
and shouldn't be implicit. Users escalate with /preset max.
2. Branch and harvest are NEVER auto-enabled by any preset. Both
multiply per-turn cost (N× and +1 flash call respectively); both
now require explicit /branch N or /harvest on.
3. Non-user-facing model calls (forced summary on budget exhaustion,
subagent runs, truncation repair) route through flash+high
regardless of the user's main-turn tier. No reason to pay pro
rates for a wrap-up paragraph or an explore subagent's grep chain.
Preset redefinition (branch=1, harvest=false for all three):
fast v4-flash + effort=high cheapest · Q&A, one-line edits
smart v4-flash + effort=max default · day-to-day coding
max v4-pro + effort=max ~12× fast · hard single-shots
Default preset is now `smart` (was `fast`) — flash+max is the best
price-per-quality point for coding work. `fast` is the "I just want
a quick answer" escape hatch.
Specific changes:
- cli/ui/presets.ts — new PresetSettings shape adds `reasoningEffort`;
PRESETS values rewritten; PRESET_DESCRIPTIONS reflect cost story;
`resolvePreset` default is now "smart".
- cli/resolve.ts — ResolvedDefaults gains `reasoningEffort`; default
preset is "smart".
- cli/commands/code.tsx — default model v4-pro → v4-flash.
- tools/subagent.ts — DEFAULT_SUBAGENT_MODEL v4-pro → v4-flash;
DEFAULT_SUBAGENT_EFFORT = "high" (down from parent's "max").
Skill frontmatter `model:` / `effort:` remain the escape hatches.
- loop.ts — forceSummaryAfterIterLimit hard-codes flash+high for the
wrap-up call; stats.record attributes the actual summaryModel so
/stats reflects reality.
- slash handlers — /preset rewritten (persists effort now); /harvest
and /branch print cost-warning suffixes; /help + /keys text updated
to match new presets and warn harvest/branch are opt-in only.
- CLI --help strings for `reasonix chat` / `reasonix code` / `--preset`
/ `--harvest` / `--branch` updated.
Tests:
- resolve.test.ts: expectations updated to new defaults (flash+max,
no branch in max preset).
- slash.test.ts: preset test expectations updated to new combos.
- subagent.test.ts: default-model fallback expectation updated.
All 1055 tests green; typecheck + biome clean.
The TUI formatting rules (GFM tables, no Unicode box-drawing, no
decorative ┌──┐ frames, flow charts as bullet lists) were
maintained as three near-identical copies across
DEFAULT_SUBAGENT_SYSTEM, BUILTIN_EXPLORE_BODY, and
BUILTIN_RESEARCH_BODY — and missing entirely from
CODE_SYSTEM_PROMPT, even though the main code reply goes through
the same markdown renderer.
Subagents also lacked the "negative claims are the #1
hallucination shape" guardrail that the main code prompt has.
When an explore/research subagent confidently reported "X is
missing", the parent swallowed it at face value.
Changes:
- New src/prompt-fragments.ts holds TUI_FORMATTING_RULES and
NEGATIVE_CLAIM_RULE as shared constants — single source of
truth, embedded literally so prefix-cache hashing stays stable.
- DEFAULT_SUBAGENT_SYSTEM, BUILTIN_EXPLORE_BODY, and
BUILTIN_RESEARCH_BODY import and interpolate both fragments
instead of open-coding their own copies.
- CODE_SYSTEM_PROMPT imports TUI_FORMATTING_RULES and appends it
after the Style section.
- CODE_SYSTEM_PROMPT's intro tool list now names every
filesystem tool (read_file, write_file, edit_file,
list_directory, directory_tree, search_files, search_content,
get_file_info) instead of trailing off at "etc." before the
essential search_content / edit_file were listed.
Behavior change is small and aligned: fewer hallucinated absences
from subagents, fewer Unicode-box-drawing tables to patch around
in markdown.tsx. Typecheck + biome + 1055 tests green.
- biome format pass on EditConfirm / edit-blocks / jobs / shell /
filesystem / compact-tokens / App / slash (auto-fixes)
- drop backtick template on a plain-string literal ("failed",
"(already reverted — …)")
- annotate interceptor useEffect with a useExhaustiveDependencies
ignore — the closure captures are intentional; adding the refs as
deps would tear down the interceptor on every mode flip
- add codeHistory / codeShowEdit to handleSubmit deps
- expand comma-operator tricks in tests/tools.test.ts into
explicit statements (biome rejects `(x = 1, "y")` and comma
operator under lint/style/noCommaOperator + noAssignInExpressions)
prepublishOnly (lint + typecheck + test + build) now passes clean.
1055 tests, dist built.
- EditConfirm modal for per-edit review (scrollable diff); Shift+Tab
cycles review/auto; 5s undo banner + `u` keybind; session edit
history with /history, /show [id] [path], /undo [id] [path]
- run_background / job_output / stop_job / list_jobs tools with
ready-signal detection; /jobs, /kill, /logs; tree-kill (Windows
taskkill /T /F, POSIX process.kill(-pid)) so dev servers actually
stop; cleanup on SIGINT / SIGTERM / exit
- Bottom mode status bar always above the prompt: mode, pending
count, Shift+Tab hint, running-jobs tag; one-time onboarding tip
on first launch after upgrade
- Context hygiene: read_file `range:"A-B"` + auto-preview for files
>200 lines; directory_tree default depth 4→2 + skip deps
(node_modules / .git / dist / …) + per-directory 50-child collapse;
auto-compact tool-call args after each tool response (>800 tok);
/compact now covers both tool results and tool-call args
- Persist reasoningEffort to config so /effort high survives restart
(earlier: silently reverted to max); editMode already persisted
- Prompt: scope discipline on "run/start/launch" requests so the
model stops after verifying instead of auto-refactoring; teach
model that run_background is for dev servers and review-mode
rejections should not be retried with the same SEARCH/REPLACE
tests: 1055 passing (+17 new)
Before: DeepSeek auth/balance/parameter errors surfaced as raw
"DeepSeek 401: {\"error\":{\"message\":\"...\"}}" JSON blobs. Users
saw a wall of JSON and had to know to parse it themselves to learn
their API key was bad or they were out of credit.
formatLoopError now recognizes the per-code cases:
401 → "Authentication failed (DeepSeek 401): <inner msg>. Your API
key is rejected. Fix with `reasonix setup` or
`export DEEPSEEK_API_KEY=sk-...`. Get one at
https://platform.deepseek.com/api_keys."
402 → "Out of balance (DeepSeek 402): <inner msg>. Top up at
https://platform.deepseek.com/top_up — the panel header
shows your balance once it's non-zero."
422 → "Invalid parameter (DeepSeek 422): <inner msg>"
400 → "Bad request (DeepSeek 400): <inner msg>"
Each unwraps `{"error":{"message":"..."}}` so the reader sees prose,
not JSON. Fallback keeps the raw body if parsing fails.
Context-overflow text also refreshed: mentions V4's 1M window AND
the legacy 131k for the chat/reasoner aliases, and drops the stale
"v0.3.0-alpha.6+" reference that's long-since rolled into the 0.5
release line. The "8k tokens per tool result" cap is current
(src/mcp/registry.ts DEFAULT_MAX_RESULT_TOKENS).
429/500/502/503/504/408 retries unchanged — fully absorbed by
retry.ts before they reach formatLoopError.
1013 tests (+6). Lint / typecheck / build clean.
DeepSeek's 2026-04 docs spell out that when concurrency is saturated
but the request is accepted, the connection stays open for up to 10
minutes while the request waits in the queue — non-streaming bodies
fill with empty lines, streaming bodies fill with `:` SSE keep-alive
comments. Both are invisible to our parsers (JSON.parse tolerates
leading whitespace; eventsource-parser drops `:`-prefixed comment
lines per the SSE spec), so no separate handling is needed.
What WAS broken: `timeoutMs` defaulted to 120s. A request that sat
in the queue past 2 min triggered our AbortController, which burned
the queue slot and bounced through retryWithBackoff — potentially
looping through the whole queue repeatedly and never landing.
Fix: bump default to 660_000ms (11 min). Server's own 10-min cap
closes the connection first on genuine queue overflow (clean EOF
→ our retry is normal), while still catching truly hung sockets.
Callers that want a tighter budget (short-lived CI checks, smoke
tests) keep their explicit `timeoutMs` override. No API shape change.
1007 tests. Lint / typecheck / build clean.
- Tagline + /preset max + /think: V3/R1 → V4 (flash + pro)
- /model row lists v4-flash/pro as primary, chat/reasoner as compat aliases
- Add /effort, /resource, /prompt, /models, /context, /stats, /keys rows
- Context window 131k → 1M; test count 648 → 1007
- New "Prompt prefixes — !cmd and @path" section documenting the bang-
mode shell shortcut (0.5.8, now session-durable) and @-mentions
picker (0.5.5-0.5.7) — both are daily-use features that had no home
in the README until now.
- Panel header example bumped from 0.4.22 to the current 0.5.21 with
the reasoning-effort `· max` badge visible.
No code changes.
Models & pricing (src/telemetry.ts):
- Add deepseek-v4-flash (¥0.2 / ¥1 / ¥2 per 1M hit/miss/out) and
deepseek-v4-pro (¥1 / ¥12 / ¥24), converted at 7.2 CNY/USD.
- deepseek-chat and deepseek-reasoner now priced identically to
v4-flash — per the 2026-04 V4 launch they're compat aliases for
flash non-thinking / thinking modes respectively.
- Context bumped to 1M tokens across all four entries.
Defaults shifted to v4-pro (agent-class flagship):
- `reasonix code` mode, subagent DEFAULT_SUBAGENT_MODEL, loop
constructor fallback, `max` preset all point at deepseek-v4-pro.
- `fast` / `smart` presets stay on chat/reasoner — those aliases are
currently our only way to pin thinking ON or OFF via model name,
so the preset system still has a cheap/fast option.
- Subagent tool enum widened to [v4-flash, v4-pro, chat, reasoner];
description flipped to treat flash as the "cheaper opt-out" path.
Thinking-mode toggle + reasoning_effort (new API params):
- src/types.ts ChatRequestOptions gains `thinking?: "enabled" | "disabled"`
serialized as extra_body.thinking.type, and `reasoningEffort?:
"high" | "max"` as the top-level reasoning_effort field.
- src/loop.ts exposes thinkingModeForModel(model) and pins the
correct value per model name (chat=disabled, reasoner=enabled,
v4-*=enabled, unknown=undefined/server-default). Every turn now
sets thinking + reasoningEffort explicitly — no more relying on
server defaults to match what reasoning_content round-trip expects.
- reasoning_effort defaults to "max" because Reasonix is exactly the
agent-class use case DeepSeek's docs call out.
UI: /effort slash + StatsPanel badge:
- `/effort [high|max]` flips the loop's reasoningEffort mid-session.
- `/effort` no-arg reports the current value.
- StatsPanel header shows a green `· max` or yellow `· high` tag next
to harvest/branch/PLAN so users always see which tier the next turn
will use. `/status` flags line also reports it.
Harvest cost tuning (src/harvest.ts):
- Default model reverted to deepseek-chat — harvest is a micro-
extraction (4 small arrays of strings), not agent work.
- chat() call explicitly pins thinking=disabled + effort=high so a
future default-model swap can't accidentally promote this micro-
call into a multi-thousand-reasoning-token request.
1007 tests (+9 new: thinking toggle, /effort slash, v4 pricing).
Lint / typecheck / build clean.
Long assistant responses with many tool_calls used to render as a
single static "building tool call <write_file> · 37 chars" spinner
for 10–30s — user could see tokens being consumed but had no sense of
how many files were coming or how far along the stream was.
Each tool_call's `arguments` blob is now tried as JSON at every delta.
Once it first parses, the index is marked "ready" and the count goes
into subsequent `tool_call_delta` events. The UI label becomes
"building tool call (call 3) <write_file> · 127 chars · 2 ready"
so the user sees progress accumulating.
Dispatch timing is UNCHANGED — this is purely a visibility upgrade.
Mid-stream eager dispatch was considered and punted because it would
interact awkwardly with the repair step (truncation fix, storm
breaker, scavenge) that runs post-stream.
+6 tests locking down looksLikeCompleteJson (the gate that decides
when a streaming call counts as "ready"). 991 tests.
0.5.15 scoped the fix too narrowly — only attached reasoning_content
when `tool_calls.length > 0`. DeepSeek's "thinking mode must be
passed back" rule applies to ANY R1-generated assistant message.
Symptom: plan approved → synthetic user message "implement it now" →
next API call 400s. The intermediate "plan submitted — awaiting
approval" plain-text R1 turn was persisted without its reasoning,
and R1 rejected the entire history the next time around.
Changes:
- assistantMessage() drops the tool_calls guard; reasoning attaches
whenever the model emitted any (even on plain-text turns).
- Forced-summary path (no-tools fallback) now captures reasoning from
the summary response.
- New syntheticAssistantMessage() stamps an empty-string
reasoning_content on synthetic turns (Esc-abort notices) when the
model is a reasoner, so R1's validator is satisfied even when no
real reasoning exists. V3 stays clean.
- Test updated: plain-text reasoner turn now asserts reasoning
DOES round-trip (reversed from 0.5.15's assumption).
985 tests.
Symptom: user wrote a game design doc to `F:/Reasonix/game-design-doc.md`,
the model cited it as `[...](/game-design-doc.md)`, and Reasonix rendered
"✗ /game-design-doc.md → file not found" even though the file was
right there on disk.
Cause: `validateCitation` ran `isAbsolute(path)` on the raw URL. A model
writing `/foo.md` means "project-root relative" (Aider / Claude-Code
convention), but Node's isAbsolute returns true, so the validator
stat'd the literal `/foo.md` under the filesystem root and got ENOENT.
Fix: strip leading `/` or `\` before the absoluteness test. Drive-letter
paths (`C:\...`) still pass isAbsolute and are respected; plain
leading-slash paths become project-relative. Unix absolute citations
like `/etc/hosts` lose precision but are vanishingly rare in code
citations — if we need them we'll add an explicit scheme.
+2 markdown tests for the new leading-slash behavior (both `/` and `\`).
985 tests.
0.5.14's clamp was insufficient. Three root causes the earlier fix missed:
1. TickerProvider kept pumping 120ms re-renders even while the picker
was up — the memo'd PlanConfirm still re-evaluated on every tick
because `onChoose` identity changed (handlePlanConfirm has `busy` in
its deps; busy toggles during model streaming). Fix: disable the
ticker while `pendingPlan` or `pendingShell` is set. No ticker = no
re-render cadence to drive Ink redraws.
2. `clampBodyByLines` clamped SOURCE lines, not rendered rows.
Markdown expands ~2× (wrap, code fences, heading blanks, list
indent), so `rows - 18` source lines still overflowed on a 40-row
terminal. Fix: divide by MARKDOWN_EXPANSION before clamping so the
rendered output actually fits.
3. `handlePlanConfirm` identity churns — wrapped in a ref-stable
`stableHandlePlanConfirm` so `React.memo(PlanConfirm)`'s shallow
compare actually skips re-renders when `plan` + `projectRoot`
haven't changed.
Together these pin the picker's rendered height to a known budget AND
eliminate the re-render loop that caused Ink to clear+redraw each
frame. The overflow-can't-scroll symptom is inherent to Ink's live
mode; only remedy is to make content fit, which the tightened clamp
now guarantees.
DeepSeek R1 thinking mode 400s with "The reasoning_content in the
thinking mode must be passed back to the API" when a tool-loop
continuation replays an assistant message that had tool_calls but
no reasoning. Root cause: assistantMessage() stripped the field.
Fix: ChatMessage gains optional reasoning_content. Loop passes the
captured reasoning into assistantMessage; we attach it only when
the turn has tool_calls AND reasoning is non-empty — plain-text
R1 turns stay lean, deepseek-chat is unaffected.
+2 tests (loop-r1-reasoning): turn-2 body asserts the echoed
assistant message carries reasoning_content on a tool-call turn,
and does NOT carry it on a plain-text turn.
- !cmd bang output now persists via loop.appendAndPersist, so session
resume sees the shell history the model already reasoned against.
- Subagent runs (run_skill · runAs:subagent) now emit cost/model/usage
on their end event. App.tsx writes one row to ~/.reasonix/usage.jsonl
per run; the completion line also shows $X inline. `/stats` and
`reasonix stats` render a new "subagent activity" section with
per-skill breakdown.
- `/resource [uri]` + `/prompt [name]` slashes with argument-level
pickers (reusing 0.5.13's SlashArgPicker). No arg lists what every
connected MCP server exposes; with arg reads via live McpClient
stored on McpServerSummary. Display-only v1 — no loop injection.
`/mcp` now hints toward these when servers expose resources/prompts,
`/keys` gets an "MCP exploration" section, `/help` lists both.
- Bug A — plan picker flicker on small terminals: PlanConfirm's
markdown body is now line-clamped to (rows − 18), and the component
is React.memoed so tick-driven parent re-renders skip the heavy
Markdown subtree when props are unchanged.
- Bug B — pending-edit queue wiped on crash: new
src/code/pending-edits.ts checkpoints the queue to
~/.reasonix/sessions/<name>.pending.json on every parse. /apply
and /discard clear the file; session resume restores it with a
visible banner. deleteSession removes the sidecar too.
981 tests (+31). lint / typecheck / build clean.
Two small course-corrections on the 0.5.13 work-in-progress. Version
stays at 0.5.13 — these land before publish.
### 1. Remove /edit
The one-shot `/edit <file> <instruction>` slash was 99% redundant
with `@path/file.ts <instruction>`: the 0.5.5 `@`-mention already
inlines the file, and code-mode's system prompt already teaches the
model to output SEARCH/REPLACE blocks. `/edit` added only the
"output ONLY a block, no prose" hint — not worth a whole slash.
Reverted:
- case "edit" handler (slash.ts)
- SLASH_COMMANDS registry entry
- /help line
- /edit test describe block + "/help mentions /edit" + required-list
- "file" from the argCompleter union type (no consumer left; the
`@` picker remains the single file-picker surface, avoiding two
competing file-autocompletes)
- "file" branch in App.tsx's slashArgMatches memo + the trailing-
space special case in pickSlashArg
Users who want one-shot edits type `@src/foo.ts fix the typo` —
clearer to read in history and the model obliges by default.
### 2. Picker blocked Enter after exact match
Typing `/preset smart` left the picker visible with one match
("smart") → Enter was intercepted and re-substituted the same value
instead of submitting the command. Fix: slashArgMatches memo now
returns null when the partial is a case-insensitive EXACT match for
an enum value (or a model id). Picker hides; Enter submits.
- Test added documenting that the detector itself remains kind-
only — the hide-on-exact-match logic lives in the App-side memo
so the detector stays UI-agnostic.
### Tests
946 (was 952; dropped 6 /edit-specific tests, added 1 regression
for the exact-match fix, dropped the File-picker-for-/edit detector
test since that path is gone). Lint + typecheck + build clean.
User feedback: "after I type `/edit` there's no hint about what files
exist — same for other commands with args." Fixed.
### Mechanism
SlashCommandSpec gains an `argCompleter` field:
- `"file"` → file picker (reuses atFiles + rankPickerCandidates
with mtime + recently-used ranking from 0.5.12)
- `"models"` → DeepSeek model-id list fetched at startup
- `string[]` → small enum (e.g. `["fast", "smart", "max"]`)
- omitted → no picker, just a dim usage hint below the prompt
Attached to: /edit → file, /preset → enum, /model → models,
/plan → on/off, /harvest → on/off, /branch → off + a few N values.
`detectSlashArgContext(input, codeMode)` in slash.ts classifies the
buffer once the user has typed `/<cmd> ` — returns `{spec, partial,
partialOffset, kind}`. `kind` is "picker" (completable first-arg
position) or "hint" (past the first arg / no completer).
`src/cli/ui/SlashArgPicker.tsx` — new component mirroring the
SlashSuggestions / AtMentionSuggestions layout. Header row always
shows `/<cmd> <argsHint> — <summary>` so even when no matches,
the user sees what's expected. Hint-only mode is a single dim row.
App.tsx: `slashArgSelected` state, `slashArgContext` memo,
`slashArgMatches` memo (dispatches on completer type), useEffect
clamp, `pickSlashArg` callback (splices at partialOffset; adds
trailing space for file picker so user can keep typing the
instruction; no trailing space for enum picks since those commands
take no further args). Wired into useInput arrow/Tab and
handleSubmit Enter intercept. Renders after SlashSuggestions +
AtMentionSuggestions.
### Tests (+11, suite 941 → 952)
tests/slash.test.ts — `detectSlashArgContext` suite covers: null
before name commit, null on unknown cmd, file picker for /edit in
code mode, contextual-command gating outside code mode, enum picker
for /preset, models completer for /model, /plan gated to code mode,
hint kind once partial has internal whitespace, picker with empty
partial (just-typed space), hint kind for free-form arg commands
like /commit.
Lint + typecheck + build clean. 952 tests, 7.5s.
Two UX polishers bundled, closing out the A-E batch.
### D. `@` picker ranking by mtime + recently-used
Alphabetical sort was arbitrary on large repos — 500 files deep, the
first page was almost never what the user wanted. New ranking:
- Empty query → recently-used paths first, then mtime descending,
then path alpha. "Recently used" = files touched by `read_file` /
`edit_file` / `write_file` / `search_content` / etc. tool calls
this session (20-slot LRU; resets on session change).
- Non-empty query → existing substring/prefix scoring, tiebreak by
recently-used membership then mtime.
- Back-compat: `string[]` input with no recency list still returns
input order (old tests pass unchanged).
Implementation:
- `listFilesWithStatsSync(root, opts)` — same walk as listFilesSync
plus a statSync per file. Stat failures don't throw; the entry
keeps `mtimeMs: 0` and sinks to the bottom of the recency bucket.
- `FileWithStats` / `PickerCandidate` / `RankPickerOptions` types
exported for library callers.
- `rankPickerCandidates(files, query, limitOrOpts)` — overloaded:
bare number still works (back-compat), or pass
`{ limit, recentlyUsed }`.
- App.tsx: `atFiles` memo switched to listFilesWithStatsSync;
`recentFilesRef` (useRef<string[]>) + `recordRecentFile(p)` LRU
callback; `tool_start` event handler inspects `toolArgs` for
`path` / `file_path` / `file` fields and feeds the LRU.
### E. `/keys` cheatsheet slash
Discoverability gap: `!` bang, `@` picker, `/` slash, Shift+Enter,
Ctrl+J, Ctrl+A/E, Esc, y/n — the kit is extensive but undocumented
in one place. `/keys` dumps a formatted table:
Keyboard & prompt shortcuts:
Enter submit the current prompt
Shift+Enter / Ctrl+J insert a newline
...
Prompt prefixes:
/<name> slash command
@<path> inline a file (code mode)
!<cmd> run <cmd> as shell
Pickers (slash + @-mention):
↑ / ↓ navigate
Tab insert without submitting
Enter insert + run/keep-editing
Added to SLASH_COMMANDS registry + cross-linked from `/help`.
### Tests (+9, suite 932 → 941)
- tests/at-mentions.test.ts — 5 new for rankPickerCandidates:
mtime sort on empty query with FileWithStats, recently-used boost
trumps mtime, non-empty query tiebreak by recent+mtime, back-compat
input-order preservation for bare strings, numeric-limit literal
as third arg.
- tests/slash.test.ts — 4 new for /keys: shortcuts listed, prefixes
listed, pickers mentioned, /help cross-reference.
### Note on release cadence
A (0.5.9) + B (0.5.10) + C (0.5.11) + D + E were split across five
commits but each dist is cumulative — publishing only the final one
gets users everything. Going forward I'll bundle closer unless the
user asks otherwise.
Lint + typecheck + build clean. 941 tests, 8.3s.
Before /apply, the UI used to show only
▸ 2 pending edit block(s) — /apply or /discard
src/a.ts (-3 +4 lines)
src/b.ts (-1 +1 lines)
— a count summary, nothing about what was actually changing. Common
mistake shape: press y, look at git diff afterwards, discover the
model edited the wrong block / wrong file.
Now each pending block is rendered as a compact diff with ±2 lines of
context and a hard cap at 20 lines per block:
▸ 2 pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop
src/foo.ts (-1 +1 lines)
function foo() {
- const x = 1;
+ const x = 2;
return x;
NEW src/bar.ts (-0 +3 lines)
+ export const bar = 1;
+ export const baz = 2;
+ export default { bar, baz };
### Mechanism
`src/code/diff-preview.ts`:
- `formatEditBlockDiff(block, opts)` — shared leading/trailing lines
collapse to context (default 2 lines each side, `… N unchanged lines
above/below` when truncated). Middle divergence is `-old` / `+new`.
Whole block capped at 20 lines with `… (N more diff lines — full
content applies on /apply)` footer when exceeded. Empty-search
(new file) case shows all-`+` lines.
- `formatAllBlockDiffs(blocks, opts)` — stitches each block's header
(path + ±line counts, `NEW` prefix for new files) + its diff body,
separated by blank lines.
Zero new deps. Small hand-rolled helper using prefix/suffix-compare;
sufficient for the typical SEARCH/REPLACE shape (small change inside
a function body, wrapped in a few lines of surrounding context).
Myers-diff quality is not needed — the model's SEARCH block already
minimizes context.
`formatPendingPreview` in App.tsx dropped its own summary line list
(paths now come from the per-block diff header) and its local
`countLines` helper (moved to diff-preview.ts alongside its only
consumer).
### No colors yet
Plain text, `-` / `+` / ` ` prefixes. ANSI colorization would need
Ink component plumbing that isn't worth the complexity for v1 —
the prefix convention is clear and universal (git / hunks / etc.).
### Tests (+10, suite 922 → 932)
tests/diff-preview.test.ts — new-file all-`+`, context collapse for
shared prefix/suffix, maxLines truncation with footer, leading and
trailing hidden-context annotations, single-line edits, custom
indent, multi-block formatAllBlockDiffs (path+counts headers, blank
separators, empty-input).
Lint + typecheck + build clean. 932 tests.
One-liner shortcut for "change this one thing in this one file" —
faster than the multi-turn code-mode dance of "explain the file",
"here's my plan", "apply", etc. Code mode only.
### Mechanism
Zero new code paths. The slash is sugar: it builds a resubmit text of
@<file> <instruction>
Output ONLY a SEARCH/REPLACE block for this one edit. No prose,
no explanation.
and hands that back through the normal turn machinery:
- 0.5.5's `@`-mention expansion inlines `<file>` under
`[Referenced files]` so the model sees the current content.
- Code-mode's SEARCH/REPLACE handling already catches the output
into `pendingEdits` (0.4.0+).
- The existing y/n confirm gate fires on the next event.
So `/edit src/foo.ts fix the typo` becomes equivalent to the user
typing `@src/foo.ts fix the typo. Output ONLY a SEARCH/REPLACE
block…` — the value is (a) discoverability via /help and slash
autocomplete, (b) the guaranteed-good prompt format without the user
having to remember it.
### Validation
- Outside code mode (no `codeRoot` in SlashContext) → refusal with a
pointer to `reasonix code <dir>`.
- Missing file arg → usage hint.
- Missing instruction → usage hint with the file name echoed back.
### /help + discovery
Added to the slash autocomplete registry (`contextual: "code"` so
it only surfaces in code mode) and to the /help code-mode block.
### Tests (+6, suite 916 → 922)
tests/slash.test.ts — /edit describe block covers: non-code-mode
refusal, missing file, missing instruction, resubmit shape
(contains `@file` + instruction + SEARCH/REPLACE + ONLY), multi-
word instruction preservation. Plus `/help mentions /edit` and
`edit` added to the `SLASH_COMMANDS registry contains every handler`
required-list.
Lint + typecheck + build clean. 922 tests.
Pasting a stack trace / log dump / sample file flooded the Historical
scrollback with a massive block, hiding prior turns. Now user input
that exceeds a threshold renders as:
▸ pasted 2.3 KB (84 lines) — first 10 shown, full text sent to model
line 1
…
line 10
… (74 more lines)
The MODEL still receives the full text. Only the displayed row
collapses — `loop.step(modelInput)` gets the original string
(including any `@`-mention expansion) unchanged.
### Mechanism
- `src/cli/ui/paste-collapse.ts` — `formatLongPaste(text, opts)` pure
helper. Collapse triggers when line count > 40 OR char count > 2000
(defaults, override via opts). Head shows 10 lines; remaining
footer reads "… (N more lines)". Byte header formats B/KB/MB.
- App.tsx — wired at the user-row push site in handleSubmit
(between the UserPromptSubmit hook gate and the loop.step dispatch).
The `pasteDisplay.displayText` goes to the Historical row; the
existing `modelInput` variable (raw or `@`-expanded) goes to the
loop.
### Scope
Affects only the regular user-message row. Separate paths for
`!`-bang commands, `@` expansions, and slash outputs are untouched.
Skipped on short messages (pass-through, no allocation overhead
beyond a `split("\n")`).
### Tests (+10, suite 906 → 916)
tests/paste-collapse.test.ts covers: short pass-through, multi-line
pass-through, line-threshold collapse, char-threshold collapse,
KB/MB formatting, 1-vs-N-more-lines pluralization, custom
thresholds, custom headLines, zero remaining (head covers all),
exported defaults.
Lint + typecheck + build clean. 916 tests.
Claude-Code-style bash mode. User types `!ls src/` or `!git status`;
Reasonix runs the command in the sandbox root, shows both the command
and its output, and appends the combined text to the conversation log
so the next model turn has the context automatically.
Faster than round-tripping through the model just to cat a file or
check git state, and closes a common UX gap vs. Claude Code.
### Mechanism
- `src/cli/ui/bang.ts` — `detectBangCommand(text)` returns the command
body (whitespace-trimmed) or null. Only a LEADING `!` counts; `!`
alone / `! ` returns null; `echo !hi` doesn't trigger (the `!`
isn't at position 0).
- `formatBangUserMessage(cmd, output)` — prepends a `[!cmd]\n`
header so the model can distinguish user-typed shell output from
its own `run_command` tool results (which are `role: tool`,
structurally different).
- App.tsx handleSubmit intercept — fires AFTER the y/n fast-path (so
pending edits still resolve cleanly) and BEFORE slash parsing:
- Push `role: "user"` Historical row with the raw `!cmd` text.
- `await runCommand(cmd, { cwd: codeMode?.rootDir ?? cwd,
timeoutSec: 60, maxOutputChars: 32_000 })`.
- Push `role: "info"` Historical row with
`formatCommandResult(cmd, result)`.
- `loop.log.append({ role: "user", content: formatBangUserMessage
(cmd, formatted) })` so the next step() includes it in
buildMessages.
- setBusy true/false around the run so PromptInput reflects the
in-flight state.
- Catch errors → warning row, don't log.
### No allowlist gate
User-typed `!` is explicit consent (consistent with Claude Code; the
allowlist exists to bound what the MODEL can do with `run_command`,
not what the user chooses by hand). If someone wants stricter gating
later a `REASONIX_BANG_CONFIRM=1` toggle could layer on — out of
scope here.
### Known limitation: session durability
`loop.log.append` updates in-memory only. On session resume, the bang
output is gone (the session file didn't see it). The next actual
step() does appendAndPersist for the next user turn, and the model
sees this bang output live within the same session either way.
Treating bang as ephemeral keeps the fast-path simple; durable
capture could land later if real usage surfaces demand.
### /help + discovery
/help gains a "Shell shortcut" section documenting `!cmd` with
example commands (`!git status !ls src/ !npm test`), plus a
"File references" section covering the `@` picker from 0.5.5 / 0.5.7
that was undocumented there.
### Tests (+9, suite 897 → 906)
tests/bang.test.ts — detectBangCommand covers: body extraction,
whitespace trim, non-bang pass-through, `!`-alone / blank body,
mid-string `!` rejection, embedded-trailing-`!` preservation,
multi-word with flags/quotes. formatBangUserMessage covers header
prepending and verbatim body preservation.
Lint + typecheck + build clean. 906 tests, 8.6s.
Two shipped, both extending 0.5's foundation:
### 1. @mentions picker UI
0.5.5 shipped `@path/to/file` inline expansion but made the user type
the full path. 0.5.7 adds a picker that mirrors the existing
/slash autocomplete: type `@` (with optional partial) in code mode,
get a filtered file list with ↑/↓ navigation and Tab/Enter pick.
- `listFilesSync(root, opts)` — sync recursive walk, skips
node_modules / .git / dist / build / .next / etc. + any dot-dirs.
Caps at 500 results by default. Forward-slash paths on all
platforms. 10-50ms on moderate repos — fits the TUI's single-turn-
per-tick model cleanly.
- `detectAtPicker(input)` — returns `{query, atOffset}` when the
buffer ends with an in-progress mention; `null` otherwise. Distinct
from `AT_MENTION_PATTERN` which finds completed mentions anywhere
for expandAtMentions.
- `rankPickerCandidates(files, query, limit)` — case-insensitive
substring filter with a boost for basename-prefix matches. Empty
query returns the first `limit` candidates alpha.
- `AtMentionSuggestions.tsx` — same shape as `SlashSuggestions`
(matches null = hide, empty = "no matches", array = highlight
selected cyan/bold). Shows basename bold + dir dimmed à la
VS Code Quick Open.
- App.tsx wiring: `atFiles` memo (walk on rootDir change), `atPicker`
/ `atMatches` memos, `atSelected` state with useEffect clamp.
Arrow keys + Tab in useInput (before slash so they don't conflict
— mutually exclusive by construction). Enter in handleSubmit
substitutes at the `@` offset and appends a space (space auto-
dismisses the picker, next Enter submits).
- Limitation intentionally not fixed: files created mid-session by
edit tools won't appear in the picker until next launch. User can
always type the full path. Rebuilding the list on every turn would
be wasteful for the 95% case.
### 2. Bundle smoke test
v0.5.4 shipped to npm with a tokenizer path resolution bug that
crashed on first API call. The unit tests were fine — they load
modules from src/, which doesn't exercise the post-bundle directory
layout. These two tests close that gap:
- `dist/index.js`: dynamic import (via file:// URL on Windows),
invoke `truncateForModelByTokens` to force a tokenizer load. ENOENT
⇒ fail.
- `dist/cli/index.js`: spawn with `DEEPSEEK_BASE_URL=127.0.0.1:1` so
fetch fails fast. Preflight's tokenizer load runs BEFORE fetch, so
if the bundled layout can't find the data file we see the ENOENT
in stderr. If tokenizer loads fine, we see connection-refused and
the test passes.
- Both tests skip when the bundle is absent (dev runs that haven't
built yet). CI runs `build` before `test` → always exercised.
Would have caught 0.5.4's regression pre-publish.
### Tests (+23, suite 874 → 897)
- tests/at-mentions.test.ts — 7 new for detectAtPicker, 2 for
AT_PICKER_PREFIX vs AT_MENTION_PATTERN sanity, 6 for
rankPickerCandidates (empty query, substring, basename-prefix
boost, path-prefix, no-match, limit), 6 for listFilesSync (recurse,
forward slashes, ignore dirs, dotfile inclusion, custom ignores,
maxResults cap, unreadable root).
- tests/bundle-smoke.test.ts — 2 tests for lib + CLI bundle
tokenizer resolution.
Library exports: `detectAtPicker`, `listFilesSync`,
`rankPickerCandidates`, `AT_PICKER_PREFIX`, `DEFAULT_PICKER_IGNORE_DIRS`,
`ListFilesOptions`.
Lint + typecheck + build clean. 897 tests, 8.1s.
**Critical production bug.** Since 0.5.0 introduced the tokenizer, any
bundled `reasonix run` / `code` / `chat` crashed with ENOENT on the
first API turn after 0.5.4 put the tokenizer on the hot path.
Root cause: `resolveDataPath()` used
`join(dirname(import.meta.url), "..", "data", "deepseek-tokenizer.json.gz")`.
- In dev (`src/tokenizer.ts`) → resolves to `data/` ✓
- In the bundled CLI (`dist/cli/index.js`) → `dist/cli/` + `..` +
`data/` = `dist/data/` ✗ — the data file ships at PACKAGE ROOT per
package.json `files` entry; `dist/data/` doesn't exist.
Why this slipped through: before 0.5.4, `countTokens()` was only
called from the opt-in `/context` slash. Casual smoke tests and unit
tests (which run tokenizer.ts directly from src/) never hit the
bundled resolution. 0.5.4's preflight put `countTokens()` on every
step() call — so the first user-facing turn after `npm publish 0.5.4`
would have crashed.
Fix: `resolveDataPath()` now tries multiple candidate paths and
returns the first one that `existsSync`:
1. `REASONIX_TOKENIZER_PATH` env override (unchanged).
2. `../data/...` — dev + bundled `dist/index.js`.
3. `../../data/...` — bundled CLI at `dist/cli/index.js`.
4. `require.resolve("reasonix/package.json")` root — fallback for
unusual bundlers.
Also falls back to `process.cwd() + data/...` if all candidates
missed, so readFileSync surfaces a concrete path in the error rather
than silently missing.
Caught via live `DEEPSEEK_API_KEY=... node dist/cli/index.js run
"hi"` against the actual bundled output. Unit tests alone would not
have caught this (they load src/tokenizer.ts directly, bypassing
the bundle path). Follow-up consideration: an integration test that
runs the bundled CLI against a fake API response — out of scope here.
874 tests still pass. Lint + typecheck + build clean.
Two shipped in one release, both closing out the 0.5 arc:
### 1. Session-load heal migrated to tokens
0.5.2 and 0.5.3 made dispatch truncation, /compact, and auto-compact
token-aware. Session load was the last char-based truncation surface;
now closed. CJK tool results in a resumed session come back at the
same effective context footprint as English instead of slipping past
the old 32k-char cap at 2× the token cost.
- `healLoadedMessagesByTokens(messages, maxTokens)` — sibling of the
existing char-based `healLoadedMessages`.
- `fixToolCallPairing(messages)` — pure helper extracted so both
variants reuse the structural tool_calls ↔ tool pairing pass.
- Session-resume call in loop.ts constructor switched to the token
variant with `DEFAULT_MAX_RESULT_TOKENS`. Stderr "healed" line now
reads "shrunk N tokens of oversized tool output" instead of chars.
- buildMessages's per-turn heal (hot path) stays on the char variant
— avoids a per-turn tokenizer pass on every tool message.
### 2. `@file` mentions in code mode
User types `@src/loop.ts` → the model sees the file content inlined
under a "Referenced files" block:
look at @src/loop.ts and explain
[Referenced files]
<file path="src/loop.ts">
...
</file>
The user's original text is preserved verbatim; expansion is append-
only so the display stays clean and the model can cite the file
unambiguously.
- Regex `(?<=^|\s)@([a-zA-Z0-9_./\-]+)` — requires word boundary so
`[email protected]` and `foo@bar` don't trigger. Trailing sentence
period (`@foo.ts.`) is stripped before lookup.
- Sandbox: relative paths only, resolved against `rootDir`, no `..`
escape, no absolute paths. Violations get
`<file path="..." skipped="escape"/>` so the model sees the refusal.
- `DEFAULT_AT_MENTION_MAX_BYTES = 64 KB` (matches tool-result cap
ballpark). Larger → skipped="too-large" with byte count.
- Missing / not-a-regular-file → skipped with reason.
- De-dupe: same file referenced twice inlines once.
- UI feedback: an info row lists inlined/skipped files so the user
sees what reached the model.
- Only active in code mode (codeMode.rootDir). Plain chat mode
doesn't expand — file references there are ambiguous.
### Tests (+15, suite 859 → 874)
- tests/at-mentions.test.ts — regex: boundary matching, email
rejection, multi-mention; expansion: inline content, de-dupe,
multiple distinct files, missing/escape/absolute/too-large skips,
trailing-dot stripping, directory rejection.
Library exports: `expandAtMentions`, `AT_MENTION_PATTERN`,
`DEFAULT_AT_MENTION_MAX_BYTES`, `AtMentionExpansion`,
`AtMentionOptions`. Plus `healLoadedMessagesByTokens` and
`fixToolCallPairing` from loop.ts.
Lint + typecheck + build clean. 874 tests, 5.2s.
Reactive auto-compact (60%/80% on prior prompt_tokens) keys off the
PREVIOUS turn's server usage, so a fresh resumed session — or one new
oversized tool result — can push the current turn's buildMessages
straight past 131,072 tokens and make DeepSeek 400 with "maximum
context length" before we see any usage number. Preflight closes that
hole by estimating locally before sending.
Mechanism:
- `estimateRequestTokens(messages, toolSpecs)` in src/tokenizer.ts:
`estimateConversationTokens(messages) + countTokens(JSON.stringify
(toolSpecs))`. Mirrors the arithmetic `/context` slash already uses
so the two numbers don't drift.
- loop.step() injection right after buildMessages(). If the estimate
exceeds 95% of `DEEPSEEK_CONTEXT_TOKENS[model]` (fallback
`DEFAULT_CONTEXT_TOKENS`), run `compact(1_000)` and rebuild
messages from the shrunk log. Warning event names the preflight
path + tokens saved.
- When there's nothing to compact (first-ever turn with a bulky
system prompt, for example), still yield a warning naming the
preflight estimate + "nothing to auto-compact — DeepSeek will likely
400". User sees the reason before the crash, can /forget or /clear.
We don't short-circuit the request — let DeepSeek decide; its 400
catch path already surfaces a useful hint.
- Non-branching AND branching paths share the `messages` variable
from the outer buildMessages call, so the one injection covers
both. Forced-summary fallback keeps its own path (a preflight
there would be too late; the summary is the recovery step).
Tests (+3, suite 856 → 859) in tests/preflight.test.ts:
- Fires when estimate > 95%: compact runs, "pre-compacted N tool
result(s), saved M tokens" warning appears, loop still completes.
- Stays silent when estimate is comfortably under 95%.
- Warns (but does not block) when over 95% with nothing to compact.
Per-test context budgets are set by mutating `DEEPSEEK_CONTEXT_TOKENS
[TEST_MODEL]` — the table is `Record<string, number>` so the write
is well-typed; teardown deletes the key. Seeded tool results are
properly paired with a prior assistant.tool_calls so
healLoadedMessages doesn't strip them as orphans (which would make
preflight never fire).
Lint + typecheck + build clean. 859 tests, 5.0s.
0.5.2 put the DeepSeek V3 tokenizer on the dispatch hot path to cap
NEW tool results by real tokens. 0.5.3 extends that to the live log:
/compact and auto-compact now shrink existing tool results by tokens
too, closing the last surface where CJK text slipped past a char cap
at 2× the intended context cost.
Mechanism:
- `shrinkOversizedToolResultsByTokens(messages, maxTokens)` in
src/loop.ts — sibling of the char-based `shrinkOversizedToolResults`.
Fast-pathes tool entries whose length ≤ cap (tokens ≤ length
guarantee); otherwise tokenizes each candidate twice (before +
after `truncateForModelByTokens`) to report exact tokensSaved.
Never tokenizes the full input (same 0.5.2 guard against BPE
O(n²) on pathological repetitive content).
- `loop.compact(maxTokens = 4000)` now shrinks by tokens and returns
`{ healedCount, tokensSaved, charsSaved }` (was `{ healedCount,
charsSaved }`). Persists to the session file when present.
- Auto-compact thresholds in `step()`:
· 60%-80% band: soft compact at 4000 tokens/result (was 16k chars,
which was 4k tokens in English but 16k tokens in CJK).
· >80% band: hard compact at 1000 tokens/result (was 4k chars).
Warnings report exact tokensSaved instead of `charsSaved / 4`.
- `/compact [N]` slash cap semantic flipped from chars to tokens
(default 4000). The `info` line now reads "saved N tokens
(M chars)". Help text + suggestion hint updated.
- Session-load heal (`healLoadedMessages`) left on the char cap so
stored session files keep loading under their existing semantics.
Live compaction and dispatch-time truncation are the only two
surfaces that went token-aware.
Tests (+6, suite 850 → 856):
- tests/compact-tokens.test.ts — small-tool no-op, oversize shrink,
input non-mutation, user/assistant protection, CJK parity, fast
path by length.
- tests/loop.test.ts — seeded log content in the two auto-compact
tests reshaped from `"Z".repeat(N)` to realistic log lines (was
hitting BPE pathological path; also the 60%-80% warning now
reads "4k tokens" instead of "16k" chars).
- tests/slash.test.ts — /compact assertions updated for token-based
output ("saved N tokens", "N tokens each"); test content reshaped
to realistic log lines.
Breaking change: library callers that pass an explicit number to
`loop.compact(N)` expecting chars will now get a tighter cap (4000
tokens ≈ 16k chars English, ~4k chars CJK). Fail mode is "compaction
is more aggressive than expected," which is the safe direction.
Lint + typecheck + build clean. 856 tests, 5.1s.
Before: every tool result was char-capped at 32K chars (8K English
tokens, but 16K+ tokens for CJK — Chinese/Japanese/Korean tool output
slipped past the budget at 2× the intended context cost).
After: dispatch truncates by REAL DeepSeek V3 tokens, using the
tokenizer that shipped in 0.5.0. Default 8K tokens per result, same
effective footprint regardless of char density.
Mechanism (src/mcp/registry.ts:truncateForModelByTokens):
- Fast path `s.length <= maxTokens` — every token is ≥1 char, so
length bounds tokens. Skip tokenize entirely for small results.
- Intermediate check for moderate strings (`length <= maxTokens * 4`)
— tokenize once to confirm it really is over budget.
- For large strings: char-slice head + tail by budget, tokenize the
slices (NOT the full input), shrink on overshoot. 1–2 iterations per
slice, bounded at 6. We explicitly never tokenize the whole input —
pathological repetitive content (`"A".repeat(50_000)`) costs 30s+
in the pure-TS BPE and is bounded to small slices.
- Dropped-tokens count in the marker is estimated from the per-slice
char/token ratio (marker reads "~N tokens") so we don't pay a full
tokenize just for diagnostics.
Wire-up:
- src/tools.ts — `ToolRegistry.dispatch` accepts both `maxResultChars`
(legacy) and `maxResultTokens` (new). Both apply if both set; the
tighter one wins. Char-only callers keep their old behavior.
- src/loop.ts — hot-path dispatch switched from
`maxResultChars: 32_000` to `maxResultTokens: DEFAULT_MAX_RESULT_TOKENS`
(8_000). Session-healing paths still use chars (preserves backwards
compat on loaded session files).
- `DEFAULT_MAX_RESULT_TOKENS` and `truncateForModelByTokens` exported
via src/index.ts for library consumers.
Tests (+9, suite 841 → 850):
- tests/truncate-tokens.test.ts — fast-path, short-string verify,
CJK cap parity with English, head+tail preservation, zero-budget,
empty input, marker format.
- tests/loop.test.ts — existing "pre-clips at dispatch" test reshaped
to use realistic log-line content (was `"A".repeat(50_000)` which
hit the BPE O(n²) pathological path, 46s+ in the suite).
Lint + typecheck clean. Suite now 5.2s total.
Before: model writes `dir | findstr foo` → tokenizer produced `["dir",
"/b", "|", "findstr", "foo"]` → quoteForCmdExe wrapped `|` as `"|"`
(literal) → cmd.exe passed `|` as an argument to dir → no pipe, no
error, silent wrong output. The 0.4.26 memory flagged this as a known
issue; encoding fix from that release made the failure visible but
didn't address the root confusion.
After: detectShellOperator() walks the raw command with quote-tracking
and returns the first unquoted operator token at a token boundary.
runCommand rejects before spawn with:
run_command: shell operator "|" is not supported — this tool spawns
one process, no shell expansion. Split into separate run_command
calls and combine the output in your reasoning...
Quoted operators (`grep "a|b" file.txt`) and chars embedded in larger
tokens (`--flag=1&2`) pass through — those are literal argv bytes.
Matches the tool's stated "no shell expansion, no pipes, no redirects"
contract; turns the silent failure into a loud, actionable one.
Tool description updated to document the rejection + the quote-it-as-
a-literal workaround so the model learns the constraint from the spec.
Tests: 841 (+13 covering pipe, redirect, fd-redirect, &&/||, stuck-
redirect, quoted operators, embedded operators).
CI fix — biome lint surfaced 9 errors on the 0.5.0 commit:
- tokenizer.ts: Infinity → Number.POSITIVE_INFINITY (style/useNumberNamespace)
- tokenizer.ts: formatter wrap on the CJS fallback branch
- StatsPanel.tsx: noArrayIndexKey on the Wordmark map — restructured to a
module-level WORDMARK_STYLES table keyed by char+color pair, dropped
the `i` parameter entirely (previous biome-ignore comment only
suppressed one of two sites the rule fires on)
- various whitespace / line-wrap fixes from `biome check --write`
Animated SVG logo at docs/logo.svg, embedded at the top of README:
- Concentric diamond brand mark (◈) with three layers of motion:
slow rotation (18s), outer-stroke pulse (2.4s), inner-fill breathing
- REASONIX wordmark in the same cyan → fuchsia gradient the TUI uses,
so the README and the running app share one visual identity
- Tagline underneath for SEO-style context
- Colors (~4.5:1 contrast on both GitHub dark and light) — no
prefers-color-scheme switching needed
828 tests, lint + typecheck clean.
Visual redesign — drop the generic vertical bars for a Reasonix-native
design language. The UI should be recognizable as ours at a glance:
- ◈ REASONIX wordmark in truecolor gradient (cyan → violet), with
breathing animation — slow when idle, faster when the model is
thinking, so the app's state is readable from the edge of vision.
- Geometric role glyphs replace all text labels: ◇ user · ◆ assistant ·
▣ tool · ▥ tool-err · ▲ warn · ✦ error. Consistent geometric family,
distinct per role, no overlap with Claude / Cursor / Cline.
- Streaming assistant glyph pulses ◆↔◇ at ~480ms — visible heartbeat
during R1's long (20-90s) pre-first-byte silence.
- Turn separators render "─── ◆ ───" with the Reasonix mark centered.
- Responsive StatsPanel: stacks metrics vertically on <120-col
terminals (SSH, split-pane); inline when there's room. Context
cell gains a 10-cell progress bar in the stacked layout.
- Cold-start cache hit ratio (turn ≤ 3) renders dim gray with a
"(cold start)" hint instead of red — new users stopped reading
"0% cache on turn 1" as a configuration error.
- Tool results tail-truncate by default (useful signal is usually at
the end). ERROR-prefixed results keep the first line + a tail.
- Modal footers gain "[↑↓] navigate · [Enter] select · [Esc] cancel"
hints; Esc actually cancels now (ShellConfirm → deny, PlanConfirm →
cancel); SingleSelect gained an optional footer slot.
- Wait-phase messaging (pre-first-byte, R1 reasoning, branching,
tool-call streaming) gets visible yellow italic instead of dim —
users had been misreading the dim variant as "frozen".
New features:
- Pure-TS port of DeepSeek's V3 tokenizer (vocab + merges + pre_tokenizer
from the official tokenizer.json). Bundled as data/deepseek-
tokenizer.json.gz (1.74MB, slimmed + gzipped from 7.5MB). Zero new
deps — uses built-in zlib. Encodes ~12k tokens of mixed source in
~40ms. scripts/prepare-tokenizer.ts regenerates the bundle from
upstream.
- /context slash — renders a breakdown of the next request's tokens:
system prompt, tool specs, per-turn log, top 5 heaviest tool results.
Answers "where is my context going?" directly; closes the gap where
StatsPanel showed ctx % without saying why.
- /models slash — fetches DeepSeek's live model catalog via
GET /models. Renders the list with the current model marked.
- /model <id> now soft-validates against the fetched catalog (warn
but still switch — accommodates newly-released models we haven't
indexed). DeepSeekClient gains a listModels() method.
Loop + billing correctness:
- Tool results pre-clipped at dispatch time (default 32k chars) via
ToolRegistry.dispatch({ maxResultChars }). Oversized results no
longer bloat the AppendOnlyLog or the persisted session file.
- New proactive-compact tier: when promptTokens / ctxMax crosses 60%
(before the existing 80% reactive guard), shrink oversized tool
results to 16k chars. Catches slow-growth patterns before they
compound into a forced summary.
- DEEPSEEK_PRICING updated to the current unified rates (¥0.2 / ¥2 /
¥3 per 1M at cache-hit / cache-miss / output; USD 0.028 / 0.28 /
0.42 at 7.2 CNY/USD). chat and reasoner are now priced identically
at source. Stats dashboard figures were systematically high under
the old tiered constants — new sessions bill correctly.
- Context display switches to binary-K (128K) to match DeepSeek's
marketing label. DEEPSEEK_CONTEXT_TOKENS stays at 131072 — only
the formatter divisor changed.
OSC 8 clickable hyperlinks in markdown were attempted and reverted:
Ink 5 strips \x1b / \x07 from Text output, so file:// links never
reach the terminal. Documented as a known limit; re-visit with a
future Ink release or raw-stdout approach.
828 tests (14 new: tokenizer golden cases + /context + /models +
listModels + pricing unification + proactive compact). Lint +
typecheck + build clean.
Pillar 2 harvesting fires an extra V3 call per turn to extract a typed
plan state (subgoals/hypotheses/uncertainties/rejectedPaths) from R1's
reasoning_content. Cost ~10-15% per turn. Closer audit of who actually
consumes the output:
- subgoals / hypotheses / rejectedPaths — purely cosmetic, only rendered
in PlanStateBlock. No programmatic consumer. Can mislead users by
giving structured-looking output extra perceived authority (today's
citation work was triggered by hallucinated "hypotheses" that looked
thoughtful).
- uncertainties.length — single real downstream use, drives self-
consistency branching when count exceeds threshold. Could be replaced
with a cheap heuristic on the raw reasoning text.
For coding tasks specifically, branching is rarely on (default budget=1)
and the cosmetic display value doesn't justify the per-turn premium.
Flip the default off; users who genuinely want the plan state surfaced
can pass --harvest. `reasonix chat` is unchanged — preset behaviour
there still controls harvest.
799 tests, lint + build clean.
Anti-hallucination intervention for evaluative tasks. Two real R1 sessions
where the model invented "Resources/Prompts/Progress not implemented" gaps
that had been shipped months ago (v0.4.5, v0.4.8) motivated this — same
hallucination shape both times, across independent prefixes. The fix is
structural: force the model to ground every codebase claim in a clickable
citation, validate them, render broken ones in red so the user sees
fabrications instantly.
- markdown.tsx: parse [text](url) links (was unsupported — rendered as
literal). External URLs (https://, mailto:, //) → blue underline.
Citation-shaped URLs (path / path:line / path:start-end / path#L42) →
validated against projectRoot, valid = cyan underline, broken = red
strikethrough + ❌. Bottom-of-message BrokenCitationsBlock lists each
failure with reason ("file not found", "line 999 > 250") so the user
can challenge the specific claim.
- code/prompt.ts + cli/index.ts: "Cite or shut up — non-negotiable"
section moved to TOP of system prompt (was at the end and ignored).
Concrete ✅/❌ examples. Negative-claim rule made imperative — "STOP.
Call search_content FIRST" instead of "qualify it" — because asserting
absence without checking is the #1 failure mode.
- App.tsx / EventLog.tsx / PlanConfirm.tsx: thread projectRoot through
every <Markdown /> callsite (defaults to process.cwd() for safety).
Behavioural validation: same "analyze the project" prompt that produced
5/8 hallucinations pre-fix returned 3/3 verifiable specific claims +
1 auto-detected broken citation post-fix. Citation feature working in
production.
799 tests (17 new in markdown.test.ts: parseCitationUrl, isExternalUrl,
validateCitation, collectCitations dedup + external skip, parseBlocks
no-regression). Lint + typecheck + build clean.
- Subagents-via-Skills (replaces 0.4.25's spawn_subagent user-facing
surface; library API kept). Skills frontmatter gains runAs:subagent +
optional model:deepseek-*. Builtin explore + research skills ship in
src/skills.ts as constants. spawnSubagent(opts) extracted from
registerSubagentTool — both surfaces share it via formatSubagentResult.
registerSkillTools moved into App.tsx with subagentRunner closure;
reasonix code no longer registers spawn_subagent in the model tool list.
Pinned Skills index marks subagent skills with a 🧬 prefix so the model
pattern-matches "user says explore -> use 🧬 explore" instead of
reasoning about whether a task is "big enough" to delegate.
- search_content: real content grep tool. Skips 18 dependency / build /
VCS dirs by default + skips binaries by extension (30+ types) and
by content sniff (NUL byte in first 8KB). Per-file 2 MB cap, output
capped to maxListBytes. Regex + literal fallback, glob substring
filter, case_sensitive + include_deps options. Closes the gap that
made subagents waste their iter budget calling search_files (which
is filename-only) for content-grep questions.
- markdown renderer: recognizes Unicode box-drawing tables (│ ─ ┼) +
┌─┐ │ └─┘ frames as code blocks. Table cells now render through
InlineMd with padTo so backticks/bold inside cells parse and column
widths align by visible (post-strip) width. Multi-line table cell
continuation rows fold back into the previous row's last cell.
- shell on Windows: prepareSpawn injects chcp 65001 prefix into every
cmd.exe /c payload + injects [Console]::OutputEncoding=UTF8 into
PowerShell -Command invocations. Fixes mojibake on CJK Windows where
cmd builtins (dir, findstr, where) and PowerShell emit text in CP936
/ CP932 / CP949 — previously poisoned the next turn's prompt with
garbled bytes.
- sandbox: filesystem tools' safePath strips leading / and \ so
POSIX-absolute paths (path: "/" or "/src/foo.ts") resolve to the
sandbox root instead of the actual filesystem root. Models routinely
pass these intending the project root; the old behavior failed the
escape check with a confusing error.
- loop: aborted signal in the API-call catch yields a clean done
instead of a red error event. The "This operation was aborted" row
was always a self-inflicted UX bug — App.tsx calls loop.abort() to
switch turns when the user picks ShellConfirm "always allow" or
PlanConfirm approve, and the resulting AbortError got rendered as
a real error. Subagent layer compensates by synthesizing an error
result when no final answer was produced (so success!=true on abort).
- prompts: dropped the fictional `grep` tool reference from
CODE_SYSTEM_PROMPT; explicit list of available exploration tools
(read_file, list_directory, directory_tree, search_files,
search_content, get_file_info). New "Path conventions" section
distinguishes filesystem-tool sandbox-relative paths from
run_command OS-shell paths (don't use leading / in shell args).
781 tests (+26 vs 0.4.24), lint + typecheck + build clean.
Every turn run through `reasonix chat|code|run` now appends one line
to ~/.reasonix/usage.jsonl carrying tokens + cost + the equivalent
Claude Sonnet 4.6 cost. `reasonix stats` (no arg) rolls that log up
into today / week / month / all-time windows with a "saved vs
Claude" column. Pillar 1's pitch (94–97% cost reduction) becomes a
fact users can check on their own machine.
Same dashboard is available in-session via the new /stats slash,
reading from the same file and rendering through a shared pure
renderer. reasonix stats <transcript> keeps the old per-file
summary (assistant turns + tool calls) for scripts.
Privacy: only tokens, costs, session name. No prompts, completions,
or tool args. Log append is best-effort — disk failure never blocks
a turn.
New files:
src/usage.ts — appendUsage, readUsageLog, aggregateUsage,
bucketCacheHitRatio / SavingsFraction
tests/usage.test.ts — 15 tests (round-trip, malformed line,
rolling windows, renderer, zero denom)
Modified:
src/cli/commands/stats.ts — dashboard mode + extracted renderDashboard
src/cli/commands/run.ts — appendUsage on assistant_final (for CI)
src/cli/ui/App.tsx — appendUsage on assistant_final (TUI)
src/cli/ui/slash.ts — /stats slash (shared renderer)
src/cli/index.ts — `stats <transcript>` → `stats [transcript]`
src/index.ts — re-export usage module
+17 tests (suite 708 → 725). Lint + typecheck + build clean.
Adds an in-session `/update` slash that reports the running version
and the last-resolved latest from the App's background npm-registry
check. Deliberately does NOT spawn `npm install` — stdio:inherit
into a running Ink renderer corrupts the display, and on Windows
the currently-running binary can be locked. Users exit and run
`reasonix update` in a fresh shell when they actually want to
install.
Also splits App state: we now track `latestVersion` regardless of
whether it's newer (so the slash can tell "on the latest" apart
from "still fetching") and derive the yellow header badge from
that. Before this, `updateAvailable` was only set on strictly-
newer, so `/update` saw null when the user was already on the
latest — the message misleadingly said "background check in
flight or offline".
`/update` also triggers a fresh `getLatestVersion({force:true})`
when latestVersion is null, so a retry a few seconds later sees
a concrete answer.
4 new tests (suite 704 → 708). All green; lint / typecheck / build
clean.
Same two-scope layout as memory and skills:
- <project>/.reasonix/settings.json (committable per-project)
- ~/.reasonix/settings.json (per-user)
A hook is a shell command. Reasonix invokes it with stdin = a JSON
envelope carrying the event, tool name, tool args, etc. Exit code
drives the decision:
- 0 = pass; loop continues normally
- 2 = block (only on PreToolUse / UserPromptSubmit); hook's stderr
becomes the synthetic tool result the model sees, or the prompt
is dropped entirely
- anything else = warn; loop continues, stderr renders inline as a
yellow row
Project hooks fire before global hooks. `match` is anchored regex on
the tool name (ignored for prompt / Stop events). Default timeouts:
5s for blocking events, 30s for logging events; per-hook `timeout`
overrides. Settings malformed? loadHooks swallows it so a typo
doesn't bring down the whole CLI.
Deliberate non-goals: no workflow DSL, no conditional chaining, no
hook templates. Hooks are shell commands — the user already has a
programming language.
New files:
- src/hooks.ts (loadHooks, runHooks, decideOutcome, matchesTool, formatHookOutcomeMessage)
- tests/hooks.test.ts (26 unit tests)
- tests/loop-hooks.test.ts (6 smoke tests — loop wiring)
Modified:
- src/loop.ts — PreToolUse + PostToolUse dispatch around tool.dispatch
- src/cli/ui/App.tsx — load settings on mount, UserPromptSubmit before handleSubmit, Stop after loop.step
- src/cli/ui/slash.ts — /hooks list + /hooks reload
- src/index.ts — re-exports
+32 tests (suite 672 → 704). Lint / typecheck / build clean.
Two small quality-of-life additions.
The stats panel now carries the running version (`Reasonix v0.4.22 ·
model …`) so users can tell at a glance whether they're on the latest
build. A 24-hour background check against the npm registry surfaces a
yellow `update: X.Y.Z` nudge on the right side of the same row when a
newer version has been published — 2s timeout, cache at
`~/.reasonix/version-cache.json`, silent on failure.
`reasonix update` is the command form: detects global install vs npx,
spawns `npm install -g reasonix@latest` for the former or prints a
cache-refresh hint for the latter. `--dry-run` prints the plan.
Also fixes a drifted VERSION constant: `src/index.ts` hard-coded
"0.4.20" while package.json was on 0.4.21. Now re-exports from
`src/version.ts`, which walks up from import.meta.url to the
manifest on first access. A regression test pins them together.
New files: `src/version.ts`, `src/cli/commands/update.ts`,
`tests/version.test.ts`, `tests/update-command.test.ts`. +24 tests
(suite 648 → 672). Lint/typecheck/build clean.
- Quick start now leads with `reasonix code` and a real SEARCH/REPLACE
walkthrough — nobody enters through plain chat.
- New Skills section covers the SKILL.md format, project vs global
scopes, /skill slash family, autonomous run_skill invocation, and
the 'not tied to .claude/' stance.
- chat mode demoted to a brief 'also works as' section pointing at MCP.
- Commands table grouped by category (Core / Model / Context & tools /
Memory & skills / Sessions / Code-mode only) instead of one flat list.
- Benchmarks promoted into their own 'verify yourself' section.
- Non-goals now names workflow DSL / DAG engine and DeepSeek-only
positioning explicitly.
- Test count 444 → 648, Node requirement 18 → 20.10, added
REASONIX_UI=plain to the env-var list.
Skills are user-authored prompt packs read from `<project>/.reasonix/skills/`
and `~/.reasonix/skills/`. Pinned index (names + one-liners) lives in
the immutable prefix; bodies load lazily via the new `run_skill` tool
or `/skill <name> [args]`. Project scope wins on name collisions.
Deliberately NOT tied to any other client's dir (.claude/, .glm/) —
Reasonix is model-agnostic at the conversation layer.
No workflow DSL or DAG engine: skills are prose, the model sequences
via the existing tool-use loop. Preserves single-loop + append-only +
cache-first invariants; "no multi-agent orchestration" non-goal stands.
Shell fixes bundled in:
- ShellConfirm "always allow" now takes effect mid-session.
extraAllowed is re-read on every dispatch via a getter, so a prefix
saved to ~/.reasonix/config.json applies to the running tool
without needing /new or a relaunch.
- Windows cmd.exe built-ins (dir, echo, type, ver, ...) no longer
crash with ENOENT. prepareSpawn routes bare unresolved Windows
commands through `cmd.exe /d /s /c` with verbatim-args quoting,
matching the wrapping strategy for .cmd/.bat files.
- MemoryStore + applyUserMemory + applyMemoryStack (src/user-memory.ts):
two scopes — global (cross-project) and project (per sandbox-root sha1).
Each scope keeps a MEMORY.md index pinned into ImmutablePrefix.system;
detail files loaded on demand via recall_memory. Byte-stable rewrite
so identical file sets produce identical prefix hashes.
- remember / forget / recall_memory tools (src/tools/memory.ts) — chat
mode gets global-only; reasonix code gets both scopes. remember's
return text is imperative so R1 treats the fact as authoritative on
the same turn.
- /memory slash extended: list | show <name> | forget <name> |
clear <scope> confirm. Bare /memory renders REASONIX.md + both
MEMORY.md blocks together.
- Prompt cleanup: dropped hardcoded dir enumerations, bun/npm examples,
"待确认" CJK fallback, DSML-hallucination historical note, and
Linear/Slack type-hint specifics. Principle-only wording + reference
to the pinned .gitignore block. Net -tokens on every turn.
- README: new "User memory" subsection under REASONIX.md.
- scripts/smoke-memory.mts: 30-assertion end-to-end regression script.
- REASONIX_MEMORY=off now disables every memory source (REASONIX.md +
user memory) — previous semantics was REASONIX.md only.
Tests: 542 → 624 (+82 incl. 36 memory-layer unit tests). Lint / tsc /
build clean.
CI runs on Linux, where pathMod.join defaults to POSIX (`/`). The
PATHEXT resolver mocks its isFile predicate with back-slashed keys
(`C:\tools\npm.CMD`), so join with POSIX produced `C:\tools/npm.CMD`
and lookups missed, failing 8 tests at origin. The runtime call path
is unaffected either way since the win32 branch is only active when
platform === "win32" anyway — but making the join explicitly win32
also hardens against weird PATHs on Windows where forward slashes
have historically crept in.
A silent storm-break was indistinguishable from a stalled turn — the
model would look like it gave up when really we'd suppressed its
repeat tool call. Now `step()` emits a dedicated warning event when
`report.stormsBroken > 0`, with distinct messages for the two cases:
- All calls suppressed (stuck retry): tell the user the model is
looping on the same (tool, args) and point them at /retry or
rewording the instruction. This is the case that used to dead-end
the turn with nothing on screen.
- Some calls suppressed (one redundant): the rest of the turn
proceeds; the warning is informational.
Also reset the StormBreaker's sliding window at the top of every
`step()` so a new user message doesn't inherit last turn's repeat
patterns (false-positive blocks on legitimate "try again" flows).
Part of the 0.4.19 batch — tag will be moved to this commit.
Two layered fixes so `run_command` actually runs npm/npx/tsc/yarn/
pnpm/bun/pytest and every other Node-ecosystem wrapper on Windows:
1. resolveExecutable() walks PATH × PATHEXT manually — spawn
with shell:false uses CreateProcess, which ignores PATHEXT, so
bare `npm` missed `npm.cmd` and ENOENT'd.
2. prepareSpawn() wraps .cmd/.bat via `cmd.exe /d /s /c` with
windowsVerbatimArguments + per-arg quoteForCmdExe — Node 21.7.3+/
24 (CVE-2024-27980) refuses direct spawn of .cmd/.bat even with
shell:false, throwing EINVAL. cmd.exe wrapping with manual
safe-quoting keeps shell metacharacters (&, |, <, >, etc.) in
arguments literal so the previous security posture holds.
Unix path unchanged. Suite 566 → 587.
submit_plan tool: model proposes a markdown plan for large tasks
(multi-file refactors, ambiguous requests, risky changes). Picker
shows Approve / Refine / Cancel with the plan rendered as live
Markdown, not raw text. Open-questions sections ("Open questions",
"待确认", "Risks", etc.) are detected; default selection flips to
Refine and a yellow hint surfaces.
Both Approve and Refine take an inline text input afterward so the
user can answer the model's open questions or attach last-minute
instructions before the loop resumes. Empty Enter on Approve skips
the extras; empty Enter on Refine tells the model to ask concrete
clarifying questions.
/plan slash flips a dispatch-level read-only gate on the
ToolRegistry — writes + non-allowlisted shell bounce with a refusal
the model reads. Read tools, web_search/fetch, and allowlisted shell
(git status / cargo check / npm test etc.) still work during
exploration. Tool specs stay pinned across the toggle so the DeepSeek
prefix cache doesn't break.
/apply-plan is a fallback that force-approves without the picker,
for cases where the model wrote the plan in assistant text instead
of calling submit_plan.
Suite 542 → 566.
Drop a REASONIX.md in the project root and its contents are pinned
into the system prompt every session that opens there. Cache-first:
read once, hashed into the prefix fingerprint, no per-turn budget.
/memory prints what's currently pinned; REASONIX_MEMORY=off opts out.
Suite 517 → 542. Re-exported applyProjectMemory / readProjectMemory /
memoryEnabled + PROJECT_MEMORY_FILE / PROJECT_MEMORY_MAX_CHARS for
library consumers that build their own system prompt.
Two DeepSeek 400s users hit in succession:
- "insufficient tool messages following tool_calls" on forced
summary: context-guard appended assistant.tool_calls then bailed
before dispatching. Fix: strip the tail before forceSummary.
- "tool must be a response to a preceding tool_calls" on the next
message: partial heals left stray tool messages in the log.
Root fix: healLoadedMessages now runs a full tool_calls↔tool pairing
validator. Any assistant.tool_calls with an incomplete response set
is dropped (with its partial responses); any stray tool message is
dropped. Runs on session load (rewrites the file so damage doesn't
re-surface) AND on every buildMessages call (defensive).
Context-guard now auto-compacts before forcing summary. Previously
80% context meant you lost a turn immediately. Now: try shrinking
oversized tool payloads first; only fall back to forced summary
when nothing's compactable.
Split shrinkOversizedToolResults from healLoadedMessages so
`/compact` (mid-turn) doesn't strip legitimate structural state.
443 tests (+5 new, 4 reshaped).
edit_file now produces a real git-diff-style output:
- LCS line-level diff (unchanged lines as ` ` context, `-/+` only
for actual changes). Fixes the user-reported case where a one-line
search with a multi-line replace showed the unchanged line as both
`-` and `+`.
- Git-style @@ -start,count +start,count @@ hunk header pointing at
the real starting line in the file.
- EventLog no longer truncates edit_file results — other tools keep
the 400-char clip, but edit diffs always show full.
Context management:
- /new (alias /reset) drops the in-memory log AND empties the
session file. Fresh conversation, same session/model/config.
- /clear now advertises that it only clears visible scrollback;
users kept expecting it to clear context. Info line points at
/new for the real clear.
- CacheFirstLoop.clearLog() is the public API.
Streaming row:
- Replaced "streaming · 391 + think 4506 chars" with explicit
phase labels: yellow "request sent · waiting for server" pre-
first-byte, cyan "R1 reasoning · N chars of thought" during
reasoning-only, green "writing response · N chars · after M
chars of reasoning" in content phase.
436 tests (+8).
Major batch of UX fixes based on user reports:
Silent-wait elimination:
- New "status" loop event + StatusRow component. Fills silent
phases with explicit magenta spinner text: "tool result uploaded
· model thinking before next response…" between iters,
"extracting plan state from reasoning…" before harvest,
"summarizing what was gathered…" before forced summary. Auto-
clears on the next primary event.
- Belt-and-suspenders "processing…" fallback when busy but none of
streaming/ongoingTool/statusLine is visible — catches any
micro-gap the targeted statuses don't cover.
- Strengthened pre-first-byte messaging: "(request sent · waiting
for server)" instead of "(streaming · 0 chars)".
Stats panel:
- Live per-iter refresh — previously frozen at prior turn's
numbers for 30-60s during multi-iter chains.
- Account balance cell. New DeepSeekClient.getBalance() hits
/user/balance (separate endpoint, no billing impact). Refreshed
after each turn, hidden on failure.
- In/out cost split. Panel now shows "cost $X (in $Y · out $Z)"
so users can see where spend lands. SessionSummary gains
totalInputCostUsd + totalOutputCostUsd; inputCostUsd() and
outputCostUsd() exposed as library utilities.
- Dropped "vs Claude / saving" cells — the synthetic ratio looked
like marketing, not measurement. Fields kept in summary for
benchmark/replay compat but deprecated.
Esc coverage:
- harvest() now takes an AbortSignal and fast-paths to emptyPlanState
when already aborted. Was the last un-signaled API call path.
edit_file visibility:
- Tool result now returns a unified-style `- search / + replace`
inline diff in addition to the header. Long blocks are truncated
with "… (N more lines)" marker in the middle; /tool N still shows
the full thing.
Markdown:
- GFM tables (|col|col| + separator) render as aligned columns
with │ dividers. CJK-width-aware padding for mixed-lang tables.
Alignment colons, pipe-less headers, escaped \| in cells all
handled. Stray | in prose no longer false-triggers the table
path.
427 tests (+11).
Three reported issues rolled into one release:
1. Esc now truly cancels in-flight work. AbortController threaded
through every I/O path:
- DeepSeekClient.chat/.stream signal wired at every call site
- ToolRegistry.dispatch gets a ToolCallContext { signal }
- McpClient.callTool({ signal }) fires notifications/cancelled
AND rejects the pending promise immediately — no waiting on
subprocess for a graceful finish
- bridgeMcpTools forwards ctx.signal down
2. Built-in filesystem tools replace the
@modelcontextprotocol/server-filesystem subprocess inside
`reasonix code`. 10 native tools, sandboxed, R1-friendly schemas.
The new edit_file takes a flat SEARCH/REPLACE shape instead of
the JSON-in-string array that was the single biggest driver of
R1 DSML hallucinations in 0.4.x. Per-call latency drops from
~500ms–2s (Windows subprocess IPC) to <10ms (direct fs).
3. PromptInput placeholder cursor now renders at position 0
(before the hint text), not after it.
4. Bonus: slow_count demo tool in examples/mcp-server-demo.ts
emits real notifications/progress frames so the progress-bar
plumbing from 0.4.8 is testable end-to-end.
ChatOptions grows `seedTools: ToolRegistry` so callers can
pre-register tools and still layer MCP on top. ToolCallContext
is re-exported for library users writing abortable tools.
416 tests (+29: filesystem-tools +26, mcp abort +3).
MCP notifications/progress now route to per-call onProgress handlers.
Long-running tool calls can stream incremental progress; the spinner
row renders an ASCII bar + n/total + pct when the server reports a
total, or free-form progress+message otherwise.
- McpClient.callTool(name, args, { onProgress }) mints a fresh
_meta.progressToken and routes progress frames back. Handler is
dropped on completion — late frames are swallowed silently.
- bridgeMcpTools({ onProgress }) pipes per-call progress through
with the registered (prefix-applied) tool name.
- chatCommand creates a shared progressSink ref; App.tsx wires its
setState handler through on mount.
Other server-initiated notifications (list_changed) still dropped
— no use case yet.
387 tests (+5).
Replaces ink-text-input in the main chat prompt with a custom
multi-line composer. Three newline-insertion paths in reliability
order: Ctrl+J (universal), Shift+Enter (modern terminals), trailing
"\" + Enter (portable fallback). Pasted multi-line content lands
intact instead of submitting on the first '\r'.
Pure processMultilineKey reducer keeps the keyboard semantics
testable; the React component is a thin wrapper. Parent-owned keys
(Tab, arrows, Esc) are no-ops in the reducer so the buffer never
eats a stray control sequence when both useInput listeners fire on
the same event.
Cursor-at-end model (no mid-string edits) — simple, predictable,
and doesn't collide with parent's arrow-key slash-nav + history.
ink-text-input still used by Wizard/Select/Setup — fine for
single-line forms.
382 tests (+18).
UX overhaul:
- Typing `/` pops an IntelliSense-style suggestion list with name +
args hint + summary. ↑/↓ navigate, Tab completes, Enter picks +
runs. Registry-driven (SLASH_COMMANDS) with code-mode gating.
- Static command-strip footer under the input is gone — superseded
by the on-demand slash popup.
MCP discovery:
- /mcp in chat is now a rich per-server view: server info + spec +
tool count + resources list + prompts list. Unsupported sections
render "(not supported)" cleanly. Inspection runs once at
startup and flows through SlashContext.mcpServers.
- New `reasonix mcp inspect <spec>` CLI for running the same
discovery outside chat (CI, scripting, "does this work?"). --json
emits the full InspectionReport.
- inspectMcpServer() + InspectionReport are public APIs; McpClient
gains serverInfo / protocolVersion / serverInstructions getters.
364 tests (+11).
Two protocol-level completions bundled:
1. DSML tool-call recovery. scavengeToolCalls gains a DSML invoke
parser (<|DSML|invoke>/<|DSML|parameter string="true|false">).
ToolCallRepair.process now scans both reasoning AND content
channels — before, DSML in a regular turn was stripped from
display but the tool never actually ran.
2. MCP resources + prompts. McpClient gains resources/list,
resources/read, prompts/list, prompts/get with full types and
cursor pagination. Initialize now advertises all three
capability families.
353 tests (+13: scavenge +5, pipeline +2, mcp +6).
EventLog clips tool results at 400 chars for display; /tool [N]
now lets users read the full text. `/tool` lists the 10 most
recent with previews and char counts; `/tool N` dumps the
Nth-most-recent in full. Wired via new SlashContext.toolHistory
callback — pure handleSlash stays stateless.
340 tests (+8 /tool cases).
User feedback: after pressing Esc, the warning fired instantly but
then the TUI blocked for the duration of a full reasoner call
(30-90s) to produce a "summary" the user hadn't asked for. Esc in a
terminal means stop. Stopping and then forcing the expensive
reasoner to wrap up is the opposite of what the user signaled.
Abort path now:
- Emits a short warning "aborted at iter N/M — stopped without
producing a summary (press ↑ + Enter or /retry to resume)"
- Appends a synthetic assistant message "[aborted by user (Esc)
— no summary produced. Ask again or /retry when ready; prior
tool output is still in the log.]"
- Yields assistant_final (tagged forcedSummary so edit applier
ignores) + done
- No API call. Takes milliseconds.
Budget and context-guard paths still call forceSummaryAfterIterLimit
because in those cases the loop stopped, not the user — leaving
them staring at nothing would be worse than one extra call. Only
user-initiated abort gets the fast path.
Test rewritten to confirm no extra API call is made (previously
asserted a "partial findings" summary from the never-needed
follow-up). Suite: 332 still passing.
Also bumps to 0.4.3 because v0.4.2 tag is already on origin at
cb2f2a5 with partial content. This release consolidates the full
0.4.2 batch + the Esc fix under one tag.
Nine UX improvements in one batch, all surfaced from real-session
feedback while testing reasonix code against a live filesystem
project.
Added slash commands:
- /retry — truncate log back before the last user message, resend
it, get a fresh sample from the model. SlashResult gains a
resubmit field the TUI honors after displaying info.
- /status — now a labeled situation-report: model, flags
(harvest/branch/stream), ctx ratio (42k/131k (32%)) from last
turn's promptTokens, MCP server + tool counts, session name +
log length + resumed count, pending edits count. One command
shows everything.
- /think (alias /reasoning) — dumps full R1 reasoning from
loop.scratch.reasoning. For when the 260-char tail preview
isn't enough. Graceful "no reasoning cached" when using
deepseek-chat.
Added interactions:
- ↑/↓ shell-style prompt history. App.tsx owns a ref array, cursor
advances on arrow keys while idle. Process-scoped, no cross-run
persistence.
- y/n fast-path when edits are pending. Typing 'y'+Enter = /apply,
'n'+Enter = /discard. Scoped: only when pendingEdits.length > 0,
so plain "y" as a normal message still works when nothing's
waiting. Preview line advertises the shortcut.
Changed:
- Tool-running row surfaces elapsed seconds + per-tool argument
summary. Before: ⠋ tool<filesystem_edit_file> running… {raw
JSON}. Now: ⠋ tool<filesystem_edit_file> running… 3s / path:
F:\... (2 edits). Summarizers for read_file, write_file,
edit_file, list_directory, directory_tree, search_files,
move_file, get_file_info. Matches suffix so namespaced and
anonymous servers both work.
- Reasoning preview shows tail (~260 chars), not head. R1 opens
every turn with the same scaffolding that hid the actual
decision in the (+N chars) elision; users reported reasoning
looked identical across turns. The tail is where the model
commits to an action.
- Tool errors render red with ✗ marker instead of yellow with →.
ERROR: prefix from flattenMcpResult (on isError) is detected.
A failure needs different attention than a listing.
Fixed:
- Forced-summary path no longer leaks DSML tool-call markup as
prose. Passing tools: undefined wasn't enough — R1 primed for
tool use would still emit <|DSML|function_calls>...</|DSML|
function_calls> as plain text in content. Two layers: (1)
inject an explicit user-role instruction at the end of the
forced-summary message list telling the model to produce prose
with no tool markup; (2) post-hoc strip known envelopes (DSML
full-width/ASCII, Anthropic <function_calls>, and truncated
un-closed DSML openers) from the model's response before
yielding. stripHallucinatedToolMarkup exported for library
callers. Fallback message when stripping leaves nothing points
at /retry and /think.
Tests: +13, suite 319 -> 332.
- tests/slash.test.ts (+8): /think empty/populated/help,
/retry happy/empty-log/help, /status new format, /status
pending-edit suppression at 0.
- tests/loop-error.test.ts (+5): stripHallucinatedToolMarkup
against live R1 DSML shape, Anthropic-style, truncated
un-closed opener, plain prose, all-markup edge case.
Bumps to 0.4.2.
Three small improvements surfaced from real-session feedback:
1. Tool-running row was just a spinner + raw-JSON args; user said
"看不到任何的输出,就只知道再转圈". Added elapsed seconds counter
and per-tool argument summarizer. Instead of
tool<filesystem_edit_file> running... {"path":"..."...}
you now see
tool<filesystem_edit_file> running... 3s
path: F:\testtest\index.html (2 edits)
Summarizers for read_file / write_file / edit_file /
list_directory / directory_tree / search_files / move_file /
get_file_info, matching by suffix so bridgeMcpTools name prefix
(e.g. "filesystem_") works too. Unknown tools fall back to a
truncated raw preview.
2. ReasoningBlock showed the first 220 chars with "(+N chars)"
elided at the end. R1 opens every turn with the same scaffolding
("let me look at the structure...") so the preview looked
identical across turns and hid the actual decision in the
truncated tail. Switched to showing the LAST ~260 chars —
which is where R1 commits to an action.
3. /think slash command dumps the full reasoning text from
loop.scratch.reasoning when the tail preview isn't enough.
Alias: /reasoning. Graceful "no reasoning cached" message when
the current model is deepseek-chat (no reasoning_content) or a
turn hasn't completed yet.
Tests: +3 in slash.test.ts (/think empty + populated + help).
Suite: 319 -> 322.
Bumps to 0.4.2.
A real-session bug report — "I asked the model to analyze the project
and it silently edited a file" — forced a rethink of v0.4.0's
auto-apply default. This release fixes the root cause plus a stack of
adjacent UX gaps surfaced during the fix.
WHY (behavior change): auto-apply was wrong because it conflated two
distinct events — "the model proposed a change" and "the user wants
to make the change." v0.4.0 treated every SEARCH/REPLACE block in
assistant output as permission to write. Analysis drifted into edits.
Preview-by-default + explicit /apply is Aider's model and it's honest.
Added (code mode):
- /apply: writes pending edit blocks to disk, snapshots for /undo,
reports per-block status
- /discard: drops pending edits, no disk writes
- /undo: rolls back the last applied edit batch (restores modified
files, deletes ones created by the batch)
- /commit "msg": git add -A && git commit -m "..." in code rootDir;
surfaces git stderr on hook failure / nothing-staged / etc.
- .gitignore awareness: reasonix code reads rootDir/.gitignore on
launch and appends it to the system prompt as "don't traverse
these paths unless asked"; hard-coded baseline (node_modules,
dist, .git, .venv, __pycache__, target, ...) baked into the base
prompt for projects without a .gitignore
Fixed:
- Edits no longer auto-write. Each assistant turn's blocks are
parsed and shown as a preview (filename + -N/+M line-count). No
disk write until /apply. Pending persists across messages.
- LoopEvent.forcedSummary flag on assistant_final events from the
no-tools fallback (budget/aborted/context-guard). Code-mode
applier skips tagged events — a wrap-up summary is not a plan.
- Token-context guard replaces iter count as primary stop
condition. promptTokens > 80% of ctx window -> yellow warning +
skip tool exec + divert to summary (reason: "context-guard").
Iter cap 24 -> 64 as last-resort backstop.
- CODE_SYSTEM_PROMPT tightened: explicit rule that edits only fire
on change/fix/add/remove/refactor intents; analyze/explain stay
read-only.
- Stray EditSummary/summarizeEdit reverted from edit-blocks.ts (a
0.4.0 forced-summary run auto-wrote it; dead code).
- SEARCH/REPLACE blocks now render as a proper diff (red -/green +)
instead of going through the markdown paragraph path, which was
joining lines with spaces and letting the bold/italic regex eat
`*` chars inside JSDoc `/** ... */` comments. New parseBlocks
exports an "edit-block" block kind.
- R1 reasoning UX no longer looks frozen. Cyan braille-spinner
heartbeat (500ms) + "reasoning" vs "streaming" label + explicit
"R1 is thinking before it speaks — body text starts when
reasoning completes (typically 20-90s)" message while body is
empty. Replaces the misleading "(waiting for first token...)".
- New "tool_start" event yielded immediately before
tools.dispatch(). TUI renders a spinner row "⠋ tool<X> running…"
with args preview while the Promise is pending — fixes the
dead-air window between assistant_final (streaming cleared) and
the tool result event, during which a multi-KB
filesystem_edit_file could hang the UI visibly for 100ms-1s.
Tests: +36, suite 292 -> 319.
- tests/edit-blocks.test.ts (+5): snapshot/restore round-trip,
delete on undo-of-create, per-path dedup, path-escape defense.
- tests/code-prompt.test.ts (+4, new file): .gitignore injection
happy/absent/truncated paths, base-prompt ignore hints.
- tests/slash.test.ts (+13): /apply /discard /undo /commit inside
and outside code mode, usage hint on empty, double-quote
stripping, help listing.
- tests/loop.test.ts (+2): context-guard warning + forcedSummary
flag when prompt > 80% of window, tool_start precedes tool.
- tests/markdown.test.ts (+5): parseBlocks recognizes SEARCH/
REPLACE into edit-block blocks, preserves multi-line JSDoc
verbatim, handles new-file empty-SEARCH, rejects stray markers
without close, multi-block + prose interleaving.
Bumps to 0.4.1.
A new opinionated subcommand that turns Reasonix into a coding
assistant, realizing the "cheap Claude Code" pitch. Layers on top of
the existing chat + MCP machinery rather than forking it.
What `reasonix code [dir]` does:
- Auto-bridges @modelcontextprotocol/server-filesystem at [dir]
(default CWD). No wizard, no config merge.
- Uses a coding-focused system prompt that teaches Aider-style
SEARCH/REPLACE blocks and forbids write_file for existing files.
- Forces reasoner + harvest (coding repays R1 thinking).
- Scopes the session name to the directory basename so projects
don't cross-pollute.
- Hooks codeMode into App.tsx — after each assistant_final, parses
SEARCH/REPLACE blocks from the response and applies them to disk,
reporting per-block results as info lines.
SEARCH/REPLACE semantics (src/code/edit-blocks.ts):
- SEARCH must match byte-for-byte. No fuzzy matching — a silent
wrong edit is worse than a loud rejection.
- Empty SEARCH creates a new file (Aider convention).
- First occurrence only; duplicate SEARCH text requires a new
block with more surrounding context.
- Path-escape defense: resolve + startsWith on the normalized
rootDir, refuses paths climbing above the sandbox.
Library surface: parseEditBlocks, applyEditBlock, applyEditBlocks,
CODE_SYSTEM_PROMPT, and EditBlock/ApplyResult/ApplyStatus types.
Compose them yourself for custom UIs.
Out of scope for v1: /commit, /undo, diff preview, .gitignore
filtering. User's `git diff` + `git checkout` is the review/undo
surface; we run inside a git repo by convention.
Tests: +13 in edit-blocks.test.ts (parse: single/multi/multiline/
empty-search/stray-markers; apply: happy/new-file/not-found/
file-missing/path-escape/first-occurrence; batch: independent
results). Suite 279 -> 292.
Bumps to 0.4.0 (minor — new user-facing primitive + library surface
additions; no breaking changes for 0.3.x users).
0.3.1 gave the loop a safety net (forced summary at maxToolIters);
this release turns that safety net into an interactive budget. Users
no longer have to wait for the ceiling to hear from the model.
- Yellow warning event fires once per step when tool-iter count hits
70% of maxToolIters. TUI renders it in the event log with an
"Press Esc to force a summary now" hint; the command strip under
the prompt also shows the Esc shortcut.
- CacheFirstLoop.abort() method + TUI Esc handler (useInput, guarded
by busy state and a once-per-turn flag). On abort, the current tool
call is allowed to finish, then the loop diverts to the 0.3.1
no-tools summary path with a different prefix:
"[aborted by user (Esc) - summarizing what I found so far]".
- New EventRole "warning" + DisplayRole "warning"; EventLog renders
them yellow. Wired through App.tsx's event dispatcher.
README rewrite: hero leads with `npx reasonix` (no flags), wizard
story in prose. --mcp and --preset examples moved to "Advanced".
What-you-get table gains Setup wizard, Context safety net row, and
merges stdio + SSE into one MCP row. Non-goals and Configuration
trimmed to match.
Tests: +2 in loop.test.ts (warning fires exactly once at threshold;
abort() diverts to summary with "aborted" prefix). Suite: 277 -> 279.
Bumps to 0.3.2.
Problem (reproduced live): user asked the reasoner to explore a Flutter
project via filesystem MCP. The model chained 8 list_directory /
read_file calls, the loop hit the default maxToolIters=8, quietly
yielded a "done" event with content "[max_tool_iters reached]", and
exited. The App.tsx doesn't render `done` content anywhere, so the
user saw a blank assistant reply after 8 tool calls — as if Reasonix
just stopped for no reason.
Fix:
- When the tool-call loop exhausts its budget with tool_calls still
pending, make one final request to DeepSeek with tools omitted.
Forces a text-only answer based on everything in history. Yield
as a normal assistant_final event, prefixed with
"[tool-call budget (N) reached - forcing summary from what I found]"
so the user knows why they got a summary instead of more drilling.
- Default maxToolIters 8 -> 24. Eight was below the floor for any
real filesystem exploration; 24 still caps a confused model's
damage.
Tests: +1 in loop.test.ts with maxToolIters=2, every response wanting
tools, proving the summary call fires and assistant_final carries the
budget annotation. Suite: 276 -> 277.
Bumps to 0.3.1.
Drops the prerelease tag and ships 0.3.0 stable. Since 0.2.2 this
includes: MCP (stdio + SSE, multi-server, curated catalog), the
first-run wizard that replaces the --mcp flag maze, config-backed
defaults, and a three-layer context-safety net (per-tool cap +
auto-heal on session load + manual /compact).
Added this commit:
- StatsPanel context gauge: "ctx 42k/131k (32%)" with yellow at
50% and red + "/compact" nudge at 80%+. Reads SessionSummary's
new lastPromptTokens field; model max comes from
DEEPSEEK_CONTEXT_TOKENS (131072 for chat/reasoner).
- /compact [cap] slash: re-applies truncation with a tighter 4k
char cap (or user-supplied), rewrites the session file on disk
so the next launch doesn't re-inherit a fat file. Reports chars
and approximate tokens saved.
- SessionSummary.lastPromptTokens, AppendOnlyLog.compactInPlace(),
session.rewriteSession(), loop.compact() — all new exports.
Tests: +5 (slash /compact x4, telemetry lastPromptTokens x1).
Suite: 276 passing (up from 241 in alpha.4).
Migration note: one silent behaviour change — sessions built with
pre-alpha.6 clients auto-heal on load (oversized tool results get
truncated). The conversation is preserved; only the bloat shrinks.
Problem: a single `read_file` on a big file returned ~3 MB of text
through flattenMcpResult; it landed in session history verbatim and
every subsequent turn 400'd with DeepSeek's "maximum context length
is 131072 tokens. However, you requested 929,452 tokens." The user
had no way to recover short of deleting the session file by hand.
Fix, at both ends:
- Prevention: bridgeMcpTools now caps each result at 32k chars by
default. truncateForModel keeps head + 1KB tail with a clear
"[...truncated N chars...]" marker, so the model sees both
"what the tool started returning" and "how it ended" (important
for error messages appended at the bottom of stack traces).
Override: bridgeMcpTools(client, { maxResultChars: N }).
- Diagnosis: formatLoopError() detects "maximum context length"
in the raw API error, pretty-prints the requested-token figure,
and tells the user exactly what to do — /forget to wipe the
session file, /clear for display-only. Other errors pass through.
Exports: DEFAULT_MAX_RESULT_CHARS, truncateForModel, FlattenOptions,
formatLoopError — so library callers get the same protection.
Tests: +3 for truncation (head+tail preserved, no-op below cap,
end-to-end dispatch), +3 for error annotation (token figure,
passthrough, figure-less overflow). Suite 262 -> 268.
Bumps to 0.3.0-alpha.6.
The previous UX required users to memorize a pile of flags
(`--mcp "name=npx -y @scope/pkg /path"`, `--harvest`, `--branch N`,
`--session`) before they could use any of Reasonix's power features.
That was wrong: the target audience is ordinary users, not CLI
archaeologists.
New flow:
- `npx reasonix` — on first run opens an Ink wizard (API key →
preset pick → MCP multi-select → per-server args → save). On
subsequent runs launches chat with the saved defaults.
- `reasonix setup` re-runs the wizard any time; existing selections
are pre-checked via package-name matching against the catalog.
- `~/.reasonix/config.json` now stores preset + mcp + session +
setupCompleted alongside apiKey. Precedence: explicit CLI flag
wins, then --preset, then config.preset, then hardcoded fast
defaults. `--no-config` is the escape hatch for CI.
- `--preset <fast|smart|max>` new on both chat and run so power
users get the bundled settings too.
- `/mcp` slash — lists attached servers + tool registry mid-chat.
- `/setup` slash — prints instructions to exit and re-run
`reasonix setup`. Live reconfig is out of scope: swapping tools
mid-session would invalidate the byte-stable prefix.
Fixes two real bugs found during manual testing:
- `@modelcontextprotocol/server-fetch` and `server-sqlite` were in
the catalog but don't exist on npm (Python-only reference
implementations). Picking either one produced a 404 that killed
the chat. Removed.
- One broken MCP server took down the whole chat via
`process.exit(1)`. Now each failure prints `▸ MCP setup SKIPPED`
pointing at `reasonix setup` and the session continues with the
servers that worked.
Tests (+21, suite 241→262):
- tests/resolve.test.ts (+11) — flag/preset/config precedence, cap
and off paths, --no-config, --no-session isolation.
- tests/config.test.ts (+2) — extended schema round-trip,
session:null meaning ephemeral.
- tests/slash.test.ts (+4) — /mcp empty + populated, /setup hint,
help coverage.
- tests/wizard.test.ts (+4) — buildSpec → parseMcpSpec round-trip
for filesystem / memory / spaces-in-path / unknown-entry fallback.
Bumps to 0.3.0-alpha.5.
Implements the MCP 2024-11-05 HTTP+SSE wire: GET the SSE URL, wait for
event: endpoint, POST every outgoing JSON-RPC frame to that URL, read
responses off the SSE channel. Headers (Authorization, etc.) pass
through to both the GET and POSTs so hosted servers behind auth work.
--mcp now routes anything starting with http:// or https:// to
SseTransport; everything else stays stdio. McpSpec becomes a
discriminated union { transport: "stdio" | "sse", … } — callers that
inspected spec.command/args must branch on spec.transport first.
Tests: in-process http.Server fake implementing the SSE wire —
relative endpoint resolution, absolute endpoints, a full McpClient
initialize → listTools round-trip, handshake failure propagation.
Plus parseMcpSpec SSE cases (case-insensitive scheme; ws:// stays
routed to stdio as there's no ws transport yet). Suite: 241 passing.
Bumps version to 0.3.0-alpha.4.
Cache-First holds
Third MCP live data point, the ecosystem proof. Run against two MCP
servers concurrently:
--mcp "demo=node --import tsx examples/mcp-server-demo.ts"
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem <dir>"
The model used tools from both in one conversation — computed 17+25
via demo_add, then wrote "42" to a real file on disk via
fs_write_file (with a graceful permission-denied recovery in
between).
turns: 5, tool calls: 4
cache: 81.1%, cost $0.00185, 95.9% cheaper than Claude
prefix hashes: ONE across all 5 turns — byte-stable prefix
survives two concurrent MCP subprocesses
Reference: benchmarks/tau-bench/transcripts/mcp-multi-server.jsonl
(replay offline to verify — no API key needed).
Also adds .claude/settings.local.json to .gitignore (local Claude Code
settings are personal and shouldn't be committed).
Adds the last bit of UX I'd actually hand to a new user: a way to
discover what MCP servers they can try.
New:
- reasonix mcp list curated catalog of popular official MCP
servers, each with a copy-pasteable
--mcp command. filesystem / fetch /
github / memory / sqlite / puppeteer /
everything. --json for machine output.
- --mcp repeatable multi-server support (already in main,
now released on npm @alpha)
- "name=cmd args..." spec per-server namespace prefix, tools land
as fs_read_file, mem_set, etc.
Packages 7cd8621 (multi-server) + new mcp list command as alpha.3.
Discovery is hardcoded not fetched: the list changes slowly, offline
users shouldn't have to wait on a network fetch to see what exists.
Updating it = one file edit + patch release.
Suite 233/233; no functional changes to the existing tested paths.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`--mcp` is now a collect-style option; pass it multiple times to attach
multiple servers to the same chat / run. Each spec can optionally name
its namespace:
reasonix chat \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "demo=node --import tsx examples/mcp-server-demo.ts"
Tools land in a shared ToolRegistry with the prefix baked in
(fs_read_file, demo_add, …). The model sees the flat namespace; the
registry dispatches to the right subprocess.
Spec syntax (new src/mcp/spec.ts::parseMcpSpec):
- "name=command args..." → namespaced; `[a-zA-Z_][a-zA-Z0-9_]*` name
- "command args..." → anonymous; tools keep their native names
The identifier regex is deliberately narrow so Windows drive letters
(`C:\...`) never accidentally look like a namespace prefix.
--mcp-prefix still exists as a global fallback, but only applies when
exactly one anonymous spec is given. With named specs, each server
brings its own name.
Also fixes a shellSplit bug: backslashes outside quotes were being
treated as POSIX escapes, which mangled every Windows path. Now they
pass through literally outside quotes (use quotes to group args with
spaces). Matches user expectation on Windows; POSIX users who want
escape-a-space can quote the arg.
+9 tests: parseMcpSpec (8 cases including Windows drive letters,
identifier-name validation, empty/malformed input) + an integration
test spawning two demo subprocesses concurrently with different
prefixes, verifying the shared registry dispatches to each correctly.
Suite: 233 passing (was 224).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Packages 5e124ce's Windows fix + second live MCP data point as an
alpha. v0.3.0-alpha.1 is technically broken on Windows (--mcp "npx ..."
can't find npx.cmd), so this supersedes it on the @alpha npm tag.
No functional changes since 5e124ce — just version bump + CHANGELOG.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
official @modelcontextprotocol/server-filesystem
Two things together — the fix is what unlocked the data.
1. StdioTransport now handles Windows .cmd/.bat shims (npx.cmd,
pnpm.cmd) without triggering Node's DEP0190 deprecation warning.
On win32, shell defaults to true; we build a quoted command line
ourselves (command bare so PATH lookup works, args quoted) and
pass it as a single string, dodging the shell:true + args[]
anti-pattern. POSIX path unchanged. New `shell?: boolean` option
lets callers override the platform default (e.g. tests spawning
node.exe directly).
2. Second live MCP run, this time against the *external*,
production @modelcontextprotocol/server-filesystem:
5 turns, 4 tool calls, cache **96.7%**, cost $0.00124,
97% cheaper than Claude at equivalent tokens.
The model tried list_directory on the wrong path, got an access-
denied, self-recovered by calling list_allowed_directories, then
list_directory + read_text_file. Messy realistic run. Byte-stable
prefix held across every turn.
This matters because the first MCP run (v0.3.0-alpha.1,
mcp-demo.add.jsonl) was against our own bundled demo server.
Someone could reasonably argue "of course it caches — you wrote
the server". This one answers that: cache-first works on code
we don't control.
Reference transcripts:
- benchmarks/tau-bench/transcripts/mcp-demo.add.jsonl (own server)
- benchmarks/tau-bench/transcripts/mcp-filesystem.jsonl (official)
README gains a two-row table with both numbers + a no-API-key
reproduction block pointing at both committed transcripts.
Tests still 224/224 green. Integration tests explicitly set
shell: false since they spawn node.exe by absolute path.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
End-to-end MCP integration verified on live DeepSeek. Recorded run at
benchmarks/tau-bench/transcripts/mcp-demo.add.jsonl:
▸ spawned bundled demo MCP server (3 tools bridged)
▸ model chose the add tool, received the result via MCP stdio
▸ follow-up turn hit 96.6% cache (byte-stable prefix held across
the tool-call round-trip)
▸ total cost $0.000254 — 94% cheaper than Claude at same tokens
This is the v0.1 Cache-First claim extending verbatim to arbitrary MCP
tools. The mechanism wasn't altered; the registry just serves MCP tools
as if they were native. That extension *is* the v0.3 headline.
Shipping as alpha because:
- one real run is proof-of-concept, not proof-at-scale
- SSE transport, resources, prompts, and progress notifications are
still deferred
- official external MCP servers (filesystem, github, etc.) haven't
been exercised in CI yet
Suite: 224 passing (10 fake-transport unit, 9 shell-split, 2 real-
subprocess integration, plus the existing 203).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
End-to-end MCP integration — any MCP server's tools flow through
Reasonix's Cache-First loop now, from one CLI flag.
CLI:
reasonix chat --mcp "<command args...>" interactive TUI
reasonix run "<task>" --mcp "<command args...>" one-shot
optional: --mcp-prefix <str> namespace tool names
The flag takes a shell-style command. shellSplit() parses it
(respecting single/double quotes, backslash escapes, tab-space
runs). Unterminated quotes throw with a clear error instead of
silently mangling argv. chat / run both spawn + bridge before
looping, tear down on exit.
App.tsx accepts an optional `tools?: ToolRegistry` prop. When
present, its specs get folded into ImmutablePrefix and dispatch
goes through it — so MCP tools are indistinguishable from native
tools to the loop.
Bundled demo server: examples/mcp-server-demo.ts
~160 lines, no dependencies beyond what's already installed.
Exposes echo / add / get_time. Two uses:
- users can try the whole integration with no external install:
reasonix chat --mcp "node --import tsx examples/mcp-server-demo.ts"
- gives the integration test a real subprocess target
Integration test: tests/mcp-integration.test.ts
Spawns the demo server (`node --import tsx ...` — cross-platform,
avoids Windows `.cmd` resolution issues), walks the full handshake,
bridges tools, dispatches through the registry. Kept in a
separate file from the fake-transport unit tests so subprocess
flakiness doesn't hide unit-test regressions.
+11 tests (9 shellSplit + 2 integration). Suite: 224 passing (was
213). src/mcp/README.md updated with CLI usage + status of what's
shipped vs deferred.
Still no version bump — next is v0.3.0-alpha, once we've seen a
real LLM call go through an MCP tool end-to-end. Everything's in
place for that now; remaining is one live run.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Minimal MCP (Model Context Protocol) client, hand-rolled, zero
runtime deps. Lets Reasonix consume tools from any MCP server while
keeping Cache-First + repair applied to the whole thing.
Why roll-our-own instead of @modelcontextprotocol/sdk:
- zero dep cost, consistent with how we wrote the DeepSeek client
- surface tuning — only initialize / tools/list / tools/call for now
- insulation from SDK breaking changes
See src/mcp/README.md for the full reasoning.
Shipped in this pass:
- src/mcp/types.ts JSON-RPC 2.0 + MCP message types
- src/mcp/stdio.ts McpTransport interface + NDJSON stdio impl
- src/mcp/client.ts connect / listTools / callTool with timeouts
+ id correlation
- src/mcp/registry.ts bridgeMcpTools(): MCP → Reasonix ToolRegistry,
so MCP tools inherit Cache-First + repair
automatically
- src/mcp/README.md design choices + usage example + what's next
Deferred (each is its own follow-up commit):
- CLI wiring: `reasonix chat --mcp <cmd>` — thin layer on top of
bridgeMcpTools + ImmutablePrefix
- resources/* and prompts/* methods — Reasonix doesn't surface those
today
- SSE transport — stdio covers common case
- Progress notifications / streaming tool results
+10 tests using an in-process FakeMcpTransport (no child processes in
unit tests — flaky). Covers initialize handshake, pre-init refusal,
tools/list, tools/call roundtrip, server errors, bridge registration,
name prefixing, and result flattening (text / image / error cases).
Suite: 213 passing (was 203).
Public surface: McpClient / StdioTransport / bridgeMcpTools /
flattenMcpResult / MCP_PROTOCOL_VERSION + all relevant types exported
from the library barrel. No version bump — foundation, not release.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
lift accuracy on math/logic; pivot Pillar 2 positioning
Second harvest eval run, 6 tasks × 3 modes × 1 repeat = 18 runs. This
time the task set included three hard tasks chosen specifically for
known V3 failure modes (base-2 Fermat pseudoprime → 341,
derangements of 7 → 1854, Euler polynomial first-fail → n=40).
mode pass cache cost harvest signal
baseline 6/6 39.5% $0.00137 —
reasoner 6/6 74.2% $0.00417 —
reasoner-harvest 5/6* 61.6% $0.00330 2.8 sg / 1.3 un
(* one 300s timeout on pseudoprime_base2)
Honest headline: **V3 passed all six.** Including the hard ones. The
checkers specifically reject the common V3 wrong-answers (561 for
pseudoprime, 265/1855 for D_7, 41/1681 for Euler) — none of those
fired. These problems are well-enough known that V3 has them in
training and R1 has no accuracy headroom to win back.
What this means for v0.3 positioning:
- We cannot ship a "harvest improves answer quality" claim off this
data — twice now. That's not a framework bug; it's a signal that
Pillar 2's value is NOT in the "make math more right" story.
- Plausible actual value surfaces: dev-facing introspection of R1's
planning, or steering tool-call sequences under uncertainty. Neither
is exercised by this harness.
- Cache-First story DOES extend to reasoner mode (74% mean cache even
on R1 turns). That's a Pillar 1 finding reinforcing the v0.1 data,
not a Pillar 2 finding.
findings section updated inside report.ts's renderFindings() so future
regens preserve the analysis. Committed results.json is the full
artifact for anyone who wants to reasonix replay / diff individual
runs.
Recommendation in-report: next release is better served by MCP client
(Pillar 1 leverage across the ecosystem) than by a third harvest-bench
data push. Pillar 2 needs a reframe — likely "debug visibility" or
"tool-sequence planning", not "accuracy multiplier".
Unexpected positive signal worth noting: cross-session prompt cache.
Baseline mean cache hit was 39.5% even on mode A — the same system
prompt across many runs warmed DeepSeek's server-side cache, showing
Cache-First's value isn't purely per-session.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Post-first-run adjustments informed by 7233edd's data:
- Seed tasks bottomed out at V3 chat (3/3 pass on all easy ones), so
harvest couldn't differentiate. Add three hard tasks picked for
known V3 failure modes:
- pseudoprime_base2 (341; V3 commonly says 561 — Carmichael)
- derangements_d7 (1854; V3 hits n!/e rounding errors)
- euler_quadratic_break (40; V3 confuses with n²−n+41 first-fail)
Each is a single-integer answer → reuse a new checkSingleInt helper.
Easy tasks stay for floor reference.
- `--timeout <seconds>` flag (default 300s, was 120s client default).
Prior run hit the 120s cap on three_hats/reasoner-harvest because R1
alone took ~100s. 300s gives headroom without encouraging runaway
loops.
+9 tests on new checkers and the common wrong answers (e.g., checker
rejects 561 for pseudoprime_base2, rejects 265/1855 for D_7, rejects
41/1681 for euler_quadratic). Suite: 203 passing.
CI --dry step still covers the runner. No API calls in this commit —
next run uses the expanded task set.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
First real data from the v0.3 harvest eval harness (3 tasks × 3 modes,
1 repeat). Findings are not the marketing-friendly "harvest +N% quality"
we wanted — but they're honest, and they sharpen what v0.3 actually
needs.
Headline numbers (per-run means):
mode pass cache cost harvest signal
baseline 3/3 0.0% $0.00142 —
reasoner 3/3 79.0% $0.00355 —
reasoner-harvest 2/3* 59.7% $0.00184 3.3 sg / 1.3 un
(* one timeout, see known issues)
Three honest findings, committed to report.md:
1. V3 chat already solves all three seed tasks. The task set bottoms
out — baseline's 3/3 pass rate means there's no headroom for R1,
let alone R1+harvest, to win on quality.
2. Reasoner costs ~2.5× chat on these problems with identical verdicts.
On this task set, there is no quality argument for R1. (The
cache-hit story DOES extend — reasoner mode still gets 79% mean
cache through the Cache-First loop, so Pillar 1 generalizes.)
3. Harvest produces real signal (3-5 subgoals, 1-2 uncertainties per
run) AND real latency — one run hit the 120s client timeout because
the harvest V3 call pushed past R1's own ~100s budget.
What this changes for v0.3:
- We cannot ship a "harvest pays for itself" claim off this data.
- The harness is fine; the task set is the bottleneck.
- Next iteration needs problems where V3 demonstrably fails, so R1
gains real headroom and harvest's uncertainty signal has something
to correlate with.
report.ts gains a renderFindings() helper so future runs can preserve
the hand-written interpretation alongside the auto-generated tables.
No release tag — this is data collection, not a version bump.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
New benchmarks/harvest/ directory alongside tau-bench/. Measures
Pillar 2 (R1 Thought Harvesting) the same way tau-bench-lite measures
Pillar 1 — isolate one variable, produce reproducible numbers.
Three modes per task, each isolates one variable:
- baseline deepseek-chat, no Reasonix tricks — V3 floor
- reasoner deepseek-reasoner, no harvest — raw R1 gain
- reasoner-harvest deepseek-reasoner + harvest — incremental cost /
quality from the extra V3 harvest call
Seed tasks (v0.3):
- mod7_list number theory, 29-element set — expansive plan state
- flips_until_3heads probability, single integer — derive vs recall
- three_hats logic puzzle, one-word answer — deduction chain
All checkers are deterministic (regex + set/value compare). No LLM
judge. Failing checker in CI catches reality drift without needing an
API key — sanity verdict is exercised on every dry-run.
Runner supports --task, --mode, --repeats, --transcripts-dir, --dry.
Transcripts reuse the same TranscriptRecord format as tau-bench, so
reasonix replay / reasonix diff work unchanged.
CI now runs the harvest harness's --dry in addition to tau-bench's,
so bench regressions get caught before a real run.
+16 tests covering checker verdicts for all three tasks, empty-input
robustness, determinism, and task-set invariants. Suite: 194 passing.
No API calls yet — next step is a live run to produce the first
harvest-bench/report.md. Expected cost for 3 tasks × 3 modes × 1
repeat: ~$0.10-0.30 (dominated by the reasoner calls).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Promotes the existing /sessions slash command into a top-level CLI
command so users can audit their stored sessions without launching
the TUI. Two modes:
reasonix sessions list every session under
~/.reasonix/sessions/
reasonix sessions <name> dump messages from one session
reasonix sessions <name> -v include system prompts + tool-call
args
Reuses listSessions / loadSessionMessages / sessionPath from
src/session.ts — no new library surface. Zero API calls; filesystem
reads only.
Use case: quickly checking "what have I been asking the assistant?"
without running chat, or piping one session's content into a tool
chain for batch analysis.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When at least one side of a transcript diff has plan state (Pillar 2
harvest output), the summary now includes three extra rows: harvest
turns, subgoals, and uncertainties. Lets a harvest-on run be compared
head-to-head with its harvest-off twin — which is exactly the
comparison v0.3's eval harness will need to produce.
Rows only appear when at least one side carries planState. No-harvest
diffs render identically to v0.2.2 — zero visual noise, zero surprise
for existing callers.
+2 tests confirming the row appears when harvest is present AND
omits entirely when both sides are clean. Suite: 178 passing.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two small adds that make the existing v0.2 infrastructure easier to
pick up:
1. CI now runs `npx tsx benchmarks/tau-bench/runner.ts --dry` on every
push and PR. Catches bench harness regressions (task factories, CLI
parsing, file IO, per-sub-call transcript emission) without needing
a DEEPSEEK_API_KEY in CI.
2. examples/replay-and-diff.ts demonstrates the library surface
programmatically — readTranscript, computeReplayStats,
diffTranscripts, renderDiffSummary, plus direct report.pairs
inspection. Runs with no API key against the committed reference
transcripts; verifies the v0.1 numbers (94% cache, −20% cost, 1
byte-stable prefix) fall out of the JSONL alone.
Useful for anyone wiring a CI gate or eval dashboard on top of Reasonix
— which is the main use case that justifies shipping transcripts in
the package in the first place.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The old PlanStateBlock rendered all four fields in the same magenta
text. On terminals with dark themes (which is most of them), magenta
is notoriously low-contrast — users reported not being able to read
harvest output.
Fix:
- label gets a semantic color (bold): subgoals cyan, hypotheses green,
uncertainties yellow, rejected red-dim.
- the item list itself renders in default foreground — always
readable on any background.
- count indicator "(N)" is dimColor so it doesn't compete with content.
Before: all four lines identical magenta (hard to tell fields apart,
hard to read on dark).
After: label color communicates meaning (rejected feels negative,
uncertainties feel like "watch out"), content stays crisp.
Used by the live chat TUI AND replay/diff TUIs, so the fix lands
everywhere harvest output shows up.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Parity with `reasonix chat`: lets a one-shot non-interactive call
produce a transcript with harvest signal, for quick API-backed
verification of a harvest session without firing up the Ink TUI.
Usage:
reasonix run "your question" \
--model deepseek-reasoner --harvest \
--transcript /tmp/h.jsonl
Afterward:
reasonix replay /tmp/h.jsonl # see the planState inline
The transcript path is self-closing — the command streams output as
usual, then prints a hint pointing at replay. No other behavior change;
`reasonix run` without the new flags behaves exactly as before.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Prep work for v0.3's harvest eval harness. The Pillar 2 plan state
already exists in the live chat UI; this commit makes it persist and
display in every replay/diff surface, so future harvest data can be
audited the same way cache hit is today.
- TranscriptRecord gains optional planState (TypedPlanState).
- recordFromLoopEvent copies it from LoopEvent.planState on
assistant_final events. Empty plan state is omitted entirely — absent
means "no signal", indistinguishable from harvest-off, saves bytes.
- PlanStateBlock extracted from EventLog to a shared component so the
live chat TUI, replay TUI, and (transitively) diff TUI all render
harvest output identically.
- RecordView shows the plan state under the assistant text when present.
- replay stdout --print mode prints the same four lines (subgoals /
hypotheses / uncertainties / rejected) under each agent turn that
carried plan state.
- ReplayStats gains harvestedTurns, totalSubgoals, totalUncertainties.
Surfaced in the replay summary so you can see at-a-glance whether
harvest produced signal across the session.
- Zero cost when harvest is off — the whole path is gated on the
presence of planState in the record.
+4 tests (round-trip, empty-state omission, aggregate counting,
no-harvest zero case). Suite: **176 passing**.
No CHANGELOG bump — this is prep, not a release.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
First three-repeat data set on τ-bench-lite. Headline numbers land in
the same region as the v0.1 16-run set, with the confidence that comes
from 3× the samples.
metric baseline reasonix delta
runs 24 24 —
pass rate 96% (23/24) 100% (24/24) reasonix holds guardrail
cache hit 46.6% 94.4% +47.7pp
cost / task $0.002599 $0.001579 −39% (×0.61)
vs Claude (estimate) — — ~96% cheaper
The one baseline failure is a t07_wrong_identity run where baseline
skipped identity verification and mutated the wrong user's order —
exactly the kind of guardrail slip you'd expect from a cache-churning
agent whose context reshuffles every turn.
Also includes:
- README hero table refreshed to the 48-run numbers + 3-repeat
reproduction command
- benchmarks/tau-bench/results.json replaced with the 48-run data
- benchmarks/tau-bench/report.md regenerated from the new JSON
(The t05 predicate fix that made 100% pass possible landed one commit
earlier at c1965b1.)
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The v0.1 16-run bench surfaced an honest false-negative on t05: the task
wanted "no refund on a processing order", and reasonix followed that —
but then offered to cancel the order instead when the user kept pushing.
The old predicate required status to stay `processing`, which penalized
agents for being helpful. It failed reasonix once and the baseline zero
times, not because reasonix behaved worse but because baseline never
reached the "offer cancel" branch.
New predicate: pass iff no refund row is written for o_1002 AND the
status ends up in {processing, cancelled}. "No refund" remains the
hard constraint. Cancellation is now honored as a reasonable business
response — which is how a real support flow would be scored.
+3 tests pinning the three outcomes (refuse / cancel / illegally
refund). Suite: 172 passing.
No report regeneration in this commit — rerun the bench in a follow-up
with the new predicate to pick up any accuracy change.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Single release covering both TUI additions (replay + diff) shipped
since 0.2.0. No functional changes; version bumps + CHANGELOG.
Highlights (see CHANGELOG.md for detail):
- reasonix replay <transcript> → Ink TUI by default (j/k/g/G nav)
- reasonix diff <a> <b> → split-pane TUI with n/N divergence
jump; --md / --print / --tui flags
to override
Stdout paths preserved via --print and non-TTY auto-detection, so CI
and pipe workflows behave as they did in 0.2.0.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`reasonix diff <a> <b>` now mounts an interactive Ink UI by default:
side-by-side panes sharing a cursor, a compact header that colors cache
and cost deltas in green/red, and a divergence-aware jump cursor. Press
n to skip straight to the next non-matching turn — the whole point of
a diff tool — or N/p to go back.
Default behavior picks itself based on context:
- stdout is a TTY and no --md: Ink TUI
- --md <path>: writes markdown AND prints the stdout summary (existing)
- --print, or piped stdout: stdout summary (existing)
- --tui: force TUI even when piped (rare)
Key bindings:
- j / ↓ / space / enter — next turn
- k / ↑ — prev turn
- n — next divergent turn
- N / p — prev divergent turn
- g / G — first / last
- q / ctrl-c — quit
Implementation:
- src/cli/ui/DiffApp.tsx — the new split-pane component.
- src/cli/ui/RecordView.tsx — extracted from ReplayApp so both UIs
share the same visual grammar (user cyan, assistant green with cache
badge, tool yellow, error red). ReplayApp now imports from here
instead of carrying its own copy.
- src/diff.ts gains pure `findNextDivergence` / `findPrevDivergence`
helpers so the nav logic is unit-testable without Ink (`n`/`N` keys).
Both guard against out-of-bounds `fromIdx`.
Cursor defaults to the first divergent turn (or 0 if everything
matches) — skips the "scroll through 7 identical turns before getting
to the interesting bit" experience.
+4 tests covering divergence navigation. Suite: 169 passing (was 165).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`reasonix replay <transcript>` now opens an interactive Ink UI by
default: j/k navigation across turn-pages, a cumulative stats sidebar
(StatsPanel reused from the chat TUI) that updates as you scrub, and
a key-bindings footer.
Key bindings:
- j / ↓ / space / enter — next turn
- k / ↑ — previous turn
- g / h / ← — first
- G / l / → — last
- q / ctrl-c — quit
The existing stdout path is preserved behind --print (also auto-
enabled when stdout is not a TTY, so pipes / CI logs still behave).
--head / --tail only work in print mode.
Implementation:
- src/replay.ts gains pure helpers `groupRecordsByTurn` (groups records
into turn-pages, preserving in-turn order) and `computeCumulativeStats`
(stats up to and including a given page index). These stay in the
library module so they're unit-testable without Ink.
- src/cli/ui/ReplayApp.tsx — the new Ink component. Reuses StatsPanel
and writes its own RecordView (lighter than EventRow, no streaming /
planState / branch paths to worry about in replay).
- Cursor defaults to the last page because users usually want the
summary + final turn first, not to start from turn 1.
+6 pure tests for groupRecordsByTurn + computeCumulativeStats.
Suite: 165 passing (was 159).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Ships the v0.1 + v0.2 work as a single versioned release.
- package.json: 0.0.6 → 0.2.0
- src/index.ts: VERSION constant synced
- CHANGELOG.md: new file, covers v0.2.0 (replay/diff/enriched transcripts)
and v0.1.0 (τ-bench-lite + first validated numbers)
- README.md: "Validated numbers" table replaced with the 16-run bench
results (94.3% cache, −42% cost, ~96% cheaper than Claude) and a
zero-cost self-verification block pointing at the committed transcripts
No API calls, no functional changes.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two fixes and one addition:
1. Baseline transcripts now emit one assistant_final per client.chat() call
(per sub-call) instead of one aggregated record per user turn. Reasonix
already emits per-model-call granularity, so diff's count was previously
apples-to-oranges ("turns 3 vs 6" looked like Reasonix doing 2× the work
when it was actually just finer record granularity).
2. Diff rendering renames "turns (assistant)" to "model calls" — less
ambiguous once both sides emit at the same granularity, and
distinguishes model calls from user turns.
3. Commit reference transcripts at benchmarks/tau-bench/transcripts/ so
readers can run `reasonix replay` / `reasonix diff` without an API key.
Gitignore carved out the directory; a brief README explains how to
regenerate (~$0.003/run) and reproduce the headline numbers.
Fresh run on t01_address_happy:
- cache hit: 45.9% → 93.9% (+48.0pp)
- cost: $0.001192 → $0.000953 (−20.1%)
- prefix hashes: 0 (baseline, untracked) → 1 byte-stable (reasonix)
Diff also surfaced a real behavioral difference the v0.1 bench numbers
hid: Reasonix calls lookup_order immediately while baseline asks for
name first. Both pass the task; the two paths are observable in the
committed transcripts.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Turns transcripts into first-class audit artifacts. Anyone with a
.jsonl transcript can reproduce the headline numbers (cache hit, cost,
vs-Claude) without re-running the LLM — the economics travel with the
data.
New surface:
- reasonix replay <transcript> pretty-print a run + rebuild its summary
- reasonix diff <a> <b> [--md] compare two transcripts: aggregate
deltas + first divergence + prefix stability
New modules:
- src/transcript.ts — canonical TranscriptRecord + writer/reader. Meta
line at top-of-file carries source/model/task/mode/repeat.
- src/replay.ts — pure parser that rebuilds SessionSummary from a
transcript's usage/cost fields. Tolerates old (pre-usage) transcripts.
- src/diff.ts — alignment by turn number, Levenshtein similarity for
text divergence, tool-name + tool-args comparison, stdout table +
markdown renderers.
Format bump (backward-compatible): transcripts now persist usage, cost,
model, prefixHash (Reasonix only), and toolArgs. All fields optional
on read — v0.1 transcripts still parse and render (cost/cache shown
as n/a). Format version lives in the _meta line at the top.
Bench runner: new --transcripts-dir <path> flag. Each (task, mode,
repeat) writes <taskId>.<mode>.r<n>.jsonl so bench runs produce
replay/diff-ready receipts, not just aggregate numbers.
Why this closes the loop on v0.1:
The τ-bench-lite report claims "baseline 43.9% / reasonix 94.3% cache
hit" — but a reader had to trust our aggregate. Now a reader can run
reasonix diff on two transcripts from the same task and see, byte by
byte, that reasonix's prefixHash stayed stable while baseline's
churned — and that the cache/cost delta is mechanically attributable
to log stability, not to a different prompt.
Tests: +16 (transcript 3, replay 3, diff 10). Suite now 159 green.
Also threads toolArgs through LoopEvent so chat's --transcript now
persists *what* the model sent to each tool, not just the result.
What's explicitly deferred to a later release:
- Full Ink TUI for replay (j/k scrubbing, search). Current replay
command is stdout-only.
- Split-pane diff TUI. Current diff command is stdout + markdown.
- MCP client (v0.3). Replay/diff infra is prerequisite: without it we
couldn't demonstrate why a Cache-First MCP client matters.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Ships the first reproducible evidence for Pillar 1 (Cache-First Loop):
8 retail-flavored multi-turn tool-use tasks run under both a naive
cache-hostile baseline and Reasonix, sharing the same client/tools/prompt
so the only variable is prefix stability.
Measured on live DeepSeek API (16 runs):
- cache hit: 43.9% → 94.3% (+50.3pp)
- cost/task: \$0.002783 → \$0.001621 (−42%)
- pass rate: 100% → 88% (1 reasonix failure, predicate too strict — see report.md)
- vs Claude Sonnet 4.6 estimated: ~96% cheaper at same token counts
New harness:
- types.ts / db.ts — task schema + per-run DB isolation
- tasks.ts — 8 seed tasks, deterministic DB-predicate pass/fail (no LLM judge)
- user-sim.ts — V3 user simulator at T=0.1
- baseline.ts — deliberately cache-hostile (fresh timestamp + shuffled tools each turn)
- runner.ts — orchestrator with --task / --mode / --repeats / --dry / --verbose
- report.ts — results.json → report.md with explicit scope caveats
- tests/benchmarks.test.ts — 8 harness smoke tests that run without an API key
Also fixes a Windows-only entrypoint bug in the original runner scaffold
(import.meta.url vs argv[1] path encoding mismatch prevented main() from
ever running on Windows).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
User feedback: 'requiring --session <name> to enable persistence is
too much friction. Most chat tools just remember by default.'
Correct. Now:
- Default behavior: every chat is auto-saved to a session named 'default'
and resumed on next launch. Zero friction — the natural ChatGPT-like UX.
- --session <name> picks a different named session.
- --no-session opts out entirely (ephemeral chat).
- App shows a one-time banner on startup describing the current session
state (resumed N msgs / new / ephemeral) so users know what's happening.
- New /forget command deletes the current session file from disk.
- /sessions now marks the current session with ▸.
- Command strip and /help updated.
Library API unchanged: CacheFirstLoop({ session }) is still opt-in.
Only the CLI is opinionated.
Tests: 3 new tests covering /help mentions sessions, /sessions hint,
/forget on session-less loop. Total: 135 (was 132).
New capability: every turn's message log is appended to
~/.reasonix/sessions/<name>.jsonl, and pre-loaded back into the loop's
AppendOnlyLog the next time the CLI is launched with --session <name>.
Rationale: the natural extension of Pillar 1's append-only-log invariant.
If the prefix is immutable AND the log is append-only, the only missing
piece for across-run continuity is writing the log to disk. DeepSeek's
prefix cache likely still hits on resume since the serialized messages
are byte-identical to what they were when originally appended.
Code:
- src/session.ts (new): loadSessionMessages / appendSessionMessage /
listSessions / deleteSession / sanitizeName / sessionPath /
sessionsDir. Name sanitization keeps [\w-] and CJK, replaces
everything else with underscore, 64-char cap. 0600 permissions on
Unix; chmod no-ops on Windows. Malformed JSONL lines are skipped
rather than crashing.
- src/loop.ts: new option on CacheFirstLoopOptions.
When set, the constructor pre-loads prior messages into the log and
every subsequent append is mirrored to disk via a small
appendAndPersist helper. Exposes for the TUI.
- src/cli/index.ts: --session <name> flag on chat.
- src/cli/ui/App.tsx: shows a one-line resume banner on startup when
the loop reports pre-loaded messages.
- src/cli/ui/slash.ts: /sessions command lists saved sessions with
message count + size + mtime, sorted by most recent.
- src/index.ts: exports the session API for library users.
Tests (tests/session.test.ts): 10 tests covering name sanitization,
round-trip append/load, malformed-line tolerance, listing + sort order,
delete. Homedir is stubbed to a tmp dir per-test for isolation.
Total tests: 132 (was 122). Bumps to 0.0.6.
User reported `\frac{总路程}{总时间}` leaked through as raw LaTeX in a
branched R1 answer even though most other \dfrac{} calls rendered fine
in the same output. Unable to reproduce from the paste alone, so
hardening the stripMath layer against the whole category:
- Frac regex now tolerates whitespace around braces and one level of
nested braces inside the numerator/denominator (\frac{\sqrt{2}}{3}).
- All braced commands now trim whitespace from their captured groups
so \frac{ a }{ b } → (a)/(b), not ( a )/( b ).
- New catch-all fallback at the end of stripMath: any surviving
\command, \command{x}, or \command{x}{y} is stripped. Users will
now NEVER see a raw backslash even if the model invents a new macro.
Also exported stripMath from markdown.tsx for direct unit testing.
12 new tests in tests/markdown.test.ts:
- \frac / \dfrac / \tfrac equivalence
- The exact Chinese \frac{总路程}{总时间} case
- Nested \sqrt{} inside \frac{}
- Whitespace tolerance inside braces
- Arrow & bare-command stripping
- Subscript/superscript Unicode mapping
- \boxed, \sqrt formatting
- Full user-reported line sanity check (no backslashes survive)
Total tests: 122 (was 110). Still v0.0.5.
Real-world test surfaced:
总时间:t_1 + t_2 = \dfrac{d}{30} + \dfrac{d}{60}
\dfrac wasn't in stripMath's regex list (only \frac was) so it leaked
through as raw backslashes. Same for \tfrac. Subscripts like t_1, t_2
were also rendering literal '_1' since stripMath did nothing for them.
Fix:
- Fractions: \frac, \dfrac, \tfrac all collapse to (num)/(den).
- New: \binom{n}{k} → C(n,k)
- New: \overline{x} → x̄, \hat{x} → x̂, \vec{x} → →x
- Subscripts/superscripts get translated to Unicode characters when the
content is a single digit/sign (or a brace-wrapped run): t_1 → t₁,
x^2 → x², a_{ij} → a_ij (groups stay readable). Falls back to
pass-through for non-mappable characters.
Existing 110 tests still pass; this is purely additive coverage in
the markdown rendering layer.
Real-world test of --branch 3 revealed the user stared at 'waiting for
first token...' for the full 30-60s it took the first sample to
complete, then saw everything dump at once. Root cause: branch_start
set the streaming slot WITHOUT branchProgress, so the UI fell through
to the non-branching preview that has no relevant info to show.
Two fixes:
1. branch_start now carries an initial branchProgress with completed=0,
total=budget. The TUI detects completed=0 and renders a distinct
'launching N parallel samples...' view explaining what's happening
and the typical wait time, instead of the misleading
'waiting for first token...'.
2. New <Elapsed /> component shows a live mm:ss counter next to the
branch header. Updates once a second via useEffect + setInterval.
Visible immediately so the user has proof the process is alive
even before the first sample completes. Also added to the
non-branching streaming view for symmetry.
README: new 'Why not just use LangChain?' table making the default-
preset value proposition explicit — the five always-on advantages
that hold even without harvest/branching.
Two usability issues from real-world feedback:
1. 'Default should be reasoner+harvest+branch?' — no, but the jump from
default-fast to everything-on requires remembering 3 commands.
Fix: /preset <fast|smart|max> flips the full config in one keystroke.
- fast: deepseek-chat (default, cheapest, ~1 cent / 100 turns)
- smart: reasoner + harvest (~10x cost)
- max: reasoner + harvest + branch3 (~30x cost, slowest)
Reasoning for keeping 'fast' as default: a new user's $1 free credit
on the 'max' preset only lasts ~150 turns; on 'fast' it lasts ~50k.
First impressions decide star conversion.
2. 'Users have to blind-type slash commands to discover them' — correct.
Fix: a CommandStrip component renders a dim hint line right below the
PromptInput showing all top-level commands. Always visible, no need
to remember or run /help:
/help · /preset <fast|smart|max> · /model · /harvest · /branch · /clear · /exit
Placeholder also updated from the wordy '"type a message, or /exit"'
to the cleaner 'type a message, or /command'.
Tests:
- /preset fast/smart/max round-trips verified through loop config.
- /preset with bad arg returns usage hint.
- /help mentions the presets block.
README updated to lead with the /preset idea rather than individual
knob commands.
Total tests: 110 (was 105). Still v0.0.5.
Two issues from the first real branched-turn test:
1. UI looked frozen for 60-90s, then everything dumped at once.
Cause: branching disables streaming because all N samples must
complete before selection. The TUI sat on an empty 'streaming'
spinner with no signal that work was happening.
2. Cost panel under-reported by ~3x.
Cause: stats.record() was called with the chosen sample's usage
only. We paid for all N samples but only counted one.
Fix 1 — progress events:
- BranchOptions gains an onSampleDone callback. runBranches fires it
as each parallel call settles (Promise.all order, but resolved as
each finishes).
- Loop wraps that callback in a queue/waiter pair and yields a new
branch_progress event in resolution order with completed/total +
the just-finished sample's index/temperature/uncertainty count.
- TUI's StreamingAssistant detects branchProgress and renders a
live-updating two-line progress block:
🔀 branching 2/3 (66%)
latest #1 T=0.5 u=2 · waiting for other samples…
- App.tsx dispatches the progress into the streaming slot.
Fix 2 — usage aggregation:
- New aggregateBranchUsage(samples) sums prompt/completion/cache
tokens across all samples.
- Loop builds a single Usage from the aggregate and records it via
stats.record(). Result: cost panel now reflects what was actually
billed. (Harvest-call tokens still not tracked — rounding error
next to the R1 calls.)
Tests:
- onSampleDone fires N times.
- aggregateBranchUsage sums correctly across 3 samples.
Total tests: 105 (was 103). Still v0.0.5.
Flag soup was hurting discoverability. Normal users run `npx reasonix
chat` and never find out harvest or branching exist. Slash commands
put every feature one keystroke away inside the chat.
Commands (see /help):
/help list commands
/status model/harvest/branch/stream state
/model <id> switch models mid-session
/harvest [on|off] toggle Pillar 2 (no arg = toggle)
/branch <N|off> set N parallel samples; N=2..8; auto-enables harvest
/clear clear history view (loop log is kept)
/exit quit
Implementation:
- src/loop.ts: CacheFirstLoop fields that made sense to change
mid-session (model, stream, harvestEnabled, harvestOptions,
branchEnabled, branchOptions) are now mutable. New
`configure(opts: ReconfigurableOptions)` method applies the same
branching/harvest/stream invariants the constructor does.
- src/cli/ui/slash.ts: parseSlash + handleSlash. Unknown commands fall
through with a hint to /help. Branch budget capped at 8.
- src/cli/ui/App.tsx: slash commands handled before normal submit;
messages rendered as info rows.
- src/cli/ui/StatsPanel.tsx: shows live `· harvest · branch3` badges
next to the model, plus a '· type /help' hint in the corner.
- tests/slash.test.ts: 14 tests covering parse, all commands, toggle
behavior, invalid args, unknown commands, branch cap.
CLI flags kept for CI/scripting; slash commands are the recommended UX
for interactive use. README updated to lead with the slash-command flow.
Total tests: 103 (was 89).
New feature: `reasonix chat --branch N` (or `{ branch: N }` in code) fans
the turn out into N parallel samples at spread temperatures, harvests each
one's reasoning, and selects the sample with the fewest flagged
uncertainties. Ties broken by answer length (Occam).
Unique value: because DeepSeek is ~20× cheaper than Claude, running N=3 R1
samples is still cheaper than a single Claude call, while the
confidence-weighted selection tends to beat single-sample answers on
multi-step reasoning.
Code:
- src/consistency.ts: runBranches + defaultSelector + BranchOptions /
BranchSample / BranchResult / BranchSelector types. Spreads temperatures
uniformly across [0, 1] by default; custom temperatures array supported.
- src/loop.ts: new branch option on CacheFirstLoopOptions (number or
BranchOptions). Enabling it forces non-streaming and auto-enables
harvest (the selector scores on uncertainties). Emits branch_start /
branch_done events plus branch summary on assistant_final.
- src/cli/index.ts: --branch <n> flag.
- src/cli/ui/EventLog.tsx: new BranchBlock renders
'🔀 branched N samples → picked #K' with per-sample temperature/uncertainty.
- src/cli/ui/App.tsx + commands/chat.tsx: branch option plumbed through.
- src/index.ts: exports runBranches + types.
Tests:
- tests/consistency.test.ts: 6 tests — selector tie-breakers, budget=1
no-op, N=3 parallel with varied temps, uncertainty-based selection,
custom temperatures override.
README rewritten:
- Badges (npm version, CI, license, downloads, node).
- Feature table covering Cache / Harvest / Branch / Repair / Retry / TUI.
- Validated numbers table with 3 real measurements.
- CLI + library usage examples with --harvest / --branch.
- Clean install / dev / non-goals sections.
docs/ARCHITECTURE.md: new Branch-and-Select section between Pillar 2 and
Pillar 3; roadmap updated.
Total tests: 89 (was 83). Bumps to 0.0.5.
Pillar 3's flatten module existed but was never called — registered
tools were sent to the model with their original schemas, even when
DeepSeek V3/R1 are known to drop arguments on schemas with >10 leaf
params or >2 levels of nesting.
Now ToolRegistry analyzes every registered schema:
- analyzeSchema() decides if flattening is warranted.
- If so, the registry stores both the original (for nestArguments) and
the flat (for the API spec) form.
- specs() emits the flat schema to the model.
- dispatch() re-nests dot-notation args back to the original shape
before invoking the user's fn — but only when the incoming args
actually use dot keys, so nested args from a model that ignored the
flat spec still work (defensive).
API:
- new ToolRegistry({ autoFlatten: false }) opts out.
- reg.wasFlattened(name) introspects the decision.
5 new tests in tests/tools.test.ts covering: shallow schemas left alone,
deep schemas flattened + re-nested round-trip, wide-schema (>10 params)
detection, defensive nested-args pass-through, opt-out.
Total tests: 83 (was 78). Bumps to 0.0.4 — Pillar 3 now ships all four
submodules wired end-to-end.
Takes reasoning_content from deepseek-reasoner and runs a cheap V3 call in
JSON mode to extract a typed plan state:
{ subgoals, hypotheses, uncertainties, rejectedPaths }
Enable with `reasonix chat --harvest` or `new CacheFirstLoop({ harvest: true })`.
Default is off — harvest adds a non-zero V3 call per turn (~$0.0001).
Implementation:
- src/harvest.ts: real harvest() replacing v0.0.1 stub. Uses DeepSeek JSON
mode (response_format: { type: json_object }). Fails closed — malformed
JSON / API errors / short reasoning all return emptyPlanState() so the
main turn is never aborted.
- src/types.ts + src/client.ts: new responseFormat option threaded through
to the API payload.
- src/loop.ts: `harvest?: boolean | HarvestOptions` in CacheFirstLoopOptions.
When enabled and reasoning present, the plan state is computed after the
model call and attached to the assistant_final event.
- src/cli/index.ts + src/cli/commands/chat.tsx + src/cli/ui/App.tsx: CLI
--harvest flag plumbed through to the loop constructor.
- src/cli/ui/EventLog.tsx: new PlanStateBlock renders the harvested state
as dim magenta `‹ subgoals (N): a · b · c` lines above the answer.
Tests:
- tests/harvest.test.ts: 12 tests covering empty inputs, JSON parsing,
prose-wrapped JSON extraction, malformed JSON, API errors, array caps,
item-length trimming, snake_case fallback, non-string filtering.
Total tests: 78 (was 66). Bumps roadmap: Pillar 2 no longer deferred to v0.2.
After the first turn finished, typing was silently ignored: the prompt
box rendered fine but keystrokes didn't register. Cause: PromptInput
conditionally rendered TextInput based on the `disabled` flag. Mount/
unmount cycles dropped Ink's stdin raw-mode claim on some terminals, so
the freshly-mounted input wasn't receiving keystrokes.
Fix: keep TextInput mounted at all times; toggle its `focus` prop
instead of unmounting. useInput inside TextInput no-ops when focus=false,
but the raw-mode claim is preserved, so keystrokes land cleanly once we
re-enable focus.
Bumps to 0.0.3 for re-publish.
Previously, the CLI errored out on first run with 'Copy .env.example to
.env and fill it in' — a lousy welcome for anyone who did `npx reasonix
chat` expecting it to just work.
Now:
- chat command renders a Setup screen with masked-input TextInput if no
key is found. Key validated by format (sk- prefix + 16+ chars), saved
to ~/.reasonix/config.json with 0600 permissions.
- run command falls back to readline.question for the same flow when
stdout is a TTY; non-TTY still errors with a hint.
- Library users unaffected: DeepSeekClient still only reads
DEEPSEEK_API_KEY from env; the config file is a CLI convenience.
New module src/config.ts with readConfig / writeConfig / loadApiKey /
saveApiKey / isPlausibleKey / redactKey — all exported from the package
root so library users can opt in to the same storage.
9 new tests in tests/config.test.ts covering env-var precedence, file
fallback, format validation, and redaction. Total tests: 66.
Bumps version to 0.0.2 for re-publish.
Without this, `npm publish` silently strips the bin field, which would
leave `npx reasonix` broken for installed users even if the tarball
otherwise looks correct. Caught via `npm pkg fix` on the first publish
attempt.
- src/retry.ts: new fetchWithRetry wrapper. Retries on 408/429/500/502/503/504
and network errors (fetch throws). Does NOT retry on 4xx auth/bad-request
errors, aborts, or mid-stream body read failures (retrying would re-bill
and desync context). Honors Retry-After header, capped by maxBackoffMs.
Exponential backoff with 75-125% jitter to spread concurrent clients out.
- src/client.ts: DeepSeekClient.chat and .stream now go through fetchWithRetry.
New { retry } option on DeepSeekClientOptions; pass { maxAttempts: 1 } to
disable.
- tests/retry.test.ts: 11 tests covering retry/no-retry statuses, network
errors, maxAttempts exhaustion, abort handling, Retry-After, onRetry.
- tests/loop.test.ts: updated the failure-path test to use status 401
(non-retryable) so it completes instantly.
Total tests: 57 (was 46). This closes the #1 production risk before launch:
a single 503 during DeepSeek peak hours no longer kills the chat session.
- Markdown: outer container now uses gap={1}, adding a blank line
between each block-level element (paragraph / list / heading / code /
hr / inline display equation after LaTeX strip). Previously sections
like '步骤:' flowed into the list without visible separation.
- ReasoningBlock: cap reduced from 500 → 220 chars, rendered as a
single dim italic line ('↳ thinking: ...') instead of a 19-line
bordered block. Full reasoning still lands in --transcript.
Two follow-up issues from the R1 test:
1. Streaming view duplicated in scrollback
- Cause: during long streams, the dynamic render area grew past the
terminal viewport. When finalize committed the full Markdown-rendered
version via <Static>, the terminal could not erase the scrolled-up
frames of the previous streaming pass, so users saw both the raw
streaming text AND the formatted final output stacked.
- Fix: new <StreamingAssistant> view keeps the dynamic region to a
fixed 1–3 line footprint — 'assistant (streaming · 245 + think 88
chars)' with a single tail-preview line. No matter how long the
stream gets, the dynamic area stays in-viewport and Ink can clear
it cleanly on finalize.
2. LaTeX commands leaking through (\implies, \to, \quad, etc.)
- Fix: extended stripMath in markdown.tsx with the full set of
common commands — arrows (\to, \implies, \rightarrow), relations
(\leq, \geq, \neq, \approx), set membership (\in, \notin),
greek letters, operators (\cdot, \times, \div, \pm), spacing
(\quad, \qquad, \,, \;, \!), and line breaks (\). Also
collapses runs of whitespace that the strip can leave behind.
Two UX issues surfaced during real R1 usage:
1. UI flicker on long streaming outputs
- Cause: every DeepSeek token triggered a React state update, which
re-rendered the entire App subtree (StatsPanel + all events + input).
On a 1320-token answer that's ~1300 full-screen rewrites in seconds.
- Fix: split state into 'historical' (completed events) and 'streaming'
(current assistant turn). Historical goes inside Ink's <Static> which
renders each item exactly once — zero redraw for old messages.
Streaming deltas are buffered in refs and flushed at 16Hz (60ms
interval) instead of per-token. EventRow is React.memo'd for good
measure.
2. Markdown / LaTeX rendered as raw text
- Cause: assistant text was dropped into <Text>{text}</Text> so users
saw literal '\(', '\)', '**bold**', '# header', etc.
- Fix: new src/cli/ui/markdown.tsx — line-based MD parser producing
Ink elements. Handles ATX headings, ordered / unordered lists,
fenced code blocks, inline bold / italic / code, and strips the
LaTeX scaffolding (\(, \), \[, \], \boxed{...}, \cdot, etc.)
that terminals can't render anyway. Markdown is applied on finalize
only — during stream we keep raw text for speed.
- Bug: assistant_final dispatched mark_assistant_done which only set
streaming=false — ev.stats and ev.repair were dropped on the floor, so
the '↳ cache X% · tokens … · $…' line never rendered.
- Missing feature: reasoning_content streamed from deepseek-reasoner was
captured by the loop but never shown to the user.
Changes:
- EventLog: DisplayEvent gains a reasoning field; assistant row renders it
in a dim italic 'thinking ›' block above the final answer (capped at 500
chars preview).
- App.tsx: new reducer actions append_reasoning and finalize_assistant
(replacing mark_assistant_done); reasoning deltas are appended as they
stream; stats + repair note are attached atomically on assistant_final.
After this, Phase C (deepseek-reasoner) will show R1's thinking live above
the answer, and every assistant turn shows the per-turn cache hit stats.
- README: replace projected ranges with measured numbers from real API runs
- 5-turn Chinese chat: 85.2% cache hit, 93.9% savings vs Claude
- 2-turn calculator tool-use: 94.9% cache hit, 95.8% savings vs Claude
- tests/loop.test.ts: 5 integration tests for CacheFirstLoop using fake fetch
(single-turn, telemetry recording, tool dispatch, prefix stability, 5xx error)
- Total tests now 46 (was 41)
loadDotenv was only called inside CLI commands, so any direct script import
(examples/*, benchmarks/*) hit 'DEEPSEEK_API_KEY is not set' even when the
user had a valid .env file. Promote env.ts from cli/ to src/, export loadDotenv
from the library index, and call it at the top of every script entrypoint.
Target branch: 2.x features and fixes go to `studio`. 1.x takes bug fixes,
provider/API compatibility, release/updater, security and platform stability
only, on `main-v2`.
Pull requests are limited to maintainers and invited contributors; one from
anyone else is closed automatically. Open an issue instead.
-->
## Summary
-
## Cause
-
## Blast radius
-
## Neighbouring behaviours tested
-
## Why this layer
-
## UI changes
<!--
Delete this section if the PR touches nothing under `desktop/frontend-next/src`
or the website pages.
-->
- Screenshots, before and after: light and dark, a wide window and a phone-width one (about 390 px). Attach them to this description.
- Entries moved, hidden or removed: none / list each one.
- Hiding or removing a visible control needs a linked issue and a release-notes line naming it. Do not retire UI with `display: none !important` or a feature flag.
- If a row of `docs/STUDIO_PARITY.md` changes, update it here.
## Issues
<!--
If this resolves a report, put `Fixes #123` on its own line — GitHub only
auto-closes from a bare line, so `- Fixes #123` in a list does nothing and the
report stays open. If it only relates to one, use `Refs #123` instead: the
release workflow then asks that reporter to verify once the fix ships.
-->
## Verification
-
For a GSAP to WAAPI/CSS migration (or any cross-API replacement), document
the source-to-target contract here: easing syntax, time units, callbacks,
cancellation, reduced-motion behavior, and failure fallback. Verification must
assert that the target API was actually called; a mock that silently skips it
does not count.
## Disclosure
- [ ] AI assistance was used for this change (optional; for transparency only, it does not change how the change is reviewed)
# An unsigned package is not a lesser APK, it is an unusable one: Android's
# package manager rejects it outright rather than reporting a signature
# mismatch. Say so where the run summary can be read, instead of letting a
# green build imply a shippable artifact.
- name:Say what an unsigned build means
if:steps.key.outputs.signed != 'true'
run:|
echo "::warning::no signing key configured, so this APK is unsigned. Android refuses to install an unsigned package, so the release will carry no APK; the file stays a workflow artifact for whoever signs it."
{
echo "### No APK on this release"
echo ""
echo "The build produced an unsigned APK, which Android refuses to install."
echo "It is attached to this run as a workflow artifact only. Add the four"
Write-Output "::error title=studio-signing.unexpected-signer::STUDIO_SIGNING_SUBJECT is '$($env:EXPECTED_SUBJECT)' but $file is signed by '$($certificate.Subject)'"
$failed = $true
}
}
if ($failed) { exit 1 }
'Certum payload and installer signing, signer, trust and timestamps passed.' >> $env:GITHUB_STEP_SUMMARY
platform=$(git diff -z --name-only --no-renames "$BASE_SHA" HEAD | bash scripts/ci-platform-scope.sh)
if git diff --name-only --no-renames "$BASE_SHA" HEAD |
grep -qE '^(desktop/electron/|desktop/packaging/|desktop/cmd/update-helper/|desktop/cmd/studio-manifest/|desktop/go\.(mod|sum)$|cmd/reasonix-studio-host/|internal/platform/(update|appupdate)/|go\.(mod|sum)$|scripts/(linux-install-smoke|verify-linux-package|verify-linux-appimage|verify-studio-artifacts)\.sh$|scripts/(windows-signing-lib|verify-windows-package|verify-windows-authenticode|install-smoke)\.ps1$|\.github/workflows/(studio|release-studio)\.yml$)'; then
if ($run.ExitCode -eq 0) { throw 'the arm64 installer exited 0 on an x64 machine' }
if (@(Get-ChildItem -Recurse -Force $target -ErrorAction SilentlyContinue).Count -ne 0) { throw 'the arm64 installer wrote into the target on an x64 machine' }
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project maintainer at <359807859@qq.com>. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
<a href="https://oosmetrics.com/repo/esengine/reasonix"><img src="https://api.oosmetrics.com/api/v1/badge/achievement/9e931d80-2050-4b10-902e-44970cc133ad.svg" alt="oosmetrics — Top 2 in Agents by velocity"/></a>
<a href="https://oosmetrics.com/repo/esengine/reasonix"><img src="https://api.oosmetrics.com/api/v1/badge/achievement/556d94b3-61b7-486b-baf2-888b9327deab.svg" alt="oosmetrics — Top 3 in LLMs by velocity"/></a>
<a href="https://oosmetrics.com/repo/esengine/reasonix"><img src="https://api.oosmetrics.com/api/v1/badge/achievement/0f457d4c-efca-4d15-ad2b-139691ff342c.svg" alt="oosmetrics — Top 3 in CLI by velocity"/></a>
</p>
<br/>
<p align="center"><strong>Open source · MIT · runs on your computer, model of your choice</strong></p>
<h3 align="center">An open-source coding agent for your terminal, desktop, browser and editor.</h3>
<p align="center">It reads your project, edits files and runs commands and tests. Have it ask before each step, or work on its own within limits you set. Files its edit tools changed can be rewound. New here? Start with the Studio desktop app.</p>
<p align="center">Maintained by <strong>Huahui Yu</strong>.</p>
> [!IMPORTANT]
> **Community · 加入社区** — bilingual Discord for setup help (`#help` / `#求助`), workflow showcases, and feature ideas. → **<https://discord.gg/XF78rEME2D>**
>
> QQ group **DeepSeek-Reasonix官方群** (`1093562660`) → **<https://qm.qq.com/q/i59b0z2R8s>** ([QR code](./docs/assets/qq-group.svg))
> Douyin: **做游戏的小鱼** (Douyin ID `22703872788`) · [QR code](./docs/assets/douyin.png)
<h3 align="center">A DeepSeek-native AI coding agent for your terminal.</h3>
<p align="center">Engineered around prefix-cache stability — so token costs stay low across long sessions, and you can leave it running.</p>
<br/>
## ❤️Sponsor
<p align="center">
<img src="docs/assets/hero-terminal.svg" alt="Reasonix code mode — assistant proposes a SEARCH/REPLACE edit; nothing on disk until /apply" width="860"/>
</p>
<table><tr><td width="180" align="center" valign="middle"><a href="https://www.rightapi.ai/register?aff=e083bf73" target="_blank" rel="sponsored noopener noreferrer"><img src="./.github/sponsor/rightcode.png" alt="Right Code" width="64"></a></td><td valign="middle">Thanks to Right Code for sponsoring this project! Right Code reliably provides routing services for models such as Claude Code, Codex, and Gemini, with both pay-as-you-go and monthly subscription billing options available. Invoices are available upon top-up, and enterprise and team users can receive dedicated one-on-one support. Register via <a href="https://www.rightapi.ai/register?aff=e083bf73" target="_blank" rel="sponsored noopener noreferrer">this link</a>.</td></tr><tr><td width="180" align="center" valign="middle"><a href="https://www.packyapi.ai/register?aff=rIbQ" target="_blank" rel="sponsored noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="./.github/sponsor/packycode-dark.svg"><img src="./.github/sponsor/packycode-light.svg" alt="PackyCode" width="80"></picture></a></td><td valign="middle">Thanks to PackyCode for sponsoring this project! Access leading AI models through PackyCode with one API endpoint and one API key, with automatic failover and dedicated high-speed routes for Codex and Claude Code. Register via <a href="https://www.packyapi.ai/register?aff=rIbQ" target="_blank" rel="sponsored noopener noreferrer">this link</a>.</td></tr></table>
<br/>
## What it is
> [!TIP]
> **Cache stability isn't a feature you turn on; it's an invariant the loop is designed around.** That's the whole reason Reasonix is DeepSeek-only — every layer is tuned to the byte-stable prefix-cache mechanic.
Reasonix is an open-source AI coding assistant. The program runs on your computer; the AI model is a service you configure, which receives what it reads. You describe a task in plain language; it reads code, edits files and runs commands and tests inside the project folder you choose, and shows you each step.
> [!NOTE]
> **Real user, single day (2026-05-01):** 435M input tokens, **99.82% cache hit**, ~$12 instead of the ~$61 the same workload would cost with no cache on `v4-flash` — see the [case study](./benchmarks/real-world-cache/README.md). DeepSeek provides the cacheable bytes; the four mechanisms in [Pillar 1](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) are how Reasonix keeps them cacheable across long sessions.
You pick the model: a DeepSeek preset is built in, any OpenAI-compatible service is one config entry, and you pay the model provider directly.
## What you get
- **Read, edit, run.** It reads code, edits files and runs tests and commands, all inside your project folder.
- **Permission levels.** Have it ask every time, or let everyday actions run on their own; your forbid rules always hold. To see the approach first, use plan mode: it starts work only once you approve.
- **Rewind.** A file is saved before it changes, so you can rewind by conversation turn without touching your git history. Only files its edit tools changed are covered, not what a shell command did.
## 30-second start
Download, add a model key, open a project. New here? Start with the Studio desktop app.
1. Download and install the desktop app, Reasonix Studio, from the [releases page](https://github.com/esengine/DeepSeek-Reasonix/releases?q=studio-v&expanded=true).
2. Open it and enter your model provider and key when asked.
3. Open your project folder and write what you want, for example "add retry on failure to the http client".
4. At the level you chose, it stops and asks before anything that needs your say-so. Allow it to continue, or refuse.
Prefer a terminal? Download the `reasonix` command-line tool, run `reasonix setup` to pick a model, then run `reasonix`. See [Install](#install) and [Quick start](#quick-start).
## Four ways to use it
- **Desktop app (Studio).** A graphical app; the best place to start.
- **Terminal.** A full-screen text interface; `reasonix run "task"` also works in scripts.
- **Browser.** `reasonix web` opens a web interface on your own machine.
- **Editor.** Install the extension in VS Code; other editors that support ACP (Agent Client Protocol, a common way for an editor to connect to an AI assistant) can connect to `reasonix acp`.
All four are the same program underneath. What follows is for advanced users and contributors.
## Use it from DeepSeek Harness
DeepSeek Harness (`dsh`) can hand a task to Reasonix as a subagent over ACP. This repository publishes a plugin index for it:
1. Run `reasonix setup` on the machine that runs `dsh`. In the DSH Web UI turn on Custom plugin markets (Plugins, More) and add this index in the Discover tab: `https://raw.githubusercontent.com/esengine/DeepSeek-Reasonix/studio/integrations/dsh-plugin/market-index.json`
2. Install "Reasonix subagent" from it.
3. Open the plugin's page and turn its switch on. While it is off the model has no `reasonix` tool and may run `reasonix -p` in its own shell, which looks like a delegation and is not one.
Setup details, the permission policy and limits are in [Using Reasonix from DeepSeek Harness](./docs/DSH.md).
## Versions
Reasonix ships on two lines. See the [version roadmap announcement](https://github.com/esengine/DeepSeek-Reasonix/discussions/10748) for the reasoning behind the split.
| Line | Branch | Status | Get it |
| --- | --- | --- | --- |
| **Reasonix 2.x** | `studio` (this branch) | Active development | [Studio releases](https://github.com/esengine/DeepSeek-Reasonix/releases?q=studio-v&expanded=true) |
| `reasonix chat` | Plain chat — no filesystem or shell tools. |
| `reasonix run "task"` | One-shot, streams to stdout. Good for pipes. |
| `reasonix doctor` | Health check: Node, API key, MCP wiring. |
| `reasonix update` | Upgrade Reasonix itself. |
Other subcommands (`replay` · `diff` · `events` · `stats` · `index` · `mcp` · `prune-sessions`) are in `reasonix --help` and the [CLI reference](https://esengine.github.io/DeepSeek-Reasonix/#cli).
### Desktop client (prerelease)
A native Tauri client for users who want a GUI over the same loop. Multi-tab, the right-panel shows files the agent has read or edited this session, the same cost / cache / token meters live at the bottom. Same DeepSeek API key, same `~/.reasonix` config — the desktop bundles its own Node runtime, no separate `npm install` step.
Download platform installers from [GitHub Releases](https://github.com/esengine/DeepSeek-Reasonix/releases). The desktop ships as a **prerelease**: the loop and protocol are the same as the CLI, but the UI is still being polished and the installers aren't code-signed yet.
- **macOS** — first launch hits Gatekeeper. One-time fix: `xattr -dr com.apple.quarantine /Applications/Reasonix.app` (or right-click → Open → confirm).
- **Windows** — SmartScreen warns "Unknown publisher". Click **More info → Run anyway**.
- **Linux** — `.deb` and `.AppImage` ship plain, no extra step.
The CLI remains the canonical surface. Anything that lands in the CLI is also available from the desktop's composer.
<details>
<summary><strong>Working in another folder · chat vs. code · author a skill</strong></summary>
**Working in a different folder.** Reasonix scopes filesystem tools to the launch directory; pass `--dir` to retarget. Mid-session switching isn't supported by design (memory paths would tangle with stale roots) — quit and relaunch.
```bash
npx reasonix code --dir /path/to/project
```
#### Studio
**Picking `chat` vs `code`.**`code` is the default and the only mode with filesystem / shell tools and SEARCH/REPLACE review. `chat` is the lighter, tools-off shell — reach for it when you want a thinking partner with MCP attached but no disk access.
Studio additionally requires **Node 24+ and pnpm 10**
**Author your first skill.** No remote registry — write them directly. Edit the file (`description:` frontmatter + body), then `/skill list`. Add `runAs: subagent` to spawn an isolated subagent loop instead of inlining the body.
```bash
/skill new my-skill # <project>/.reasonix/skills/my-skill.md
/skill new my-skill --global # ~/.reasonix/skills for cross-project use
```
See the [Studio build guide](desktop/README.md#prerequisites) for platform
webview dependencies and Linux build tags.
</details>
## Quick start
<br/>
### Reasonix Studio
## Configuration
Install and launch Studio, then connect a provider and model in the app. No CLI
setup is needed.
One JSON file at `~/.reasonix/config.json` plus per-project overrides under `<project>/.reasonix/`. The full bilingual reference — every key, every slash command, the on-disk shape of skills/memory/hooks — lives at:
| [MCP servers](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#mcp) | stdio · SSE · Streamable HTTP. One spec format works for both `config.json` and `--mcp`. |
| [Skills](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#skills) | Markdown playbooks the model can invoke. `inline` or `subagent` mode. |
| [Memory](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#memory) | User-private knowledge pinned into the prefix. `user` / `feedback` / `project` / `reference` types. |
| [Web search](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#search) | Mojeek by default; switch to self-hosted SearXNG with `/search-engine`. |
| [Semantic index](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#index) | `reasonix index` — local Ollama or any OpenAI-compatible embedding endpoint. |
In an interactive session, run `/init` when you want Reasonix to create project
instructions.
<br/>
For advanced CLI usage and configuration, see the **[CLI reference](./docs/CLI.md)**,
The loop is organized around three pillars. Each one solves a problem generic agent frameworks don't even see — because they were designed for a different cache mechanic.
<sub align="center">
Click through to the full architecture writeup → [Pillar 1 — Cache-first loop](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) · [Pillar 2 — Tool-call repair](./docs/ARCHITECTURE.md#pillar-2--tool-call-repair) · [Pillar 3 — Cost control](./docs/ARCHITECTURE.md#pillar-3--cost-control-v06)
| Open community development | yes | — | — | yes |
For live cache-hit rates, costs, and methodology, see [`benchmarks/`](./benchmarks/) — the numbers move with model pricing, so they live with the harness, not in the README.
- [**Code of Conduct**](./CODE_OF_CONDUCT.md) · [**Security policy**](./SECURITY.md)
<br/>
## Community
> [!NOTE]
> Reasonix is open source and community-developed. The contributors wall below isn't decoration — every avatar is a real PR that shipped.
Scoped starter tickets — each with background, code pointers, acceptance criteria, and hints — live under the [`good first issue`](https://github.com/esengine/reasonix/labels/good%20first%20issue) label. Pick anything open.
**Open Discussions — opinions wanted:**
- [#20 · CLI / TUI design](https://github.com/esengine/reasonix/discussions/20) — what's broken, what's missing, what would you change?
- [#21 · Dashboard design](https://github.com/esengine/reasonix/discussions/21) — react against the [proposed mockup](https://esengine.github.io/DeepSeek-Reasonix/design/agent-dashboard.html)
- [#22 · Future feature wishlist](https://github.com/esengine/reasonix/discussions/22) — what would you build into Reasonix next?
**Already using Reasonix and willing to help others discover it?** Publish blog posts, articles, screenshots, talks, or videos to [**Show and tell**](https://github.com/esengine/reasonix/discussions/categories/show-and-tell). The project has no marketing budget — community word of mouth is how new users find it. Sustained advocates earn the badge below, displayed next to the contributors wall once awarded:
<img src="https://img.shields.io/badge/REASONIX-📣%20ADVOCATE-c4b5fd?style=for-the-badge&labelColor=0d1117" alt="Reasonix Advocate badge — earned by sustained advocates"/>
</a>
</p>
**Before your first PR**: read [`CONTRIBUTING.md`](./CONTRIBUTING.md) — short, strict rules (comments, errors, libraries-over-hand-rolled). `tests/comment-policy.test.ts` enforces the comment ones; `npm run verify` is the pre-push gate. By participating you agree to the [Code of Conduct](./CODE_OF_CONDUCT.md). Security issues → [SECURITY.md](./SECURITY.md).
<img src="https://contrib.rocks/image?repo=esengine/DeepSeek-Reasonix&max=100&columns=12" alt="Contributors to esengine/DeepSeek-Reasonix" width="860"/>
</a>
</p>
<br/>
## Non-goals
> [!IMPORTANT]
> Reasonix is opinionated. Some things it deliberately *doesn't* do — listed here so you can pick the right tool for your work.
- **Multi-provider flexibility.** DeepSeek-only on purpose. Coupling to one backend is the feature, not a limitation.
- **IDE integration.** Terminal-first. The diff lives in `git diff`, the file tree in `ls`. The dashboard is a companion, not a Cursor replacement.
- **Hardest-leaderboard reasoning.** Claude Opus still wins some benchmarks. DeepSeek is competitive on coding; if your work is "solve this PhD proof" rather than "fix this auth bug," start with Claude.
- **Air-gapped / fully-free.** Reasonix needs a paid DeepSeek API key. For air-gapped or zero-cost runs see Aider + Ollama or [Continue](https://continue.dev).
| `src/telemetry/` | Usage records + cross-session stats |
| `src/server/` | Dashboard HTTP server + REST API |
| `tests/` | Vitest tests, flat `*.test.ts` |
| `examples/` | `basic-chat.ts`, `mcp-server-demo.ts`, etc. |
| `benchmarks/` | Harvest + tau-bench harnesses |
| `dashboard/` | Compiled dashboard SPA assets |
| `data/` | Tokenizer data (`deepseek-tokenizer.json.gz`) |
| `dist/` | Build output — **do not edit** |
| `.github/` | CI + issue / PR templates |
## Commands
```sh
npm run build # tsup → dist/
npm run dev # tsx src/cli/index.ts
npm run chat # tsx src/cli/index.ts chat
npm run test# vitest run
npm run test:watch # vitest
npm run lint # biome check src tests
npm run lint:fix # biome check --write src tests
npm run format # biome format --write src tests
npm run typecheck # tsc --noEmit
```
`prepublishOnly`: lint → typecheck → test → build.
## Conventions
-Go kernel under `internal/`; each package owns one concern. A package's long
explanation belongs in its `doc.go`, not spread across implementation files.
-One transport-agnostic `control.Controller` sits behind every frontend (chat
TUI, HTTP/SSE serve, Electron desktop). Add behavior to the controller, not a
frontend, so all three inherit it.
-Layering (enforced): utility packages import nothing under `reasonix/` except
one another — that layer is closed, so a leaf reaching a leaf drags no graph
along, while refusing it leaves one judgement copied into several of them; only
the frontends `cli`, `serve`, `acp`, `boot` and the hosts `cmd/`, `desktop/`
may import `control`; nothing below a frontend may import one. The declared
sets live in `tools/repolint/layers.go`.
- Subagent delegation keeps five concepts apart: a profile says how a worker
thinks, `TaskSpec` what this call wants, `CapabilityGrant` what it may touch,
`ContextRequest` what it starts from, `SchedulerPolicy` when it runs. Put a
field in whichever member decides its value — profiles carry ceilings, never
per-call values. `internal/runtime/delegation/profile_boundary_test.go` enforces it.
- Cache-first: the system-prompt prefix (base prompt, tools, declared prefix
configuration) must stay byte-stable across turns so DeepSeek's automatic
prefix cache stays warm. Never mutate it mid-session — ride the turn tail
instead (see `control.Compose`), under the rules in *Context projection*.
- Performance features land with an effect test at their final boundary
(`internal/assembly/boot/effect_test.go` pattern): assert what actually reaches the
provider request, frontend sink, or trajectory through the real `boot.Build`
assembly. Component correctness is not system effectiveness.
- A mutex- or atomic-guarded struct is ratcheted on its **scalar** field count
(`struct-state`), not its total: independent flags multiply into states no
type records as legal. Fixing a boundary case by adding one more `bool` is
the move this blocks — group by lifetime into a named sub-state instead
(`agent.perTurnState` is the pattern), which costs one field and removes the
whole product.
- The context window (projection, compaction, estimation) owns `windowState`;
the loop reaches it via `a.window()`, it reaches the loop via `windowHost`.
`window-state` fails any other read of `sess.win`.
- Judgements read structure, never wording: shell ASTs (`shellparse`), types,
contracts, tool schemas. Phrase tables and message sniffing have been retired
in batches (task-policy prose, the planner's approval phrases, the executor
handoff tables) because each one misfires on real input, and a misfiring
judgement inside a gate is worse than no gate. Security allow-lists are the
exception and stay. Something that can only be built by matching words does
not get built — say what is missing instead of guessing at it.
- The other half of that rule: an error a caller must tell apart **carries an
identity** — a sentinel, a typed code — never a sentence. Only the producer
knows a deadline expired rather than a socket closed, and a message is where
that knowledge goes to die: the reader is left matching words, or with
nothing. Across HTTP the identity is a dotted code through `refuse`;
`refusal-path` fails a new `http.Error` in `internal/frontend/serve`, and the parity
test fails a code the frontend cannot say. Inside Go it is `errors.Is` on a
sentinel the wrapping preserves; `error-text` fails a new match against an
error message, following it one hop into a local because storing the text
first is what the direct form turns into.
- **Whoever first knows why an operation failed owns its class.** A transport
status is not a domain identity, and a display string is not a classification;
past that boundary a layer may project the class, never re-derive it. Both
directions were live: `catalog.go` answered 400 for a name nobody declared and
for a disk that would not write, so a failed store told the user their request
was wrong; `ServerRow` decided a connection was an authorisation problem by
matching `/401|403|unauthorized/` against prose an external MCP server wrote,
which the host had sanitised and truncated on the way through. Domain,
internal and dependency are three answers with three different things to do
next, and a caller that cannot tell them apart reports the last two as the
first.
- Failure attribution is host-owned state. When the host can determine why an
operation failed or stopped — truncation, timeout, unavailable context,
dependency skipping, policy refusal, output spill, argument parsing — that
cause goes to the model. Surfacing only the downstream symptom leaves it to
invent one, and the invented rule outlives the incident: a response cut at the
output limit reaches the model as "invalid arguments", and the session learns
to stop batching calls that were never the problem.
- A host-owned identity has to cross the model-visible boundary. Stable step
ids, typed error codes, boundary causes — anything the host expects the model
to cite must appear wherever that state is rendered for it. Telling the model
in a schema to prefer X while every concrete rendering shows only Y trains it
to use Y; `complete_step` said `step_id` PREFERRED while all four todo
renderers printed bare ordinals. Canonical dynamic state still stays out of
the cache-stable prefix — project the identities needed to act on it at the
turn tail.
- A metric is its definition, not its name. Before a number becomes a finding,
state what it counts, from which anchor, over which population, and what it
excludes. Three readings in one study died in that gap: a command of unknown
extent read as a proven write, the latest report's adjudication read as every
report's, and a syntactically accepted call read as a closed one. Each time a
convenient proxy had been left standing in for the state it was named after,
and each time the mechanism story built on it was wrong. A number without
those four lines is an observation, not a result.
- A constructed state is not a reachable one. Before a destructive test or a
counterfactual is reported as a defect, say who in production produces that
state, through which transitions, across which persistence boundary, under
whose authority, and whether a real run has been seen reaching it. A test that
assigns a private field proves the mechanism *given* the state and must be
reported as exactly that: `a.projectChecks` is written once at boot and never
again, so reassigning it stood in for a resume rather than demonstrating one,
and the bypass built on it was never shown to be production-reachable.
Severity is reachability times frequency times authority, not "can be
bypassed".
- A wire type the desktop re-declares by hand is held to the kernel's by
`wire-parity`, both directions: a field one side sends and the other cannot
read fails, and so does one it reads that nothing sends. The two are compiled
by different toolchains and meet only over JSON, so nothing else in the tree
notices when one of them grows a field. The pairs are declared in
`tools/repolint/wireparity.go`, never inferred — no spelling tells a mirrored
contract from a struct that merely carries json tags.
- "Add behavior to the controller so every frontend inherits it" is held by
`frontend-parity`: a capability one frontend already drives, a frontend whose
declared port carries it, and no call, is a missing edge, and the ratchet
counts edges. Which port each frontend drives is declared in
`tools/repolint/frontendparity.go`; a deliberate exception goes in the scope
table there with an issue and a reason, and costs what the edge cost, so the
table cannot become where debt disappears. The matrix is read from
`go/types` at one pinned build target, never from selector names — `Close`
and `Status` are capabilities and also stdlib methods, and a name match
records `os.File.Close` as a frontend driving `Lifecycle.Close`, a false
"wired" that hides real debt. How a verb is spelled — `/branch`,
`POST /branches` — is presentation and stays out of it.
- The desktop's presentation layer answers to canonical state and never
redefines it. Six rules, each held by a gate rather than by memory:
presentation reorders and reweights what the kernel owns but never restates
it; **mount is not a motion cause** — a fact enters once, and replay or
virtualization bringing its element back is not that fact happening again;
a search alias buys discoverability and never becomes a thing's identity;
when a setting takes effect is declared per block, from what its endpoint
does, never inferred from wording or handler names; ordering panels by
lifecycle moves them and must not remount them; and a control's identity
survives a change of where it is drawn — the settings sheet and the composer
render `chrome.preset` because that is one intent, not two.
-**Imports** — explicit `import type` for type-only imports (Biome `useImportType: warn`). Direct relative imports within project, no barrel re-exports.
- **Exports** — named exports only; no `export default`. Entry: `src/index.ts`.
-**Tests** — vitest `describe`/`it`/`expect`, no globals. Naming: `<module>.test.ts` flat in `tests/`.
- **JSX** — `.tsx` for Ink components. `jsx: "react"` in tsconfig.
> Any state that can both be modified by an action and influence the delivery
> claim must either be observable by the host or protected from modification by
> host-enforced boundaries. An incomplete observation never establishes scope.
Effects and state answer different questions and never stand in for each other —
observation proves what an action did, verification proves what the resulting
state satisfies — which is why `unproven_mutation` is settled only by
observation, never by a check that ran afterwards.
What follows bounds Observable today. It is not a restatement of the invariant:
moving a number here must not move the promise.
-`scanWorkspace` walks the workspace and every granted extra root recursively,
skips VCS store dirs, and is `complete` only below 50k files in total. Over that, or past a walk error, it
establishes nothing and the mutation stays unproven.
- Symlinks are recorded by `Lstat`, so a write through one lands outside what
the walk compares. Confining the resolved target is the sandbox's job.
-`internal/safety/sandbox` confines writes to the workspace, configured extras, temp
and toolchain caches on macOS and Linux.
- On Windows a user-enabled write-restricted token bounds the *creation* of files
(create, append, overwrite, `mkdir`, HKCU writes, global git config, writes through links).
- There, deleting or renaming away an existing file is not bounded, and with the
setting off nothing the host enforces bounds `Writable`.
- The caches a command may write can be poisoned for the user's later unsandboxed
builds, on every platform.
- The governed host authorities are a *named* set — ssh-agent, docker, podman.
DBus, Wayland, X11, gpg-agent, keyrings and arbitrary sockets stay reachable,
so the claim is "these endpoints are governed", never "host IPC is isolated".
`stateEpoch` tracks host-observed mutations, not an exact filesystem snapshot;
unobserved external writers are a gap shared by the whole verification model. Go
baseline test criteria use the toolchain's build overlay and therefore share
ordinary verification's epoch semantics; the overlay is not a general filesystem
view.
A captured criterion may be superseded only by authority outside
execution-mutable state; the current workspace, its tests, and the agent itself
cannot authorize supersession.
Two gaps follow and are open, not decided: a build that reads `.git` makes VCS
state VerificationRelevant while the scan skips it, and on Windows a symlink out
of the workspace is neither observed nor protected. Closing either means
widening observation or narrowing writability — never widening what a check is
taken to prove.
## Sandbox dimensions
`HostProtected` above is the delivery-level abstraction. Sandbox policy refines
it into three independent protection dimensions. Their separation is empirical:
measured bypasses showed that protection on one dimension cannot be assumed to
imply protection on another.
- **Integrity** — what host state may be mutated. Expressed by write roots.
- **Confidentiality** — what host information may be observed. Expressed by
`ForbidReadRoots`.
- **Authority** — what host capabilities may be exercised *without* possessing
their secrets. Expressed by `HostAuthorities`.
`ReadOnly` is therefore an Integrity property only; it makes no Confidentiality
or Authority claim.
Network transport and host authority are independent even when a backend
primitive conflates them: on macOS, `(deny network*)` also cut ssh-agent, so one
flag could not express "no internet, still sign".
Filesystem visibility is not authority: denying `file-read*` on a socket did not
stop a connect. Possession is not authority: the key can be unreadable while an
agent still signs with it.
A protection claim exists only where a backend has a demonstrated enforcement
primitive for that dimension. Unsupported dimensions stay explicitly unsupported,
because a claim that outruns its enforcement is worse than an absent one: it is
believed.
Windows enforces Integrity on file creation only, when the user turns it on.
Deletion and rename, Confidentiality and Authority (the named pipes of ssh-agent
and docker, COM and RPC services) are not enforced there.
**Known unmeasured surface — macOS host-mediated delegation:** Apple Events and
Mach-service lookup are not denied by the current allow-default profile. Prior
`osascript` and `launchctl submit` probes were inconclusive; no delegation
effect has been demonstrated. This surface is outside the currently governed
host-authority endpoint set.
- **This IS Reasonix** — edits to `src/loop.ts`, `src/repair/`, `src/tools/`, `src/mcp/` affect every session. Test before publishing.
- **SEARCH must match byte-for-byte** — the edit-gate in `src/code/edit-blocks.ts` enforces exact match. Trailing whitespace or wrong indent = mismatch.
- **`dist/`** is generated by `tsup`. Never hand-edit.
- **`.reasonix/semantic/`** is auto-generated vector index. Never hand-edit.
- **`sessions/` and `.reasonix/sessions/`** are user-private, git-ignored (per `.gitignore`).
| Older releases, forks, or modified builds | Not covered unless the issue is reproducible upstream |
Email <359807859@qq.com> with:
If you are unsure whether a version is affected, report against the newest
released 1.x version and include the exact version or commit you tested.
- a clear description of the issue
- steps that reproduce it (a minimal repro is fine)
- the version (`reasonix --version`) and platform you observed it on
## Reporting a Vulnerability
You'll get an acknowledgement within a few days, and a fix or mitigation as soon as the maintainer can land it. If you'd like attribution in the release notes when the fix ships, say so in your report — the default is a quiet patch.
Please report security issues privately. Do not open a public issue with exploit
details, secrets, crash dumps, or proof-of-concept payloads.
## Supported versions
Preferred reporting path:
Only the latest published minor of `reasonix` on npm is actively maintained. If you're on something older, please reproduce on the latest before reporting.
1. Use GitHub private vulnerability reporting for this repository, if available.
2. If private reporting is not available to you, open a minimal public issue
asking for a private maintainer contact path. Do not include exploit details
in that issue.
## Scope
Please include:
**In scope:**
-Affected Reasonix version, commit, operating system, and installation method.
- The feature or surface involved, such as CLI, desktop app, HTTP `serve`, bot
gateway, MCP plugin, built-in tool, updater, or configuration loading.
- Clear reproduction steps using dummy credentials and non-sensitive files.
- The expected impact, such as secret disclosure, arbitrary file access,
command execution, sandbox escape, authentication bypass, or supply-chain risk.
- Any relevant logs with API keys, tokens, local paths, and personal data
redacted.
-The published `reasonix` npm package and its CLI / TUI
- The dashboard SPA shipped under `dashboard/` and the local HTTP server that serves it
- The shell sandbox, edit gate, and tool dispatcher in `src/`
Do not send real provider API keys, bot credentials, OAuth tokens, private
workspace files, or third-party user data.
**Out of scope:**
## Security Boundaries
- Third-party MCP servers attached via `--mcp` (report to those projects)
- Misconfiguration of the user's own DeepSeek API key, environment, or shell profile
- Vulnerabilities in upstream Node.js or in the DeepSeek API itself
- Denial-of-service via deliberately oversized prompts or tool inputs (Reasonix is a single-user CLI; there's no multi-tenant boundary to defend)
Reasonix is a local coding agent. Many features intentionally operate on the
user's local machine and workspace, including file reads, file writes, shell
commands, MCP plugins, language servers, bot sessions, and model-provider
requests. A finding is security-relevant when it crosses a supported boundary or
bypasses an explicit guard.
## Hardening notes
Supported boundaries include:
A few practical reminders for users running Reasonix:
-Workspace confinement for file operations that are documented or implemented
as workspace-scoped.
-Permission checks for tool calls, shell commands, file writes, and approvals.
- Sandbox behavior for built-in shell execution where the platform supports it.
- HTTP `serve` protections, including the default per-launch token, the launch
token every state-changing request requires when authentication is opted
out, localhost binding assumptions, JSON-only state-changing requests, and
CORS restrictions.
- Desktop and bot session isolation, including per-workspace session metadata
and configured bot allowlists.
- Updater, install, and release verification paths.
The following are normally treated as trusted local/operator-controlled inputs
unless another bug lets an untrusted actor supply them:
- CLI arguments and text typed directly by the local user.
- The user's own configuration under the Reasonix home directory.
- Explicit `@path` references supplied by the local user to attach local files.
- MCP servers, language servers, hooks, and slash commands installed, enabled,
or approved by the local user.
- Provider base URLs and model names configured by the local user.
The following can be security issues when reachable by an untrusted actor or
when they bypass the intended boundary:
- Reading or writing files outside the configured workspace without explicit
local-user intent.
- Following symlinks or path traversal to escape workspace confinement.
- Running shell commands or external tools without the required permission gate.
- Leaking credentials, environment variables, prompt history, local files, or bot
messages to logs, model providers, MCP servers, crash reports, or telemetry.
- Allowing a website to drive the local HTTP server through CSRF, CORS, or
content-type bypasses.
- Letting a bot user outside the configured allowlist submit prompts, approve
tools, or access a project workspace.
- Trusting unverified update artifacts, plugin definitions, or downloaded
binaries.
## Project Configuration
Files that arrive with a workspace are untrusted input: `reasonix.toml`,
`.reasonix/settings.json`, `.mcp.json` and the project `.env`. Cloning a
repository is not a decision to trust its author, so these files may narrow
what the user configured and never widen it.
| Setting | What a workspace file may do |
| --- | --- |
| `sandbox.bash` | Move `off` to `enforce`, never back |
| `sandbox.network` | Move `true` to `false`, never back |
| `sandbox.forbid_read`, `sandbox.denied_domains` | Add to the user's lists |
| `sandbox.allow_write`, `sandbox.workspace_root` | Apply only when they resolve inside the workspace, symlinks followed; `${VAR}` in any sandbox path expands from the process environment only |
| `sandbox.host_authorities`, a user's `sandbox.allowed_domains` | Nothing |
| `permissions.deny`, `permissions.ask` | Add to the user's rules |
| `[[providers]]`, `tools.system_one` endpoints | Declare them; they stay out of use until approved, and model settings naming them fall back to the user's |
An "always allow" answer, or extra write access, granted in a workspace is
stored under the Reasonix home, not in the workspace.
Programs a workspace names for the host to run stay off until the user
approves them for that workspace:
- Hooks, language server commands, `tools.search.rg_path`,
`tools.shell.path`, `[browser]` and `tools.system_one.laya.python` are
approved with `reasonix trust`, or for hooks by saving them from the hooks
editor.
- An approval is stored under the Reasonix home with a digest of the
declaration and of the workspace files it names; any change needs approval
again. Approvals and grants belong to one workspace folder.
- Hooks and language servers are checked against their approval again before
each start, and refused if a file they name changed, appeared or now
resolves elsewhere.
- A single program path (`tools.shell.path`, `tools.search.rg_path`,
`[browser]`, `laya.python`) may not point into the workspace, an
`allow_write` root, a temporary directory or a toolchain cache the bash jail
leaves writable, and may not climb with `..`; its approval covers the
program file's content.
-`tools.system_one.laya.local` is read from the user's configuration only.
- Without an interactive frontend they stay off.
- MCP servers a workspace declares stay off until the user enables them for
that workspace.
A project value that is not applied is reported as a load warning with the
reason. A way for workspace files to widen any of the above without the
user's approval is a security issue.
## `@` File References
Reasonix supports `@path` references so users can include local files and images
in a prompt. This is intentional local functionality, but implementations must
preserve these invariants:
- In workspace-scoped sessions, relative and absolute paths must resolve under
the active workspace root before file content is read or attached.
- Path traversal such as `..` must not escape the workspace root.
- Symlinks must not be usable to bypass the intended workspace boundary.
- Unscoped local CLI compatibility must not be exposed to remote, bot, or
browser-controlled inputs unless an equivalent workspace boundary is applied.
- File content should be size-limited and binary content should not be dumped as
prompt text.
Static analysis alerts about path expressions should be triaged against these
rules: user-controlled path data is expected, but the access must either stay
inside the configured workspace or be clearly limited to trusted local CLI use.
## Out of Scope
The following reports are usually out of scope unless they demonstrate a bypass
of one of the boundaries above:
- A local user intentionally asks Reasonix to read, edit, or send their own
files to a configured model provider.
- A local user installs or enables a malicious MCP server, hook, slash command,
language server, or shell command and then grants it permission.
- A configured model provider, proxy, or MCP server receives data the user
intentionally sent to it.
- Denial-of-service issues that only affect the local user's own session and do
not corrupt files, leak secrets, or bypass permissions.
- Issues requiring administrator/root access on the user's machine before
interacting with Reasonix.
- Vulnerabilities in third-party services, models, proxies, or plugins that are
not caused by Reasonix behavior.
## Coordinated Disclosure
This is a community-maintained project. Maintainers will make a best-effort
assessment, ask follow-up questions when needed, and coordinate fixes before
public disclosure for confirmed vulnerabilities.
Please give maintainers reasonable time to investigate and release a fix before
publishing exploit details. If you plan to disclose on a timeline, include that
timeline in your initial report.
-API keys live in `~/.reasonix/config.json`. Treat that file like any other credential store.
-`run_command` and the `!` shell shortcut respect a permission allowlist; the safe default is `ask` on anything not pre-approved. Don't set `editMode: yolo` on machines that hold secrets you'd regret leaking.
-Hooks (`PreToolUse`, etc.) execute arbitrary shell scripts the user has configured. Audit `.reasonix/settings.json` before running Reasonix in a directory you didn't author.
`verify-page.sh` is the one to run after a change: it starts the kernel with the
same arguments `Kernel.kt` uses (`--auth token`, `--token-file`, `--port-file`,
`-page`) and checks that it binds a port and answers 200. Without a device, that
is as deep as the chain can be verified.
## Where the code is
| File | Owns |
| --- | --- |
| `MainActivity.kt` | The WebView, the back gesture, downloads, external links, renderer restart |
| `Kernel.kt` | Unpacking the page, starting and stopping the kernel, waiting for the port, health probes, logs, the workspace directory |
| `KernelService.kt` | The foreground service that keeps a long turn alive |
| `NativeBridge.kt` | `@JavascriptInterface`: what the page may ask the phone for |
| `BrowserShellServer.kt` | Loopback HTTP server the kernel's browser tools drive the overlay WebView through |
| `Downloader.kt` | Writing a kernel-produced file through the system document picker |
The page reaches the shell through `window.reasonixHost` and `ReasonixNative`,
defined in `desktop/frontend-next/src/port/host.ts` (`AndroidHost`).
**Phone and desktop share one page build.** What differs only on a phone is
decided at runtime, not by a second set of components. `phoneShell()` in
`src/port/host.ts` and the `[data-shell="android"]` selector in `mobile.css` both
read `<html data-shell="android">`, which `index.html` sets before the bundle
loads.
One attribute feeding both is what keeps style and components from disagreeing
about what a phone is.
## What the page may ask the phone for
`NativeBridge` is reachable from whatever document the WebView holds, so every
method that touches the device asks `trusted()` first.
The activity answers by comparing the **main frame's** origin against the
kernel's and against the one paired computer the person scanned a code for. A
page that navigated elsewhere is not trusted, even though it may still hold the
object.
Five methods answer without the check — `version`, `systemTheme`, `safeArea`,
`setLayerOpen`, `setRunning` — because they report back what the page already
knows about its own window and grant nothing.
`openInApp(url)` is the pairing decision, not a navigation one: it loads a URL in
this window only for the origin the scanner just returned, and only once.
Without that, any page holding the kernel origin could hand itself the bridge.
External links leave through the browser. A non-web scheme is routed to the
system only for `mailto:` and `tel:`; everything else is dropped, because an
`intent://` URL can start an arbitrary exported activity with caller-supplied
extras.
## Permissions, and what they cost
`MANAGE_EXTERNAL_STORAGE` — opening a folder on the phone as a workspace. The
kernel is a Go binary: it opens real paths with `open(2)`, and SAF hands back a
`content://` URI it cannot open.
Requested from the folder-picker action, never at launch. Android shows no dialog
for it and opens system settings instead.
**There is no OS-level sandbox around this kernel.** The PR sets the sandbox to
off on Android, so confining the agent to the chosen folder is Reasonix's own
write-root check and nothing else. A shell tool with all-files access can reach
all shared storage.
`REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` — Doze freezes the app group, which stops
a turn that is still running. Asked once when a turn actually runs, never at
launch, and the person can refuse. Refusing costs battery life during long turns
and nothing else.
**Google Play restricts this permission**: fine for a sideloaded build, a
store-policy risk if this is ever listed.
`FOREGROUND_SERVICE` / `FOREGROUND_SERVICE_DATA_SYNC` — keeping the kernel alive
while the screen is off. `dataSync` is capped per 24 hours from Android 15. It is
the closest honest description of "an agent is working".
`CAMERA` — reading the pairing code a computer shows. Requested when the person
asks to scan, never at launch. `ScanActivity` is not exported.
`READ_EXTERNAL_STORAGE` / `WRITE_EXTERNAL_STORAGE` — the same folder walk below
API 33. `maxSdkVersion`-gated; above 33 they are superseded by the permission
above.
`allowBackup=false` with explicit extraction rules, so a `keystore` or a token in
app storage never leaves the device in a cloud backup.
## Cleartext HTTP
The kernel serves its page on `127.0.0.1:<port>`, and a paired computer serves
the same page over its LAN address. Both are plain HTTP.
Neither address can be written into a `network-security-config`: the port is
chosen at start, the LAN address at scan time, and the format matches literals
and domains, not subnets.
So the config permits cleartext and the boundary is in the code instead.
`shouldOverrideUrlLoading` sends every other http(s) origin to the browser, and
the bridge answers only the kernel and the just-paired computer. A plaintext page
on the LAN cannot become the document holding the bridge.
## What goes into the APK
| Content | Size | Why it is shaped this way |
| --- | --- | --- |
| `lib/arm64-v8a/libreasonix.so` | 45 MB | Go static binary, stripped. It is a `.so` rather than a file in `assets/` because only `nativeLibraryDir` is guaranteed executable — a binary copied to app storage fails on a device whose data partition is mounted `noexec`. |
| `assets/page/` | 14 MB | The frontend build, including the Inter and Noto Sans SC fonts, `noCompress` |
| `assets/LICENSE` | 1 KB | The repository's MIT licence, verbatim. MIT requires the notice and the licence text to accompany a binary distribution. |
`assets/LICENSE` is generated by `sync-page.sh` from the repository's root
`LICENSE`, not committed a second time: a checked-in copy drifts when the root
file is updated.
It sits in `assets/` rather than `assets/page/` because that directory is removed
and rebuilt on every build.
A release APK is about 31 MB.
## Building
**The Gradle wrapper is committed**, jar and all. `build.sh` refuses to run
without `gradlew` rather than generating one from whatever `gradle` is on `PATH`:
the dependency versions are part of the build.
`gradle-wrapper.properties` pins `distributionSha256Sum`, so a mirror that serves
a different distribution zip fails verification instead of being unpacked and
run. Dependency repositories are the official ones only — a mirror belongs in a
user-level init script.
**Signing.** A release with no key configured comes out **unsigned**
(`app-release-unsigned.apk`) with a warning. It used to fall back to the debug
key, which produced an artifact that looked shippable and was signed by a
per-machine key nobody chose: it could not install over the previous build.
Point the build at a real key by writing `keystore/keystore.properties`
(`storeFile`, `storePassword`, `keyAlias`, and optionally `keyPassword`) or by
setting the matching `REASONIX_KEYSTORE*` environment variables. Key material
stays out of the repository and out of build logs.
Debug builds always use the debug key. Signing a debug build with the release key
would let anyone who can read the keystore produce a build that installs over the
shipped one under the same signature.
**Non-ASCII checkout paths.** AGP refuses to build under a path with non-ASCII
characters on Windows unless `android.overridePathCheck=true` is set. That is a
property of one machine's disk layout, not of this project, so it is not in the
repository's `gradle.properties`.
Set it in a user-level `~/.gradle/gradle.properties` or pass
// The extraction script: prefer article/main for content pages,
// fall back to body. innerText preserves visual line breaks. It
// also stamps a ref on every element a person could act on, so the
// kernel can name one in an act step the way the desktop backend
// names an accessibility node. A ref already on an element is kept,
// so it stays the same across snapshots of one document; a fresh
// document starts the numbering over, and the kernel only accepts a
// ref from the snapshot it last read.
valscript="""
(function(){
var seq = window.__rxRefSeq || 0;
var used = {};
var marked = document.querySelectorAll('[data-rx-ref]');
for (var i = 0; i < marked.length; i++) { used[marked[i].getAttribute('data-rx-ref')] = true; }
function roleOf(el) {
var tag = el.tagName.toLowerCase();
var role = (el.getAttribute('role') || '').toLowerCase();
if (role) return role;
if (tag === 'a') return 'link';
if (tag === 'button') return 'button';
if (tag === 'select') return 'combobox';
if (tag === 'textarea') return 'textbox';
if (tag === 'input') {
var t = (el.getAttribute('type') || 'text').toLowerCase();
if (t === 'checkbox' || t === 'radio' || t === 'submit' || t === 'button' || t === 'reset') return t;
return 'textbox';
}
return 'generic';
}
function nameOf(el) {
var n = el.getAttribute('aria-label') || el.getAttribute('placeholder') || el.getAttribute('name') || '';
if (!n) { n = (el.innerText || el.textContent || '').trim(); }
return n.replace(/\s+/g, ' ').slice(0, 160);
}
var sel = 'a[href],button,input,select,textarea,[role=button],[role=link],[role=checkbox],[role=radio],[role=tab],[role=menuitem],[contenteditable=true]';
var els = document.querySelectorAll(sel);
var elements = [];
for (var j = 0; j < els.length; j++) {
var el = els[j];
var ref = el.getAttribute('data-rx-ref');
if (!ref) {
do { seq++; ref = 'e' + seq; } while (used[ref]);
el.setAttribute('data-rx-ref', ref);
used[ref] = true;
}
var raw = (el.value != null && String(el.value) !== '') ? String(el.value).slice(0, 160) : '';
Cleartext HTTP is permitted, and the platform has no way to permit less.
Two kinds of page load over plain HTTP: the kernel's own page on
`127.0.0.1:<port>`, and the same page served by a paired computer on whatever
address its router handed out. The port is chosen when the kernel starts and
the LAN address when a code is scanned, so neither can be written here — and a
`domain-config` matches literals and domains, never a subnet.
So the boundary is not this file. `MainActivity` decides which cleartext origin
may become the window: `shouldOverrideUrlLoading` sends every http(s) origin
that is not the kernel's or the one just paired out to the browser, and the
native bridge answers only those two. A plaintext page on the LAN therefore
cannot become the document holding the bridge, which is what the reviewer's
"deliberate path for LAN pairing" asks for.
HTTPS is untouched: nothing here downgrades a request, and `trust-anchors`
keeps the system roots for every TLS connection that is made.
-->
<network-security-config>
<base-configcleartextTrafficPermitted="true">
<trust-anchors>
<certificatessrc="system"/>
</trust-anchors>
</base-config>
</network-security-config>
Loaded 100 of 11713 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.