Resuming a session (reasonix code) whose persisted assistant message holds a
tool_call without a function — e.g. a streaming delta saved before its function
landed — threw "Cannot read properties of undefined (reading 'arguments')" in
hydrateCardsFromMessages, taking down the whole UI at startup. Skip the partial
tool_call; the orphaned tool-output message already no-ops when its card is
absent.
Follow-up polish to the cache-efficiency guardrails (#2314):
- /status "cache detail" line was hard-coded English; route it through i18n
(statusCacheDetail / statusCacheChurn) so it matches every other status row.
EN + zh-CN translated; ja/de/ru inherit EN like the rest of their
observability block.
- sortToolSpecs used localeCompare, which is locale-sensitive and could let
the host locale reshuffle the serialized tool prefix and reintroduce the
very cache churn the sort is meant to prevent. Switch to a stable
codepoint compare. No change for ASCII tool names (all existing tests pass).
Co-authored-by: yhh <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
#2252 added a 15s AbortSignal.timeout to searchBing; the other engines
(Searxng, Metaso, Baidu, Tavily, Perplexity, Exa, Ollama, Brave) still
relied on opts.signal only and could hang indefinitely.
Extract searchSignal() helper that combines the caller's abort signal with
a per-request SEARCH_TIMEOUT_MS cap, and apply it uniformly.
Bing 搜索缺少 AbortSignal.timeout(),响应慢或被墙时请求会无限挂起,
导致 web search 工具卡死在 research 步骤。添加 15 秒超时并与外层 signal 组合。
fix(web): add 15s timeout to searchBing to prevent infinite hangs
Bing search lacked AbortSignal.timeout(), causing infinite hangs on slow
responses or blocked connections. This left the web search tool stuck in
the research step. Add a 15s timeout combined with the outer signal.
Closes#2241
Co-authored-by: Claude Opus 4.7 <[email protected]>
侧边栏拖拽最小宽度从 160px 调整为 200px,防止拖拽时「新建会话」文字被隐藏(CSS 在 ≤190px 时隐藏文字)。
Increase sidebar minimum drag width from 160px to 200px to prevent the "New Chat" text from being hidden when dragging (CSS hides text at ≤190px container width).
Closes#2166
Co-authored-by: Claude Opus 4.7 <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Users who want a fresh session each time (e.g. agents calling reasonix
in loops) had to manually pass --no-session every invocation. Add:
- config.autoResumeSession (default true = existing behaviour)
- /session-persist on|off slash command to toggle and persist the setting
- resolveSession() respects the new flag: when false, skips the 'default'
session fallback so each launch starts with a new timestamped session
## What
New unified \`PlanPanel\` right-side component replacing the modal-overlay pattern.
Covers five plan states: pending / refining / executing / checkpoint / revising.
Layout changes:
- App.tsx: side-by-side flex layout — left conversation column at 35% width,
right PlanPanel at flexGrow=1 when plan is active
- LiveActivityArea: new \`suppressPlanLiveRow\` prop avoids duplicate plan card
- Refine flow: inline plan body display + text input instead of separate modal
## Why
The current modal-overlay pattern replaces the composer area with plan modals,
hiding the conversation. A persistent right panel keeps the conversation visible
while showing plan detail, and the inline refine flow lets users reference the
plan body while typing feedback instead of switching to a blank text input.
## How to verify
1. Start plan mode, let model submit a plan — panel opens on right
2. Click refine — plan body stays visible, input appears below
3. Click approve — panel persists showing step progress
4. Complete all steps — panel auto-closes
5. Confirm conversation still scrollable, composer accessible at bottom-left
The theme system defines SURFACE.bg and SURFACE.bgInput but no
component applied them — the entire UI rendered on the terminal's
default background, causing:
- Input text invisible when terminal bg differs from theme
- No visual separation between card stream and input area
- Theme surface colors completely unused
Add backgroundColor to three layout containers:
- App root Box → SURFACE.bg (app canvas)
- ComposerArea wrapper → SURFACE.bgInput (input dock)
- PromptInput bordered Box → SURFACE.bgInput (input field)
Co-authored-by: HUQIANTAO <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
Adds a top-level `shellAllowedGlobal` config list, auto-approved across ALL
projects and merged (union) with the per-project allowlist when deciding
whether a shell command needs approval. Manage it via a `--global` (or `-g`)
flag on the existing `/permissions` subcommands:
/permissions add --global <prefix>
/permissions remove --global <prefix-or-N>
/permissions clear --global confirm
/permissions list # now shows a Global section above Project
The flag is parsed as a flag (not a positional keyword), so command prefixes
like `g` or `global` remain manageable from the slash UI.
`shellAllowedGlobal` is registered in `STRING_ARRAY_FIELDS` so a malformed
hand-edited value is sanitized on read instead of crashing the merge in
`code/setup.ts`'s `extraAllowed` getter.
Config accessors (load/add/remove/clearGlobalShellAllowed) mirror the
project ones; EN/zh-CN/ja/de strings added (ru falls back to EN).
The scroll-follow useEffect had no dependency array, so it ran on every
render but did not check atBottomRef — meaning it would try to re-pin
even when the user had scrolled up to read earlier content, and conversely
the missing dep array caused React to skip the effect in some batched
renders during fast streaming.
Add a guard on atBottomRef.current and a proper [messageItems] dependency
so the effect only fires when new messages arrive and only scrolls when
the user is already pinned to the bottom.
Claude Code .mcp.json files commonly use ${TOKEN_NAME} or ${env:TOKEN_NAME}
in header values (e.g. Authorization: Bearer ${API_KEY}). Reasonix was
passing these through as literal strings, making migration from Claude Code
require manual header editing.
Add expandEnvInRecord() which resolves ${VAR} and ${env:VAR} patterns in
header records at normalization time. Unset variables are left as-is.
The two symlinked-skill tests added in #2137 — "loads skills from
symlinked directories (#2104)" and "skips broken symlinks gracefully" —
call symlinkSync with no Windows guard, so `npm run verify` fails with
EPERM for contributors on Windows that lack Developer Mode / admin. CI's
Windows runner has the privilege so it slipped through. Add
`.skipIf(process.platform === "win32")`, matching the #2124 symlink tests
already in this file.
Co-authored-by: yhh <[email protected]>
Skills following the Anthropic Skills spec ship a references/ subdirectory
with depth material. Reasonix only loaded SKILL.md, leaving [[references/...]]
wikilinks as dead text and making the depth content invisible to the model.
Append each references/*.md file to the skill body at load time under a
'## Reference: <slug>' header (sorted alphabetically). This follows Option A
from the issue: zero protocol overhead, all depth material available immediately.
Only dir-layout skills (those with a SKILL.md) can have a sibling references/;
flat <name>.md skills are unaffected.
By default api.deepseek.com is in NO_PROXY so clash/v2ray users avoid 403s
from shared exit IPs. Corporate users whose firewall blocks direct egress get
a silent 'fetch failed' with no guidance.
Add a stderr hint when api.deepseek.com is bypassed, pointing users to
REASONIX_PROXY_DEEPSEEK_DIRECT=0 or bypassDeepSeekDirect:false in config.
When REASONIX.md or a global memory file is edited between sessions, the
system prompt is rebuilt on next launch and the resumed session gets a full
cache miss with no explanation. This adds a one-time warning on resume
when the system prompt fingerprint differs from what was saved.
- session.ts: add hashSystemPrompt(); add systemFingerprint to SessionMeta
- App.tsx: save fingerprint on every turn; compare on resume and warn
- i18n/types.ts + EN + zh-CN: systemPromptChanged + systemPromptChangedDetail
## What
Add abortTurn(tab) in the plan_response cancel handler.
## Why
When the user cancels a plan, the agent loop continues running. The
model receives the cancellation signal via pauseGate but the in-progress
turn is not aborted, causing the model to re-submit the plan or continue
generating output that the user already rejected.
## How to verify
1. Start a session with plan mode enabled
2. Let the model submit a plan via submit_plan
3. Click Cancel in the plan approval
4. Confirm the agent loop stops immediately — no further streaming or
tool calls from the rejected turn
* fix(ink): add dependency arrays to useBoxMetrics and useTerminalViewport to prevent scroll jitter (#2076)
- useBoxMetrics: add [ref.current] deps so measurement only runs when element changes
- useTerminalViewport: add [elementRef.current, terminalSize] deps to skip expensive parent-chain walk on every render
- App: memoize TerminalSizeContext.Provider value to keep reference stable
During rapid mouse wheel scrolling (10-20 events/100ms on Windows), the
missing dependency arrays caused each wheel event to trigger 3-5 cascading
renders (30-80 renders/100ms), producing visible text jitter.
* fix(ink): address PR #2095 review — remove ref.current anti-pattern from hook deps
- useBoxMetrics: remove [ref.current] dep array (React anti-pattern);
add 16ms throttle to limit measurement frequency during rapid scrolling
- useTerminalViewport: remove elementRef.current from deps, keep only
[terminalSize] as the reactive dependency
- Add regression test verifying useBoxMetrics re-measures on parent resize
* feat(prompt): prefer MCP search tools over built-in defaults
Add a `# Tool Selection` section to the default system prompt that
instructs the model to prefer MCP-provided tools (e.g. Exa) over
the built-in web_search/web_fetch. MCP tools typically offer
higher quality — semantic search over keyword matching, date and
domain filtering. The instruction includes a fallback to built-in
tools when MCP tools are unavailable.
This is a low-risk change: one paragraph of prompt text, no
runtime overhead, and fully backward-compatible.
* feat(prompt): prefer MCP search tools over built-in defaults
* revert: cli/index.ts back to upstream original
* feat(prompt): add MCP tool selection guidance to code system prompt
* fix(server): convert sync fs I/O to async across server API layer and session memory
Replace blocking readFileSync/writeFileSync/readdirSync/statSync/existsSync
with non-blocking readFile/writeFile/readdir/stat from node:fs/promises in
all server API handlers and session.ts. This prevents the event loop from
blocking on disk I/O during concurrent HTTP requests.
- assets.ts: async cached reads (resolveAssetDir stays sync for module load)
- skills.ts, memory.ts, hooks.ts, browse.ts, project-tree.ts, files.ts,
checkpoint-diffs.ts, health.ts, sessions.ts: async handlers
- session.ts: added async variants (listSessionsAsync, deleteSessionAsync,
loadSessionMessagesAsync, readTailMessagesAsync, etc.)
- atomic-write.ts: added async atomicWrite alongside sync atomicWriteSync
- index.ts: await renderIndexHtml/serveAsset in dispatch
Co-Authored-By: Claude Opus 4.7 <[email protected]>
* style: fix biome formatting and lint errors
- files.ts: add explicit Stats type annotation (noImplicitAnyLet)
- browse.ts: organize imports
- assets.ts, skills.ts, memory.ts, sessions.ts, session.ts,
atomic-write.ts: biome format (line length, trailing commas)
Co-Authored-By: Claude Opus 4.7 <[email protected]>
* fix(test): await async serveAsset/renderIndexHtml in dashboard smoke tests
These functions now return Promises after the sync→async conversion,
so the test calls must await them.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
* style: remove banner separator comments in session.ts
Co-Authored-By: Claude Opus 4.7 <[email protected]>
* fix: eliminate TOCTOU race in memory file read
Read the file directly instead of stat-then-read to avoid a window
where the file could be deleted between the two calls. CodeQL flagged
this as a potential file system race condition.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
---------
Co-authored-by: HUQIANTAO <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(theme): meet WCAG AA contrast for fg.faint and fg.meta across all themes
fg.faint failed WCAG on all 4 dark themes (ratios 1.63-2.56:1, need 4.5:1).
fg.meta failed on midnight (2.35-2.91:1) and was borderline on others.
Dark theme bgElev (#151d2f) was too close to bgInput for surface distinction.
Changes per theme:
- dark: meta #778294→#9aa5b5, faint #4d5666→#8791a3, bgElev #151d2f→#1c2844
- light: meta #6b7280→#5c6371, faint #9ca3af→#666d7b
- midnight: meta #565f89→#9da5bb, faint #414868→#8a92a8
- deep-blue: meta #808080→#909090, faint #606060→#8c8c8c
- high-contrast: already passes, no changes
* fix(ui): replace dim with explicit colors in ReasoningCard and ToolCard
- ReasoningCard: replace `dim` prop with explicit `FG.sub` color
- ToolCard: replace conditional `dim` with explicit `FG.faint`/`errColor`
Co-Authored-By: Claude Opus 4.7 <[email protected]>
* fix(ui): replace all remaining ANSI dim with explicit FG.faint colors
Replace every remaining `dim` prop across 22 UI components with explicit
`color={FG.faint}` (or conditional color logic where dim was used as a
boolean toggle). The ANSI `dim` attribute (SGR 2) halves brightness of
the foreground color, causing near-invisible text on dark terminals
where the default foreground is already low-contrast.
Components fixed:
- mcp-browse, AtMentionSuggestions, DiffApp, EditConfirm
- McpBrowser, McpHub, McpMarketplace
- PlanReviseConfirm, PlanStepList
- RecordView, ReplayApp, Select, Setup
- SlashArgPicker, SlashSuggestions, SplitDiff
- StatsPanel, Wizard, char-bar, ctx-breakdown
- markdown-view (SpanText ambientDim), primitives (Bar, ContextCell)
For conditional dim (e.g. `dim={isDone}`), replaced with conditional
color logic (`color={isDone ? FG.faint : originalColor}`). The Bar
component's `dim` prop was removed entirely — callers now pass the
appropriate color directly.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
---------
Co-authored-by: HUQIANTAO <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
- dashboard/src/i18n/ja.ts: rewrite from standalone 1333-line file to spread
pattern with `...en` fallback; keep only 5 translated sections (app, changes,
common, settings, chat), remove ~30 English-copy sections
- desktop/src/i18n/ja.ts: add `...en.sectionName` spreads to all 30+ sections
including nested objects (app.toast, app.cmd, app.skill, app.titlebar, etc.)
- src/i18n/JA.ts: add `import { EN } from "./EN.js"`, `...EN` top-level spread,
and `...EN.sectionName` spreads to all 46+ sections including deeply nested
objects (slash.*, handlers.*, planFlow.*, ui.*, wizard.themeCaption,
modelPicker.effortDesc)
Missing keys now fall back to English instead of returning undefined.
Co-authored-by: HUQIANTAO <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
Replace per-key `new RegExp(\`\\{${k}\\}\`, "g")` with native
`replaceAll(\`{${k}}\`, String(v))` — avoids regex construction overhead
on every translation lookup. ReadConfig cache already merged in #2162.
Co-authored-by: HUQIANTAO <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
- Create desktop/src/i18n/ru.ts and dashboard/src/i18n/ru.ts using the
spread-fallback pattern (...en), so all keys fall back to English
- Register "ru" in both index.ts: Lang type, SUPPORTED_LANGS, LANG_LABELS
("Русский"), dicts, and detectDefault (navigator.language starts with "ru")
Co-authored-by: HUQIANTAO <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(desktop): resolve FilePill click path against session-tracked files
When clicking a file reference (FilePill) in the desktop chat view, the
path was resolved by blindly joining workspaceDir + displayText. This
fails when the AI writes a short path in conversation (e.g. 'config.yaml')
but the actual file lives in a deeper subdirectory or outside the workspace.
Now resolveAgainstWorkspace first attempts suffix matching against
sessionFiles — paths tracked from actual tool call arguments (read_file,
edit_file, write_file, multi_edit). If a match is found, the tracked path
is used as the base; if absolute it's used directly, if relative it's
resolved against the workspace. Falls back to the old behavior when no
match is found.
Also excludes src-tauri/target/ from Vite's file watcher to prevent
EBUSY crashes on Windows.
* fix(desktop): positional matching for ambiguous file pill resolution
When multiple session files have the same basename (e.g. a/1.yaml and
b/1.yaml), suffix matching alone cannot distinguish them. Add positional
matching: the Nth FilePill in the conversation text maps to the Nth
tool-call path in currentToolPaths (per-message context).
Also pass currentToolPaths through WorkspaceContext so each assistant
message's text segments can resolve file references against the tool
calls that happened in the same message.
`readEntry` used `Dirent.isDirectory()/isFile()` to classify entries, but
both return false for symlinks even when the target is a directory or file
— so a `skills.sh`-style `~/.agents/skills/` layout that symlinks every
skill into a central repo silently saw zero entries with no error or
warning. Resolve symlinks via `statSync` to get the real target type
before branching; a broken symlink is skipped silently instead of
aborting the whole scan.
Add a dirty flag to AppendOnlyLog that tracks mutations (append, extend,
compactInPlace, initWindow). The two expensive full-scan consumers —
healActiveLogBeforeSend() and getLogTokens() — now check+clear this flag
and return a cached result when the log hasn't changed since the last call.
This eliminates 3-4 full array passes with tokenization of every tool-call
argument JSON on every agent-loop iteration when no new messages were
appended — the common case between the model's response and the next
tool-call dispatch.
Changes:
- AppendOnlyLog: add _dirty flag, consumeDirty() method, set on mutations
- CacheFirstLoop: cache healActiveLogBeforeSend() result, skip when clean
- ContextManager: cache getLogTokens() result, skip when clean
Co-authored-by: HUQIANTAO <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
* feat: expand Reasonix theme palettes
* fix: align localized CLI theme choices
Show localized theme labels while preserving stable theme IDs for config and slash commands.
Expose the same public theme list in CLI, dashboard, and desktop, while keeping legacy theme aliases accepted.
* fix: preserve resolved theme picker selection
Use the normalized visible theme as the picker initial value so legacy saved values such as dark select Graphite instead of falling back to auto.
* fix: keep porcelain accent additive
Adds /max-tokens <N|off> slash command and persisted maxOutputTokens config
field so users can limit output tokens per turn, preventing runaway reasoning.
- config: maxOutputTokens field, load/saveMaxOutputTokens accessors
- loop: stored on loop instance, passed as max_tokens to chat and stream calls
- loop/streaming.ts: maxTokens forwarded through StreamModelOptions
- slash: new /max-tokens setup-group command with handler + i18n (EN/zh-CN/de)
- App.tsx: seeded from config on loop construction
Replace hardcoded PILL_SECTION, PILL_PATH, PILL_MODEL constants with
theme-aware functions (pillSection, pillPath, pillModel) that read from
a new `pill` field in ThemeTokens. This ensures Pill components respect
the active theme instead of using static colors that ignore user theme
choices.
Adds `pill()` derivation function in tokens.ts following the existing
CARD proxy pattern, and exports PILL via proxyTokens().
Co-authored-by: HUQIANTAO <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
- auto-git-rollback: write_file output changed from 'wrote N chars' to
'edited ... (M→N chars)' unified-diff format (#2173); update regex.
- slash + ui-slash-suggestions: Telegram /telegram command added by #2168
brings the release command count from 43 to 44; update both assertions.
* perf: eliminate sync I/O from agent loop hot paths
Three independent cache layers that together remove redundant disk reads
and deep-cloning from the per-iteration fast path:
1. readConfig() mtime cache — 37+ calls per session each did readFileSync
+ JSON.parse; now statSync (~0.005ms) short-circuits on mtime hit.
writeConfig() invalidates so writes are immediately visible.
2. ImmutablePrefix.tools() — every loop iteration deep-cloned the full
tool-spec array via structuredClone (~hundreds of KB for 20+ tools).
Now returns a frozen shallow copy, invalidated only by addTool/removeTool.
3. AppendOnlyLog.toFullHistory() — buildMessages() calls this 2-3x per
iteration; when the log window doesn't cover full history, each call
did sync openSync/readSync/closeSync in 64KB chunks. Now caches the
parsed result keyed by totalLength, invalidated by append/compactInPlace.
* fix(config): eliminate TOCTOU race in readConfig via fd-based atomic read
Use openSync → fstatSync(fd) → readFileSync(fd) → closeSync so the
mtime check and content read operate on the same file descriptor,
removing the CodeQL-flagged race window.
Also:
- Add immutability + mtime caveat comments on _configCache
- Type tools() return as readonly ToolSpec[]; widen ChatRequestOptions
and StreamModelOptions to accept readonly arrays
Co-Authored-By: Claude Opus 4.7 <[email protected]>
* fix: use cryptographically random temp file names (CodeQL)
Replace predictable temp file names (based on process.pid, Date.now,
Math.random) with crypto.randomBytes in all 3 atomic-write call sites
to prevent symlink-following attacks on temp files.
Fixes CodeQL "Insecure temporary file" alert on PR #2162.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
---------
Co-authored-by: HUQIANTAO <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
* perf: optimize tokenizer hot paths and prompt builder
Four independent optimizations targeting CPU and allocation pressure in
the token-counting and prompt-formatting pipeline:
1. byteLevelEncode: O(n²) += loop → pre-allocated array + join("")
For a 10KB text chunk this eliminates ~10K intermediate string copies.
2. countTokens: skip number[] allocation — encode(text).length built a
full token-ID array just to read .length. New version counts inline,
saving ~60KB of transient heap per 50KB input string.
3. formatDeepSeekPrompt: += string concatenation → parts[] + join("")
The prompt can be 100K+ chars in long sessions; += copies the entire
accumulator on each iteration, making it O(n²). Array push + join is O(n).
4. cachedBoundedTokens: skip caching strings >10KB in the content-token LRU.
Without this guard, 4096 entries of 50KB+ tool outputs can retain 200MB+
of string keys. Small strings (the common case) still cache normally.
* test(tokenizer): pin countTokens ↔ encode equivalence across a corpus
Add a regression test that asserts countTokens(x) === encode(x).length
for 17 inputs covering: empty string, plain ASCII, CJK, emoji (surrogate
pairs), special/added tokens, code, JSON, repeated text, whitespace, and
a >10KB blob. This is the safety net that makes the countTokens
duplication (which avoids allocating the full number[] array) safe to
live with — any future tokenizer drift will be caught immediately.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
---------
Co-authored-by: HUQIANTAO <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(desktop): composer inline mentions, command chips, and text highlighting
- Allow @ and / insertion at any cursor position (not just end-of-text)
by replacing $ regex anchor with cursor-position-based active-range
detection via findActiveRange / activeRangeRef.
- Remove redundant chips from non-insertOnly slash commands (they
execute immediately and the chip added confusion).
- Derive mention/command chips from draft text (useMemo) instead of
imperative state; remove X dismiss button so chips are read-only
indicators that always match the text.
- Add textarea overlay (composer-backdrop) for @path / /cmd
highlighting via highlightTokens + transparent textarea technique.
- Add onSelect handler so clicking or arrowing into an existing @word
or /word opens the popup for inline editing.
- Sync backdrop scroll position with textarea via onScroll handler.
* fix(desktop): truncate long chip labels to filename, themed scrollbar
* fix(desktop): hide textarea scrollbar to keep backdrop alignment
* fix(cli): commit settled cards to native scrollback
* fix(cli): freeze verbose state for static history
---------
Co-authored-by: Reasonix Test <[email protected]>
* fix: batch store notifications to prevent React max update depth (#2123)
During rapid streaming, dozens of chunks arrive within a single
event-loop drain. Each dispatch() synchronously notified all
useSyncExternalStore listeners, causing React to re-render on
every single token. When renders couldn't keep up with the
streaming speed, nested updates exceeded React's 50-update limit
and threw 'Maximum update depth exceeded'.
Defer state-listener notification via setTimeout(0) so all
synchronous dispatches within the same tick coalesce into a single
notification burst. Event listeners (non-React) are still notified
synchronously for transcript/logging consumers.
Closes#2123
* fix: correct misleading RAF comment, add store batch-notify test
- Replace 'RAF-batched' with 'Macrotask-batched' in store.ts comment
(code uses setTimeout(0), not requestAnimationFrame)
- Add focused test covering dispatch→stateListeners batching path:
state listeners coalesced to one macrotask, event listeners remain
synchronous per-dispatch
* fix(ink): reduce VS Code terminal lag by throttling drain and debouncing damage (#2080)
- Increase scroll drain interval from 4ms (~250fps) to 16ms (~60fps) to
stop overwhelming xterm.js single-threaded ANSI parser
- Only trigger full-screen damage on selection/highlight TRANSITION frames
(activate/deactivate), not every frame while continuously active, cutting
~50% diff work in VS Code terminal
- Coalesce microtask queueing to prevent leading+trailing throttle edges
from double-firing onRender ~0.1ms apart (acknowledged jank in comments)
* fix(ink): remove no-op selTransition/hlTransition change per review
Keep drain interval fix (4ms→16ms) and microtask coalescing.
Remove selection/highlight transition tracking which was a no-op:
prevFrameContaminated already forces full-screen damage every frame
while selection/highlight is active, making the transition tracking
redundant.
* fix(desktop): auto-switch to new session after deleting active session
When the user deletes the currently-active session via the sidebar,
the UI remained stuck on the now-deleted session. Now the backend
detects when the deleted session is the active one and:
1. Aborts any in-flight turn
2. Mints a fresh session for the workspace (reusing startNewChatInTab)
3. Emits \$session_loaded to the frontend so it navigates to the new session
* fix(desktop): emit ctx_breakdown after deleting active session
Add emitCtxBreakdown(tab) call after $session_loaded in the
session_delete active-session branch, matching the canonical
session_load path. Without it, the frontend context-usage bar
reads 0 until the next turn fires a fresh $ctx_breakdown.
- StatusBar: display cache hit ratio to 2 decimal places (e.g. 72.13%)
- StatusBar: show hit/total token details on hover (tooltip)
- StatusBar: cap displayed value at 99.99% unless truly 100.00%
- UsageFull: update pct() helper to return 2-decimal precision
- MetricStrip: accept pre-formatted string for cacheHit prop
Applies to both desktop/ and dashboard/.
SkillStore.readEntry() used entry.isDirectory() to detect skill
directories, but Node.js Dirent.isDirectory() returns false for
symlinks. This caused symlinked skill directories to be silently
skipped with no error or warning.
Added isSymbolicLink() check with statSync fallback to resolve
symlinks and verify the target is a directory. Broken symlinks
are safely skipped without throwing.
Closes#2104
Add a user-configurable per-model context-window override so third-party
models (e.g. mimo, qwen) no longer fall back to the 131 K default that
triggers premature auto-compact.
- config: new contextTokens field (Record<string, number>)
- stats: new resolveContextTokens(model) — user config > built-in > 131K
- context-manager / observability / ctx-breakdown / StatusRow: use it
- desktop settings: context-window size input below custom model ID
- desktop protocol: contextTokens in SettingsPatch
- i18n: en / zh-CN / ja / de strings
- tests: 4 new loadContextTokens round-trip + validation cases
Commands like \`find / -name "xxx"\` bypassed the sandbox because
path arguments were never checked against the workspace boundary.
Only redirect targets and sensitive-path prefixes were validated.
Add a workspace-escape check in \`isAllowed\`: when \`projectRoot\`
is provided, any non-flag argument that resolves to an absolute
path outside the project root demotes the command back to the
confirm gate (user approval required).
Affected patterns:
- find / —name ...
- tree /etc
- grep foo /etc/passwd
- cat /opt/external/file
Workspace-relative commands (find ., tree src, cat README.md)
remain auto-allowed as before.
Co-authored-by: Yapu <[email protected]>
* feat(desktop): add /retry to QQ remote commands
* feat(desktop): add model and mode QQ commands
* fix(desktop): gate QQ model and plan changes behind busy state
* feat: configurable maxIterPerTurn per-turn iteration cap (#2037)
The main loop had no hard iteration limit — a runaway model could consume unlimited API budget. Added maxIterPerTurn config (default 9) with env override REASONIX_MAX_ITER. Plumbed through all loop construction sites (App, desktop, run, acp). Updated i18n strings.
* fix: address review feedback — default 50, drop per-iter env lookup, add iterLimitReached type
- Change DEFAULT_MAX_ITER_PER_TURN from 9 to 50 (real workloads need 15-30 calls)
- Remove redundant parsePositiveIntEnv() inside the loop; use this.maxIterPerTurn directly
(loadMaxIterPerTurn() already resolves config > env > default at construction time)
- Add iterLimitReached to i18n types (fixes CI build failure)
- Move cap check before model call to avoid wasting an API request on the cap-hit iter
- Add test for custom maxIterPerTurn option
* fix: reconcile field doc default to 50
Commands like \`find / -name "xxx"\` bypassed the sandbox because
path arguments were never checked against the workspace boundary.
Only redirect targets and sensitive-path prefixes were validated.
Add a workspace-escape check in \`isAllowed\`: when \`projectRoot\`
is provided, any non-flag argument that resolves to an absolute
path outside the project root demotes the command back to the
confirm gate (user approval required).
Affected patterns:
- find / —name ...
- tree /etc
- grep foo /etc/passwd
- cat /opt/external/file
Workspace-relative commands (find ., tree src, cat README.md)
remain auto-allowed as before.
Completed tasks were rendered as `[x]` markdown which appears as
strikethrough text — still visible and cluttering the display. Filter
them out so only pending and in_progress items are shown, while the
header line still reports the done count.
Co-authored-by: 王锦坤 <[email protected]>
Dashboard + desktop ja.ts missed webSearchEngineBingIntl from #1990;
root JA.ts missed builtinSkills.qq from #2004. Both broke the
required-key check on the strict TranslationSchema, failing CI
typecheck on main.
* fix(desktop): add DeepSeek API and updater domains to CSP connect-src
The desktop app's Content Security Policy was missing required domains
in the connect-src directive, causing requests to fail:
- https://api.deepseek.com — DeepSeek API calls
- https://pub-147fb53b9c1e4bbf891a257968619ea7.r2.dev — updater R2 CDN
- https://github.com — updater GitHub Releases fallback
Changes:
- Added only essential domains (no wildcards, no dev-only localhost)
- Added regression test to prevent future removal
Comparison with PR #2033:
- More restrictive: uses specific R2 URL instead of *.r2.dev wildcard
- Removes unnecessary domains: *.githubusercontent.com, localhost, ws://
- Better security posture for production builds
Closes#2020
* fix(desktop): change Porcelain theme accent color from orange to purple
The Porcelain (light) theme had --accent set to orange (hue 36) instead
of purple (hue 285), causing buttons to appear orange instead of purple.
Changes:
- Changed --accent from oklch(58% 0.18 36) to oklch(56% 0.12 285)
- Changed --accent-soft and --accent-strong to match purple hue
- Now consistent with Midnight theme which uses purple accent
Closes#2022
---------
Co-authored-by: Bernardxu123 <[email protected]>
The permission approval prompts (ConfirmApprovalCard / PathAccessApprovalCard)
in the desktop and dashboard UIs could previously only be granted by clicking.
Wire the global key handler so Enter grants the pending authorization (run
once) when focus is outside an editable field and no modal is open, mirroring
the TUI where Enter confirms the highlighted choice.
Closes#1962
Subagent child-loop usage (cost, cache hit/miss, completion tokens) was written to the global usage.jsonl log but never folded back into the parent session SessionStats. The TUI stats panel and session meta only saw the parent loop API calls.
Added SessionStats.recordExternal() to fold external usage into carryover without creating a turn entry. Wired it through useSubagent onSubagentEnd callback so subagent completion feeds usage back to the parent stats.
Fixes#2008.
MCP servers default to a 60s per-request timeout. Some servers need more. Added requestTimeoutMs to McpServerConfig, McpServerSpec, and all McpClient construction sites so the timeout is configurable per-server in .reasonix/config.json mcpServers section. Plumbed through: mcp-runtime, run, acp, mcp-inspect, reconnect.
- Desktop now bridges both legacy cfg.mcp and canonical cfg.mcpServers.
- Empty-MCP hint, doctor report, install collision checks, dashboard API
all updated to use normalizeMcpConfig() instead of cfg.mcp directly.
- Add regression tests: desktop-mcp-servers + mcp-tui-survival.
Fixes#1993
Refs #2002
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
The ja locale added in #1915 was missing keys that broke `tsc --noEmit`
in desktop/: app.cmd.skill, the sidebarPanel workspace + session-import
strings, settings.webSearchEngine{Brave,Ollama}, and the matching
webSearchApiKey.{brave,ollama} entries. Backfill them with Japanese
translations so the desktop package typechecks again.
* fix(desktop): protect \[4pt] spacing and replace | with \vert in math
* fix(desktop): protect \[4pt] spacing and replace | with \vert in math to avoid GFM table breakage
---------
Co-authored-by: Xingbo Zhao <[email protected]>
* feat(i18n): add Japanese (ja) locale
- src/i18n/JA.ts: full JA translation for CLI/TUI (~1900 lines)
- desktop/src/i18n/ja.ts: full JA translation for desktop shell (~740 lines)
- dashboard/src/i18n/ja.ts: JA translation for dashboard SPA (~1320 lines)
- All three index.ts: register 'ja' in Lang type, dicts, detection, labels
- Wizard.tsx: add 日本語 to language picker
* chore(i18n-ja): fix registration casing + missing keys + lint
- src/i18n/index.ts: register translations.ja with JA (uppercase
export), not the undefined `ja` identifier
- src/i18n/JA.ts: add braveMissingKey / braveUnauthorized /
braveRateLimit / braveServerError / braveParseError (added on
main in #1916 after this branch forked)
- dashboard/src/i18n/ja.ts: add webSearchEngineBrave /
webSearchEngineOllama (added on main in #1916 / #1900)
- tests/i18n-detect.test.ts: ja-* variants map to ja; allow ja+ru
in the Intl-default-arg check
- biome --write across the new ja files and index registrations
---------
Co-authored-by: reasonix <[email protected]>
useBoxMetrics ran a useEffect with no dependency array and called
setSize inside, so any Box whose content shape depended on its own
measurement (directly, or transitively via a store-reported height)
oscillated within a single React commit batch and crashed with
"Maximum update depth exceeded". The crash surfaced in two stacks:
1. Direct: setSize inside useBoxMetrics' useEffect.
2. Indirect: MeasuredCard.useEffect reports a new height after each
oscillating measurement → chat-scroll-store's debounced
flushShrink fires → set() notifies → React's nestedUpdateCount
overflows on the next forceStoreRerender.
Both point to the same root cause: synchronous setState chains
ratcheting React's depth counter without macrotask separation.
Each measure is now scheduled via setTimeout(0). The store update
that follows starts a fresh root render instead of chaining inside
the depth counter, so oscillating call sites still don't converge to
a single value (the underlying anti-pattern in the caller is unchanged)
but the user no longer sees a crash.
Update the existing oscillator repro test to assert the new property:
no max-depth crash + heights still alternate (proving we haven't
silently converged the anti-pattern, just stopped the crash).
Co-authored-by: reasonix <[email protected]>
Context-guard and stuck-state recovery were calling
ctx.client.chat({ model: "deepseek-v4-flash" }) regardless of what the
user actually configured. Third-party DeepSeek-compatible endpoints
(mimo, self-hosted, Azure forks) that don't expose flash 400 on every
force-summary, the recovery path crashes, and the session looks like
it lost context — the messages are still there, but the user sees an
error and has no way back without /clear.
Pass this.model through summaryContext() and use it for the summary
call. `thinking: "disabled"` still keeps reasoning tokens off the bill
even when the active model is pro.
Add a regression test that asserts the force-summary path hits the
active model, not flash.
Co-authored-by: reasonix <[email protected]>
* feat(desktop): show all currency balances from user/balance API
DeepSeek's /user/balance endpoint returns a balance_infos array with
separate entries per currency (CNY, USD). The desktop client was only
showing the single largest balance (pickPrimaryBalance), hiding the
other currency.
- Add BalanceInfoItem type and balanceInfos array to BalanceEvent protocol
- Pass all currency balances through emitBalance() in the Node child process
- Store multiple balance infos in the frontend Balance type
- Render all balances as a single segment: \$ X.XX / ¥ YY.YY
- Preserve existing single-balance fallback for backward compatibility
* fixup(desktop): restore click-to-toggle on balance segment
The multi-currency rendering dropped onClick={onToggleCurrency}, breaking
the mouse path to flip the cost segment between CNY/USD. Restore it with
the existing switchCurrency tooltip — the balance now shows both, but
the cost figure still tracks the user's chosen currency.
---------
Co-authored-by: reasonix <[email protected]>
Desktop never wired the hook runner — `buildRuntimeFor` constructed
CacheFirstLoop without `hooks`/`hookCwd`, and `runTurn` had no
UserPromptSubmit/Stop dispatch. So hooks defined in
~/.reasonix/settings.json silently no-op'd in the desktop app even
though they fired fine under `reasonix code`.
Load hooks per tab from `tab.rootDir`'s project scope + global,
thread them into the loop (covers Pre/PostToolUse via the loop's own
trigger), fire UserPromptSubmit before `loop.step` and Stop in the
turn-complete tail, and re-load on workspace switch so project hooks
follow the new root. Non-pass outcomes surface via $error; a blocking
UserPromptSubmit aborts the turn before the prompt reaches the model.
Closes#1942
Co-authored-by: reasonix <[email protected]>
When the SSE stream terminates mid-turn (proxy/LB idle drop, undici
`Error("terminated")`), the loop yields a role:"error" event and
returns. The reducer flips `busy:false` and appends the error card,
but the in-progress assistant message keeps `pending:true` — so the
UI shows a "thinking" spinner above the red error box and looks stuck.
Reported as "对话卡死" in #1660.
Loop has already returned by the time we receive the error, so any
streaming assistant message is no longer streaming. Settle it.
Co-authored-by: reasonix <[email protected]>
Reported: user installed via npx, ran setup, then switched to the
desktop app. Saving a fresh key from the desktop UI updated
config.json but every request still 401'd with the old key as the
masked tail in the error message.
Root cause: loadEndpoint's fallback (no custom baseUrl on either
side) prefers process.env.DEEPSEEK_API_KEY over cfg.apiKey on the
read path — a 12-factor convention. A stale env (User-level Windows
env var, ~/.env, shell rc) then shadowed the just-saved config
forever inside the running Node sidecar.
Fix: have saveApiKey mirror the new value into process.env so the
explicit UI save wins inside the current process. Read precedence is
unchanged — env still beats config for users who deliberately set
DEEPSEEK_API_KEY to override.
Co-authored-by: reasonix <[email protected]>
Context-guard and stuck-state recovery were calling
ctx.client.chat({ model: "deepseek-v4-flash" }) regardless of what the
user actually configured. Third-party DeepSeek-compatible endpoints
(mimo, self-hosted, Azure forks) that don't expose flash 400 on every
force-summary, the recovery path crashes, and the session looks like
it lost context — the messages are still there, but the user sees an
error and has no way back without /clear.
Pass this.model through summaryContext() and use it for the summary
call. `thinking: "disabled"` still keeps reasoning tokens off the bill
even when the active model is pro.
Add a regression test that asserts the force-summary path hits the
active model, not flash.
Co-authored-by: reasonix <[email protected]>
Desktop palette had no /skill entry, so typing /skill (which works in
the CLI) showed "no matches". Add /skill + /skills as palette commands
that open Settings → Skills, and handle the same names on submit so
pressing Enter goes there too (mirrors the /search-engine special case).
Co-authored-by: reasonix <[email protected]>
When launched with cwd=/ (e.g. some daemon/IDE contexts), saveTruncatedResult
joined the project root to .reasonix and tried to mkdir /.reasonix/truncated-results,
which fails with ENOENT and crashes run_skill on oversized results.
Treat fs-root rootDir the same as empty and write under the user's home dir
instead. Closes#1959.
Co-authored-by: reasonix <[email protected]>
`truncateForModel` and `truncateForModelByTokens` slice on UTF-16 code
units. When the cut lands inside a surrogate pair (emoji, supplementary
CJK) the resulting head ends with a lone high surrogate / tail starts
with a lone low surrogate. The lone-surrogate sanitizer in `client.ts`
catches one downstream layer, but the safer fix is to never produce
the malformed slice in the first place — keeps tool results clean even
on the disk transcript path that bypasses the client sanitizer.
Reported: HTML file full of emoji caused DeepSeek to reject the chat
request with `serde_json: unexpected end of hex escape at line 1
column 38621` once the file content was sliced to fit the result-token
budget.
Co-authored-by: reasonix <[email protected]>
* fix(web_fetch): fall back to DoH when system DNS returns fake internal IPs
TUN mode proxies (Clash Meta, Sing-box, etc.) use Fake-IP DNS strategy,
returning reserved addresses (e.g. 198.18.0.0/15) for all domain lookups.
The SSRF check in assertPublicHttpUrl treats these as internal hosts and
rejects legitimate public domains like github.com.
Add dohResolve() that queries Cloudflare 1.1.1.1 DNS-over-HTTPS to get
real public IPs. When system DNS returns any internal/reserved address,
fall back to DoH and only reject if the DoH results are also internal.
This preserves SSRF protection while correctly handling DNS pollution
from TUN/mitm proxies.
* test(web_fetch): update SSRF test to account for DoH fallback
The old test asserted that globalThis.fetch was never called when DNS
returned internal addresses. After adding the DoH fallback in the
previous commit, the code now makes a single DoH query to verify.
Update the test to stub fetch with a rejected promise and assert it
calls the correct Cloudflare DoH endpoint.
* fixup(web_fetch): compress dohResolve JSDoc to one line (comment-policy)
---------
Co-authored-by: reasonix <[email protected]>
* fix(desktop): support \[ \] and \( \) math delimiters in markdown
* fix(desktop): protect \[4pt] LaTeX line-break spacing from math delimiter normalization
---------
Co-authored-by: Xingbo Zhao <[email protected]>
Follow-up on #1918 — strip the four loose joints that surfaced in review:
- Replace `(err as any).code` / `(err as any).phase` casts with a small
`errorMeta(err)` narrowing helper in `loop/errors.ts`. Same payload,
no escape hatch.
- Extract `is4xxError` alongside `is5xxError` so the loop's "client
error → not retryable" branch reads like the existing 5xx code path
instead of an inline regex.
- Decouple `recoverable` from `retryable` in the loop's API-failure
yield. `recoverable` is the historical "agent can keep going" flag
(consumed by event listing), `retryable` is the new external retry
hint; conflating them changed event-listing output silently.
- Carry `name` through `ErrorEvent` + eventize so the ACP dispatcher
surfaces the real error name instead of `ev.message.split(":")[0]`.
Co-authored-by: reasonix <[email protected]>
* fix(tui): break CardStream measure→render→measure loop (#1955)
CardStream measured the inner scroll Box via `useBoxMetrics`, derived
maxScroll from `inner.height - outer.height`, then pinned-mode wrote
that back to scrollRows — which feeds into `marginTop` and items
composition, which feeds back into inner.height. Several edit_file
results streaming in one turn was enough to stack the cascade past
React's nested-update limit (50).
Inner height is already known per-card in the chat-scroll store —
the per-card `useBoxMetrics` in MeasuredCard reports it. Summing the
store gives the same total without ever measuring inner, so scrollRows
can no longer feed back into the value used to compute maxScroll.
- ink-update-depth-repro.test.tsx: pins down the underlying pattern
(a component that decides its own render from its own useBoxMetrics
reading trips Max update depth).
- cardstream-architecture.test.tsx: side-by-side pre/post-fix harness
proving the post-fix path stays linear and converges on the right
maxScroll.
Closes#1955
* test(tui): assert oscillation by render count, not Max-depth firing
CI hit a flaky failure: Linux + Windows runners didn't trip React's
nested-update guard within 80ms while local Windows did. The guard
firing is timing-dependent (depends on how the event loop happens to
interleave commits and setInterval) — what's deterministic is that the
broken pattern keeps re-measuring forever. Assert that instead: stable
layouts converge in a few renders, the bad pattern compounds without
bound.
* test(tui): loosen oscillation count threshold for slow CI runners
Windows CI cleared 22-26 renders in 80ms versus hundreds locally;
the 10× multiplier kept tripping. Switch to an absolute floor of 15
— still far above the stable-layout converge (≤ 3) and proves the
"doesn't converge" property without coupling to runner speed.
---------
Co-authored-by: reasonix <[email protected]>
When a proxy/LB idle timeout cuts an SSE stream, undici throws "terminated" as a bare string and ACP headless clients lose the context needed to decide whether to retry. Thread structured `errorDetail` ({name, message, code, phase, retryable, recoverable}) through client → loop → kernel events → transcript → ACP so the failure cause survives every hop.
All changes are additive: `LoopEvent.errorDetail`, `TranscriptRecord.errorDetail`, `SessionPromptResult.transcriptPath`, and `SessionUpdate.metadata.error` are all optional, so existing clients that ignore unknown fields keep working.
Closes#1884.
Replace any with named response shapes (ServerSessionsResponse /
ServerOverviewResponse) so mapSessionItem / emitSessionsSnapshot /
emitOverviewSnapshot read off real fields instead of structural any.
Callers still get any from apiFetch — narrowing happens at the boundary.
Co-authored-by: reasonix <[email protected]>
* fix(desktop): normalize path separators for Windows file opening
Markdown file references and context panel paths use forward slashes from AI output, causing cmd.exe to fail on Windows. Normalize to backslash when the workspace path indicates Windows.
Closes#1869
* chore: retrigger CI
---------
Co-authored-by: Bernardxu123 <[email protected]>
Was a stub `src/vendor/ink/index.d.ts` plus an empty `index.js` (the
real runtime arrived obfuscated, source unreachable). Moving the
source into `packages/ink` as a workspace dep gives consumers real
types and makes the runtime editable in-repo.
API migrations forced by the new stricter types:
- Text/Box `color` is a typed union now (`ansi:<name>` | `#hex` |
`rgb()` | `ansi256()`); bare ansi names get the `ansi:` prefix
- `dimColor` → `dim`; Text's bold/dim discriminated union relaxed
so the two can coexist (terminals collapse them anyway)
- `ThemeTokens` fields typed as `Color` so theme-derived values flow
through helpers / props without manual casts
Markdown OSC 8 hyperlinks switch from `<Transform>` (a shim that
silently ignored the `transform` prop, breaking Ctrl+click hyperlinks)
to `<Link url>`, which uses ink's existing `ink-link` plumbing.
Dropped dead shims: `Transform`, `useAnimation` (zero callers after
the markdown rewrite).
Comment-policy pass on the new package: stripped 638 multi-line
essay block comments to 1-line summaries to match the repo rules.
Co-authored-by: reasonix <[email protected]>
* fix(desktop): separate ctx scrollbar from resize handle
* fix(desktop): add gap beside context scrollbar
* fix(desktop): push thread scrollbar away from right edge (#1695#1793)
* fix(desktop): push thread scrollbar away from right edge
* thread scrollbar hover: thumb expands from 4px to 8px on hover
* fix(desktop): un-pin during scrollbar drag to stop rubber-banding
Three small improvements on top of #1889:
- JS: read the clipboard Blob with file.arrayBuffer() and pass the
ArrayBuffer straight through invoke(). Drops the FileReader → data URL
→ atob → Uint8Array → number[] chain, which inflated the IPC payload
by ~5x on every paste.
- Rust: tighten extension validation. sanitize_image_extension now
requires the post-trim/lowercase value to be 1–8 ASCII alphanumeric
chars, otherwise falls back to "png". Belts-and-braces vs a renderer
passing "png/../../escape".
- Rust: spawn a startup thread that removes files older than 24h from
the pasted-images temp dir so it doesn't grow unbounded between OS
temp wipes.
Includes Rust unit tests for the extension sanitizer.
Co-authored-by: reasonix <[email protected]>
* i18n: add Russian (ru) language pack
* fix(i18n): apply biome format, add ru wizard label + slash.language description
- biome format wrapped long ru.ts lines (CI was red on format).
- LANGUAGE_LABELS in Wizard.tsx now includes ru ("Русский"), restoring the Record<LanguageCode, string> exhaustiveness.
- slash.language entry needs an explicit description override since the spread doesn't carry it through TypeScript's narrowing.
---------
Co-authored-by: reasonix <[email protected]>
Inlining the size/background ternary into JSX made the render branch
hard to read. Move it back into dotProps() — same matrix:
hover/near > active > base, hover transition-delay only when hovered.
Co-authored-by: reasonix <[email protected]>
- Capitalize 30 German sentence starts per orthographic rules
('noch keine ...' -> 'Noch keine ...', etc.)
- Fix terminology: Systemeingabeaufforderung -> System-Prompt,
Denkaufwand -> Reasoning-Effort, Veranstaltungstyp -> Ereignistyp,
Tree-Kill -> Prozessbaum
- Translate ratelimited -> Rate-Limit erreicht across all 6 search engines
- Add missing ui.yoloHint translation (was falling back to English)
- Plural format {e}/{en} -> (e)/(en) for i18n compatibility
- Fix typo: fortgesetzen -> fortgesetzt, awd -> CWD, du -> Du
- Tighten descriptions: zwangsweise/Stelle diesen String vor -> Praefix fuer
- Add German slash-command description coverage test
- Use z.B. consistently instead of z. B.
(42 insertions, 38 deletions)
Co-authored-by: hermitokatt <[email protected]>
Users running an internal Nginx proxy in front of api.deepseek.com pick
the env name from the OPENAI_BASE_URL convention and try
DEEPSEEK_API_BASE_URL. We only read DEEPSEEK_BASE_URL, so the proxy
silently isn't used. Accept the alias (canonical name still wins on
conflict) so the obvious env name works.
Co-authored-by: reasonix <[email protected]>
Desktop and GUI users on Windows often can't reliably set HTTPS_PROXY
for the spawned Reasonix process — env vars set in Clash, system
settings, or PowerShell profiles don't always reach a Tauri-launched
child. The proxy plumbing is in place; only the env-var source path
was wired.
Add cfg.proxy.url as a first-class source: it wins over HTTPS_PROXY /
HTTP_PROXY / ALL_PROXY when set, normalizes bare host:port like the env
path, and tags the install result with source: "config" | "env" so
/doctor can show which one is active.
Closes#1868
Co-authored-by: reasonix <[email protected]>
The drag-path direct DOM writes for --thread-max-width and --composer-max-width
were unitless strings, so the consumer max-width var() fell back to its default
for one frame per mousemove until React's render caught up — a visible flicker
that cancels the perf win.
- Suffix both writes with `px`
- Replace the duplicated formula with the existing getThreadMaxWidth helper
- contain-intrinsic-size: 1px 100px → auto 100px, so the browser remembers
the actual rendered size instead of pinning offscreen messages to 1px wide
Co-authored-by: reasonix <[email protected]>
The web client was POSTing to /api/modal with {id, response}, but
the server expects /api/modal/resolve with {kind, choice, text?},
so every web confirmation returned 405 and the TUI's pauseGate
stayed open. The reverse direction was broken too: the tauri-bridge
SSE handler ignored modal-down, leaving the web modal up after the
terminal user resolved it.
- bridge confirm/choice/plan/checkpoint/revision RPCs through the
real /modal/resolve endpoint with the right body shape
- carry "shell" vs "path" on confirm_response so the server can
route to the matching TUI handler
- emit \$modal_dismissed from modal-down so the web reducer clears
pending lists when another surface resolves first
Co-authored-by: reasonix <[email protected]>
The update notice rendered at the top of the thread scroll area, so a
restored session with messages would scroll the banner out of view and
the user had to open a new tab to see it. Lift it out of `thread-inner`
into a fixed-position overlay anchored to the viewport, rendered once at
the App root instead of per tab.
Co-authored-by: reasonix <[email protected]>
The desktop client had no UI for filling in API keys for web search
engines that require them (metaso, tavily, perplexity, exa) or for the
SearXNG endpoint. The `/search-engine` slash command also fell through
to the chat input instead of being handled locally.
- General settings page now renders a credentials row below the engine
selector that adapts to the chosen engine: a URL input for searxng,
a password input + signup link + clear button for the API-keyed
engines. Existing keys show a masked prefix.
- Server-side `settings_save` accepts `webSearchEndpoint`,
`metasoApiKey`, `tavilyApiKey`, `perplexityApiKey`, `exaApiKey`
(with `null` to clear); `$settings` reports the masked prefix for
each so the UI can render a "set" indicator without leaking the key.
- `/search-engine` and `/se` now open the general settings page
instead of being forwarded as user text.
Closes#1844
Co-authored-by: reasonix <[email protected]>
- Reset activeIdx to 0 on popup.kind switch (slash <-> at) instead of
clamping into the new popup's range, which left users on an arbitrary
row after switching.
- Drop the lastActiveRef guard in Popup — useEffect([activeIdx]) already
reruns only on change.
- Move the conditional class join out of a template literal so the
non-at branch doesn't leave a trailing space.
- Remove unused EditMode / ReasoningEffort type imports from the test.
Co-authored-by: reasonix <[email protected]>
Follow-up to #1857. The argsHint values are BNF over English command
keywords (`connect [appId appSecret [sandbox]] | status | disconnect`)
— there's nothing to translate. The merged zh-CN override dropped the
sub-argument structure and inlined an EN+CN gloss (`connect连接`)
that read awkwardly.
Removing the key lets zh-CN fall back to spec.argsHint, so users see
the same syntax as English and don't lose the appId/appSecret hint.
Co-authored-by: reasonix <[email protected]>
`rootUri` and `workspaceFolders` are LSP concepts, not part of the MCP
2024-11-05 `initialize` schema. Strict servers (e.g. ida-pro-mcp on the
official Python SDK with pydantic) reject the request with
`Invalid params: unexpected parameters: ['workspaceFolders', 'rootUri']`.
Workspace roots are already exchanged the correct way: the client
advertises the `roots` capability, and the server requests them via
`roots/list` (already wired up).
Co-authored-by: reasonix <[email protected]>
The test was the only consumer routing through useEditHistory.ts —
import undo-context.ts directly. Six re-exports gone, no behavior
change.
Co-authored-by: reasonix <[email protected]>
Stage 1 of #1829: ship the renderer as a separate private package
instead of vendoring at src/ink/. Picks up the tui-polish work that
landed alongside it (visuals, pulse animations, ghosting fix).
## Renderer extraction
- src/ink/ removed; renderer lives in esengine/reasonix-ink (private)
- package.json: ink dep points at @esengine/ink (file: tarball for
local dev; swap to npm: alias post-publish); react-reconciler and
yoga-layout added as direct deps so they hoist to a single top-level
instance (single React dispatcher, single reconciler instance);
17 transitive runtime deps and 3 @types removed
- tsconfig: ink path-map removed
- vitest.config: ink alias removed
- tests/helpers/ink-stdio.ts: text() uses strip-ansi + restores
CSI N C cursor-forward back to literal spaces
- tests/helpers/ink-test.ts (new): replaces ink-testing-library;
lastFrame() joins all chunks instead of returning only the most
recent write() — required because the diff-based renderer emits
multi-chunk frames per commit
- 15 test files migrated; 13 obsolete UI snapshot tests removed
(5 files)
## Visual alignment
- UserCard: single full-row backgroundColor=MESSAGE_BG.user fill
- ApprovalCard: round border with borderLeft/borderRight=false
- PromptInput: round border (top + bottom only) + borderText with
plan / history / mode / model
- ReasoningCard: italic + dim header; collapsed state appends
(ctrl-o to expand) hint
- theme/tokens: new MESSAGE_BG section (user/bash/selected) for all
5 themes
- CardHeader: glyph prop accepts string | ReactElement
## Pulse animation system
- Pulse primitive: generic frame cycler with DIAMOND/SQUARE/
TRIANGLE/CIRCLE/HEX presets aligned to existing brand glyphs
- Wired into 7 cards + 4 LiveRows components
- ThinkingRow + OngoingToolRow: live elapsed time + output token
count + t/s rate
- ticker.tsx: useTick / useSlowTick switched from
useAnimationTimer (keepAlive=false) to useAnimationFrame
(keepAlive=true) so the shared clock actually starts
## Bug fixes
- PromptInput: removed systemCursorSync — the out-of-band CSI CUP
write desynced the renderer's screen model under sync-output mode,
causing residual glyphs starting at the 3rd typed character
- Wizard: TextInput now sourced from ink (drop-in TextInput exposed
by the package); ink-text-input dep removed
## Tests
279 files, 3722 passed, 11 skipped, 0 failed.
Refs #1829 (Stage 1).
Co-authored-by: reasonix <[email protected]>
State requires `memoryDetail` since #1779 added it; test initial-state
builder and ContextPanel render fixture were missing the field. Root
`verify` doesn't run desktop tsc, so this surfaced only in the desktop
release matrix build for desktop-v0.51.0.
Ink 7.0.3 (Static stale-output fix, useBoxMetrics ref) and 7.0.4
(shared resize listener, useEffectEvent dependency fix) ship upstream
fixes worth picking up. None of them include the overflow-frame
flicker reduction from #1791, so dropping the patch reverts that
optimisation — accepting the regression in exchange for not carrying
a local fork of ink's render path.
- bump `ink` ^7.0.2 -> ^7.0.4 in package.json + lockfile
- delete `patches/ink+7.0.2.patch`
- drop `patch-package` from dependencies (and its transitive tree)
- remove the patch-package execSync from scripts/postinstall.mjs
Co-authored-by: reasonix <[email protected]>
advanceActivePlanSteps marks the next non-settled step as `running`
whenever a step completes, but nothing demotes it when the agent stops
calling mark_step_complete mid-plan. The card then displays "step N in
progress" indefinitely even though the turn has ended.
Dispatch a new plan.idle event from the App.tsx turn-end finally; the
reducer maps running→queued on active plans. Multi-turn flows are
unaffected — the next mark_step_complete re-advances the marker via
advanceActivePlanSteps.
Closes#1784
Co-authored-by: reasonix <[email protected]>
`search_content` was dispatching every pattern that parsed as a valid
RegExp — including plain literals like `new ToolRegistry` — to the
worker thread, paying full postMessage round-trip per file. On
multi-file scans this dominates wall time; one report hit the 120s
walk deadline on a query grep finished in 0.72s.
Detect patterns with no regex metacharacters and route them to the
existing main-thread `text.includes` branch. Also short-circuit
files whose buffer doesn't contain the substring so we skip the
line-split for misses.
Local bench (full repo, ~20K walkable files): root no-glob literal
2255 ms → 809 ms (2.8x); src/ *.ts literal 132 ms → 74 ms (1.8x).
Regex patterns still take the worker path; all 3731 tests pass.
Closes#1748
Co-authored-by: reasonix <[email protected]>
Typing or pasting tokens like `[DEBUG]` was being parsed as a stripped
left-arrow (`[D`) plus the leftover `EBUG]`. The ConPTY ESC-strip rescue
now only fires when the matched tail ends the chunk or chains into
another control byte; printable letters/digits after the tail mark the
input as user text.
Closes#1771
Co-authored-by: reasonix <[email protected]>
#1657 dropped the preset abstraction and exposed reasoning effort
directly, keeping `max` as a DeepSeek-only extension that users opt
into knowing standard OpenAI / vLLM / Azure reject it with 400. The
TUI still advertised `max` everywhere — `/effort` argsHint, slash-arg
picker, ModelPicker effort rows, /effort handler — even when the
active endpoint was a third-party host that can't accept it. Users
on those endpoints saw `max` in every suggestion and reported it as
a preset-era leftover (#1794).
Endpoint-aware filter: when `loop.client.baseUrl` is not api.deepseek.com,
drop `max` from the choices the TUI surfaces:
- `/effort` argsHint and argCompleter (autocomplete + arg picker)
- ModelPicker effort rows
- /effort handler's accept list + status / usage message
- new `effortUsageNoMax` i18n key (EN / zh-CN / de) so the error
on bad input doesn't itself name `max` as an option
`max` stays available on DeepSeek endpoints — that's the design from
#1657, just no longer visible where it would 400.
Fixes#1794.
Co-authored-by: reasonix <[email protected]>
- /language de: add 'de' to argCompleter and argsHint in commands.ts
- Capitalization: fix ~90 lowercase German sentence starts throughout de.ts
- Backfill: add ~95 new translations for CLI hints, slash command
descriptions, MCP marketplace text, and UI labels previously falling
back to English via ...EN spreads
- Native-speaker review: multiple rounds of corrections to word choice,
terminology consistency, and formatting
- Preserve T1anjiu's existing translations and the ...EN fallback pattern
Co-authored-by: hermitokatt <[email protected]>
Windows cmd.exe rings the system bell when stdout receives a bare BEL
byte (0x07). Third-party libraries (ansi-escapes, terminal-link, ink's
own deps) embed BEL as an OSC sequence terminator — perfectly valid VT
syntax that Windows Terminal, ConEmu, and every *nix terminal handle
silently — but cmd treats the unrecognized OSC start as junk and beeps
on the BEL byte. Visible on #1786 as the system bell ringing on every
assistant response chunk.
Patching every emitter individually doesn't scale (the constants are
scattered across several deps). Instead wrap process.stdout/stderr on
Windows and rewrite `\x07` → `\x1b\` at the boundary. ST and BEL are
both valid OSC terminators per VT 510, so legitimate OSC sequences keep
working (Windows Terminal / ConEmu / conhost-with-VT accept either);
stray BEL outside an OSC turns into ESC backslash which cmd treats as
junk text instead of a bell.
Installed via side-effect import at the very top of src/cli/index.ts,
after node-version-guard and heap-limit-launch (which may re-exec) so
the wrap is in the process that actually runs the CLI.
Fixes#1786.
Co-authored-by: reasonix <[email protected]>
* fix(ui): patch Ink to reduce terminal flicker on overflow frames
* fix: move patch-package to dependencies for global install
---------
Co-authored-by: Bernardxu123 <[email protected]>
When the assistant triggered a `run_command` shell confirmation in the
web dashboard, the tool card stayed on "running" indefinitely with no
Approve / Deny button. CLI and Tauri desktop worked fine.
Root cause: `modal-up` is broadcast at the moment the gate opens. If the
dashboard tab wasn't already connected to /api/events at that instant,
the event went out to zero subscribers and the dashboard never learned a
modal was up. The SSE handler already snapshotted `busy-change` for this
exact "client connects mid-state" reason; `getActiveModal` existed on
DashboardContext for the same purpose ("Snapshot of any modal currently
up (for SSE clients that connect mid-modal)") but was never wired into
the SSE stream.
Send the modal snapshot alongside `busy-change` on every new SSE
connection. Verified the new regression test fails on main (the read
times out at 5s — no modal-up ever arrives) and passes with the snapshot.
Fixes#1770.
Co-authored-by: reasonix <[email protected]>
Remove the duplicated Download item from the top nav while keeping the desktop download CTA, and add priority-based nav tiers so lower-value anchor links progressively disappear at narrower widths.
Tighten layout details across the landing page: prevent nav/version/language text wrapping, clean up hero metric alignment, and normalize spacing in feature cards, roadmap columns, and config bullet rows.
PR #1766 reshaped MemoryEntryInfo to include `kind`/`path`/`type` and
added a `memory_read` RPC for the detail view, but only wired the
Tauri-desktop emit path. The web dashboard still mapped the old
response shape via #1775's loader, so:
- frontend uses `m.path` as React key + onClick arg → undefined keys,
duplicate-key warnings
- clicking a memory row dispatches `memory_read` with undefined path →
bridge default case warns, nothing happens
Plug the gap:
- new GET /api/memory/entries → MemoryEntryInfo[] via the shared
collectMemoryEntriesForWorkspace, identical to desktop's $memory shape
- new GET /api/memory/read?path=... → MemoryEntryDetail via
readMemoryEntryDetail
- bridge: loadAndEmitMemory hits /memory/entries and emits entries
verbatim; new memory_read RPC handler fetches /memory/read and emits
$memory_detail
Co-authored-by: reasonix <[email protected]>
* fix(desktop): keep ctx resize handle off scrollbar
* feat(i18n): add German locale support
* feat(i18n): complete German translation for all three UI layers
Translate every untranslated key in src/i18n/de.ts (CLI/TUI),
dashboard/src/i18n/de.ts (web dashboard), and desktop/src/i18n/de.ts
(desktop app) — ~3,200 new lines of native German strings.
Covers all sections: common, cli/commands, ui, slash (all 42
commands), wizard, planFlow, errors, handlers, statusBar, editMode,
composer, path/shell/edit confirm, pickers, webErrors (all search
engines), marketplace, cards, labels, skills help, shortcuts, and
every other i18n namespace.
Terminology is consistent across all three layers. Translations
follow German typographic conventions (guillemets for quotation,
correct apostrophes, natural compound nouns).
writeConfig and rewriteSession used renameSync for the final atomic swap.
On Windows, when ~/.reasonix sits inside a OneDrive-managed folder or
crosses a junction / reparse-point boundary, rename refuses with EXDEV
(-4037) even though the tmp file and destination are siblings. The CLI
then crashed on every launch trying to mint the dashboard token (#1738).
Extract a shared atomicWriteSync helper that catches EXDEV from rename
and falls back to copyFileSync + unlink. Atomicity is lost on that path
(no other safe option on Windows), but a working write beats the
launch-blocking error.
Fixes#1738.
Co-authored-by: reasonix <[email protected]>
The CLI-hosted web dashboard's `serverInit()` only fetched settings,
sessions, and overview on mount — it never called `/api/mcp`,
`/api/skills`, or `/api/memory`. The reducer waits for `$mcp_specs`,
`$skills`, `$memory` events that the bridge had no path to emit, so
those three panels rendered empty and stayed empty until the user
triggered settings_save or restarted. Desktop (Tauri) shipped a
matching emit triple in desktop.ts on tab open — web mode regressed
on the equivalent.
Add three loaders that GET the REST endpoints and map their response
shape onto the dashboard event shape (`McpSpecInfo` / `SkillInfo` /
`MemoryEntryInfo`), fire them from `serverInit()`, and wire the
`mcp_specs_get` / `skills_get` / `memory_get` RPC commands so the
panels' refresh buttons also work. `mcp_specs_add` / `_remove` now
also re-emit the live list after the POST.
Fixes#1715.
Co-authored-by: reasonix <[email protected]>
clearLog() and switchWorkspace() left _steerQueue untouched. If the user
had typed a steer mid-turn in the prior session and the queue still held
text at the time of /new, the very next step() would pop it, wrap it in
the steer scaffolding, and ship it to DeepSeek as a user message — the
first prompt after /new would silently carry a fragment of the previous
conversation's intent.
Fixes#1707.
Co-authored-by: reasonix <[email protected]>
The scrollbar in the context panel was being overlapped by the resize
handle when the window was resized to trigger responsive breakpoints.
- Added padding-right: 20px to .ctx-body to create space for scrollbar
- Increased scrollbar width from 4px to 8px for better usability
Fixes#1695
Co-authored-by: Bernardxu123 <[email protected]>
Three hot-path fixes in the cards reducer measured to cut per-event
cost dramatically on long sessions:
- mutateCard now does a Map<CardId, number> lookup instead of a full
state.cards.findIndex scan. Each streaming/reasoning/tool chunk used
to walk the whole transcript; on a 2000-card session that cost
~12.7ms per 1000 chunks, now ~1.7ms (86% faster).
- plan.drop replaces a .map() containing a .slice(i+1).some() with a
single backward scan to find the last active plan, then one in-place
patch. 1000-card session: ~65ms -> ~0.34ms per drop (99.5% faster).
- elideOldCardContent now starts from a persistent elideCursor that
advances past stubbed and immutable-kind cards, so repeated appends
no longer re-scan all prior elision-zone cards. 500 appends on a
1000-card session: ~3.1ms -> ~1.6ms (48% faster).
The cardIndex map is mutated in place on append; structural changes
(session.fork, session.reset) rebuild it. tools/bench-reducer-hotpath.mjs
keeps the inlined old vs new comparison as a regression check.
All 3694 existing reducer / memory-budget / hydrate tests pass.
Co-authored-by: reasonix <[email protected]>
* feat(ui): configurable cost display currency with click-to-toggle
Add a costCurrency config option and a clickable status bar that
lets users toggle between USD and CNY display on the fly.
- costCurrency config field seeds the display preference on startup
- costDisplayCurrency state field drives reactive re-rendering
- mouse click on bottom status bar toggles USD/CNY instantly
- Wallet balance always stays in its own currency unaffected
- Module-level fallback ensures formatCost works without state
- All existing tests pass unchanged
* feat(ui): toast notification on cost-currency toggle
When clicking the status bar to swap display currency, a brief
toast confirms the change: 'Costs: $USD' or 'Costs: ¥CNY'.
* feat(ui): reactive UsageCard follows live cost currency toggle
* feat(ui): visual click hint on cost pill
Replace the generic '▸' arrow with '↻' (cycle arrow) on the
turn-cost pill to hint the display currency is clickable/togglable.
* style: trim comments to comply with comment policy
* refactor(ui): drop click-to-toggle, keep config-only cost currency
Per PR review feedback:
- Remove click-to-toggle interaction (hit-area too broad)
- Remove toast notification on toggle
- Remove module-level _defaultCostCurrency global (redundant with session state)
- Revert ↻ → ▸ glyph
- Keep costCurrency config field + costDisplayCurrency state plumbing
- Keep reactive UsageCard via useAgentState
- Keep precedence chain costDisplayCurrency ?? balanceCurrency in callers
---------
Co-authored-by: annon <[email protected]>
Session restore on a 1000-turn workspace was committing every card to
ink's <Static> in one synchronous render — measured 4.5s of frozen
terminal. The cards array can't shrink (Static is append-only by
design), but it can grow incrementally.
useProgressiveBacklog snapshots the initial cards.length on first
non-empty render, releases the first INITIAL_BATCH (30) immediately,
then drains the rest in PROGRESSIVE_BATCH-sized chunks via setImmediate.
Each batch yields back to the event loop between renders so keystroke
input stays responsive during the catch-up.
Cards added AFTER the snapshot bypass the gate — new live turns
(streaming responses, mid-turn tool output) appear instantly even when
the historical backlog is still draining.
Cards added DURING the drain (rare — user typing during restore) are
deferred until the snapshot drains. This trades a small UX hiccup
(brief delay before a new card appears) for Static's append-only
contract — out-of-order commits would re-render history in the wrong
chronological order.
Measured (probe-render-large-session.mts, heavy 1KB card bodies):
backlog | before | after | speedup
--------+-----------+-----------+--------
100 | 738 ms | 399 ms | 1.9x
250 | 1440 ms | 419 ms | 3.4x
500 | 2520 ms | 411 ms | 6.1x
1000 | 4520 ms | 429 ms | 10.5x
First paint is now ~constant regardless of backlog size. Total mount
time is unchanged (the rest still has to render), but the user sees
the most-recent context immediately and can type while the rest
catches up.
Tests cover three invariants:
- small backlog (<= INITIAL_BATCH) releases everything immediately
- large backlog releases initial batch first, drains the rest in
batches across setImmediate ticks
- chronological order is preserved across the drain (no card index
reorder when more batches release)
Co-authored-by: reasonix <[email protected]>
Add CLAUDE.md and .claude/CLAUDE.md to the project memory file search order (after REASONIX.md, before AGENTS.md) and read ~/.claude/CLAUDE.md as a global memory source alongside ~/.reasonix/REASONIX.md.
Changes:
- src/memory/project.ts: PROJECT_MEMORY_FILES now includes .claude/CLAUDE.md and CLAUDE.md
- src/memory/user.ts: add readGlobalClaudeMemory() and applyGlobalClaudeMemory() for ~/.claude/CLAUDE.md
- src/memory/user.ts: wire applyGlobalClaudeMemory into applyMemoryStack
- tests/project-memory.test.ts: add tests for CLAUDE.md priority and fallback
* feat: preserve full tool results when truncated (#1615)
When a tool result exceeds the per-call token cap, auto-save the full
content to .reasonix/truncated-results/ and embed the file path in the
truncation marker so the model can read_file the complete result.
Changes:
- src/tools/truncated-result-saver.ts — new file: save + cleanup + skip
- src/mcp/registry.ts — truncateForModel/truncateForModelByTokens gain
optional extraNote param appended to marker when truncated
- src/tools.ts — ToolDefinition.skipTruncationSave; dispatch save logic
- src/loop.ts — pass hookCwd as rootDir to dispatch
- src/tools/filesystem.ts — skipTruncationSave on read-only fs tools
- .gitignore — ignore .reasonix/truncated-results/
- tests/truncated-result-saver.test.ts — coverage for all paths
* fix: fix truncated-result-saver for CI + review — double .reasonix, Windows paths, comment policy, cleanup wiring, drop RFC doc
- Fix double .reasonix in fallback path (TRUNCATED_DIR had prefix, storageDir added it again)
- Normalize returned paths to forward slashes for cross-platform consistency
- Shrink multi-line block comments to one line (comment policy violation)
- Export storageDir for test consumption
- Align test file-creation patterns with project conventions (mkdtempSync, HOME redirect, top-level imports)
- Strengthen cleanupOldResults assertions to actually verify file removal
- Call cleanupOldResults(rootDir) at start of saveTruncatedResult so old files don't accumulate
- Drop .reasonix/rfc-1615.md — design docs don't belong in source tree
Windows hosts without Developer Mode (or non-elevated shells) can't
create symlinks via fs.symlinkSync — the call throws EPERM. The new
symlink-preservation test added in b40a569 didn't guard for this and
failed for any contributor running `npm test` on a default Windows
setup.
Match the pattern already used in tests/at-mentions.test.ts: probe
symlinkSync once, set symlinksWorked = false on throw, return early
so the test passes vacuously on hosts that lack the capability.
Co-authored-by: reasonix <[email protected]>
Extend src/cli/ui/render-trace.ts:
- readRenderTraceStats(): snapshot the counters directly instead of
scraping stderr. Lets probes report numbers in their own format and
decide when to read.
- resetRenderTraceStats(): clear between scenarios.
scripts/probe-render-large-session.mts runs two scenarios:
- (a) Mount of N cards via ink-testing-library — proxies session-restore
paint cost. Real Ink reconciliation + yoga layout.
- (b) K parent-state ticks via react-test-renderer (which fires effects;
ink-testing-library does not) — measures whether memo'd children
actually skip work when an unrelated parent state changes.
Numbers from this probe answer the App.tsx-split debate:
cards | (a) mount | per-card | (b) StaticCardStream re-renders / 200 ticks
------+------------+-----------+--------------------------------------------
100 | 738 ms | 7.38 ms | 1
250 | 1441 ms | 5.76 ms | 1
500 | 2521 ms | 5.04 ms | 1
1000 | 4517 ms | 4.52 ms | 1
Memo holds — parent re-rendering 200x cascades to ZERO StaticCardStream
re-renders. The "log append re-renders the whole App" hypothesis is
disproved. The real perceived cost is the ~5 ms/card initial-paint
hit on session restore (4.5 s freeze for a 1000-turn resume), which an
App.tsx structural split would not fix — that's a Static-priming /
progressive-render problem, not a memo problem.
react-test-renderer added to devDependencies for the probe (ink-testing-
library doesn't fire useEffect, so it can't be used to count renders).
Co-authored-by: reasonix <[email protected]>
Before further App.tsx-shaped optimization (the "split into InputArea /
MessageList / Sidebar" advice), wire in cheap measurement so we cut
where the cost actually is, not where intuition points.
src/cli/ui/render-trace.ts
- useRenderTrace(name): noop when the flag is off (hooks still called
unconditionally for rules-of-hooks compliance). When on, records
count + avg/max ms per name and prints a one-line summary per second
per traced component to stderr.
Wired into the four components most likely to dominate:
- AppInner — confirms whether App is actually re-rendering per keystroke
- ComposerArea — the input region; expected to re-render on every char
- StaticCardStream — the message list; should stay flat once history is
in <Static>
- LiveActivityArea — the activity row; expected to tick on busy state
Usage:
REASONIX_TRACE_RENDERS=1 reasonix code
# then type — see lines like:
# [render-trace] AppInner 42 renders · 7.0/s · avg 0.84ms · max 3.2ms
# [render-trace] ComposerArea 42 renders · 7.0/s · avg 0.43ms · max 1.8ms
The existing memo boundaries (ComposerArea, StaticCardStream,
LiveActivityArea, CardRenderer all React.memo'd) make the obvious
optimization moves already in place. This lets a future PR target the
component whose number is actually too high, rather than splitting
App.tsx on principle and hoping.
Co-authored-by: reasonix <[email protected]>
Five hot-path call sites had grown the same patterns inline — Map +
delete-on-hit + size-cap eviction (tokenizer BPE + content caches),
and `await import()` scattered through tool handler bodies. Collapse
into three primitives.
src/core/lru.ts
- LruCache<K,V>: insertion-ordered Map with promote-on-hit + oldest-out.
- TtlLruCache<K,V>: LruCache wrapping {value, expiresAt}; stale read
is a miss. One place owns the eviction rules.
src/core/lazy.ts
- lazy<T>(loader): memoize the loader's promise. First call starts the
work, every later call returns the same pending/resolved promise.
Failures stay sticky — the caller sees the same error on retry.
Call-site simplification
- src/tokenizer.ts — bpeCache + contentTokenCache: 14-line ad-hoc LRU
→ `cache.get/set`. Also exposes `warmupTokenizer()` so callers don't
have to know how to trigger the gunzip + Map build.
- src/gitignore.ts — adds 5s TTL cache around loadGitignoreAt /
loadGitignoreAtSync. Per-keystroke @-pickers walk every ancestor
.gitignore; cached lookups inside the same tick are now free.
- src/at-mentions.ts — listDirectory result cached with 5s TTL, 64-entry
cap. Same-tick keystroke bursts collapse to one readdir.
- src/tools/code-query.ts — `await import()` inside the fn bodies
replaced with module-level `lazy(() => import(...))` factories.
Lazy intent is declared at top of file; the handler body just awaits.
Sessions that never call code_query no longer pay the multi-MB
web-tree-sitter Emscripten runtime.
- src/code-query/grammar-map.ts (new) — extension→language detection
as pure data, no web-tree-sitter dependency. parser.ts re-exports for
back-compat.
- src/cli/ui/App.tsx — `setTimeout(warmupTokenizer, 0)` after first
paint, amortizing the ~100ms / 35MB cold load while the user reads
the banner.
Tests: tests/lru.test.ts (10 cases covering LRU promotion, eviction,
clear, TTL fresh/stale/refresh) and tests/lazy.test.ts (single-load,
identity, sticky rejection). All 3653 existing tests still pass.
Co-authored-by: reasonix <[email protected]>
* feat(acp): support REASONIX_ACP_SYSTEM_APPEND env var for system prompt injection
* fix(tui): show plan mode badge in input bar footer
The ModeStatusBar component was imported but never rendered after the
ComposerArea extraction (#565 Phase 2), making plan mode invisible to
users running editMode=yolo + plan=on.
Fix: render the plan mode indicator as a localized [PLAN]/[计划] badge
directly inside the input bar's footer, to the right of the mode label.
No extra row, no layout shift — uses the existing i18n key
statsPanel.modePlan for automatic Chinese/English display.
Closes#1502
---------
Co-authored-by: Bernardxu123 <[email protected]>
The Delete key was treated identically to Backspace (both deleted the
character before the cursor). Split the handling so Delete removes the
character at the cursor position (forward-delete) while Backspace
continues to remove the character before the cursor.
Fixes#1728
cli-highlight's tokenization ran on every CodeBlock render — multi-block
assistant replies were re-highlighting on every parent re-render
(slow-tick during streaming, theme change, terminal resize). Wrap the
highlight + entity decode in useMemo keyed on the token text and lang
so it only fires when the block content actually changes.
Settled cards already render via Static and skip re-render entirely;
this matters for the live streaming card where the parent re-renders
on every chunk while the code block content is stable.
Co-authored-by: reasonix <[email protected]>
Three changes that together cut per-turn CPU ~57% and steady-state RSS
~22% in the 200-turn fakeFetch probe (rss=256MB→181MB at log.len=800).
- bpeEncode: in-place splice instead of slice/spread rebuild on every
merge, plus 8K-entry LRU cache. Repetitive tool output (padded
payloads, identifiers in code) re-encodes the same byte-level chunks
thousands of times per session; the cache caps that at ~400KB.
- estimateConversationTokens: drop the full formatDeepSeekPrompt
rebuild + single bounded tokenize. Sum per-message bounded counts
with a fixed template overhead, gated by a content-string-keyed
4K-entry LRU. Same entry tokenizes once over its lifetime instead of
once per turn. The estimate drives fold thresholds (50%/75% of ctx)
where ±5% slop is harmless.
- truncateForModelByTokens: sample-based fast path. For inputs in the
[maxTokens, maxTokens*4] range the old code unconditionally tokenized
the full string (37% total CPU on the 200-turn probe). Now we use a
2KB-sample estimate with a 1.15x safety margin; only borderline cases
fall through to a precise tokenize.
Regression origin: #1642/#1646 collapsed the conditional preflight into
an unconditional estimateTurnStart that runs every turn, surfacing the
underlying tokenizer cost. The tokenizer itself has always been a
pure-TS BPE port without caching — fine when called rarely, expensive
when called on every turn against growing logs.
Also adds three probes that reproduce + measure:
- scripts/probe-mem-leak.mts — drives CacheFirstLoop through N turns
with fakeFetch, samples RSS/heap/log
- scripts/probe-jobs-leak.mts — confirms JobRegistry's MAX_COMPLETED_JOBS
cap actually evicts
- scripts/analyze-cpuprofile.mjs — flat self/total roll-up for any
.cpuprofile produced by --cpu-prof or `reasonix code --profile`
Co-authored-by: reasonix <[email protected]>
step() was a ~560-line method doing model streaming, repair, context
decisions, and tool dispatch in one body. Pull two independent pieces
into their own files so future edits to either don't risk the other.
- src/loop/streaming.ts — async generator that owns the chunk loop,
toolCallDelta buffering, and readiness counting. Caller uses yield*
to splice events and capture {content, reasoning, toolCalls, usage}.
- src/loop/dispatch.ts — chunked parallel dispatch with per-call
inflight tracking, tool_start/tool yields, and rate-limit warning.
Env reads (REASONIX_TOOL_DISPATCH, REASONIX_PARALLEL_MAX) move with
the dispatch logic.
loop.ts: 1174 -> 1022 lines. Public API of CacheFirstLoop unchanged.
Full test suite green (3625 / 12 skipped).
Co-authored-by: reasonix <[email protected]>
Floating right-edge dock that surfaces the last 10 user messages as
horizontal bars: hover to magnify + preview text, click to scroll the
thread to that turn. Bar widths step 32 / 20 / 14 / 12 px around the
hover point with staggered cubic-bezier transitions for the wave feel.
Adds data-turn on each user message in the thread so JumpBar can
querySelector the scroll target.
Thanks @CVEngineer66 for the original idea and the polished landing.
#1637 handled the canonical ESC [ M ... legacy mouse form, but Windows
ConPTY can strip the leading ESC, leaving a bare [M... that fell back to
the printable-text path. A burst of these (e.g. holding the mouse over
the terminal) would keep growing composer state — residual of #1598.
Add tryEscapelessLegacyMouse() parallel to the existing escapeless SGR
mouse path: recognize [M + 3 payload bytes as a fixed 5-byte packet,
consume it, surface no input event. Wire it into both the main parse
loop and the printable-run terminator so a stray [M mid-typing breaks
the run instead of swallowing the report into text.
Tests cover: single packet dropped, 1000-packet flood produces no
events, printable text either side of a report stays intact.
Trade-off: literal user input of "[M" followed by exactly 3 chars is
also swallowed — but [M is not a realistic typing pattern and the
flood-protection win is worth it.
Thanks @GTC2080 for tracking down the residual case.
applyEditBlock previously truncated the target file in-place before
writing the new bytes. A crash between truncate and writeAll could leave
the file empty, partially rewritten, or NUL-padded — high blast radius
since model-generated edits all flow through this path.
Switch to the standard atomic-replace pattern:
1. Resolve realpath so edits through a symlink modify the referent.
2. Write the new bytes to a sibling .tmp file with wx (exclusive create).
3. chmod to preserve the original mode under umask.
4. fsync the temp fd, close, then rename onto the target.
5. Best-effort fsync the parent directory.
6. On any error, unlink the temp file so we don't leak .tmp clutter.
Also fixes a latent short-write bug in the previous loop: `if (n <= 0)
break;` would silently truncate on a partial write. The new writeAllSync
throws instead.
One semantic change worth noting: atomic-rename breaks hardlinks. The
edited path now points at the new file while any other hardlink to the
old inode is left pointing at the pre-edit content. Industry-standard
tradeoff (same as the editor in your shell does), but a behavior change
versus the old in-place truncate.
New test covers the symlink-preservation case (edit through link →
link still exists → referent file has new content).
Thanks @YoungDan-hero for the careful patch.
Three stale-doc fixes:
- ARCHITECTURE.md §4.3 — replace removed /pro single-turn arming with the
current /model flash|pro + settings.json model selection. Note the
removal in 0.50.0 (#1657, #1630).
- ARCHITECTURE.md §4.4 — replace the never-existed FAILURE_ESCALATION_THRESHOLD
counter with the actual <<<NEEDS_PRO>>> model self-report mechanism. No
failure-counter; purely LLM-initiated, no-op on pro tier.
- benchmarks/real-world-cache/README.md — fix 10× pricing error in
v4-flash cache-hit ($0.028 → $0.0028) and entirely wrong v4-pro pricing
($0.139/1.667/3.333 → $0.003625/0.435/0.87). Recalculated cost tables;
headline 99.82% hit ratio unchanged, savings now correctly show ~97.7%
(flash) / ~98.9% (pro).
Thanks @FriendsHL for catching this — the benchmark pricing in particular
is the public cache-first defense link, the old numbers would have been
embarrassing.
.devenv/ and .direnv/ in Nix/devenv-based projects hold cargo registries,
uv caches, and Nix store symlinks — easily 1.5 GB and tens of thousands of
files. A bare glob("**/package.json") would stat every entry under those
trees before matching. Add them to DEFAULT_INDEX_EXCLUDES.dirs alongside
node_modules / .git / target / etc; include_deps:true still lets users
opt in.
Thanks @bluedevil947 for the patch.
On session resume, if a stored plan has every step completed, archive it
and skip restoration so users don't see a stale "resumed plan" card on
every open. Same archive-instead-of-persist behavior triggers mid-session
when the final step completes.
Thanks @paradoxSCH for the patch + tests.
Closes#1355
A user on a corporate intranet running a local model saw "DeepSeek 服务不可用 …
查看状态页 https://status.deepseek.com" after their local model returned a 500.
Three hardcoded assumptions stacked up: the client error prefix is always
"DeepSeek N:", is5xxError matched it regardless of provider, and the probe
hit /user/balance (a DS-only endpoint that 404s on ollama/vLLM/etc.), so the
unreachable branch fired and pointed users at DeepSeek's status page for an
outage that didn't exist.
Allow-list api.deepseek.com explicitly. For any other host, skip the
/user/balance probe and use provider-neutral wording that surfaces the
configured host instead of "DeepSeek".
Co-authored-by: reasonix <[email protected]>
* fix(api): self-heal stale model id in settings GET
#1663 added `loadModel()` which maps unsupported model ids (e.g. v3
`deepseek-chat` / `deepseek-reasoner` left over in a user's config)
to `DEFAULT_MODEL` when no custom endpoint is set. The CLI uses it,
but the dashboard/desktop `/settings` GET endpoint still returned the
raw `cfg.model`, so users upgrading from a pre-v4 config saw their
desktop landing on the stale id and the model picker rendering it as
"custom" — looks like the app forgot which model it's on.
Route the GET through `loadModel(ctx.configPath)` so the same
self-heal applies on the wire. Custom-baseUrl users still keep their
custom ids unchanged (`loadModel` trusts non-empty `baseUrl`).
* feat(plan): expose plan as a 4th editMode in API + desktop + dashboard UIs
#1681 wired `editMode === "plan"` into the ToolRegistry dispatch gate
so plan mode is now a persisted state, not a slash-only toggle. The
desktop and dashboard surfaces never grew a control to set it though —
the settings API + edit-mode API still rejected "plan" with a 400, the
composer's ModeSwitch hardcoded review/auto/yolo, and the settings
page tri-state only listed the same three. Net: plan mode was
reachable from the CLI's `/plan` slash and direct config edits, but
not from either GUI surface.
Admit "plan" in both validation sets (`src/server/api/settings.ts`,
`src/server/api/edit-mode.ts`) and the `/mode` slash completer
(`src/cli/ui/slash/commands.ts`). Add a "plan" entry to MODE_INFO in
both composers with `I.list` and a planHint string. Add "plan" to the
settings page button maps. Extend the local `EditMode` string unions
in `desktop/src/{protocol,App,ui/composer}.tsx` and the dashboard
equivalents so TS accepts it everywhere.
i18n: add `editMode.plan` + `editMode.planHint` (and `planDesc` on
desktop) in both en + zh-CN for each surface.
---------
Co-authored-by: reasonix <[email protected]>
Node 18+ refuses to execFile `npm.cmd` directly on Windows
(CVE-2024-27980 mitigation), throwing `spawnSync npm.cmd EINVAL`.
Failed every Windows CI matrix entry on main after 0.50.1.
`execSync` routes through cmd.exe / sh, matching what the original
inline `&&`-chained postinstall did before #1584's regression.
End-user installs of [email protected].1 are unaffected: postinstall
short-circuits via the `dashboard/package.json` existence check before
reaching the broken execFile call. Only repo checkouts at tag v0.50.1
hit the bug, which is dev-side only.
#1584 wired `npm --prefix dashboard ci && npm --prefix desktop ci` into
root `postinstall` to fix CI's missing workspace deps. But the
published tarball ships only build artifacts under `dashboard/`
(index.html, app.css, dist/) and no `desktop/` at all, so end-user
`npx [email protected].0 code` failed during the dashboard `npm ci` and
the bin never ran — the only visible output was npm's cleanup
warnings on the half-extracted tree.
Move the workspace install into `scripts/postinstall.mjs`, which
exits 0 when `dashboard/package.json` is absent (i.e. when running
from the tarball, not the repo). Ship the script via `files:`.
Deprecate 0.50.0 on npm so existing installers see the warning.
Dashboard smoke tests added in #1418 read `dashboard/dist/app.js` and
`app.css` at filesystem level. They pass under `npm run verify` (which
builds first) but fail under `npm publish`, whose `prepublishOnly` ran
in `lint → typecheck → test → build` order — tests fire before the
artifacts they need exist.
Reorder to `lint → typecheck → build → test` so the publish-time gate
matches the verify-time gate. Caught when the v0.50.0 publish-npm.yml
run failed before reaching `npm publish`.
Two bugs in the same `Cell` body (#1671):
- truncation used `raw.length > inner`, which undercounts wide chars —
a CJK row that was visually too wide for the column slipped past the
check and overflowed into the gutter
- padding used `padEnd(inner)`, which counts string length not cells —
short CJK content got padded as if each wide char were 1 cell, so the
background-color stripe ran past the column edge
Repo already has a cell-aware clipper (`clipToCells`) for the cut and
a private `padToCells` in `markdown.tsx` for the pad. Promote
`padToCells` to `text-width.ts` so SplitDiff can use both — collapses
the original four lines (slice + ternary + padEnd + ascii comment) to
a single `padToCells(clipToCells(raw, inner), inner)` and drops the
duplicate definition from `markdown.tsx`.
Supersedes #1683, which fixed the detection half but left the slice +
padEnd in place — for CJK content the truncated string ended up wider
than `inner` and short rows still over-padded.
Co-authored-by: reasonix <[email protected]>
Co-authored-by: Bernardxu123 <[email protected]>
#1661 fixed the lang-detection bug for desktop only. Dashboard's pre
handler has the same `c.type === "code"` check that fails when
react-markdown's component override replaces `code` — the element's
type is the override function, not the string "code". For dashboard
this didn't just mislabel the language; the fallback returned a vanilla
`<pre>` and skipped CodeBlock entirely, so syntax highlighting and the
copy button were missing for every fenced code block.
Extracted the lang lookup into `extractFencedLang` in both files so it
can be unit-tested without rendering CodeView (prism-react-renderer
pulls in each package's own React copy under vitest, which breaks
full-render tests across desktop/dashboard).
Co-authored-by: reasonix <[email protected]>
overflow-wrap is an inherited property; .msg-text already declares it,
so the duplicate declarations on .msg-text .markdown and .msg-text p
are noise. The combined `.msg-text X, .markdown X` selectors keep their
declarations because the standalone .markdown case (cards) has no
ancestor setting overflow-wrap.
Co-authored-by: reasonix <[email protected]>
Two related papercuts in the desktop client:
1. Esc during streaming with a modal (settings / about / jobs popover /
workdir popover) open used to fire `abort()` and leave the modal
sitting on screen. Now the global Esc handler bails out when any of
those flags is set; settings/about modals each install their own
`keydown` listener that calls `onClose()`. JobsPop and WorkdirPop
already had their own handlers, so this just rounds out the set.
2. Clicking (or Enter-ing) the already-active session in the sidebar
used to round-trip a session_load and clear live in-turn state
(issue #1653). Skip when `s.name === activeName`.
Co-authored-by: reasonix <[email protected]>
Co-authored-by: CVEngineer <[email protected]>
`ToolRegistry.setPlanMode(true)` (src/tools.ts:86) already blocks every
non-readonly tool at dispatch — but the only path that ever turned it
on was the `/plan` slash command. Persisted `editMode = "plan"` (set via
config edit or a settings UI that surfaces it) was previously inert:
the registry's `_planMode` stayed false across boots, so the model
could still call `write_file` etc.
Extend `EditMode` to include "plan", and have `buildCodeToolset` mirror
the loaded mode into the registry on construction. Desktop host calls
the new `applyPlanMode` helper in three places: on `emitSettings`, on
every `buildRuntimeFor`, and inside the `settings_save` handler when
the user toggles edit mode — so live changes take effect without a
rebuild. CLI's `/plan` slash continues to work as the direct toggle.
This is the minimal foundation needed before a settings UI in desktop
or dashboard can offer "plan" as a 4th edit-mode option.
Co-authored-by: reasonix <[email protected]>
Co-authored-by: T1anjiu <[email protected]>
#1667 added totalCompletionTokens to SessionMeta and wrote it after every
turn via patchSessionMeta, but the carryover plumbing in SessionStats
was incomplete:
- seedCarryover didn't read meta.totalCompletionTokens
- SessionStats had no _carryoverCompletion field
- the write call summed only this.turns (no carryover), and trimOldTurns
dropped completion tokens into the void
Net effect: on every resume, the first turn's patchSessionMeta call
overwrote the previously-saved totalCompletionTokens with just the new
turn's tally — counter reset to ~0 across restarts. (Cost / cache hit /
miss don't have this problem because they each have proper carryover
plumbing.)
Currently zero user-visible impact since no UI reads the field yet, but
the data was already flowing through UsageStats in both dashboard and
desktop, so the next surface that exposes it would inherit the bug.
Fix mirrors the cacheHit/Miss pattern: new _carryoverCompletion field
seeded from meta, a cumulativeCompletionTokens getter, trimOldTurns
folds completion tokens into carryover like the other counters, and
loop.ts switches the write to use the new getter.
Co-authored-by: reasonix <[email protected]>
#1666 renamed/dropped themes (tokyo-night → midnight, removed
default/github-dark/github-light, added deep-blue) but missed three
surfaces:
- `/theme` slash command's `argsHint` and `argCompleter` still advertised
the removed names and were missing `midnight` / `deep-blue`
- i18n `themeCaption` dicts in EN.ts and zh-CN.ts still held the removed
entries and had no labels for the new themes, so the picker would
render the literal i18n key (e.g. `wizard.themeCaption.midnight`)
next to the new theme names
Drop the stale entries from both locales, add captions for `midnight`
and `deep-blue`, and trim the slash command lists to the actual theme
set. The "default" caption is gone because the theme itself was removed.
Co-authored-by: reasonix <[email protected]>
- Simplify themes from 7 to 5 (dark, light, midnight, deep-blue, high-contrast)
- Add new deep-blue theme with #0153e5 brand color
- Rename tokyo-night to midnight (remove geographic name)
- Fix input text color to follow theme changes (add FG.body)
- Add history mode indicator (↑ history) when viewing past inputs
- Optimize bgInput color values for better contrast
Closes#1665
Co-authored-by: Bernardxu123 <[email protected]>
`loopEventToDashboard` was generating dashboard event ids as
`${assistantId}-${role}-${Date.now()}` for both tool_start and tool
events. Different role string and different timestamp → completely
different ids. The SSE bridge passes that id through as the segment
callId, and the dashboard reducer keys segments by it — so tool.result
never matched the segment created by tool.intent, segment.result
stayed undefined, and the card sat in `running` state forever
(its only "done" trigger is `result !== undefined`).
LoopEvent already carries a stable `callId` for this exact purpose
(see `src/loop/types.ts:40-41`: "UI uses this as the card id"). Use
it for both tool_start and tool so they share an id and the reducer
can pair them.
Regression-tested in `tests/loop-to-dashboard.test.ts`.
Co-authored-by: reasonix <[email protected]>
The composer's "N queued" label called `t("composer.queueCount", { n })`
but the i18n templates use `{count}` — variable mismatch left the
placeholder un-interpolated, so the UI rendered the literal string
`{count} 个排队` whenever a message was queued while busy.
Co-authored-by: reasonix <[email protected]>
The SSE bridge was reading the loop's `assistant_final` event as a
turn-end signal and synthesizing `$turn_complete`, but loop emits
`assistant_final` after EVERY model iteration — including mid-turn
iterations whose response carries tool_calls. So once the model said
"I'll run the test", busy flipped to false and the composer swapped
the stop button for send while npm test was still spawning.
The bridge also reset `sseTurnStarted` on that same event, which then
suppressed the real turn-end synthesis when `busy-change` (busy=false)
arrived later from the CLI's `handleSubmit` finally block. Drop both
the synthesized event and the flag reset; `busy-change` is the
authoritative turn-end signal and already drives `$turn_complete`
correctly via the case below it.
Co-authored-by: reasonix <[email protected]>
A stale `deepseek-chat` / `deepseek-reasoner` (or any other id no longer
accepted by api.deepseek.com) persisted in config.json bricked the next
launch with "Bad request (DeepSeek 400): supported API model names are
deepseek-v4-pro or deepseek-v4-flash, but you passed …". The picker
fallback list (used when the live catalog fetch fails) still surfaced
the v3 ids as selectable, so users could land there without ever
hand-editing config.
loadModel now keeps the persisted id only when (a) the user has a
custom baseUrl set — in which case we trust their model namespace —
or (b) the id is in the supported v4 allowlist. Otherwise it returns
DEFAULT_MODEL, and the next /model or picker write replaces the stale
config value.
Also drops the v3 ids from all six picker / settings fallback lists
(CLI, QQ, desktop composer + settings, dashboard composer + settings).
Co-authored-by: reasonix <[email protected]>
The "aborted at iter N" warning duplicated the synthetic assistant_final
that follows it; only the iter number was unique, and that's debug noise.
Removed the warning yield + the i18n string in both locales, and updated
the three loop tests that asserted on it.
Co-authored-by: reasonix <[email protected]>
When a user set a custom baseUrl + apiKey in config.json (e.g. routing
DeepSeek through new-api) but also had a stale env DEEPSEEK_API_KEY
left over from a default-endpoint setup, the resolver pulled baseUrl
from one source and apiKey from the other. The request hit the proxy
URL with the wrong token and the API returned auth errors with no
obvious cause.
Reported in #1631, root-caused but unfixed in #1577.
New loadEndpoint() resolves (baseUrl, apiKey) atomically: whichever
source defines baseUrl owns apiKey too. 12-factor env > config is
preserved for the default-endpoint apiKey case. New bridgeEndpointEnv()
mirrors the resolved tuple into process.env so subprocess constructions
and lazy DeepSeekClient instances see the matched pair. Every
DeepSeekClient construction site now passes both apiKey and baseUrl
explicitly via loadEndpoint().
Closes#1631
Presets bundled (model, reasoning_effort, thinking) under names like
flash/pro/auto. The bundling forced "max" as the cap and silently broke
OpenAI-compatible endpoints that only accept the standard literal set
(vLLM rejects "max" with a 400 — saw it in the wild against a
self-hosted DeepSeek-V4-Pro).
Direct controls instead:
- ReasoningEffort widens to low | medium | high | max
- Default cap is now "high" — the value every OpenAI-compatible
endpoint accepts; users opt into "max" knowing it's DeepSeek-only
- Dashboard + desktop settings: model picker + effort buttons,
both apply live through the existing settings bridge
- CLI: /model and /effort slash commands; ModelPicker shows EFFORT
and MODELS sections with full enumeration
- Config: preset field removed, model field persisted directly
Co-authored-by: reasonix <[email protected]>
Two small tidies left over from the edit-approval i18n PR:
- `entryStatusLabel(status)` was added to edit-history.ts but never
imported anywhere. The status-label i18n keys it wrapped are still
resolved inline by useEditHistory.ts (the only real consumer), so
the helper is pure dead code. Drop it, drop the now-unused `t`
import.
- `const status = t("app.editHistoryStatusApplied")` in useCodeMode's
discard path was unused. Even if it had been used, "applied" is
semantically wrong inside discard — the surrounding tail is built
from `discardedCount` and `nothingWritten` already.
Co-authored-by: reasonix <[email protected]>
Add a LIGHT_THEME (GitHub-style palette) alongside the existing
DARK_THEME and a usePrismTheme() hook that watches `<html data-theme>`
via MutationObserver, so code blocks switch highlight colors when the
app theme toggles. Without this, light mode rendered code in pale
dark-mode greys that were nearly invisible on the white background.
The MutationObserver only fires on data-theme changes (attributeFilter)
and skips no-op state writes via a prevRef, so the cost per toggle is a
single re-render.
Dashboard has the same hardcoded theme bug (dashboard/src/CodeView.tsx)
— good follow-up candidate.
Follow-up to #1650. Completes the system-event surfacing work:
1. Desktop bridge — the kernel WarningEvent (added in #1650) already
flowed through eventize → desktop sidecar → webview as a Tauri
event, but desktop's protocol type and App reducer didn't know
about it. Add WarningEvent to desktop/src/protocol.ts (matches
dashboard shape), grow ChatMessage with a "warning" kind, reducer
gated on severity === "high", thread renderer adds the
.sys-event-row inline divider (same styling as dashboard).
2. Settings toggle — new config field thread.showSystemEvents
(default true) with load/saveShowSystemEvents helpers in
src/config.ts. Desktop sidecar pushes it in $settings and handles
it in settings_save. Both SPAs grow Settings/SettingsEvent/
SettingsPatch, reducer stores it, warning render gates on
settings.showSystemEvents !== false. Settings panel adds a
seg-ctrl row in the Behavior section, en + zh-CN strings.
Default remains "shown" — severity filter (high-only) already caps
visible events to ~1-3 per session, so this is a preference, not a
noise mitigation.
Follow-up to #1585. The responsive sidebar logic was split across six
refs (autoSideCollapsedRef / autoCtxCollapsedRef / suppressSide... /
suppressCtx... / sideCollapsedRef / ctxCollapsedRef) and a 70-line
useEffect that did everything inline. Each panel's "is this collapsed
because the user asked, or because the layout forced it" state was
encoded across two of those refs; the resize logic had to spell out
all 6 stage-transition combinations by hand.
Extracted the per-panel collapse into useAutoCollapse(persistKey):
- collapsed: the boolean for CSS
- toggle: user-driven flip; persists to localStorage
- requireCollapsed: layout asks for collapsed — claims as auto if
the panel wasn't already collapsed
- releaseCollapsed: layout asks for expanded — restores only if WE
collapsed it (manual collapses stay)
The resize effect drops to one branch per stage:
WIDE → release both
COMPACT → require ctx (only when entering from wider — coming from
narrow we preserve a user's manual ctx-open); release side
NARROW → require both
Also: fixed the one-line CSS indent slip on .app[data-side-collapsed].
Behavior is unchanged — same five stage-transition outcomes that #1585
hand-coded, just expressed declaratively.
Co-authored-by: reasonix <[email protected]>
Layer 1 follow-up to #1649 (CompactionCard). Before this, every loop
warning fell through eventize.classifyWarning's default branch and
became an "error" event — Dashboard rendered compaction notices and
storm-stuck interrupts as alarming red error cards. Chatty warnings
(per-iter repeat-tool nudges, storm-suppressed counters) flooded the
thread.
- Add EventSeverity ("low" | "high") to LoopEvent. Tag the two known
chatty sites in loop.ts (repeatToolCallWarning, stormSuppressed
counter) as "low"; everything else is "high" by default — safer for
new emit sites added later.
- Add a typed WarningEvent to the kernel + dashboard protocol.
Eventize.classifyWarning now: drops low-severity entirely, emits a
proper warning event (not an error) for high-severity. Existing
policy.escalated / policy.budget classification still wins for those
patterns.
- Dashboard SPA: add warning kind to ChatMessage, reducer case in
applyIncoming (filters anything not "high"), render as a quiet
inline divider (.sys-event-row) — single line, dim, ~0.7 opacity,
flanked by hairline rules. Visually weak so several can stack
through a long session without crowding the conversation.
Tests: low-severity warnings dropped, high-severity emit typed warning
(not error), unmarked warnings default to high.
Follow-ups not in this PR:
- Desktop bridge equivalent (Tauri IPC + Tauri-side event types).
- Settings toggle to fully hide system events for users who want a
cleaner thread.
Co-authored-by: reasonix <[email protected]>
* chore(desktop): tidy follow-ups from #1645
Three small cleanups landed alongside the desktop UX bundle:
- composer: extract `recordSendAndReset` so the history-push + browse-
index reset logic is one helper, not duplicated between the Enter key
path and the send-button onClick.
- composer: drop the duplicate IME-quirk comment at the use site; the
ref declaration block at the top of the component already documents
the macOS Chinese IME ordering quirk.
- App: hoist the inline `onEdit` arrow into a useCallback so UserMsg's
memo isn't busted by a fresh function identity on every render of the
message list.
* test(server-dashboard): isolate from real \$HOME/.reasonix
The v0.13 panels suite uses mkdtempSync for cfgPath and usagePath but
the handlers it exercises (/api/health, listSessions) still call
homedir() under the hood. On a dev machine with thousands of session
jsonl files in ~/.reasonix/sessions the readdir + per-file statSync
walk blows past the 5 s default test timeout, even though the same
test runs in ms on a clean CI box.
Redirect HOME and USERPROFILE inside the suite's beforeEach so the
walks land in the suite's already-empty temp dir, and restore the
originals in afterEach. No production-code change — the handlers'
homedir() coupling is a separate cleanup.
Whole file now runs in 1.7 s.
---------
Co-authored-by: reasonix <[email protected]>
* feat(desktop): copy/edit overlay, msg history nav, IME guard, card collapse
* fix(desktop): guard history nav behind cursor position; keep reasoning open while streaming
---------
Co-authored-by: wufengfan <[email protected]>
After auto-compaction, the synthesized recap was being stored as a
plain assistant message with a HISTORY_FOLD_MARKER prefix. None of the
three surfaces special-cased it — TUI hydrated it as a regular streaming
card on resume; Desktop and Dashboard rendered it inline through
AssistantText. Users had no way to tell compaction had happened or
distinguish the recap from a real model reply.
- Single-source the marker + helpers in @reasonix/core-utils/compaction
(COMPACTION_SUMMARY_MARKER, isCompactionSummary, stripCompactionMarker).
Re-export the constant from src/context-manager.ts so existing
HISTORY_FOLD_MARKER imports keep resolving.
- TUI: new kind: "compaction" in state/cards.ts, renderer in
cards/CompactionCard.tsx, hydrate.ts emits it instead of a streaming
card when the marker is present.
- Desktop / Dashboard: CompactionCard component in ui/cards.tsx,
intercepted in the assistant-segment renderer in ui/thread.tsx.
Default-collapsed, archive icon, header shows char count, body renders
the recap markdown.
- Wire vite + tsconfig aliases for the sub-import path so browser bundles
don't pull in Node-only siblings (tildeify) via the barrel.
Tests: marker detection edge cases in core-utils, hydrate emits
compaction card for the marker, full verify (262 files / 3595 tests).
Follow-up: surface the loop "warning" event ("folded N messages → M")
as a visible row on Desktop / Dashboard (currently flows through
protocol, no ChatMessage reducer).
Route multi_edit through the same review gate that edit_file and
write_file already use, so the model can't mutate files in review mode
without surfacing pending edits to the user. Extract the gate logic from
App.tsx into edit-tool-gate.ts (pure, unit-tested) and add
setEditModeLive that updates the ref, React state, and disk in one
atomic callback — fixes the stale-ref window where an in-flight tool
call could see the old mode immediately after the user toggled it.
Closes#1639
Follow-up to #1642. After landing the fold-first preflight, the next
question was whether preflight needs to exist at all — and on a 1M-context
provider it doesn't: post-response decideAfterUsage already folds at
75%, upstream tool-result caps prevent single-message blowups, and the
byte ceiling the preflight was originally guarding against is gone.
Converge on the Claude-Code-style single compaction path: one fold check
per turn, at turn start.
- Delete decidePreflight, mechanicalTruncate, related constants, the
PreflightDecision interface, and the per-iter preflight block in step().
- Add a single turn-start check after the user message is appended:
if local request estimate > TURN_START_FOLD_THRESHOLD (90%), fold once
before the iter loop.
- No mechanical fallback. If fold can't shrink the log, the request goes
out and DeepSeek's error surfaces to the user — honest beats silent
re-compaction with worse semantics.
- Drop preflight i18n keys + delete tests/preflight.test.ts.
Net -393 lines. E2E (live DeepSeek) green across baseline, high-ratio
terminal turn, and turn-start fold scenarios.
Show the full tracked path for files in the desktop context panel, plus
per-file open/copy actions. Open honors `settings.editor` when set, else
falls back to the system default opener. Add an in-window completion
toast when a long task (>= COMPLETION_NOTIFY_MIN_MS) finishes while the
window is focused; unfocused windows continue to use the existing native
desktop notification path.
Closes#1638
The right-side context meter summed cacheHitTokens and cacheMissTokens,
which are session-wide running totals. After ~20 cached turns of a
50k-token context, the cumulative cacheHit alone reaches 1M+ and the
panel renders "1,500,000 / 1,000,000" with the bar pegged at 100%.
What the meter is supposed to show is the *current* context size — i.e.
prompt_tokens of the most recent API call. That value is already
captured per-turn as lastCallCacheHit / lastCallCacheMiss; switch the
meter to use those. Cumulative totals are still used elsewhere (status
bar / settings) for the cache-hit-rate display, where summing is the
right semantic.
Also mirror the reset into lastCall* on the $ctx_breakdown event so
/compact takes effect immediately instead of waiting for the next
model.final to overwrite a stale pre-compact value.
Co-authored-by: reasonix <[email protected]>
Live probe shows DeepSeek's gateway accepts at least 8MB request bodies —
the empirical ~880KB ceiling MAX_BODY_BYTES guarded against no longer
exists. Remove the byte path from decidePreflight + mechanicalTruncate
and converge on a single fold-first pipeline: preflight tries semantic
fold first, mechanical truncate is last-resort only when fold cannot
summarize.
fold() per-message token estimate now counts tool_calls JSON so heavy
args can't slip past the tail-budget check. New requireTailBoundary
option (preflight-only) prevents fold from wiping an active tool turn.
Preflight sets _foldedThisTurn to block decideAfterUsage from re-folding.
Disable font ligatures and contextual alternates for markdown code blocks
in both dashboard and desktop, so operator sequences like `->` `=>` `!=`
render as separate glyphs instead of shaped ligatures.
Closes#1636
Right-clicking in the WebView2 surface showed the browser's default
menu, where "Reload" wipes the in-memory session and leaves a blank
white screen. Block the contextmenu event at app startup. F5/Ctrl+R
are already trapped earlier in the same file.
Co-authored-by: reasonix <[email protected]>
* feat(subagents): per-skill flash/pro override + Settings UI
Subagent skills (`/explore`, `/research`, `/review`, `/security-review`
out of the box, plus any user-authored `runAs: subagent` skill) had only
one knob for picking the spawn model: a `model:` line in the .md
frontmatter. That meant users couldn't tune the four built-ins without
shadowing them by copying the bodies into a custom file, and the desktop
/ web settings had no surface for it at all.
Adds a per-skill `flash | pro` selector:
- `config.json` gets `subagentModels?: Record<skillName, "flash" | "pro">`
with `load`/`save` helpers that filter to valid values
- `SkillStore` accepts `subagentModels` in its constructor and applies
the override only to `runAs: subagent` entries (inline skills with
the same name are untouched, frontmatter `model:` is overridden
when an entry exists)
- `registerSkillTools` plumbs it through; `buildCodeToolset` reads
`loadSubagentModels()` so the runtime path picks up the live value
- desktop `settings_save` accepts the field, persists via
`saveSubagentModels`, re-emits the skill list so the UI's
inline-rendered model badge stays in sync
- dashboard `POST /api/settings` validates the same shape, GET surfaces
the current map, `appliesAt.subagentModels` = "next-skill-run"
- both desktop and dashboard Settings → Skills page render a
`<select flash | pro>` per subagent skill — inline skills get no
selector
`flash`/`pro` map to `deepseek-v4-flash`/`deepseek-v4-pro` inside
`SkillStore` so the config stays human-readable across model id swaps.
Tests:
- config: round-trip, filter unknown values, clear-all removes field
- SkillStore: override applies to builtins, doesn't touch inline `test`,
override beats frontmatter `model:` when both set, frontmatter still
wins absent override
* fix(settings): reject prototype-pollution keys in subagentModels POST
CodeQL js/remote-property-injection — `__proto__` / `constructor` /
`prototype` in a POST /api/settings body would land as own properties
on the sanitized map and persist into config.json.
* fix(settings): null-prototype map for CodeQL sanitizer recognition
The previous fix's explicit string blocklist wasn't recognized by
CodeQL's js/remote-property-injection rule as a barrier. Object.create(null)
is the canonical sanitizer — keeps the explicit blocklist so dangerous
keys still get dropped before persistence.
* fix(settings): use Map+Object.fromEntries for CodeQL sanitizer
CodeQL js/remote-property-injection didn't accept the explicit blocklist
or Object.create(null) as a barrier. Map.set bypasses the writeAccess
sink CodeQL tracks, and Object.fromEntries constructs via
[[CreateDataProperty]] which the rule trusts.
---------
Co-authored-by: reasonix <[email protected]>
Per-turn stats array grows indefinitely — iterated on every
summary() call. Over long sessions this causes both memory growth
and O(n) cost on each summary.
Add MAX_TURNS=200 cap: when the array exceeds this, oldest turns
are dropped and their costs/cache tokens folded into carryover
fields. Session totals remain accurate (totalCost, cacheHitRatio)
while the array stays bounded.
The cap is generous — 200 turns covers a full day of active use.
The carryover aggregation means resuming a session after trim still
reports correct cumulative totals.
Co-authored-by: Bernardxu123 <[email protected]>
Auto-escalation (flash → pro via the `<<<NEEDS_PRO>>>` marker) and the
one-shot `/pro` arming were both surfaces that could spend money behind
the user's back: a turn that ran on flash could silently re-bill on pro,
and `/pro` plus an idle session compounded the same risk. Both are gone.
PresetName is now exactly `"flash" | "pro"`. Old configs holding
`auto` / `smart` / `fast` / `max` keep loading: `loadPreset` and the
loose-input `resolvePreset` / `canonicalPresetName` silently coerce
anything that isn't `flash`/`pro` to `flash`. No legacy migration
notice — the user just gets the new safe default.
Surface dropped:
- `CacheFirstLoopOptions.autoEscalate`, `loop.autoEscalate`, the
streaming-time NEEDS_PRO buffer/flush, the post-call NEEDS_PRO retry,
`src/loop/escalation.ts`, the `loop.flashEscalation` i18n string.
- `loop.armProForNextTurn`, `loop.disarmPro`, `loop.proArmed`,
`loop.escalatedThisTurn`, `loop.currentCallModel`, the `_escalateThisTurn`
/ `_proArmedForNextTurn` state, the `loop.proArmed` warning yield.
- `/pro` slash command + handler + i18n.
- Dashboard `proNext` field on `POST /api/settings` + ctx.setProNextLive
+ the proNext / proArm / proArmed / proNextNote i18n bundle.
- StatsPanel's pro pill (escalated / proArmed props + rendering).
- ModelPicker's `currentAutoEscalate` prop and detect.
- usePresetMode's proArmed / turnOnPro state.
- ResolvedDefaults.autoEscalate, handleWarningEvent's setTurnOnPro hook,
AppProps.autoEscalate / ChatOptions.autoEscalate.
- "auto" preset card in both desktop and dashboard Settings → Models.
Tests updated:
- tests/presets.test.ts: legacy + unknown values coerce to flash.
- tests/resolve.test.ts: legacy auto/smart/fast/max coerce silently.
- tests/slash.test.ts: `/preset auto` returns usage; `/preset flash` /
`/preset pro` keep working; arg-picker enum is `["flash", "pro"]`.
- tests/loop.test.ts: NEEDS_PRO describe block and the proArm/disarm
tests are gone with the features.
- tests/server-dashboard.test.ts: proNext field is gone from the live
callback test.
- tests/preset-effort-isolation.test.ts: only flash/pro iterated.
- tests/ui-slash-suggestions.test.tsx: advanced-group count 11 → 10.
Verify: tsc clean (root + dashboard), biome clean (only pre-existing
welcome-banner warning), 3576 tests pass.
Net -669 lines.
Co-authored-by: reasonix <[email protected]>
iTerm2 light theme + reasonix theme `github-light` still rendered the
composer dock as a black band (#1607). The composer and the user-message
card both hardcoded `#1e1e1e` for their bg and `#0153e5` for the brand
accent — the proxy-tokens system (`SURFACE.bgInput`, `TONE.brand`) was
bypassed entirely, so theme switches did nothing to either surface.
What looked in the screenshots like "the status bar is also black" is
actually `PromptInput`'s inline mode/model row, which lives *inside* the
dark Box. The real `<StatusRow>` rendered below it with no bg and stayed
themed correctly all along.
Replaces four hardcoded literals with their theme tokens:
- composer left accent stripe #0153e5 → TONE.brand
- composer body bg #1e1e1e → SURFACE.bgInput
- composer inline mode label color #0153e5 → TONE.brand
- user message card bg #1e1e1e → SURFACE.bgInput
All six themes already define matching `bgInput` values, so dark themes
get the same near-black they had before and light themes (`light`,
`github-light`) get the near-white they were missing.
EditConfirm + SplitDiff still tint diff lines with hardcoded dark
red/green and will need new `diffAddedBg`/`diffRemovedBg` tokens for
light-theme parity — separate PR.
Closes#1607
Co-authored-by: reasonix <[email protected]>
- Auto-evict oldest completed jobs when count exceeds MAX_COMPLETED_JOBS (20)
- Cleanup runs on job completion (settleClosed) and list() calls
- No time throttle — gate on count only, O(jobs.size) is trivial at N=20
- Initialize lastCleanupAt to 0 so first call always runs (fixes dead zone)
Fixes#1571 (JobRegistry portion)
Co-authored-by: CI Fix <[email protected]>
The dashboard's <select> for switching web search backends shipped in
#1558 against the old Preact panel; the React port (#1418) dropped it
silently and the i18n strings have been dead code since. The desktop
settings panel never had it. Both surfaces now expose the same dropdown
under General → Behavior, alongside reasoning effort / edit mode /
budget — six engines (bing, searxng, metaso, tavily, perplexity, exa)
matching the `/search-engine` slash.
- protocol: `webSearchEngine` on SettingsEvent + SettingsPatch in both
desktop and dashboard mirrors
- backend: `src/cli/commands/desktop.ts` settings_save persists the
field via writeConfig; emitSettings reads it back via webSearchEngine()
- dashboard bridge: emitServerSettings forwards the field from
`GET /api/settings` (server side was already wired by #1558)
- desktop i18n: copies the six already-translated strings that were
living only in the dashboard bundle
API keys for metaso / tavily / perplexity / exa still go through the
slash command (or config.json) — UI-side key entry can come later if
demand shows up.
Co-authored-by: reasonix <[email protected]>
Place `node` next to a `com.apple.security.inherit` entitlement so the
child Node process inherits the .app's Documents / Desktop / Downloads
TCC grants instead of re-prompting on every spawn.
- entitlements/main.plist applied via bundle.macOS.entitlements; Tauri's
--deep codesign propagates inherit to Contents/Resources/node when
Developer ID is configured
- bundle-node.mjs adds an ad-hoc codesign with the helper plist so the
inherit entitlement still attaches on unsigned local / CI builds where
--deep never runs
Closes#1611
Co-authored-by: reasonix <[email protected]>
* feat(config): add dashboard.enabled setting to suppress auto-start
Add a `dashboard.enabled` boolean config field (default true) so users
can permanently disable the embedded dashboard without passing
--no-dashboard on every launch. The CLI flag still overrides the config
(--no-dashboard wins over enabled: true).
* test(config): cover loadDashboardEnabled defaults, explicit values, and noConfig
* fix(desktop): prevent stale events from corrupting UI after session switch (#1217)
When a session switch happens while a turn is running, the old turn's
cleanup code may still emit events (, , etc.)
that arrive after the new session is active, causing UI lag and state
corruption.
Add a switching flag to the Tab interface:
- Set tab.switching = true before aborting in session_load/new_chat
- In runTurn's finally block, check tab.switching to suppress stale events
- Reset tab.switching = false after processing
This prevents the old turn from emitting events that would interfere
with the new session's state.
Fixes#1217
* fix(desktop): only set switching flag when aborter is live (#1217)
The previous implementation set tab.switching=true unconditionally in
session_load/new_chat handlers. When no turn was in flight (the common
case), the flag stayed true and suppressed events for the first turn
in the new session.
Fix: only set switching=true when tab.aborter exists (live turn).
---------
Co-authored-by: CI Fix <[email protected]>
codeCommand was directly reading readConfig().mcp which only handles
the legacy string array format. When users configured mcpServers
(the object format) without the mcp array, MCP servers would not start.
Fixed by using normalizeMcpConfig() which processes both mcp and
mcpServers formats, then converts back to string array via specToRaw().
Fixes#1568
Co-authored-by: CI Fix <[email protected]>
* fix(dashboard): scope session list to current workspace + fix new-chat flow
Two related sidebar bugs:
1. The session list was unfiltered — users with thousands of subagent
transcripts (`subagent-sub-*.jsonl`) and cross-workspace sessions
in `~/.reasonix/sessions/` saw 10 000+ entries. The CLI's session
picker already uses `listSessionsForWorkspace(currentRootDir)`;
the dashboard's GET /api/sessions handler now does the same when
`ctx.getCurrentCwd()` is wired. Also surface `meta.summary` in the
listing so the bridge stops falling back to bare session names.
2. Clicking "new chat" pushed an error card into the transcript via
`$session_empty` ("loaded with no messages") and never updated
state.currentSession, which left #1586's URL mirror pointing at
the old session. The new endpoint echoes the freshly-minted
session name, and the bridge fires a real `$session_loaded` with
empty messages so the reducer resets cleanly and the URL flips.
Sessions-ops test grows by two cases covering each behaviour.
* feat(dashboard): cross-session stability, persistent URL, polish pass
Squash-merges a chain of fixes prompted by post-#1418 user feedback on
the live web dashboard. The unifying themes: nothing should change
when you don't expect it to (token, port, URL, SSE stream), and
everything should give visible feedback when you do change it.
Server
- POST /api/sessions/new now echoes the new session name so the bridge
can update state.currentSession without diffing the list.
- parseTranscript surfaces reasoning_content, tool_calls, and tool
results (by tool_call_id) so historical replays show what the model
actually did, not just the raw text turns.
- serveAsset injects ?token=... into CSS url() font references in
addition to the existing JS-import rewrite — the previous gap 401'd
every Geist / KaTeX font fetch.
- New /api/browse?path= lists immediate subdirectories (Windows drive
letters included on first call) so the web runtime can ship a real
directory picker.
- startDashboardServer exposes updateContext(ctx) — the handle now
outlives a chat.tsx-driven App remount, and the new App rewires its
loop/refs in place instead of forcing a port rebind that the OS
hadn't released yet (EADDRINUSE -> ephemeral fallback -> new URL).
- Dashboard token + actual bound port are persisted to config.json on
first run via ensureDashboardToken / saveDashboardPort, with an
EADDRINUSE fallback to ephemeral. /dashboard reset-token rotates
the token and restarts the server.
CLI
- listSessions workspace filter now reaches the dashboard's GET
/api/sessions, cutting sidebar entries from "every subagent
transcript on disk" (10 000+ for active users) down to the current
workspace's chats.
- getDashboardUrl appends &session=<name> so the printed URL points
at the attached session and survives copy/paste.
Dashboard UI
- Persistent module-level dashboardHandle + eventSubscribers Set so
React App remounts (session swap) don't tear the server down and
don't drop SSE subscribers on the floor — fixed the "send a message
after switching, web stays silent" desync.
- session_load bridge handler emits $session_loaded with the new
name and full segments (text + reasoning + tool calls stitched to
results), instead of pushing an error card via $session_empty.
- Thread renders use index-based React keys for AssistantMsg —
replayed transcripts arrive with turn=0 for every assistant row,
so the turn-keyed list was collapsing every assistant message into
one stale slot on every session switch.
- Sidebar gets a per-row loading spinner; thread shows a centered
overlay during the swap so big sessions don't look dead.
- CSS containment on .session-item, .msg, and .thread; dropped a
needless backdrop-filter on the loading overlay. Together these cut
the Paint/Layout/pointerover budget noticeably on long transcripts.
- New WorkdirInputModal backed by /api/browse — the web build
previously stub'd openDialog to "" so clicking Browse did nothing.
- Removed the "+ new tab" affordance from the tab bar (web has no
multi-tab story).
- URL session mirror from #1586 reverted to read-on-mount only so
clicking a session doesn't churn the address bar.
i18n
- statusbar.themeStyle{Graphite,Sandstone,Porcelain,Midnight}
- settings.themeStyle* + Desc, settings.page* Label + Desc for all 8
pages, sidebarPanel.loading, workdir.{cancel,go,goTip,loading,
emptyDir,openHere,pathPlaceholder}, handlers.dashboard.tokenReset*
(en and zh-CN where relevant).
Tests
- tests/dashboard-token-persistence.test.ts (9 cases) for
ensureDashboardToken / saveDashboardPort / clearDashboardToken.
- dashboard-sessions-ops gains coverage for the workspace filter
and the new POST /sessions/new name echo.
- dashboard-smoke verifies CSS font url() token injection in
addition to the existing JS chunk-import rewrite.
---------
Co-authored-by: reasonix <[email protected]>
After #1586 the browser URL stays in sync with the active session,
but the URL the CLI prints on startup and via /dashboard still only
carried `?token=`. Copying it never restored the right session.
Append `&session=<name>` in `getDashboardUrl()` and use it for the
auto-start log line and openUrl call too, so the URL you see, copy,
or click always points back at the session the CLI is attached to.
Co-authored-by: reasonix <[email protected]>
Builds went from a 943 KB monolithic `app.js` to a 224 KB entry plus
five lazy-cacheable vendor chunks (react, markdown, katex, prism,
icons). Total bytes are unchanged but the browser can fetch chunks
in parallel and reuse them across deploys when only app code moves.
Browsers strip query strings when resolving relative ESM imports, so
chunk-to-chunk references like `from "./vendor-react.js"` would 401
against the token-gated /assets/* route. `serveAsset` now rewrites
every relative `.js` import to carry the live token before sending
the body — same shape as the existing index.html templating, just
applied to JS bodies.
Before: app.js 942.61 kB │ gzip: 292.58 kB
After: app.js 223.76 kB │ gzip: 74.75 kB
vendor-react.js 192.84 kB │ gzip: 60.17 kB
vendor-katex.js 258.26 kB │ gzip: 77.53 kB
vendor-markdown.js 171.91 kB │ gzip: 52.18 kB
vendor-prism.js 86.04 kB │ gzip: 26.77 kB
vendor-icons.js 8.07 kB │ gzip: 1.98 kB
Co-authored-by: reasonix <[email protected]>
Until now the dashboard URL only carried the auth token, so a copied
link always landed on whichever session the CLI happened to be
attached to — refreshing a tab or pasting the URL elsewhere never
restored the session the user was actually viewing.
Mirror state.currentSession to a `?session=NAME` query param via
`history.replaceState` (no back-button noise) and, on the active
tab's first ready+sessions tick, read the same param back and
auto-dispatch session_load if the named session exists. Unknown
session names clear the param instead of erroring.
Both effects are gated on the tab being active, so multi-tab tabs
don't fight over the URL.
Co-authored-by: reasonix <[email protected]>
CI's `npm ci` at the root only triggers `npm --prefix dashboard ci`,
leaving `desktop/node_modules` empty. Vitest scans `desktop/src/**`
for tests, so the first desktop test that imports a transitive dep
(e.g. `react-markdown` via `Markdown.tsx`) fails to resolve in CI
even though it passes locally for anyone who's ever run
`npm install` inside `desktop/`.
Unblocks #1562.
Co-authored-by: reasonix <[email protected]>
* feat: port desktop dashboard from Tauri+Preact to CLI-hosted React Web app
Migrate the desktop Tauri + React UI to a CLI-hosted Web dashboard,
replacing the legacy Preact UI and laying groundwork for mobile compatibility.
- Independent Vite + React 19 dashboard build chain (dashboard/)
- Mock/Server dual-mode bridge layer (tauri-bridge.ts)
- REST API routing alignment (sessions, settings, submit, abort)
- editMode support (review/auto/yolo) with runtime setEditMode
- User message deduplication in busy state (App.tsx:546-549)
- assistant_final event carries usage + costUsd fields
- Binary asset serving fix (woff/woff2/ttf/png as Buffer, not UTF-8)
- Smoke tests (10 cases) + editMode regression tests
- Build chain: npm run build now runs dashboard build first
- Removed 38 legacy Preact files + 8 obsolete tests
- SSE reconnection: fixed 3s retry, no exponential backoff or max attempts
- settings_save: does not merge overview for complete broadcast
- session_load: still uses POST /api/sessions/load, not switch + GET
- app.js bundle size ~900KB (code-splitting deferred)
- Mobile layout optimization (deferred until desktop Web is stable)
- npm run build: pass
- npm run typecheck: pass
- npm run lint: pass
- npm run test: pass (229 files / 3271 tests)
* fix(ci): run build before test so smoke tests find dashboard artifacts
* cleanup: remove updater mechanism from web dashboard (CLI manages updates)
Web version doesn't need Tauri's @tauri-apps/plugin-updater since
updates are handled by CLI (npm). Removed:
- Imports and usage from App.tsx (pendingUpdate state, UpdateBanner component, check() call)
- about.tsx update checking UI (CheckStatus component, checkForUpdates)
- tauri-bridge.ts mock exports (Update type, check function)
- tsconfig.json and vite.config.ts path/resolve aliases
* fix: add /dashboard copy subcommand to copy URL to clipboard
Users could not copy the dashboard URL because /copy mode only captures
conversation cards, not the WelcomeBanner which displays the URL.
This caused repeated failed attempts (infinite loop).
Add /dashboard copy as a quick way to yank the live dashboard URL to
the clipboard via OSC 52.
Fixes#1450
* fix(ci): restructure settings.ts to fix biome parse errors
Move orphaned code (GET response body, declarations, helper function)
back into proper positions within the module. The merge left code
scattered at module level causing 41 biome lint errors.
- Move handleSettings function and its complete GET/POST handlers
into correct position after declarations
- Move VALID_WEB_SEARCH_ENGINES, VALID_EDIT_MODES, void saveEditMode,
and debugLogPresetWriteFromDashboard before the main function
- Restore complete GET response with session, model, proNext, budgetUsd,
skillPaths, appliesAt fields
* fix(i18n): add missing translation keys for dashboard components
Add 200+ missing i18n keys to en.ts and zh-CN.ts for new React
dashboard components (cards, composer, contextPanel, sidebar,
statusbar, thread, etc.). Also fix settings.ts structural issues.
* fix(ci): add postinstall to install dashboard deps automatically
npm ci in CI only installs root dependencies. Add postinstall script
that runs npm ci --prefix dashboard to ensure dashboard deps
(prism-react-renderer, lucide-react, etc.) are available for
typecheck and build steps.
* fix(tui): surface failure signals in collapsed run_command cards (#1496)
When a command exits non-zero, the collapsed card now:
- Shows error-relevant lines (error/fail/exception/assertion patterns)
mixed with tail lines instead of only the last N lines
- Displays exit code in the truncated hint: 'N lines hidden · exit 1'
- Uses 'Ctrl+R to expand' instead of confusing 'use /tool to read full'
Smart truncation for failed commands:
- Scan output for error-pattern lines (error, fail, fatal, exception, etc.)
- Include those lines + context + tail in visible output
- Add separators for hidden gaps between error regions
* Revert "fix(tui): surface failure signals in collapsed run_command cards (#1496)"
This reverts commit 3d71f613a2.
---------
Co-authored-by: Reasonix Dev <[email protected]>
Co-authored-by: CI Fix <[email protected]>
The 75%-off promo became the permanent rate on 2026-05-31, so the
parenthetical caveat is now misleading — readers think pro is on a
limited-time sale that will expire. Pricing math is unchanged
(stats.ts already uses the 1/4-of-original rate).
Closes#1559
Co-authored-by: reasonix <[email protected]>
read-before-edit gate (#1563) and cache-aligned fold summary (#1565)
landed after the release commit was written. Document them in the
0.49.0 entry before tagging so the published CHANGELOG matches what
ships.
Co-authored-by: reasonix <[email protected]>
* chore(release): 0.49.0 — static-history TUI, queued steers, Bing default, lifecycle plans
Headline themes:
- TUI: Static-history renderer is the only path; virtual-viewport layers removed (#1529 stages 1-4)
- Chat: queued mid-turn steer handling so input mid-render doesn't drop or fight the live frame (#1501)
- Web search: default switches to Bing; dashboard engine switcher; Mojeek dropped (#1558)
- Plans: lifecycle evidence summaries surface why a plan is ready to accept (#1500)
- Desktop: native OS notifications for approvals + completion (#1519)
- i18n: CLI command output (/mcp /sessions /prune /theme) + approval-prompt labels translated (#1524, #1560)
- Security: SSRF block in web_fetch (#1544), edit-snapshot path containment (#1454), shell redirect sandbox (#1457), Task integrity guardrail (#1516)
- Tools: per-turn dispatch-rate limit (#1356); run_command discourages shell-based edits (#1514)
- Client: DeepSeek 429 → concurrency-limit hint (#1526); timeoutMs honored with AbortSignal (#1535); --no-proxy opt-out for direct route (#1507)
- Files: read/edit/restore preserves source encoding (GB18030 / UTF-8 BOM) (#1518)
- Context: pinned constraints survive folds + full tail capture (#1515, #1552)
- Refactor: lifecycle risk policy extracted into its own module (#1557)
See CHANGELOG for the full list.
* fix(context): align fold summary prefix with main agent for cache reuse
The summarizer call was sending a bespoke "You compress conversation
history" system prompt and no tools, guaranteeing a 0% cache hit
against the main agent's just-cached prefix. Reshape the request so
system + tools + head bytes mirror the live agent's last call — the
only novel bytes are the trailing summarize instruction.
Skill-pin handling now collects bodies read-only instead of stubbing
mid-head, so the cache prefix stays unbroken. The summarize
instruction names pinned skills so the model knows not to paraphrase
their bodies (which we append verbatim regardless).
Measured on a real session at 48.7K prompt tokens:
OLD shape: 0.0% cache hit → $0.145 per fold
NEW shape: 99.6% cache hit → $0.015 per fold
saving: 89.6% per fold
* tools: add fold-cache shape + live benchmarks
bench-fold-cache-shape.mjs replays real session jsonls, simulates
OLD vs NEW summary-call shapes at the fold point, and reports
byte-level shared-prefix with the main agent's preceding request.
Pure local — no API required.
bench-fold-cache-live.mjs sends one priming + two summary calls to
DeepSeek and reports prompt_cache_hit_tokens / cost for each shape.
Used to confirm the shape change actually translates to API-side
cache hits.
---------
Co-authored-by: reasonix <[email protected]>
Soft prompt hint ("read_file first so SEARCH matches byte-for-byte")
was easy for the model to skip — the failure mode is a tool round
spent on "search text not found", a guess at the bytes, and a retry.
Each round is a cache-miss tail and an obviously-not-grounded edit
that erodes trust.
New ReadTracker lives on CacheFirstLoop and threads through
ToolCallContext. read_file marks the absolute path on any successful
load (full, range, head, tail, outline); write_file marks too — the
model knows what it just wrote. edit_file / multi_edit consult the
tracker before applying and refuse unread targets with a message
that names the path and tells the model to call read_file first.
multi_edit refuses the whole batch if any target is unread, so a
partial-knowledge cross-file refactor can't half-apply.
ContextManager fires a new onLogRewrite callback from fold and
mechanicalTruncate; the loop wires it to ReadTracker.reset() because
once the byte-level history is folded away the model's "I saw it"
claim no longer holds. The tracker is in-memory only, so session
resume also starts empty — the model must re-read before editing
after a restart.
tools.ts's repeat-rejection detector recognizes the "read_file first"
gate so a 2nd identical unread edit gets the sharper "do not retry
identical args — call read_file on the target path first" hint
instead of the same refusal echoed back.
Path normalization lower-cases on win32 so case variants of the same
file resolve to one tracker entry.
11 new tests in tests/read-before-edit-gate.test.ts cover: refusal,
post-read success, write_file-counts-as-read, partial-read accepted,
multi_edit all-or-nothing, repeat-rejection sharpening, reset
semantics, and backwards compat when no tracker is injected.
Co-authored-by: reasonix <[email protected]>
`toApprovalPrompt` in core-utils mints English labels so the ACP surface
(no i18n layer) can render immediately — but the CLI surface was rendering
those English strings verbatim, leaving "Run command" / "Run once" /
"Always allow — …" / "Deny" on screen even when the locale was zh-CN.
ShellConfirm and PathConfirm now override `prompt.title` and each
`action.label` with locally-translated strings keyed off `action.id` and
`prompt.data` (so we can still tell foreground vs background and read vs
write apart, even after the unified `prompt.kind` collapses each pair).
New i18n keys in both EN.ts and zh-CN.ts:
- `shellConfirm.promptTitleRunCommand` / `promptTitleRunBackground`
- `shellConfirm.actionRunOnce` / `actionAlwaysAllow` (with `{prefix}`) / `actionDeny`
- `pathConfirm.promptTitleRead` / `promptTitleWrite`
- `pathConfirm.actionAllowRead` / `actionAllowWrite` / `actionAlwaysAllow` / `actionDeny`
Test plan:
- `tests/shell-confirm-render.test.tsx` gains a `setLanguageRuntime("zh-CN")`
case that asserts 运行命令 / 运行一次 / 始终允许 / 拒绝 render and the
English labels do NOT survive.
- `npm run verify` passes (3554 tests).
Closes#1560
Co-authored-by: reasonix <[email protected]>
* feat(web-search): default to Bing (cn.bing.com), drop Mojeek, dashboard switcher
Mojeek's IP-geolocation reputation system 403s most CN-residential
clients on the very first request, leaving the default `web_search`
tool unusable for the bulk of this project's users. cn.bing.com serves
clean HTML from CN without a proxy, returns real URLs (not the
`/ck/a?u=a1<base64>` click-tracking wrappers the international `www.bing.com`
uses), and has no per-IP daily quota. Live probes across three queries
× two endpoints returned 200 with zero anti-bot markers.
- New `searchBing` + `parseBingResults` scrapes `<li class="b_algo">`
blocks (h2 a[href] + div.b_caption p) from cn.bing.com.
- `webSearch` dispatcher's fallback is now Bing; `webSearchEngine()`
loader returns "bing" for unset / unknown / legacy "mojeek" values.
- Legacy migration is read-only — we don't rewrite the user's
config.json. `/search-engine mojeek` is no longer in the slash
validation set, so users who explicitly retry the dead name see an
immediate "invalid engine" reject instead of a silent revert loop
on the next launch.
- Dashboard settings panel gets a Search Engine `<select>` with the
six valid backends; POST /api/settings validates the new
`webSearchEngine` field, persists to config, and includes it in the
GET response + `appliesAt` hints.
- searchMojeek/parseMojeekResults/MOJEEK_ENDPOINT removed; i18n
webErrors.mojeek* renamed to bing*; public-API surface swaps
parseMojeekResults for parseBingResults.
Tests:
- parseBingResults: real cn.bing.com HTML fixture, empty input, h2-less
block skip
- webSearch dispatcher hits cn.bing.com with browser UA
- webSearchEngine config loader: enum round-trip, default = bing, legacy
"mojeek" value reads back as bing
* fix(web-search): switch parseBingResults to DOM walk to silence ReDoS scanner
CodeQL flagged three polynomial-backtracking patterns in the regex-based
parser. node-html-parser is already in the file (used by
parseSearxngHtmlResults); using its selector API eliminates the
backtracking class entirely without changing parse semantics.
---------
Co-authored-by: reasonix <[email protected]>
Users still report `preset` flipping back to its prior value after a
relaunch, even with the BOM-cascade root cause (#1431) fixed. Two
follow-on changes to close the gap:
1. `writeConfig` now writes to a sibling `${path}.${pid}.tmp` and
`renameSync` into place. The previous `writeFileSync` is not atomic
on Windows — a concurrent reader during the write window can see a
truncated file, `readConfig` falls through to `{}`, and the next
read-modify-write saves an empty baseline that loses every other
field. The temp + rename pattern guarantees readers see either the
old file or the new one, never an in-flight blob.
2. Restore the `REASONIX_DEBUG_PRESET` env-gated trace retired in
#1431. Logs every `savePreset()` call, every `writeConfig()` call,
and the dashboard PATCH bypass — each with a short stack — so the
`tools/debug-preset-launcher.ps1` script can pinpoint who flipped
the preset when it does. Zero cost when the env var is unset.
Co-authored-by: reasonix <[email protected]>
`opts.signal ?? ctrl.signal` orphaned the timer's controller whenever the
loop forwarded its `_turnAbort.signal` — i.e. every real call. A genuinely
stalled SSE body (TCP open, no `[DONE]`, no close) then sat on
`reader.read()` forever and the TUI hung in "…waiting for response…"
until the user restarted it, even though the server-side request had
already completed.
Combine both signals with `AbortSignal.any` and have the timer abort with
a reason so the loop's error path surfaces "timed out after Xms" instead
of a silent stall.
Closes#1535
Co-authored-by: reasonix <[email protected]>
For example: just in this repo
- before:
1. input @benchmarks/compression-eval/.git
2. press tab
3. reasonix would show @.gitignore
(if just input @benchmarks/compression-eval/ and press tab, then would get benchmarks/compression-eval/.gitignore correctly)
- after: same step1 and step2, in step3 reasonix would show @benchmarks/compression-eval/.gitignore
Pure prompt-engineering tweak — addresses #1495. In long sessions the model has been rationalizing scope cuts to itself ("save tokens", "be efficient") and silently narrowing the user's task instead of asking. Adds a "Task integrity — non-negotiable" paragraph to the code-mode system prompt:
> The user's original objective and ALL constraints (especially "do NOT do X", "avoid Y", "never Z") remain in force for the entire session. You may NOT unilaterally simplify, narrow, or change the objective to save tokens, time, or steps. If you believe the objective needs adjustment, ask the user — do NOT decide on your own.
Inserted before `__ESCALATION_CONTRACT__`, after the format-rules section. About 50 tokens, in the static prefix so it caches with the rest. Additive — the existing cost-aware escalation contract is unchanged.
Refs #1495.
Small follow-up to #1515.
`extractPinnedConstraints` used `.match()` without the `g` flag, which only returns the first capture. The system prompt can carry multiple blocks under the same prefix:
- `# User memory — global` and `# User memory — this project` both exist when a user has both (`src/memory/user.ts` emits them as separate sections).
- Multiple `# Project memory (filename)` sections can show up when a project carries per-subdir memory.
Single-match meant the second one was silently dropped from the fold-tail constraint reinforcement.
Combined the three prefixes into one regex and switched to `matchAll` so every pinned block makes it into the fold summary.
Two fixes around context-fold memory preservation, plus a behavior-stability harness to regression-test them.
**`context-manager.ts`** — fold now reinforces pinned constraints after the summary:
- New `extractPinnedConstraints()` pulls the `# HIGH PRIORITY constraints`, `# User memory`, and `# Project memory` blocks out of the live system prompt and appends them verbatim under a `[PINNED CONSTRAINTS — preserved verbatim]` tail on the synthetic fold summary message. The system prompt always survives the fold (only history is compressed), but in long sessions the model's attention drifts away from instructions at the top; restating them near the current context window mitigates the "lost in the middle" effect.
- Summarizer system prompt now explicitly tells the model to preserve "do not" / "never" / "avoid" instructions when compressing — independent improvement, useful regardless of whether the new constraint tail fires.
**`loop.ts`** — wires `getSystemPrompt: () => this.prefix.system` into `ContextManagerDeps` so the fold can read the current system prompt.
**`benchmarks/behavior-stability/`** — small evals scaffold (harness / runner / report / types + one scenario). The `constraint-persistence` scenario stuffs the log with 40 synthetic turns, triggers a fold with a tiny `keepRecentTokens` budget, and asserts all four pinned constraints (2× HIGH PRIORITY, 1× User memory, 1× Project memory) survive in the folded summary. Local: `npx tsx benchmarks/behavior-stability/runner.ts --local` — 1/1 passing.
Refs #1462.
Pure prompt-engineering tweak. Issue #1372 reports the model reaching for `echo`/`cp`/`sed` through `run_command` to edit files, which trips the confirmation gate and ignores the dedicated `write_file` / `edit_file` / `multi_edit` / `copy_file` / `move_file` / `delete_file` tools that already have validation + rollback.
Prepends a negative-constraint paragraph to the `run_command` tool description telling the model not to use shell utilities for file operations and pointing at the right alternatives. About 50 tokens, included in the static tool spec so it caches with the rest of the prefix.
No behavior or schema change — just text the model sees every turn `run_command` is in scope.
Tiny follow-up to #1499. The harness helper used to register only mutation tools (`delete_file`, `move_file`, etc), but #1499 extended it to register `read_file` too so the cancel/stop-recovery tests could verify read-only operations still work. The old name `registerMutationTools` doesn't fit anymore — renaming to `registerLifecycleToolFixtures`.
Test-only, behavior-neutral.
Refs #1285. Follow-up to #1499.
Lets users type into the composer while a turn is busy and have those messages queued as mid-turn steers — they're appended as user-role guidance at the next loop iteration boundary, never interrupting the in-flight request.
**Loop side (`src/loop.ts`)**
- `_steer: string | null` → `_steerQueue: string[]`. `steer(text)` pushes; `steer(null)` clears.
- At the iteration boundary, shift one off the queue, wrap with `MID_TURN_STEER_WRAPPER` ("Do not treat this as a new task; use it only as additional guidance for the current task after completing the current step.") and `appendAndPersist` it as a `user` message before the next `buildMessages()`.
- `steerConsumed` now means "queue empty after consume" — the UI gate against double-submit.
- All abort / budget / 5xx / context-guard / final-done paths clear the queue so steers can't survive past the turn that owned them.
- When a model response has no tool calls but a steer is queued, the loop now `continue`s instead of returning `done` — so the queued steer drives one more iteration.
**TUI side (`App.tsx`, `PromptInput.tsx`, `ComposerArea.tsx`)**
- New `isBusyPromptCommand(text)` rejects slash / `!`-bang / `#`-memory while busy; ordinary text is accepted as steer.
- `submitPrompt` (dashboard ctx) and the busy keystroke branch both gate on it.
- `PromptInput` separates `inputFrozen` (`disabled && !steerBusy`) from `inputActive` (`!disabled || steerBusy`); placeholder, accent color, and cursor track that. New hint row: `⏎ send — injected mid-turn · esc to stop`.
**Dashboard side (`chat.ts`, `changes.ts`)**
- Both ChatInputs drop `disabled={busy}` on textarea + submit button; placeholder switches to `chat.placeholderSteerBusy`; popover dismisses when busy.
- `loop-to-dashboard` maps `steer` events to `user` messages so the consumed steer shows up in the dashboard transcript.
**i18n** — EN + zh-CN: `placeholderSteerBusy`, `steerHint`, `steerInjected`, `steerCommandRejected`, `steerPlaceholder`, `steerHint`.
**Tests** — 3 new `tests/loop.test.ts` cases:
- steer is persisted wrapped (not raw)
- multiple steers queue + FIFO consume
- `steerConsumed` flips back to `false` on a fresh steer
Adds e2e coverage for two strict-lifecycle recovery paths that weren't pinned down:
1. **User cancels a proposed plan** — after `submit_plan` returns `plan cancelled: ...`, snapshot resets (`planSteps=[]`, `completedStepIds=[]`, `mutatedSinceLastStep=false`); a fresh user prompt flips state back to `armed`; read-only tools work; a follow-up mutation is still rejected with `nextAction: "submit_plan"`.
2. **Checkpoint stop** — same assertions on the post-stop fresh prompt.
To make these tests possible the harness also picks up:
- `QueueGate` now handles the `cancel` verdict on `plan_proposed` (calls `lifecycle.cancel()`).
- Registers a `read_file` tool with `readOnly: true` so the test can prove the read path still works after recovery.
Tests-only — no runtime, prompt, or tool-schema changes.
Refs #1285.
Drops the misleading `^O expand` action hint from the paste-sentinel chip and tightens the Ctrl+O / Ctrl+P shortcut-panel labels.
`Ctrl+O` only toggles the streaming-reply expand view; it does nothing during input, and certainly nothing for pastes. Showing `^O expand` next to a paste chip is a false promise — issue #1493's reporter pressed it and (correctly) got no response. The chip now reads `📋 pasted ... · ⌫ remove`, which is the actual interaction it offers.
While in the strings file, the shortcut descriptions are sharpened:
- `descCtrlO`: "Expand stream" → "Expand reply (streaming only)" (EN) / "展开流式输出" → "展开回复(仅流式输出期间)" (zh-CN) — clarifies the streaming-only scope.
- `descCtrlP`: "Toggle shortcut panel" → "Show/hide shortcuts" / "打开/关闭快捷键面板" → "显示/隐藏快捷键" — shorter, same meaning.
Issue #1493 also reports a separate Shift+Enter bug; that's out of scope for this PR.
Refs #1493.
Adds OS-level notifications to the Tauri desktop app so a user away from the window finds out when:
- a new approval request appears (shell command / path access / choice / plan / checkpoint / revision)
- a long-running turn finishes (only after at least 15 s of busy → idle, to skip quick replies)
Design:
- Pure `deriveDesktopNotifications(...)` derives the list from previous-vs-current snapshots; no Tauri calls inside, so the unit tests run without a window.
- `dispatchDesktopNotifications(...)` takes injected deps (`isFocused` / `isPermissionGranted` / `requestPermission` / `sendNotification`) so the App.tsx wiring is the only place that talks to the Tauri plugin. Focus check is repeated at dispatch time as a second guard.
- Notification permission is requested at most once per session; a denial sticks.
- All copy goes through `t()` against the active desktop UI language; both EN and zh-CN added.
Wiring lives in `TabRuntime` via a `useEffect` over the pending-state slices + busy flag.
`tauri-plugin-notification` is added on both the JS and Rust sides (`Cargo.toml` + `capabilities/default.json`). A vitest alias maps the plugin to a mock so the desktop test suite stays hermetic.
Follow-up to #1546: gate the new `@mention` popover behind `MODE === "attached"`, matching the existing pattern in `chat.ts`.
Without this guard, standalone dashboard clients call `/files` on every `@` keystroke and get a 503 (`"@-mention picker requires a code-mode session"`) back — the popover never opens but each `@` still costs a round-trip. The `MODE` import added in #1546 becomes load-bearing here.
Brings the `@`-mention file picker to the dashboard's Changes / ChatPane, mirroring what's already in `chat.ts`:
- `PopoverKind` extended with `"mention"`.
- `updatePopover` detects the trailing `@prefix` token and posts to `/files` for matching paths.
- `applyPopover` replaces the `@prefix` token in place (not the whole input) so the user keeps anything they typed before it.
- Popover header / row icon switch between `/` and `@` based on `popoverKind`.
The `chat.projectFiles` i18n key already exists in EN + zh-CN — no new strings.
Closes a real SSRF hole in `web_fetch`. Previously the tool accepted any `http(s)` URL and auto-followed redirects, so the model could:
- hit `127.0.0.1` / `::1` directly,
- reach private / link-local / metadata ranges,
- or be redirected from a public host into an internal one mid-chain.
Defense-in-depth in `src/tools/web.ts`:
- Scheme allowlist (`http:` / `https:` only).
- IP-literal check rejecting RFC 1918 + loopback + link-local + CGN (100.64/10) + TEST-NET-1/2/3 + multicast + reserved + benchmarking (198.18/15).
- IPv6 check covering `::`, `::1`, ULA (`fc00::/7`), link-local (`fe80::/10`), multicast (`ff00::/8`), and `::ffff:` IPv4-mapped (recursing into the v4 check).
- For hostnames, `dns.lookup(host, { all: true })` and reject if **any** resolved address is internal — defends against half-public/half-private multi-A records.
- Manual redirect handling with re-validation on every hop + a 5-redirect cap.
- Timeout / response-size limits untouched.
Tests cover loopback literal, hostname resolving to an internal IP, and a public→internal redirect.
Localizes the remaining hardcoded CLI output strings — `reasonix mcp list / search / install` flow, `sessions` listing, `prune-sessions`, and the `/theme` slash handler — so zh-CN users see translated text instead of mixed EN/CN output.
31 new keys across `sessions` / `mcpCli` / `app` namespaces with full EN ↔ zh-CN parity. Mechanical migration — `t()` calls replace each string with the same parameters; no behavior change.
Verified clean rebase on top of the stage-1-through-4 refactor (#1530 / #1534 / #1536 / #1537) plus the path-approval bridge (#1540): typecheck + lint + 3528 tests all pass.
When the model asked for file access outside the sandbox, the TUI opened `PathConfirm` but the web dashboard stayed blank — the loop hung waiting for a decision the web user couldn't make. Same shape as #832 (plan-checkpoint). This PR bridges the path-approval gate end-to-end.
- `ActiveModal` gains a `path` variant (path / intent / toolName / sandboxRoot / allowPrefix).
- `DashboardContext.resolvePathConfirm` mirrors `resolveShellConfirm`.
- `App.tsx` broadcasts `modal-up` / `modal-down` for `pendingPath`, surfaces it in `getActiveModal` (mid-modal reconnect repaints correctly), wires `resolvePathConfirm` to `handlePathConfirmRef`.
- `/api/modal/resolve` accepts `kind: "path"` with `run_once` / `always_allow` / `deny`.
- New `PathModal` Preact component renders with sandbox / allow-prefix rows and three resolution buttons. EN + zh-CN strings added.
Audited every loop-blocking gate while in there — after this lands all of run_command / path_access / plan / plan_checkpoint / plan_revision / choice / edit_review have a TUI ↔ web bridge. Slash-command pickers (ModelPicker / ThemePicker / EditPicker / WorkspacePicker) are still TUI-only but don't block the loop, so out of scope here.
Closes#1538.
Final stage of #1529. The Frame algebra (`vstack`, `hstack`, `slice`, `overlay`, `viewport`, `bottom`, `fitWidth`, etc.) and its ANSI rasterizer existed so a full-screen persistent frame could be composed cell-by-cell. With Static-anchored history and Ink-native rendering, none of that is exercised — `frame-render.tsx` was the only caller of the Frame layer, and it itself had zero callers.
**Deleted:** `src/frame/{frame,ansi,types,index}.ts`, `src/cli/ui/frame-render.tsx`, `tests/frame.test.ts`.
**Migrated:** `src/frame/width.ts` → `src/cli/ui/text-width.ts`. These are text-cell utilities (`stringWidth` passthrough to the `string-width` lib, grapheme-safe `clipToCells` / `wrapToCells` / `graphemes` / `graphemeWidth`) that card renderers and markdown still need — they're not "frame" anything. Implementation is unchanged. 6 src callers and 2 tests updated. New `tests/text-width.test.ts` rescues the width-relevant edge-case coverage that lived in the deleted `frame.test.ts` (CJK, Hiragana / Katakana / Hangul, emoji, ZWJ clusters, combining marks, control chars, mixed scripts) and adds cases for `clipToCells` / `wrapToCells`.
Net: 907 deletions, 9 insertions across 16 files (plus the new 60-line `text-width.ts` and 100-line test file as untracked-then-added).
Closes#1529. Cumulative across stages 1–4: ≈ -2620 lines.
Stage 3 of #1529. The vertical row allocator existed so a full-screen persistent frame could parcel rows between zones (modal, status, input, stream, safety). With Static-anchored history the persistent frame sizes to content and the zones don't compete; there's nothing left to allocate.
**Deleted:** `src/cli/ui/layout/viewport-budget.tsx` (reducer + allocator + `ViewportBudgetProvider` + `useReserveRows` + `useTotalRows`) and its tests.
**Trimmed:** `App.tsx` drops the `<ViewportBudgetProvider>` wrapper (and the indentation it imposed). `StreamingCard`, `PromptInput`, `ChoiceConfirm`, `PathConfirm`, `ShellConfirm`, `PlanCheckpointConfirm` were all side-effect-only callers — removed. `EditConfirm` and `PlanConfirm` were the only consumers that read the allocator's return value; both swap `useTotalRows()` for `useStdout().stdout?.rows` and inline the max into a direct expression. `tests/plan-confirm.test.tsx` renders without the provider wrapper now.
**Kept:** `src/cli/ui/prompt-viewport.ts` — composer-internal input-cell math (CJK width, paste sentinels, single-row slicing). The stage 3 plan said "drop viewport-budget / prompt-viewport, after confirming the composer no longer depends on them"; the composer still depends on prompt-viewport, so it stays.
Net: 727 deletions, 433 insertions across 12 files (most of the App.tsx insertion count is biome re-indenting the subtree that lost its wrapper).
Stage 2 of #1529. `StaticCardStream` landed behind a flag in Stage 1 and held up under real use; this stage promotes it to the only path and deletes the machinery whose entire job was fighting the terminal for scrollback.
**Deleted:** `CardStream` (virtual viewport + height measurement + monotonic-shrink lock + scroll indicator), `chat-scroll-store` + `chat-scroll-provider`, `copy-mode/` (vim/tmux selection mode + OSC 52 snapshot), `InputAreaWithHistoryHint` (unused dead leaf), 5 obsolete tests, the `/copy` slash command + `openCopyMode` slash result + the qq-channel terminal-only notice + the `copyMode` i18n block.
**Trimmed:** `App.tsx` -114 net (drops `STATIC_HISTORY` flag, `HistoryTypingCapture`, `ChatScrollProvider` wrapper, `useChatScroll*` subscriptions, `pendingCopyMode`, the PgUp/PgDn/End/wheel/arrow keystroke handler, the conditional outer Box height); `ComposerArea` no longer wraps the input area in the "scrolled-up history hint" branch; `PromptInput` drops the absolute IME cursor write (its math required the persistent UI at terminal bottom and the Static frame floats); `mouse-mode` defaults to `off` everywhere with the env-var override kept as an escape hatch.
Net: 1545 deletions, 48 insertions across 26 files.
Stage 1 of #1529. Adds a Static-based history renderer behind `REASONIX_STATIC_HISTORY=1` so we can validate it in parallel before later stages delete the virtual-viewport CardStream + chat-scroll-store + copy-mode entirely.
- New `StaticCardStream` partitions cards at the first unsettled entry: settled prefix goes through Ink `<Static>` (terminal owns scrollback), live tail renders dynamically.
- Outer Box drops `height={stdout.rows}` under the flag so the persistent frame doesn't push Static commits straight into off-screen scrollback.
- Mouse mode resolves to a known wheel-passthrough state under the flag, and emits disable sequences for `?1000 / ?1002 / ?1003 / ?1006 / ?1007 / ?1015` on every "off" enable so stale capture from a crashed prior session can't keep eating wheel events.
- `PromptInput`'s absolute IME cursor positioning is skipped under the flag — its `\x1b[row;colH` math assumed the persistent UI sits at the terminal bottom; with the floating Static frame the absolute write desynced Ink's cursor tracking and ghosted previous frames.
Off by default; nothing changes for users who don't opt in.
Ctrl+Enter now inserts a newline instead of submitting, matching the behavior of Shift+Enter and Alt+Enter.
Changes:
- multiline-keys.ts: add key.ctrl to newline condition
- PromptInput.tsx: HintRow shows ^J as alt newline shortcut
- ShortcutsHelpModal.tsx: add Ctrl+Enter and Ctrl+J entries
- i18n: add descCtrlEnter / descCtrlJ translations
Refs #1493
DeepSeek's actual rate limit is concurrency-based, not RPM (500 for
v4-pro, 2500 for v4-flash, account-wide across API keys). When the
account exceeds it the server returns HTTP 429, which currently
surfaces as a raw `DeepSeek 429: {...body}` string — fine for a
maintainer to read, useless for a user trying to figure out why.
Add a friendly message that names the actual cap, identifies the
likely cause (another reasonix process on the same key, or a
parallel subagent fan-out that overshot), and points at the
remediation (wait + retry, reduce parallelism, or request expansion).
Same shape as the existing 401/402/422/400 cases.
Also clarify the `rateLimit.rpm` config docstring: it's a client-side
self-throttle for politeness on shared infra, not a DeepSeek-enforced
limit. DeepSeek has never had a published RPM cap.
Closes#1522
Co-authored-by: reasonix <[email protected]>
* fix(edit): preserve file encoding on read/edit/restore (GB18030, UTF-8 BOM)
read_file / edit_file / multi_edit / applyEditBlock all hard-coded
UTF-8 in readFileSync + writeFileSync. On Chinese Windows hosts most
project files are GB18030; lossy UTF-8 decode mangled the bytes so
the model's SEARCH text never byte-matched, edit_file silently
failed, and the model fell back to PowerShell + git-replay (token-
expensive and lossy for any user manual edits in between).
The shell stdout path already handled this via smartDecodeOutput's
UTF-8-fatal → GB18030 fallback. Same pattern, applied to the
filesystem path, plus encode-back via iconv-lite so the file stays
in its original encoding. UTF-8 BOM round-trips too. Snapshot
records prevEncoding so restoreSnapshots writes back correctly.
Closes#1445
* fix(edit): make GB18030 fallback platform-independent
CI ubuntu build flagged the previous platform gate — GB18030 files
are portable, Linux developers can have CN-Windows-origin files in
their projects. The gate was a copy of smartDecodeOutput's
cmd.exe-specific behavior that doesn't apply to file-on-disk
encoding detection.
---------
Co-authored-by: reasonix <[email protected]>
Mouse wheel sensitivity is terminal-dependent — most emit 2-5 SGR
mouse reports per physical notch (#1419 settled SCROLL_WHEEL_ROWS=1
to keep that case bearable), but some emit one report per notch and
the resulting 1-row-per-notch scroll feels broken (#1494).
A constant-bump fix would regress the over-sensitive class. Add
`mouseWheelRows?: number` (clamped to [1,10]) so affected users can
tune without compromising the default that #1419 validated.
Closes#1494
Co-authored-by: reasonix <[email protected]>
`DEFAULT_NO_PROXY` hardcoded `api.deepseek.com` / `*.deepseek.com` so
the dispatcher always routed them through `undici.Agent()` direct,
bypassing HTTPS_PROXY. Corporate firewalls that block direct egress
therefore broke `reasonix doctor`'s api-reach check with a
ConnectTimeoutError, with no way for the user to override.
Split the defaults: loopback stays mandatory, DeepSeek becomes opt-out
via `proxy.bypassDeepSeekDirect: false` (config) or
`REASONIX_PROXY_DEEPSEEK_DIRECT=0` (env). Default behaviour preserves
the clash/v2ray US-exit-IP 403 fix that put the bypass there.
Closes#1497
Co-authored-by: reasonix <[email protected]>
Validate redirect targets before execution to block sandbox escapes, symlink traversal, and sensitive redirect paths. Preserve PauseGate test stub typing and support case-insensitive Windows environment variables in executable resolution.
- App.tsx $session_empty branch was missing `id` on the error card so
TS rejected the literal against ChatMessage's required-id variant.
- App.test.ts stub state still used the pre-#1487 UsageStats shape
(`tokens.{input,output,...}`); update to the current flat shape so
the test compiles.
Caught by the desktop-v* release workflow — root verify doesn't run
desktop tsc, so these regressed silently after #1487.
`npm ci` inside desktop/ failed with EUNSUPPORTEDPROTOCOL because desktop/
is not listed under root workspaces, so the `workspace:*` spec added in
#1443 had no resolver. Replace with `file:../packages/core-utils`,
which is what the desktop install actually wants (source-only package,
type-only import in desktop sources).
Reported in #1448. With YOLO mode enabled, file edits skip confirmation
(editModeRef path) but shell commands still prompt — defeating the "fully
unattended" promise.
Two layers were supposed to bypass shell prompts in YOLO:
1. shell.ts's `isAllowAll()` check — should skip `gate.ask` entirely.
2. `pause-policy.ts:autoResolveVerdict` — should auto-resolve any
gate.ask that does slip through.
Layer 2 only handled `plan_checkpoint` and `path_access`. `run_command`
and `run_background` fell through to the UI for a manual prompt. That
gap matters because shell.ts's `allowAll` closure reads on-disk config
via `loadEditMode()`, but:
- `reasonix acp --yolo` sets `opts.yolo = true` in-memory without
calling `saveEditMode`, so shell.ts can't see it.
- Anywhere a desync between the in-UI editMode and the persisted
config can occur (e.g. mid-toggle races), shell.ts will let the
gate.ask through.
Extend `autoResolveVerdict` to return `{ type: "run_once" }` for
`run_command` / `run_background` when `editMode === "yolo"` — same
pattern as `path_access`. `run_once` (not `always_allow`) so a YOLO
session doesn't pollute the persisted allowlist with every transient
command. Matches the documented intent ("yolo mirrors shell.ts's
allowAll bypass").
Tests in tests/acp-yolo.test.ts:
- Replaced the previous assertion that `run_command` falls through to
the bridge under --yolo (that was the old design that's now the
bug) with one that asserts auto-resolve to `run_once`.
- Added the same coverage for `run_background`.
- Added a regression that `run_command` in auto mode still bridges to
the client (only yolo bypasses).
Closes#1448
Co-authored-by: reasonix <[email protected]>
User report: storm-repair / repeat-loop warnings pile up as red error
cards in the desktop transcript with no way to close them. A handful
of self-repaired loops in a long session leaves a wall of "错误" cards
permanently sitting in the chat, even though the loop already worked
around the underlying problem.
The kernel-side already classifies these correctly — KernelErrorEvent
carries `recoverable: true` for storm-repair / repeat-loop notices and
`false` for hard failures. The desktop just wasn't using either signal:
- Every error event got the same red tone with no dismiss UI.
This commit:
- Adds an id to each error chat message so dismiss can target one
without taking out unrelated messages.
- New `dismiss_error` action + reducer case removes by id.
- Each error card now renders a close (×) button. Click dispatches
`dismiss_error` for that id.
- When the kernel event marks the error `recoverable: true`, the
card renders with warn tone (warningLabel + tone-warn border/text)
instead of error tone — softer signal for things the loop already
handled.
- Protocol `$error` events (RPC-layer hard failures) keep the red
error tone.
i18n: added `app.warningLabel` and `app.dismissError` for en + zh-CN.
3539 tests pass (+4: dismiss_error by id; no-op for missing id;
recoverable=true from kernel error; recoverable=false from \$error).
Co-authored-by: reasonix <[email protected]>
Follow-up to #1477. The alternate-scroll switch fixed native text
selection / right-click on terminals that honor `?1007h` properly, but
Windows Terminal turns out NOT to be one of them — it advertises the
mode but doesn't reliably translate wheel events into keys, so reasonix
sees nothing and the wheel goes dead in-app. That's exactly the
regression #514 was originally fixed by `?1000h` mode in the first
place. Tested on a fresh checkout: pre-#1477 Windows Terminal wheel
worked; post-#1477 it doesn't.
Pick the protocol by platform:
- `process.platform === "win32"` → `?1000h+?1006h` (proven on
Windows Terminal / conhost / ConEmu, restores wheel for everyone
who had it before #1477)
- otherwise → `?1007h` (still gives back native text-select and
right-click on iTerm2, GNOME Terminal, kitty, Alacritty, recent
xterm — the platforms whose users asked for #1337 / #677)
`REASONIX_MOUSE_MODE=sgr|alternate-scroll|off` still overrides for the
edge cases (e.g. a Linux user whose terminal also breaks under `?1007h`,
or a Windows user who wants the new selection behavior at the cost of
wheel scroll).
Tests use platform-conditional expected sequences so both branches are
verified on CI (Ubuntu hits the alternate-scroll path, Windows hits
SGR). New test specifically covers
`REASONIX_MOUSE_MODE=alternate-scroll` as an override on Windows.
Co-authored-by: reasonix <[email protected]>
* feat(ui): redesign input area and integrate Ctrl+P shortcut help modal
- Remove border lines from PromptInput, keep blue left bar + #1e1e1e background with 5-row internal padding
- Add ShortcutsHelpModal as floating overlay triggered by Ctrl+P, styled with round border and #649ed2 accent
- Remove Ctrl+P from multiline-keys ↑ alias (was conflicting with shortcut panel)
- Mode display in PromptInput now uses i18n (t('statsPanel.modeYolo/Auto/Review'))
- StatusRow: remove PresetPill ('▴ auto'), fix balance order to '剩余 balance', i18n Ctrl+P hint
- Remove edit-mode status bar (ModeStatusBar) from ComposerArea (duplicated with shortcut modal)
- InputAreaWithHistoryHint restyled with blue left bar + #1e1e1e to match input box
- All shortcut descriptions in ShortcutsHelpModal use i18n via t() calls
- Add i18n keys for shortcutsHelp + statusBar.shortcutsHint in EN / zh-CN / types
* fix(tests): update multiline-keys tests for Ctrl+P removal as arrow alias
Ctrl+P now handled by App.tsx shortcut modal, no longer maps to arrow-up in multiline-keys.ts. Tests updated to verify NOOP behavior for Ctrl+P and moved arrow-up cursor tests to use upArrow key.
---------
Co-authored-by: Reasonix Dev <[email protected]>
Reported in #1456. Repro:
1. /plan → agent generates plan → plan approval card renders below
the assistant message
2. User types follow-up guidance and presses Enter → queued (busy=true)
3. User clicks what looks like the send button — but with busy=true the
composer swaps it for the stop/abort button. The turn aborts.
4. \`$turn_complete\` fires (busy=false), the queue drains, send_user
appends the user's text to state.messages. But pendingPlans was
never cleared, so the orphaned plan card is still rendered AFTER
all messages. Result: the new user message visibly lands ABOVE
the plan card, exactly the layout the issue screenshots show.
By the time the loop emits \`$turn_complete\` any modal still in a
pending* array is orphaned — the tool call that opened it has either
resolved already (so the array entry is gone) or the turn aborted
(so the model isn't coming back for it). Clear all six pending arrays
at that point.
The error toast the user also saw is from the aborted submit_plan call
unwinding through pauseGate; that path is unchanged.
Closes#1456
Co-authored-by: reasonix <[email protected]>
Reported in #1479. The bottom status bar shows the session-aggregate cache
hit (intentional, per the comment in state/events.ts — same number as the
web dashboard). `/cost` was showing the LAST TURN's ratio, so on any
session where one turn ran cold (e.g. the first one, or right after a
fold) the two numbers diverged and looked like a bug.
Switch `/cost`'s Usage card to `summary.cacheHitRatio`. The card also
shows `sessionCost`, so a session-aggregate cache hit reads cleanly
alongside it. Per-turn metrics in the card (prompt/output tokens, turn
cost) are unchanged.
Closes#1479
Co-authored-by: reasonix <[email protected]>
Reported in #1475. After pressing Esc on the plan picker (entering the
reject staged input), pressing Esc again restored the picker but choosing
"Accept" then surfaced ANOTHER staged input — the "approve mode" optional-
guidance prompt. That input was visually close enough to the regular
composer that users assumed they were back in normal chat and typed
follow-up instructions (e.g. "执行计划") into it, which actually went
through as the approve verdict's `feedback` field. The user's mental
model — "Accept means run it" — kept breaking.
The optional-guidance staged input only makes sense when the plan has
open questions that the user needs to address before approving. When
the plan is fully specified, Accept should resolve the pause gate
directly. Updated handlePlanConfirm so:
- `approve` with no open-questions section → resolve the gate immediately
via the same handleStagedInputSubmit override path used by /dashboard,
so plan-card lifecycle hooks (recordPlanApproved, showPlan(active),
persistPlanState) all fire identically to the explicit-feedback path
- `approve` with open questions → staged input still appears so the user
can answer them
- `refine` → unchanged, always shows the input (feedback is the point)
- `/apply-plan` slash fallback (no pending plan, no gate) → unchanged
The Esc-back restoration loop now terminates the moment the user picks
Accept, instead of dropping them into a deceptively-similar second input.
Closes#1475
Co-authored-by: reasonix <[email protected]>
Adds a session_rename IPC command that writes to meta.summary, plus an inline edit affordance in the sidebar (pencil icon, Enter/Esc/blur). Reorders the header title to prefer meta.summary over the first user message so a rename is reflected immediately.
The TUI never reacts to mouse clicks or drags — only the wheel — but the
old `?1000h+?1006h` default made the terminal capture ALL button events
and route them to reasonix. Reasonix then dropped them, which silently
broke native text selection and right-click context menus for every user
just to get wheel scrolling working. The same pattern shows up across at
least four bug reports (#1266 wheel broken on Linux, #1337 left-drag and
right-click broken on Windows Terminal, #677 PowerShell long answers
can't be selected, #1419 wheel too sensitive + selection broken).
`?1007h` (DECSET alternate scroll) is the correct protocol for an app
that only cares about wheel events: the terminal translates the wheel
into cursor/PageUp/PageDown keys (which reasonix's chat-scroll handler
already understands) and leaves clicks/drags alone for the terminal to
handle natively. Supported by Windows Terminal, iTerm2, GNOME Terminal,
kitty, Alacritty, recent xterm. Old emulators that don't recognise it
silently ignore the sequence — wheel falls back to the host terminal's
own scrollback, still functional.
Escape hatch via `REASONIX_MOUSE_MODE=sgr|alternate-scroll|off` for the
small slice of users on edge-case terminals; default is alternate-scroll
so the common case needs zero configuration.
Closes#1266
Co-authored-by: reasonix <[email protected]>
Three bugs piled up on the desktop /btw path so the user saw nothing after
pressing enter until a delayed error showed up:
1. The composer never dispatched send_user for the /btw line, so the typed
text never landed in the message stream and the user had no confirmation
the command was received. Mirrors the CLI shape (log.pushUser(text))
now: the full /btw line is echoed and busy flips on while the side call
runs.
2. $btw_result didn't clear busy on arrival, so even after the answer
showed, the composer would have stayed disabled. Reducer now flips
busy back off when the result lands (matches $error which already
clears busy on the failure branch).
3. The backend sent the question to the model with the FULL coding system
prompt (tab.system) instead of the brief side-question prompt the CLI
uses. That put the model into coding-agent mode for an unrelated side
question — it would either hang trying to call tools that weren't
wired up for the side-channel or take a long time to produce an
answer, which is exactly what the bug report described
("过了一段时间出现一个报错提示"). Backend now mirrors the CLI's
one-shot side-question prompt.
Closes#1470
Co-authored-by: reasonix <[email protected]>
The first test in `chat-mcp-startup-summary.test.ts` timed out at 15s
on Windows CI during the #1439 post-merge run. Vitest's coverage (v8)
instrumentation roughly doubles cold dynamic-import cost, and the first
`captureStartupState` call eats most of that — the SECOND test in the
same describe was back to ~400ms once the worker was warm.
Bump the describe-level timeout to 30s. Happy-path runs are unchanged
(each test still finishes in well under 500ms after the first cold
load); only a hung/genuinely-broken test gets a longer chance to fail.
Co-authored-by: reasonix <[email protected]>
* fix(desktop): sync context token meter after /compact (#1305)
Problem: Desktop ContextPanel showed stale token counts after /compact
because it relies on per-turn API usage events (model.final) to update
cacheHitTokens/cacheMissTokens. /compact is a local operation with no
API call, so no usage event fires and the meter never refreshes.
Fix (high-cohesion):
1. ContextManager.getLogTokens() — real-time token count of current log.
2. Loop.getCurrentLogTokens() — forwards to ContextManager.
3. Extend \$ctx_breakdown event with optional logTokens field.
4. emitCtxBreakdown() now computes + pushes logTokens alongside
reservedTokens, becoming the unified context-refresh entrypoint.
5. compact_history handler calls emitCtxBreakdown(tab) on success so
the frontend immediately receives the compressed token count.
6. App.tsx \$ctx_breakdown handler resets cacheHitTokens=0 and
cacheMissTokens=logTokens when logTokens is present, calibrating
the meter to the actual current context size.
This keeps all computation in ContextManager, all emitting in
emitCtxBreakdown, and all consumption in App.tsx — no new event types.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* feat(core-utils): introduce ApprovalPrompt unified data model (#1322 Phase 3 PR 1)
- Add `toApprovalPrompt()` and `resolveApprovalPrompt()` in `@reasonix/core-utils`
to serve as the single source of truth for PauseRequest → UI metadata mapping.
- Define `ApprovalPrompt`, `ApprovalAction`, `ApprovalTone`, `ApprovalPromptKind`
types with English fallback labels.
- Move `derivePrefix` computation into `toApprovalPrompt` so all surfaces share
one implementation.
- Add `secondaryInput` to `ApprovalAction` to describe two-phase deny flows.
- Replace ACP `gates.ts` inline mapping with calls to the new unified helpers,
deleting duplicated `permissionOptionsFor`, `permissionTitleFor`,
`permissionKindFor`, `verdictFor`, and all `ID_*` constants.
- Update `acp.test.ts` to use new semantic action IDs (`always_allow`, etc.).
- Add `packages/core-utils/tests/**/*.test.ts` to vitest include pattern.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* feat(cli): migrate ShellConfirm and PathConfirm to ApprovalPrompt model (#1322 Phase 3 PR 2)
- Update `ShellConfirm.tsx` and `PathConfirm.tsx` to accept `prompt: ApprovalPrompt`
instead of individual raw fields.
- Drive `SingleSelect` items from `prompt.actions` instead of hardcoded options.
- Trigger deny phase via `action.secondaryInput` detection instead of hardcoded
"deny" value check.
- Remove `clampCommand`, `tildeify`, and `derivePrefix` from ShellConfirm/PathConfirm
(computed centrally in `toApprovalPrompt`).
- In `App.tsx`, call `toApprovalPrompt()` at render time for both shell and path
confirmations, removing inline `derivePrefix` at the component boundary.
- Update `shell-confirm-render.test.tsx` to use `ApprovalPrompt` fixtures.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* feat(desktop): migrate ConfirmApprovalCard and PathAccessApprovalCard to ApprovalPrompt (#1322 Phase 3 PR 3)
- Add `@reasonix/core-utils` workspace dependency to `desktop/package.json`.
- Extend `ConfirmRequiredEvent` and `PathAccessRequiredEvent` with optional
`prompt: ApprovalPrompt` for backward-compatible RPC.
- In `src/cli/commands/desktop.ts`, call `toApprovalPrompt()` when emitting
`$confirm_required` and `$path_access_required` events.
- Update `ConfirmApprovalCard` and `PathAccessApprovalCard` in
`desktop/src/ui/thread.tsx` to consume `prompt` instead of raw fields.
- Drive primary/secondary/tertiary buttons from `prompt.actions` mapped by
`kind` (`allow_once`, `allow_always`, `reject`).
- Map `ApprovalPrompt.tone` to Desktop `ApprovalTone` (warn/danger/info/brand).
- Remove inline `derivePrefix` from card components.
- Update `PendingConfirm` and `PendingPathAccess` types in `desktop/src/App.tsx`
to store `prompt`, and pass it to the card components at render time.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* test(desktop): add ApprovalPrompt reducer and component tests
- Add desktop/src/App.test.ts (5 reducer integration tests)
- Add desktop/src/ui/thread.test.tsx (6 component rendering tests)
- Install @testing-library/react and jsdom for Desktop component testing
- Configure vitest with React aliases to prevent duplicate React copies
- Fix tildeify double-slash normalization bug on Windows
- Fix ACP gates comment length to pass policy check
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* fix(desktop-tests): mock Tauri and lucide-react imports for CI
CI installs only root dependencies; desktop-specific deps like
@tauri-apps/api and lucide-react are not available in test runners.
Add vi.mock() calls to App.test.ts and thread.test.tsx so vitest
can resolve these imports without the desktop node_modules.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* fix(tests): add vitest aliases for desktop-only dependencies in CI
CI installs only root dependencies; desktop-specific packages like
lucide-react and @tauri-apps/api are not available. Add mock modules
in tests/mocks/ and wire them via resolve.alias in vitest.config.ts
so desktop tests can resolve these imports without desktop/node_modules.
Also remove redundant vi.mock() calls from App.test.ts and thread.test.tsx
since aliases now handle module resolution globally.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* fix(desktop-tests): mock local desktop modules to avoid transitive dep loading
App.test.ts imports reduce from App.tsx, which transitively loads
CommandPalette, Markdown, and theme modules with desktop-only deps.
thread.test.tsx imports from thread.tsx, which loads cards.tsx,
which loads Markdown.tsx with react-markdown and other deps.
Add vi.mock() for these local module boundaries so tests resolve
without needing the full desktop/node_modules dependency tree.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
---------
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
End-to-end benchmark across 12 runs (3 repeats × 4 thresholds on the
"audit src/ and write an architecture overview" task, ctxMax forced to
120k to make folds reachable) showed normal fold at 0.5 is a stable net
loss:
config folds hit% miss cost
no-fold 0.0 92.7±1.3 75k±4k $0.0169±0.0006
current 50/70 2.3 83.0±9.5 127k±48k $0.0221±0.0054
late 75/90 0.0 92.7±1.7 82k±26k $0.0184±0.0040
agg 90/95 0.0 92.6±0.3 57k±8k $0.0142±0.0014
Every fold wipes the prefix cache: in current_50_70 prompt tokens drop
63k→16k at the fold, then the next ~9 turns rebuild a fresh prefix and
miss tokens climb 2-3×. Task quality is unchanged across configs (all
12 runs completed the audit), so fold was buying nothing in exchange.
Raising HISTORY_FOLD_THRESHOLD to 0.75 keeps fold available as a
last-mile-before-force-summary mechanism without firing on mid-context
turns. Aggressive lifted to 0.78 to stay in the same band.
The benchmarks/compression-eval/ harness is included so future tuning
can re-run on the same task.
Co-authored-by: reasonix <[email protected]>
A user reported a cryptic `DeepSeek 400: messages[156].content: unexpected
end of hex escape at line 1 column 884819` mid-session. Reproducing against
real session logs: Node's `JSON.stringify` can't emit a malformed `\u`
escape, and no lone surrogates exist in any of 10 saved sessions — the
gateway is truncating the request body mid-escape because it exceeds the
DeepSeek API's body-byte limit, which is independent of the 1 M-token
context window the existing preflight checks.
Token preflight stays at 95% of ctxMax. New byte preflight trips when the
stringified messages array exceeds `MAX_BODY_BYTES` (700 KB, ~80% of the
observed 884 KB failure point). Either signal triggers the existing
`mechanicalTruncate` path; the truncate now bounds output by tokens AND
bytes so byte-triggered folds actually shrink the body.
The `trigger` field on `PreflightDecision` records which signal fired so
follow-up diagnostics (and the user-facing warning, now showing body KB)
can distinguish the two paths.
Two `tests/loop.test.ts` fold cases used 2 MB seed logs and a 1 M-token
ctxMax to verify fold tier behavior. With the new 700 KB byte gate the
preflight emptied those logs before fold could run; switched both to a
100 K test ctx + proportionally scaled seed sizes so they exercise fold
tiers within both windows.
Two reusable tools added under `tools/` (`analyze-session-body.mjs`,
`scan-all-sessions.mjs`) so future "DeepSeek 400 from a long session"
reports can be diagnosed from the user's local session files without
guessing.
Co-authored-by: reasonix <[email protected]>
The dsnix workspace landed in #1440 but its addition wasn't reflected
in package-lock.json, so `npm ci` fails on every fresh checkout — main
CI has been red since the merge. Regenerate the lock so workspace
entries match the new package.json shape.
Also extend the README install section with the dsnix one-liner so the
shorter command is discoverable, not just a hidden bin alias.
Co-authored-by: reasonix <[email protected]>
`reasonix` is nine characters; users asked for a shorter form. Ship
a thin alias under `dsnix` that resolves to the same CLI:
- bin alias on the main package so global installs expose both
- dedicated shim package on npm so `npx dsnix@latest` works
- independent publish workflow keyed on `dsnix-v*` tags
Version tracks reasonix 1:1; first release at 0.48.0.
Co-authored-by: reasonix <[email protected]>
Headline themes:
- Network: full NO_PROXY support + per-host routing visible in /doctor
- Code intel: tree-sitter get_symbols/find_in_code + Java source/decompile + Perplexity/Exa search
- Lifecycle: gate mutations during checkpoints, preserve state across plan revisions
- Subagent: live byte progress + top-level explore/research/review
- Desktop: QQ sessions usable, custom fonts, lots of reliability fixes
See CHANGELOG for the full list.
Surfaces basic project metadata inside the chat without sending the user
to the docs site or package.json. Lives in the info group next to
/feedback so the discoverability path is obvious from the bare-slash
picker.
Output (EN):
Reasonix vX.Y.Z — a cache-first DeepSeek coding agent
Website https://esengine.github.io/DeepSeek-Reasonix/
GitHub https://github.com/esengine/DeepSeek-Reasonix
License MIT
URLs + license tag are constants in the handler (language-agnostic);
header + row labels go through i18n so the zh-CN bundle matches the rest
of the TUI.
Co-authored-by: reasonix <[email protected]>
Two changes:
1. `readConfig()` strips a leading UTF-8 BOM before `JSON.parse`. Windows
PowerShell 5's `Set-Content -Encoding UTF8` and several text editors
emit `EF BB BF` at the head of the file; `JSON.parse` rejects that
and throws, which used to fall through to the `return {}` branch
and silently nuke every saved field on the next read-modify-write —
you'd lose `apiKey`, `preset`, `mcp`, the whole config after one
`saveEditMode` or `markEditModeHintShown`. Reproduced reliably in
diagnostic-probe sessions; verified fixed by injecting a BOM and
confirming all 13 fields survive a normal run.
2. The trace hooks added in #1429 (`debugLogConfigWrite`,
`debugLogPresetWrite`, `debugLogPresetWriteFromDashboard`) did their
job: they confirmed every `writeConfig` callsite preserves fields,
and that no hidden bypass exists. The "preset flipped to pro after
relaunch" report was a BOM-corruption cascade, not a stealth save.
Drop the diagnostic now that the underlying bug is fixed at the
source.
Test plan:
- `npx tsc --noEmit` clean
- `npx biome check src/config.ts src/server/api/settings.ts` clean
- Manual: inject `EF BB BF` head into config.json, run `reasonix code`,
exit, confirm all 13 fields preserved (was: collapsed to 3 fields)
Co-authored-by: reasonix <[email protected]>
PR #1055 capped tool-card output but left reasoning.text, streaming.text,
and diff.hunks on every card forever. On thinking-model sessions
reasoning.text dominates the cards array: 50KB-1MB per turn x thousands
of turns drags it into the GB range until Mark-Compact gives up. The
heap snapshot in #1031 is the symptom.
Generalize elideOldToolOutputs into elideOldCardContent. Same window
(200 cards), same idempotent stub prefix, same on-disk-log pointer
message; now also stubs reasoning + streaming text and clears
diff.hunks (stats stay so the badge still renders). Streaming cards
mid-flight (streaming===true / done===false) skip elision so chunks
don't land on a stub. UserCard text is left full — user input is
small and precious.
End-to-end budget test (cards-memory-budget.test.ts) drives 1000-turn
realistic sessions and asserts state.cards retains under 10% of raw
input bytes. Measured: 5.4 MB retained vs 110 MB raw (95% off); V8
heap delta 3.4 MB with --expose-gc.
Co-authored-by: reasonix <[email protected]>
WebView reload flashes a white frame and drops React state (open
composer, in-flight gates) — packaged apps shouldn't expose browser
shortcuts users hit by reflex. Gate on !import.meta.env.DEV so the
dev workflow still has the escape hatch if HMR ever gets stuck.
Co-authored-by: reasonix <[email protected]>
REASONIX_DEBUG_PRESET=<path> turns on a timestamp + stack trace at three
points: the writeConfig() sink (catches any path that goes through it),
the savePreset() callsite, and the dashboard /api/settings PATCH branch
that mutates cfg.preset directly. Zero-cost when the env var is unset.
Co-authored-by: reasonix <[email protected]>
Windows users reported the desktop window booting into a near-black
screen with `rpc_spawn failed: rpc already spawned` in DevTools. Two
issues conspiring:
1. The Rust `rpc_spawn` command errors out if the Node child is already
running. Any path that remounts the React effect (WebView reload via
DevTools F5, host-side respawn, transient re-render) hits this and
logs to console.
2. Node's bootstrap events (`$tab_opened`, `$settings`, `$needs_setup`,
`$ready`) are fire-once during `bootstrapTab`. A reloaded React app
never receives them — the Setup view stays in its initial state and
structural copy renders against unset CSS variables, so the user
sees a mostly-empty dark window.
Make `rpc_spawn` idempotent (a second call is a no-op for the spawn
itself) and have the frontend follow up with a new `desktop_resync`
command. The Node handler walks every live tab and re-fires the
bootstrap events; the reducers already dedupe by tab id so an extra
emit on the fresh-spawn path is harmless.
Co-authored-by: reasonix <[email protected]>
The POST /settings handler rejected an empty baseUrl with 400, so once
a user had typed a base URL into the dashboard they could only edit it,
never clear it — the only way back to the default was hand-editing the
JSON config. Treat empty / whitespace-only as "clear" instead: drop the
key from disk so loadBaseUrl() falls through to DEEPSEEK_BASE_URL or the
built-in default on next start. GET continues to surface null when the
key is absent, which the dashboard already renders as an empty input.
Closes#1409
Co-authored-by: reasonix <[email protected]>
* fix(ui): map mouse wheel to single-row scroll, not page
Wheel ticks were routed to scrollPageUp / scrollPageDown (5 rows each).
Most mice emit 2-5 SGR mouse reports per physical notch, so one flick of
the wheel jumped the buffer by 10-25 rows — what the issue describes as
"abnormally sensitive". Splits wheel into its own action backed by
SCROLL_WHEEL_ROWS=1 and leaves PgUp / PgDn on the page step. PlanConfirm
detail pane gets the same treatment so the modal scroll matches.
Closes#1419 (first half).
* fix(ui): collapse per-card stdout resize listeners into one broadcaster
Ink's useBoxMetrics calls stdout.on('resize', ...) once per mounted
card. A long chat legitimately holds dozens, so any fixed cap is a
band-aid — the previous setMaxListeners(200) just delayed the
MaxListenersExceededWarning, it didn't fix it.
Shim stdout.on / .off for the 'resize' event into a single subscriber
Set with one real native listener. Ink's per-card subscribe path is
unchanged but no longer touches Node's EventEmitter accounting. Install
before render() so Ink's own constructor-time subscribe is shimmed too.
Closes#1419 (second half).
---------
Co-authored-by: reasonix <[email protected]>
Refuse text edit blocks when the SEARCH content matches more than once in the target file. This keeps the `/apply` path aligned with `edit_file` behavior and prevents silently modifying the first matching occurrence when the model did not provide enough context.
Update the edit block test to assert that ambiguous SEARCH text leaves the file unchanged.
Co-authored-by: Cursor <[email protected]>
* chore(desktop): document writeAllSync + drop redundant optional chain on caught err
* feat(subagent): live byte progress + top-level explore/research/review tools
The "subagent looks frozen" UX problem had two roots — fixed both, with
one architectural change and one set of progress affordances.
1. Sink wiring (the actual bug): `buildCodeToolset` runs before the TUI
mounts, so its `subagentRunner` closure can't capture a sink ref.
Introduce `SHARED_SUBAGENT_SINK` — a process-wide `{current: null}`
singleton both sides reach through. Setup reads `.current` at
dispatch time; `useSubagent` writes `.current` on mount. The wiring
resolves itself in time order without prop-drilling through
`chatCommand`. Tests / library callers can override via the new
`subagentSink` option on `buildCodeToolset`.
2. Live byte counters: `spawnSubagent` now emits throttled
`stream-progress` events carrying monotonic `outputChars`,
`reasoningChars`, and `toolReadChars`. `SubagentRow` renders these
as `↓ read X · ↑ out Y · ◆ think Z`. `OngoingToolRow` carries the
same line as a fallback (so the bytes show even if the rich
SubagentRow is off-screen) and adds `args N B` for any in-flight
tool dispatch.
Two unrelated improvements bundled:
3. Top-level subagent tools: `explore` / `research` / `review` /
`security_review` registered as siblings to `read_file`. Same
`subagentRunner` path as `run_skill(name="explore", ...)` — the
surface change is purely affordance. Models pick the tool whose
name matches the verb in the question; the `run_skill` meta-API
was too indirect. Empirically lifts the model's "spawn vs chained
read_file" decision toward the right choice on broad audit
queries. User-defined skills still flow through `run_skill`.
4. `forceSummaryAfterIterLimit` now passes `thinking: "disabled"` —
the task is "paraphrase tool results into prose", which needs zero
reasoning. Pinning was `thinking: enabled` + `reasoningEffort:
high` and burning reasoning tokens on every storm-breaker /
context-guard summary.
Verification:
- `npx tsc --noEmit` clean
- `npx biome check src` clean
- Full suite: 3420 passed / 9 skipped
- New tests: 7 cases for the top-level wrappers (registration,
dispatch, model→skill name mapping for security_review, no-runner
error, empty-task guard, inline-override bounce)
---------
Co-authored-by: reasonix <[email protected]>
Desktop runTurn checks its own outer aborter after each yielded event and
break's out of the for-await on stop. That calls generator.return() on
loop.step(), which throws into the suspended yield and skips any
straight-line code after it. Both abort handlers (iter-start and
in-flight) had `_turnAbort = new AbortController()` after the bail-out
yields, so the reset never ran when the consumer broke early. The next
step() then carried the stale aborted state via the carry-abort check at
the top and re-fired the "在第 0 次工具调用处中断" warning at iter 0
without making any API call — every subsequent user message in the
session was effectively dead until restart.
Move the reset into a finally block in both handlers so generator.return()
still runs it. Existing turn-bleed test only drained events to completion
and didn't catch the consumer-break path; added a regression that mirrors
the desktop pattern (break right after the abort warning yield).
Co-authored-by: reasonix <[email protected]>
End-to-end validation showed model-driven spawn_subagent loses 5× vs
no-spawn baseline due to spawn storms; the orchestrator topology RFC
is moot since production already routes subagents through named skills
(/explore, /research, /review, /security-review) rather than a
free-form model-callable tool. The 9 probe scripts existed to measure
the deferred-cost case for an unshipped model-spawn surface and no
longer have a referent.
Co-authored-by: reasonix <[email protected]>
Refs #1285 / #1306.
The lifecycle state machine in `src/code/lifecycle.ts` already exposed a `checkpoint` state but the runtime never entered it — checkpoint pauses ran through `approved`/`executing` instead. That meant high-risk mutations weren't gated while a checkpoint was waiting on continue/revise/stop, and a stopped checkpoint could leave the lifecycle in an execution-shaped state instead of cleanly cancelling.
- New `EngineeringLifecycleRuntime.recordCheckpointReached()` — flips `approved` / `executing` → `checkpoint`. `guardToolCall` already blocks high-risk mutations when state isn't `approved` or `executing`, so the new transition picks up gating for free.
- `App.tsx` plan-checkpoint hook calls it as soon as the gate fires.
- If the user picks `stop` at the checkpoint, `App.tsx` now calls `lifecycle.cancel()` so the lifecycle ends cleanly instead of staying mid-flight.
Tests cover the gated-mutation path and the clean-cancel path.
`npm run verify` was OOMing on 16-core hosts mid-run with V8 `Zone Allocation failed`, causing cascading flake (`spawn UNKNOWN`, dashboard 21s timeouts, `jobs.tailLines` mismatches).
Root cause: vitest defaults to `pool: "threads"`, so all worker threads share one Node process's ~4GB heap. With 16 cores, ~15 workers × ~300MB each — each loading the tokenizer BPE + tree-sitter wasms + sqlite handles — blows past the heap cap. `retry: 1` doubles transient state on flakes.
Switch to `pool: "forks"` with `maxForks: 8` so each test file runs in its own process with its own heap; process exit frees everything. Costs ~20% wall-clock (62s → 74s on this box) for full isolation.
3412 tests / 244 files pass, no OOM, no `spawn UNKNOWN`, no zone-allocation failures.
The end-to-end `run_background → list_jobs → wait_for_job → job_output → stop_job` test added in #1400 (`tests/shell-tools.test.ts:647`) used the default 5s vitest timeout. On Windows the full chain — Node child spawn + 500ms `wait_for_job` + SIGTERM grace inside `stop_job` — runs ~3-8s depending on load. Verified failing on plain main under moderate load.
Raise the per-test timeout to 15s. No functional change.
Refs #1285 / #1301 / #1306.
The repeated-rejection guard in `ToolRegistry.dispatch` already sharpens the error message when the model retries the same lifecycle interceptor rejection. Two gaps:
1. **Sensitive to JSON key order.** `{command, cwd}` vs `{cwd, command}` fingerprinted as different calls, so the guard didn't fire on a real retry.
2. **Only triggered on structured `rejectedReason` payloads.** Plain-text host denials (`run_command` / `run_background` `user denied:` and `edit_file` / `write_file` `User rejected this edit`) flew under the guard, so the model could keep submitting the same shell or edit until the user gave up.
- `fingerprintArgs` now runs JSON through a recursive key-sort before stringify; `rawFingerprintArgs` keeps the literal string path for invalid-JSON malformed feedback.
- New `plainTextRejectedReason()` recognises shell-gate and edit-gate text patterns and tags them with a `rejectedReason` for the storm guard.
- `rejectionRecoveryHint()` returns per-reason guidance instead of a single generic hint, so the second-rejection error message names the actual escape hatch (allowlisted command vs different edit vs revise plan).
- Internal `_lastInterceptorRejection` → `_lastGateRejection` rename reflects the broader scope.
Test coverage: lifecycle gate with reordered keys; shell-gate corpus across `run_command` / `run_background`; edit-gate corpus.
Refs #1285 / #1306 / #1302.
The plan store already persists structured step evidence from `mark_step_complete`, but the scrollback only shows generic "step N/M complete" progress. During an active engineering lifecycle that means verification / diff / checkpoint / manual evidence stays buried in the plan state and only appears via `/plans show`.
Adds a compact ghost-styled scrollback line right after the step-progress line when `mark_step_complete` returns structured evidence:
```
evidence: verification - lifecycle tests passed (npm test -- tests/lifecycle.test.ts); diff - runtime transition added (src/code/lifecycle.ts, tests/lifecycle.test.ts)
```
- New `formatStepEvidenceSummary` / `formatStepEvidenceItem` helpers in `src/cli/ui/hooks/handle-tool-event.ts`.
- Path list capped at first 3 to keep the line tight.
- Plan store format unchanged.
New `tests/handle-tool-event.test.ts` covers the formatting path with a mocked Scrollback.
Refs #1285 / #1306.
Previously the App handled an accepted plan revision by replaying state through `recordPlanApproved(merged)` + a loop of `recordStepCompleted()` calls. That round-trip resets approval state and can clear mutation-evidence obligations earned during the steps that were already done — which weakens the reliability rail right after a redirected step.
- New `EngineeringLifecycleRuntime.recordPlanRevised(remainingSteps)` — first-class lifecycle transition for accepted revisions.
- Keeps already-completed steps in `_planSteps`, replaces only the remaining tail.
- Preserves `mutatedSinceLastStep` so the next `mark_step_complete` still needs evidence.
- App `applyPlanRevision` switches from the replay loop to the single API call.
Test coverage: revision keeps completed steps + new tail; revision after a mutation still requires evidence for the next step.
Refs #1285 / #1306.
After #1306, strict lifecycle is opt-in, but the App had no way to tell `/plan off` (an explicit user request to leave) apart from the internal plan-mode shutdown that happens after plan approval. Result: lifecycle rails could stay armed even after the user explicitly asked to leave.
Threads a `PlanModeToggleSource` through `togglePlanMode` so the slash-driven path can release the lifecycle while the internal post-approval path preserves it.
- `/plan off` → release strict lifecycle immediately
- internal plan-mode shutdown after approval → keep lifecycle execution state intact
Refs #1343 — clearer desktop QQ path and a slimmer top-level README.
- README.md / README.zh-CN.md: trim QQ section to a short overview + entry points, link out to the dedicated guide. The full tutorial belonged in `docs/qq-connect.md`, not the top-level README.
- docs/qq-connect.md: new "Desktop quick start" with the actual button flow (`Settings -> General -> QQ Channel -> Configure -> Save and connect`) + the active-tab binding note, plus a troubleshooting case for "configured but no round-trip."
- docs/qq-connect.zh-CN.md: mirrors the English changes; replaces English desktop labels with the real Chinese i18n labels (`设置 -> 通用 -> QQ 通道`, `配置`, `沙箱` / `正式`, `保存并连接`). Verified all label strings exist in `desktop/src/i18n/zh-CN.ts`.
Fixes#1305 — Desktop ContextPanel shows stale token counts after `/compact`.
`/compact` is a local operation (no API call), so the `model.final` usage event that normally refreshes `cacheHitTokens` / `cacheMissTokens` never fires. The meter stays pinned to pre-compact numbers until the next real API turn.
- New `ContextManager.getLogTokens()` — sums `countTokensBounded(content)` per message (plus assistant `tool_calls` JSON when present).
- `Loop.getCurrentLogTokens()` forwards to it.
- `$ctx_breakdown` event gains an optional `logTokens` field; `emitCtxBreakdown()` populates it.
- `compact_history` handler emits `$ctx_breakdown` on success so the panel refreshes immediately.
- Frontend resets `cacheHitTokens=0`, `cacheMissTokens=logTokens` when `logTokens` is present — a transient calibration; the next real API turn overwrites both with actual usage numbers.
The token count is approximate (skips role markers + DSML wrappers), which is fine for a UI meter — directionally correct is what matters here.
The top-level `run_command` description already enumerates the chain operators / redirects / rejected forms. The `command` parameter's own description repeated the same list verbatim — 432 chars of duplicated syntax docs the LLM was paying for on every uncached turn.
Schema token cost: 415 → 296 (−119, −28.7% on this tool). Total fixed-prefix tool tokens: 6997 → 6878. All 106 `tests/shell-tools.test.ts` cases pass — the trimmed text contained no decision-making content, only restated syntax the top-level already covered.
Verified via `scripts/measure-tool-token-cost.mts`.
`scripts/measure-tool-sizes.mts` reports byte counts — useful for compression planning but not what gets billed. The prompt-token cost is what the V4 BPE charges, and byte count is only a rough proxy. This script measures the real thing.
`scripts/measure-tool-token-cost.mts` registers the full tool suite in a tmp workspace, dispatches each with a representative input, and reports schema / args / output token counts using `src/tokenizer.ts`. Gate-bound tools (`submit_plan`, `ask_choice`, …) are skipped because they block on the user. Every non-skipped tool executes against real filesystem / shell / mocked-fetch state, so the table doubles as a boundary smoke check.
Current snapshot: 35 tools, ~7000 schema tokens fixed per turn (cache-miss rendering — actual cost is ~120× lower once cache is warm). Top spenders: `run_command`, `submit_plan`, `glob`, `install_skill`, `create_skill`.
Closes dispatch-level E2E gaps in the tool suite — 7 registered tools had unit coverage of their `fn` but were never exercised through `ToolRegistry.dispatch()`, so the boundary itself (plan-mode gating, parallel-safe checks, error wrapping, result augmentation) wasn't tested for them.
- `shell-tools`: new dispatch tests for `run_background` / `job_output` / `stop_job` / `list_jobs` — full start → list → read → stop round-trip, plus not-found and `cwd`-escapes-workspace cases.
- `web-tools`: dispatch tests for `web_search` (mocked Mojeek fetch) and `web_fetch` (mocked HTML).
- `tools-scaffold`: switched the in-file `call()` helper from `def.fn(args)` to `reg.dispatch(name, JSON.stringify(args))` — all 16 existing `create_skill` / `add_mcp_server` tests now flow through dispatch with no per-test churn.
Net: 3388 → 3394 passing tests.
Strip constant pool, debug tables (`LineNumberTable`, `LocalVariableTable`, `StackMapTable`), and `Compiled from` header from `javap` output — large generated classes (protobuf, ANTLR) were hitting the 10MB buffer limit, and the constant pool accounted for most of the output (useless for an AI reading it). Roughly 60–80% token reduction on those classes.
Also raises `javap` `maxBuffer` from 10MB to 15MB as a safety margin, and reorders the tool description so `className + jarKeyword` is the documented default — encourages the LLM to pass a keyword instead of scanning the entire `~/.m2/repository`. The schema is unchanged; `jarKeyword` remains optional.
readConfig() previously cast JSON.parse output to ReasonixConfig with no runtime validation. Hand-edited config.json could put objects, numbers, or null into fields typed as `string[]` (mcp, mcpDisabled, recentWorkspaces, skills.paths), corrupting downstream consumers — see #1295 / #1394 where non-string mcp items reached JSX and crashed the desktop tools panel.
- New `sanitizeStringArrayField` in `src/config.ts` drops non-string items at the boundary and warns once per field with the file path + dropped count.
- Removes the now-dead downstream defenses (#1394's filter in `emitMcpSpecs`, `typeof` ternaries in `context-panel.tsx` / `settings.tsx`, `summarizeMcpSpec`'s non-string catch). `summarizeMcpSpec` no longer needs to be exported.
- Test file renamed to `config-sanitize-string-arrays.test.ts` and rewritten against `readConfig` (where the validation actually lives).
Closes#1395
Fixes#1295 — Desktop MCP tools panel crashes with React error #31 ("Objects are not valid as a React child") when `config.json` contains non-string items in the `mcp` array.
Root cause: `readConfig()` does `JSON.parse` without runtime validation, so `cfg.mcp` can contain objects even though it's typed as `string[]`. When `summarizeMcpSpec()` threw on these object inputs, its catch block returned `summary: raw` directly, leaking objects into JSX.
Fix:
- `summarizeMcpSpec` catch block — stringify non-string `raw` before returning.
- `emitMcpSpecs` — filter `cfg.mcp` to string items before mapping.
- `CtxTools` / `PageMCP` — render `summary` / `name` only when string.
- Regression test in `tests/mcp-desktop-react31.test.ts`.
Follow-up tracked separately: tighten `readConfig` with zod schema validation so this boundary check lives in one place.
* feat(code-query): tree-sitter get_symbols + find_in_code tools for TS/TSX/JS
Two grammar-aware tools for single-file code structure queries, scoped
per the #556 RFC's "narrowly-scoped one-tier pilot" constraint.
- get_symbols: outlines top-level + nested symbols (function, class,
method, interface, type, enum, namespace) with 1-based positions
- find_in_code: identifier search with role classification (call /
definition / reference), AST-filtered so comments + string literals
do not match; handles `new X()` and `obj.X()` as calls on X
Bundles tree-sitter-typescript + tree-sitter-javascript wasm from the
official npm packages (~3.4 MB in dist/grammars/). Non-TS/JS files
return an "unsupported; use search_content" hint. Within-file only —
cross-file resolution stays out of scope per the RFC.
Closes#556
* feat(code-query): extend to Python / Go / Rust / Java
Adds 4 grammars beyond the TS/TSX/JS/JSX pilot: tree-sitter-python,
tree-sitter-go, tree-sitter-rust, tree-sitter-java. Total bundled
grammar wasm now 5.5 MB.
Per-language symbol queries land function / class / method / interface /
type / enum / namespace / property kinds with consistent shape. Methods
detected via post-process when a `function_definition` / `function_item`
sits inside a class, impl, or trait container; Rust impl blocks set the
parent name from impl's `type` field so `impl Foo` and `impl Trait for
Foo` both attribute methods to Foo.
find_in_code's classifier learns each language's call shape:
- Python `call`, Java `method_invocation`, `object_creation_expression`
- Go selector_expression, Rust field_expression, Python attribute, JS
member_expression — all handled uniformly via field-name lookups so
obj.X() is a call on X across languages
---------
Co-authored-by: reasonix <[email protected]>
`/btw` with no question silently returned in desktop/src/App.tsx:1267,
matching the slash-command picker's behavior of pre-filling "/btw " —
users who hit Enter without typing a question saw nothing happen at all
(#1370).
Push a status message with the usage string when the payload is empty,
and re-fill the draft with "/btw " so the user can immediately type
the question without retyping the slash. New `push_status` reducer
action backs this and stays available for other client-side hints.
Closes#1370.
Co-authored-by: reasonix <[email protected]>
The final tier of the proxy UX work. After Tier 1/2 wired NO_PROXY,
the DeepSeek-bypass default, the CLI flag, the env override, and the
config field, users still had no way to see what actually applied —
`reasonix doctor` just printed the proxy URL.
Add a separate `proxy routing` doctor check below the `http proxy`
line that shows:
- Pattern-count summary by source: defaults, env NO_PROXY,
REASONIX_NO_PROXY, cfg.proxy.noProxy.
- Routing simulation for three probe hosts (api.deepseek.com /
github.com / api.github.com) — "direct" or "via proxy" — so a
CN user with clash sees at a glance that DeepSeek bypasses but
GitHub still routes through, and they can immediately tell whether
their NO_PROXY layering matches intent.
The proxy-routing simulator and installProxyIfConfigured both go
through a new shared `resolveNoProxy()` helper so the two paths
can't drift apart.
Co-authored-by: reasonix <[email protected]>
Tier 1 (#1373) honored NO_PROXY at the env level and baked the DeepSeek
bypass into the default whitelist. Tier 2 layers app-specific overrides
on top so users don't have to fight system-wide env vars:
- `--no-proxy` CLI flag on the top-level program, code, chat, and run
subcommands. Detected by argv peek before commander runs so it takes
effect for the same boot that argv set it.
- `REASONIX_NO_PROXY` env var — parsed with curl-style syntax, additive
on top of system `NO_PROXY`. Pattern matches GitHub CLI's
`GH_HTTPS_PROXY` shape (app override > system env).
- `cfg.proxy.disabled` / `cfg.proxy.noProxy` config fields — persistent
per-user override, loaded via new `loadProxyConfig()` reader.
Precedence: --no-proxy / cfg.proxy.disabled short-circuit the install
entirely. Otherwise default whitelist + env NO_PROXY + REASONIX_NO_PROXY
+ cfg.proxy.noProxy all merge additively.
Co-authored-by: reasonix <[email protected]>
Reasonix's proxy hookup (#646) installed undici's ProxyAgent globally
without checking NO_PROXY. CN users with HTTPS_PROXY pointed at clash /
v2ray would route api.deepseek.com through their foreign-exit pool, land
on an abused shared IP, and 403 — even though the API host is in CN and
shouldn't need a proxy at all.
Route around it: ship a SelectiveProxyDispatcher that picks the proxy or
a direct Agent per-request based on a curl-style NO_PROXY pattern list.
Default whitelist (always applied) covers api.deepseek.com / *.deepseek.com
/ localhost / 127.0.0.1 / ::1; user-set NO_PROXY entries layer on top.
Startup now logs '[proxy] using <url> (NO_PROXY: ...)' so the routing
decision is visible without /doctor.
Co-authored-by: reasonix <[email protected]>
src/tools/filesystem.ts aliased SKIP_DIR_NAMES directly to the semantic
indexer's exclude list (DEFAULT_INDEX_EXCLUDES.dirs), which contains
'.reasonix'. The indexer correctly skips that path so session logs and
caches don't get embedded — but the same alias made search_files,
search_content, directory_tree, and glob blind to user skills living
at <root>/.reasonix/skills/ and ~/.reasonix/skills/. Agents would see
the skill in /skills but report 'no skill found' when search_files
went looking for it.
Decouple the two: filter '.reasonix' out of SKIP_DIR_NAMES while
leaving DEFAULT_INDEX_EXCLUDES.dirs untouched. Indexer behavior is
unchanged; FS tools now reach into .reasonix/ on a normal walk.
Closes#1357.
Co-authored-by: reasonix <[email protected]>
Both desktop renders swap in the ¥ symbol when the wallet currency is
CNY but forget to multiply the underlying USD value by the 7.2 FX
factor:
- desktop/src/ui/statusbar.tsx — formatMoney() emitted '¥ <usd>'
- desktop/src/ui/settings.tsx:1023 — billing card emitted '¥ <usd>'
Result: a turn that costs ~$0.14 (the actual DeepSeek deduction is
~¥1.03) showed as '¥ 0.1428' — wrong by roughly the FX rate. The
TUI's tokens.ts formatCost has done this conversion correctly all
along; only the desktop forgot. The costCurrencyHint copy already
claimed the conversion happens, which is what masked the regression.
Closes#1354.
Closes#1367.
Co-authored-by: reasonix <[email protected]>
Two follow-ups to #1350:
1. Perplexity / Exa landed without unit tests, while tavily has 5
covering missing-key / 401 / 429 / parse-error / body shape. Mirror
that pattern so a fetch-shape change in either backend can't regress
silently. Also add a formatSearchResults case for the new "answer +
sources" dual-section branch.
2. Drop the `// ── Perplexity ──` / `// ── Exa ──` / `// ── API-key
engines ──` section-banner separators — CLAUDE.md bans them; group
by export instead.
Co-authored-by: reasonix <[email protected]>
* chore(java): strip section-banner comments and module-header essays
#1344 followed conventions from a different codebase — `// ── types ──`
banner separators, multi-line module-header essays, and JSDoc-style
`@param`/`@returns` text restating type signatures. CLAUDE.md bans all
three. Trim to plain code with comments only on hidden constraints or
non-obvious invariants.
No behavior change; all 41 java-source tests still pass.
* test(java-source): isolate project-search tests from real ~/.m2 cache
Three searchProject tests ("returns not-found", "skips common non-source
directories", "handles empty project root gracefully") were walking the
real ~/.m2 / ~/.gradle defaults — fine on a fresh CI runner, flaky on a
dev machine with a populated cache under full-suite I/O contention.
- Pass repoPaths: [] so the not-found path skips the jar scan entirely.
- Bump per-test timeout to 30s as a defensive cap; the searches now run
in ms, but Windows AV scanning of fresh tmp dirs can still spike.
---------
Co-authored-by: reasonix <[email protected]>
#1331 added augmentProcessPath() in desktopCommand so the Tauri-spawned
Node could see nvm/asdf/fnm/volta/mise PATH entries — the GUI process
never runs the user's shell init. #1334 was branched before #1331 landed
and the rebase dropped the import + call without it being part of the
QQ-runtime work.
Re-add the import and the call site, no behavior change beyond restoring
the previous fix.
Co-authored-by: reasonix <[email protected]>
0.47.1 published with @reasonix/core-utils as a runtime dependency
pinned to workspace:*. Because the workspace package is private:true,
npm publish did not rewrite the protocol literal, breaking install with
EUNSUPPORTEDPROTOCOL on consumer machines.
The bundled dist/ already inlines core-utils at build time — it is not
needed at runtime. Move it under devDependencies.
#1043 (in 0.46.0) flipped read_file from "head+tail+outline preview"
to "full content for files ≤ 512 KiB" on the theory that the prompt
cache amortizes the cost. Multiple users have reported significantly
higher token consumption since — and they are right: cache hits cost
~10% of input price, so a 10× bigger tool result still pays 10× more
on the hit path, plus full miss price on first read.
Drop the default to 64 KiB, which covers ~99% of source files in
real-world repos while pushing generated bundles, lockfiles, novels,
and other genuinely large files into outline mode (head + symbol map
+ drill-in hints). Users who really want the old behavior can set
`filesystem.outlineThresholdBytes: 524288` in config.
config.ts gets a new `filesystem.outlineThresholdBytes` field plus a
`loadFilesystemOutlineThresholdBytes` loader that returns undefined
on unset / non-positive / non-numeric values, letting the registered
default win. setup.ts wires the loader into registerFilesystemTools.
Expected savings: 5-15k tokens per typical session, depending on how
many >64 KiB files the user touches. read_file's own description was
already updated to reflect "FULL CONTENT for files ≤ N KiB" via the
existing interpolation, so the tool description shifts to "≤ 64 KiB"
automatically.
Co-authored-by: reasonix <[email protected]>
The system prompt was 24,387 bytes (≈ 6,100 tokens) — much of it
overlapping with the tool descriptions sitting right next to it in
the cache prefix. Sections like "When to propose a plan", "When to
ask the user to pick", and "When to track multi-step intent" each
recited rules that the tool's own description already carried.
Aggressive dedup pass:
- Drop the redundant "you have these filesystem tools" opening
sentence — the API ships the tool list separately.
- Merge the three independent submit_plan / ask_choice / todo_write
sections into one short "Picking the right tool" block.
- Fold "Exploration", "Trust what you already know", and "When the
user wants to switch project" into shorter equivalents — same
rules, no narrative.
- Collapse the foreground/background section. The full how-to lives
in the run_command / run_background tool descriptions; the prompt
only needs the picking rule.
- Compress the audit-mode rails (#610) prose around the six rails
themselves. Every rail's load-bearing phrase is preserved verbatim
so tests/code-prompt.test.ts still asserts on them.
Result: 24,387 → 11,956 bytes (-51%, ≈ 3,100 tokens per request).
Combined with PR #1320 / #1321 the cache-prefix tax per request is
now ~16k tokens instead of ~36k.
Behaviour unchanged — every rail / gate / mode constraint is still
asserted by the existing prompt tests.
Co-authored-by: reasonix <[email protected]>
Every byte of a tool's description and JSON-schema parameter blob ships
in every request. The spec list had grown to 39,377 bytes (≈ 10k tokens)
across 35 tools — much of it teaching guidance that was already covered
in the system prompt, plus verbose schema property descriptions that
restated what the parameter name already conveys.
Compress the heaviest twelve tools while preserving the actually
load-bearing rules (don't-use-for-A/B/C-menus on submit_plan, plan-mode
gate behavior on run_command, prefix-stable warning on remember):
submit_plan 3517 → 1648 (-53%)
revise_plan 2554 → 1482 (-42%)
create_skill 2379 → 1367 (-43%)
install_skill 2293 → 1510 (-34%)
search_content 2167 → 1263 (-42%)
mark_step_complete 1988 → 1037 (-48%)
add_mcp_server 1898 → 1213 (-36%)
run_command 1862 → 1376 (-26%)
todo_write 1675 → 872 (-48%)
ask_choice 1807 → 1313 (-27%)
remember 1812 → 1306 (-28%)
run_background 1611 → 1186 (-26%)
Total: 39,377 → 28,412 bytes (-28%, ≈ 2,740 tokens per request).
Behaviour unchanged — guidance that lived only in tool descriptions
(plan-mode interaction, ChoiceRequestedError stop semantics, prefix
re-load timing) is preserved verbatim. The system prompt and tool
error messages already carry the longer-form teaching content.
scripts/measure-tool-sizes.mts added so future audits don't have to
re-derive per-tool byte counts by hand.
Co-authored-by: reasonix <[email protected]>
Every byte of the system prompt and tool spec list ships in every
request — paid at full miss price the first time and ~10% on every
subsequent cache hit. Recent PRs have grown both without anyone
tracking the cumulative cost.
Lock the current values:
- CODE_SYSTEM_PROMPT.length ≤ 24_500 bytes
- code-mode tool spec list ≤ 40_000 bytes
- no single tool description > 8 KiB
A failing assertion forces the PR author to either compress an
equivalent section or raise the budget explicitly with a
justification in the commit message — visible in code review.
Co-authored-by: reasonix <[email protected]>
Restores the `devtools` Cargo feature dropped in #1188 and removes the
contextmenu suppression. The original lockdown treated end users as
needing protection from the inspector; for an open-source dev tool
that argument inverts. Users can right-click → Inspect or use the
standard Cmd+Option+I / F12 shortcut to get a real console for bug
reports — which we lost any cheap path to after #1188 + #1297-class
issues started landing without reproducer info.
Reverts #1187 / #1188.
`/search-engine tavily` silently fell back to Mojeek and got 403s,
two bugs stacked:
1. `webSearchEngine()` only branched on `searxng` / `metaso`; `tavily`
slipped to the `mojeek` default. Add the missing arm.
2. `registerWebTools` cached the engine + endpoint at registration
time via opts, so a runtime `/search-engine` switch never reached
the tool fn. Drop both opts; read fresh inside the dispatch.
Closes#1309
`powershell.exe` runs under conhost, which repaints each Ink frame
visibly — at 8Hz spinner + 20Hz streaming flush, a maximized window
shows continuous flicker and content "jumping" during model reasoning.
Windows Terminal double-buffers, so this is conhost-specific.
Detect legacy conhost (win32 && !WT_SESSION && !TERM_PROGRAM) and
drop FAST_TICK_MS 120→250 and the default FLUSH_INTERVAL_MS 50→150
on that path. Modern terminals see no change. Reasoning streaming
goes from ~28Hz total repaints to ~11Hz on conhost.
Closes#1300
About-modal's "Check for updates" was a raw WebView `fetch()` to `api.github.com`, which the Tauri CSP (`connect-src 'self' ipc: http://ipc.localhost`) blocks before the request leaves the browser. Switch to `check()` from `@tauri-apps/plugin-updater` — same R2 endpoint as the background auto-check, IPC → Rust, not bound by CSP. Drops the bespoke `cmpSemver` and the orphaned `checkNoRelease` i18n key.
Switch heap re-exec to resolve the child entrypoint from `import.meta.url` instead of `process.argv.slice(1)`, preserve the parent's `execArgv` (so `--inspect` survives the relaunch), and treat Vitest workers as already-reexec'd so tests don't get process-replaced.
Adds optional `targets`/`acceptance`/`verification` to plan steps, structured `evidence` on `mark_step_complete`, and a v2 plan-store schema with v1 read fall-through. Final-step checkpoint UX flips to a finish/summarize label. Exposes `requireStepEvidence` and `onPlanStepCompleted` as host hooks; no caller wired here.
Adds `ToolRegistry.addToolInterceptor(id, fn)` for ordered host-side interceptors; legacy single `setToolInterceptor` keeps working and runs after the chain. Intercepted short-circuit results now flow through the existing result augmenter, matching the normal tool-result path.
Thanks @dimasd-angga — surfacing the per-call gate in three first-run spots is exactly the right scope, and the tests pin it down well. CI tripped on a one-line biome wrap in zh-CN.ts; fixing that on main in a follow-up.
R2 path and GitHub release-asset URL were still built as `v${version}`,
but desktop bundles now live under `desktop-v${version}` after the
release-namespace split (#1153). Every Download-page link 404'd.
The docs site hardcoded `window.REASONIX_VERSION = "0.45.1"` in
i18n.jsx. Every release that didn't remember to bump that line left
the install commands, mirror grid, footer badge, terminal demo and
hero badge stuck at a stale value — and the bump was easy to forget
because no test catches it. By the time CLI was at 0.46.1 the docs
still read 0.45.1.
Read it dynamically from R2's `latest/latest.json` (which the release
mirror already keeps up to date, and which is desktop-release-owned
since the latest.json artifact only comes from desktop bundles). The
fetch kicks off as i18n.jsx loads, sets `window.REASONIX_VERSION` and
`window.REASONIX_VERSION_STATUS`, dispatches a `reasonix:version`
event when it settles.
`useVersion()` (a new hook in i18n.jsx) subscribes to that event and
returns `{ version, status: "loading" | "ok" | "failed" }`. Each
consumer renders a localised "正在获取…" / "fetching…" string while
status === "loading"; the mirror grid swaps its whole panel for a
"fetching latest version…" line because its URLs aren't usable yet.
On hard failure (5s timeout or non-2xx) we say so explicitly rather
than fall through to a stale literal — the previous behaviour was
already a stale literal, so "fetch failed" is a strict improvement.
No hardcoded fallback in i18n.jsx anymore; the value either comes
from R2 or doesn't come at all. The synchronous version.js shim I
prototyped first turned out worse than this — it would have meant a
console 404 on every page load until the next desktop release, and
no loading state for the in-between window.
Co-authored-by: reasonix <[email protected]>
Squash-merge of #1274 inadvertently included `效果图.png`, the preview
image the contributor attached to the PR. GitHub renders PR-body
attachments without needing them tracked; in-repo binaries just bloat
git history and rot fast.
Co-authored-by: reasonix <[email protected]>
PromptInput:
- Add backgroundColor={SURFACE.bgInput} to the round-bordered input
box, giving it a subtle dark fill that visually separates it from
the chat area above.
UserCard:
- Replace the generic Card wrapper with a custom layout:
- Left stripe: 1-column Box with backgroundColor={CARD.user.color}
(brand blue), matching the input border color.
- Card body: flexDirection="column" Box with
backgroundColor={SURFACE.bgElev} (elevated surface) and
paddingLeft={1}, creating a dark background panel.
- This gives user messages the same "blue stripe on dark panel"
visual identity as the input box.
Performance: backgroundColor does not affect Yoga layout. One extra
1-wide Box per user card adds ~1 Yoga node per message — negligible.
Before: the banner flipped to "Installing…" the moment the user clicked
Install and stayed there until the app relaunched. On a 30+ MB install
over a slow link that looked like a hang and the user had no signal
about what was happening.
Wire `pendingUpdate.downloadAndInstall((evt) => …)` to the Tauri
updater's per-chunk event stream:
- Started — capture `contentLength` if the server sent Content-Length
- Progress — accumulate `chunkLength` into a running byte counter
- Finished — pin progress to total so we don't undershoot at the end
`UpdateBanner` now renders "Downloading · 4.2 MB / 31.7 MB (13%)" plus
the existing `.meter-mini` progress bar (already styled in styles.css,
just unused). When the server doesn't advertise a content length we
fall back to "Downloading · 4.2 MB" with no bar — better honesty than
a fake ratio.
The Later button disables during install so the user can't accidentally
dismiss a half-completed download. Failure state still shows the same
"Installation failed" line as before.
i18n strings (`downloading`, `downloadingUnknown`) added in en + zh-CN.
Co-authored-by: reasonix <[email protected]>
`tauri.conf.json` was pointing the updater at
`github.com/.../releases/latest/download/latest.json`. GitHub's "latest"
is a single global pointer — every CLI patch release moves it, leaving
the desktop updater chasing a 404 (or worse, the wrong artifact set).
With desktop and CLI on independent release cadences this would only
get more painful as CLI ships more often.
Two coordinated changes:
1. `tauri.conf.json` — list the R2 manifest first
(`https://pub-147fb53b9c1e4bbf891a257968619ea7.r2.dev/latest/latest.json`)
and keep the GitHub URL as a fallback. R2 is owned by the desktop
release pipeline, so it only changes when the desktop ships; CLI
releases don't touch the `latest/latest.json` object.
2. `release-mirror.yml` — rewrite the platform `.url` fields inside
`latest.json` to `<R2_BASE>/<TAG>/<file>` before uploading to R2.
Without this the updater would fetch the small JSON from R2 but
still pull the heavy installer from github.com, defeating the
mirror. minisign signatures are bit-identical content checksums,
so swapping the URL doesn't invalidate them. Skips gracefully when
`latest.json` isn't in the release (CLI-only tags).
Public R2 base URL matches the one already hardcoded in
`docs/src/mirrors.jsx`, so the download page and the in-app updater
agree on where bundles live.
Co-authored-by: reasonix <[email protected]>
`u` used to fire whenever any non-undone edit batch sat in history, not
just while the auto-apply banner was visible. That meant a stray `u`
tap minutes (or hours) after a batch landed quietly rolled back files
the user had already moved on from. Issue #1249.
Drop the `|| hasUndoable()` half of the gate; only `undoBanner` keeps
the keybind live. Older batches now go through `/undo` (already wired,
takes an optional index), so nothing is taken away — just the
zero-friction destructive path.
The existing i18n copy already says "within the 5s banner" / "press u
within 5s", so no string changes are needed; the keybind now matches
what the UI was already telling users.
Co-authored-by: reasonix <[email protected]>
Ink writes a full ANSI frame each render; the terminal's system cursor
ends up at the bottom of that output. IMEs query the system cursor for
candidate-window placement, so fcitx5 / ibus / Microsoft Pinyin draw
their popup at screen bottom instead of next to the visual ▌. Closes
#1261.
PromptInput now emits an absolute CUP escape (`\x1b[<row>;<col>H`)
inside a render-effect, landing the system cursor on the same cell as
the visual block:
- absolute row = stdout.rows − (linesBelow + largeHint + 3 + rowsAfter),
where the constant 3 covers the blank marginTop, HintRow, and bottom
border of the prompt box; rowsAfter is parent-supplied.
- absolute col = paddingX(1) + prefix(2) + cell width of the typed
prefix on the cursor line, computed via stringCells so CJK and
paste-sentinel widths land correctly.
ComposerArea passes rowsAfter that accounts for LoopStatusRow,
ModeStatusBar, and StatusRow rendered below the prompt box.
Cross-platform: no `process.platform` guard. The earlier Windows-only
attempt (closed PRs #1222 / #1225 / #1232) used relative CUU+CUF
without `\r`, which drifted on CJK columns and skipped Linux entirely.
Co-authored-by: reasonix <[email protected]>
Two more claude-code-parity bindings:
ctrl+r — verbose mode
- New VerboseContext provided at App.tsx, toggled by global ctrl+r
keystroke. Persists across turn boundaries; resets on restart.
- ReasoningCard skips head/tail elision while verbose, rendering the
full body via the existing BodyLines slice.
- ToolCard drops the per-tool tail cap while verbose; full stdout
flows through instead of the last 2-5 lines.
- Status info row toasts the new state on every toggle.
esc esc — rewind to a previous user turn
- New loop.rewindToUserTurn(N) — mirrors retryLastUser but takes a
0-based user-turn ordinal so the picker can target any earlier
turn, not just the last one. Reuses rewriteSession for disk
persistence; in-memory log compacts even if the disk write fails.
- New session.fork reducer event splices state.cards at a given
cardId; everything from that card onward is dropped.
- New EditPicker overlay component lists user cards with previews;
↑↓ to focus, Enter to pick, Esc to cancel.
- App.tsx tracks the previous Esc timestamp; a second Esc inside
500 ms with an empty composer + no other modal collects the user
turns and opens the picker. On selection, the loop rewinds, the
cards splice, and the composer pre-fills with the original text.
/keys reference + i18n strings updated in EN + zh-CN.
Co-authored-by: reasonix <[email protected]>
Spell out that .claude/skills/<name>/SKILL.md loads alongside .reasonix/skills/
(landed in #1259) and show the OpenSpec recipe — `openspec init --tools claude`
drops openspec-* skills that invoke through /skill openspec-propose, no upstream
adapter needed. Closes#1184.
Co-authored-by: reasonix <[email protected]>
When the chat has no messages and the terminal window is resized
taller, CardStream's flexGrow=1 inner Box expands to fill all
available vertical space above the composer. Since the stream has
no cards to render, this creates a large blank gap that pushes the
WelcomeBanner just above the input — making the UI feel top-heavy
and uncentered on tall terminals.
Fix: wrap the WelcomeBanner in a flexGrow=1 Box with
justifyContent="center". This Box competes with CardStream for
the remaining space in the parent flex column. When CardStream is
empty (0 intrinsic height), the two flexGrow children split the
available space equally — so the WelcomeBanner renders near the
vertical center instead of flush against the composer.
This has no effect when the chat has messages — the WelcomeBanner
is not rendered (hasConversation is true), and CardStream retains
its full flexGrow for scrolling as before.
Refs #743
* feat(tui): surface /copy in the scroll hint + full-row background on history hints
Two complementary discoverability nudges for the existing copy-mode
entry point and the "scrolled up" state:
- CardStream's ScrollIndicator now appends `· /copy to select` after the
PgUp/wheel/↑ keys, so anyone who notices the scroll affordance sees
the copy entry next to it without digging through /help.
- Both `<ScrollIndicator>` and the two history-hint paths
(InputAreaWithHistoryHint + ComposerArea.HistoryHint) pad to the full
terminal width with `SURFACE.bgElev` background, so the row reads as a
status band instead of a stray faint line. `string-width` handles the
CJK + arrow glyphs in the localized text correctly.
New i18n key `cardStream.scrollCopy` (EN / zh-CN / types).
* feat(tui): align composer keys + visuals with claude code
- ↑/↓ now navigate prompt history (single-line) or move the per-line
cursor (multi-line). Ctrl+P / Ctrl+N kept as readline aliases.
Chat scroll is owned by PgUp/PgDn + mouse wheel + End; arrows only
scroll when the composer is hidden (chat scrolled up).
- Drop the duplicate ↑/↓ branches from the App-level picker handler
— picker selection now flows through PromptInput → historyHandoff
→ handleHistoryPrev/Next which already checks pickers first.
- Composer border: top + bottom rule only (no left/right verticals),
muted FG.meta color when active.
- StatusRow: each segment wraps in a Pill with bgElev background +
1-space padding, separated by a 1-cell gap. Dot separators removed.
- UserCard body now carries a subtle bgElev background so the user
can spot their own messages while scrolling.
- HintRow shows ↑↓ instead of ^P/^N for prompt history.
- /keys + tipMouseClipboard + scrollPgUp + scrollCopy strings updated
in EN + zh-CN. /copy reads "enters copy mode" / "进入复制模式" to
avoid the "did that just copy?" misread.
---------
Co-authored-by: reasonix <[email protected]>
#514 dropped mouse tracking because it broke native drag-select copy
and right-click. The trade was made on the assumption that every terminal
in alt-screen translates wheel→arrow for free. In practice (Windows
Terminal + PowerShell at least) that translation doesn't always fire, so
the wheel just scrolls the parent terminal's scrollback while the TUI
sees nothing. Users have been complaining about exactly this.
Re-enables `\x1b[?1000h\x1b[?1006h` at chat-command startup; the existing
SGR parser in stdin-reader.ts already maps `mouseScrollUp/Down` to
chat scroll. Disable escape fires on the `finally` cleanup, plus
`process.once("exit"|"SIGINT"|"SIGTERM")` so the sequence can't leak into
the parent shell on a hard kill.
Trade-off acknowledged: native drag-select stops working with mouse
tracking on. Shift+drag still selects in most terminals (Windows Terminal,
iTerm2, GNOME Terminal all honor the shift bypass). For users who'd
rather have native select than wheel, `mouseTracking: false` in
~/.reasonix/config.json opts out.
Co-authored-by: reasonix <[email protected]>
* feat(search): add Tavily as web_search backend — escape hatch for Mojeek 403s
Users hit "frequent 403s" with the default Mojeek backend; it's HTML scraping
with no official API and gets anti-bot'd routinely. Tavily is the LLM-agent
ecosystem's de facto answer: real JSON API, 1000 searches/month free per
account, returns LLM-ready snippets out of the box.
- `webSearchEngine` accepts `"tavily"` alongside mojeek/searxng/metaso.
- New `tavilyApiKey?: string` in config + `loadTavilyApiKey()` (env > config >
undefined). No baked-in default — the free quota wouldn't survive being
shared across the user base; missing key throws a setup-pointing error.
- `searchTavily` POSTs to api.tavily.com/search and maps 401/403/429 to
actionable hints.
- `/search-engine tavily` slash entry + EN/zh-CN strings.
- 5 new test cases — missing-key error, body wire shape, 401/403, 429,
empty-results.
Default is still Mojeek; switching is one slash command. Users who get
fed up with 403s now have a free, no-scraping path that doesn't require
self-hosting (SearXNG) or a Chinese phone number (Metaso).
* test(web): use plain-string assertion for tavily.com signup URL message
CodeQL's `js/regex/missing-regexp-anchor` rule flags `/tavily\.com/` as a
URL check that could match `evil-tavily.com.attacker.org` — it can't tell
the regex is matching inside an error-message string, not a URL field.
Switching to `.toThrow("tavily.com")` preserves the substring-match
intent (does the error mention the signup URL?) without the regex.
---------
Co-authored-by: reasonix <[email protected]>
Stage 1 of the Claude-compat layer — the cheapest 80% of "users can't copy
their Claude config / skills folder over" complaints. No behaviour change for
existing Reasonix users; new paths and aliases are additive.
MCP:
- `McpServerConfig` accepts `type` as an alias for `transport`; `"http"` maps
to `"streamable-http"` so Claude's shorter spelling Just Works.
- New `src/mcp/dot-mcp-json.ts` reads project-level `.mcp.json` from cwd; its
`mcpServers` block merges into the resolved config with project entries
winning on name collision (same precedence Claude uses for shared,
git-committed team configs).
Skills:
- `~/.claude/skills/` and `<project>/.claude/skills/` join the existing
Reasonix + .agents search roots, so a user can drop a Claude skill folder
in and it loads.
- Frontmatter aliases: `context: fork` and any non-empty `agent:` both flip
runAs to `subagent` — same semantics, different field names.
- Missing `description:` now warns to console instead of silently dropping
the skill from the prefix index (the most common "why doesn't my skill
show up" footgun).
Co-authored-by: reasonix <[email protected]>
When navigating / and @ popups with arrow keys, the active item can
fall outside the visible area because the popup-list has overflow-y:
auto but no programmatic scroll. This makes keyboard navigation
difficult when the item count exceeds the container height.
V8 finishes any non-catastrophic regex on the 2 MiB per-file cap in seconds
even on slow hardware; the previous 5 s default risked false-positives on
WSL / low-end laptops while only marginally improving the catastrophic
case (ESC tears the worker down immediately anyway). 60 s gives generous
headroom for legitimate slow patterns; ReDoS still gets caught — just after
a longer unattended wait.
Walk deadline must stay above the per-file timeout so one timed-out file
doesn't always trip the walk guard immediately after; 120 s leaves room for
a second slow file plus the rest of the walk.
Co-authored-by: reasonix <[email protected]>
Relaunching only kept the set of open tab workspaces (#933); window
geometry, the focused tab, each tab's conversation and scroll position
were all lost.
- Window — replace the hand-rolled useWindowBounds hook (debounced
save, no flush on close, unreliable window.screenX/innerWidth) with
tauri-plugin-window-state, which persists size/position/maximized
and restores them cross-platform.
- Per-tab session — desktopOpenTabs persists { dir, session, active }
instead of a bare dir; bootstrapTab reopens the conversation when
its jsonl is still readable.
- Active tab — the frontend reports focus via a tab_activate message;
$tab_opened carries an `active` flag so restore reopens on the
previously focused tab, not the last one created.
- Scroll — the transcript offset is saved per session and restored on
boot via useAutoScroll, which stays un-pinned so growth doesn't yank
it back to the bottom.
- Sidebar and context panel collapse state persist to localStorage.
Closes#1244
V8's regex engine is uninterruptible and exponential for catastrophic
patterns (`(a+)+!`, `(.+)*x`); the walk-level 15 s deadline can't help if a
single re.test wedges inside one file. Moves the per-line regex match into a
worker thread and arms a 5 s timeout per file: a wedged worker is killed via
worker.terminate(), the file is recorded as `regex timed out` in the result
footer, and the walk continues with a freshly spawned worker.
- new src/tools/fs/regex-runner.ts: singleton Worker manager with eval-mode
source so nothing has to resolve a path at runtime, AbortSignal-aware so
ESC tears the worker down immediately, and a respawn-on-timeout policy
that keeps the singleton useful across the rest of the session.
- search.ts: regex path now delegates to the runner; substring fallback
(invalid regex) stays inline. Regex-timed-out files are summarised in a
single footer line.
Zero new deps — uses Node's built-in node:worker_threads. Cold-start cost is
amortised across calls in the same TUI session.
Closes the catastrophic-regex limitation called out in #1246 / #1236.
Co-authored-by: reasonix <[email protected]>
The truncation test asserted out.length < CODE_SYSTEM_PROMPT.length +
5000. The builtin Skills index injected by applyMemoryStack has since
grown past that 5000-char slack, so the test fails even though
truncation still works.
Compare against a prompt built with a tiny .gitignore instead, which
isolates the truncation delta from fixed-size, unrelated prompt
additions — the bound no longer goes stale as the prompt grows.
- Implement regex-based slash command detection in `TabRuntime` to trigger skills
- Add `insertOnly` property to `SlashCmd` to support command insertion without immediate execution
- Update `Composer` to handle conditional execution based on `insertOnly` flag
- Include `state.skills` in `TabRuntime` dependency array for correct command matching
Pass resolved preset metadata through chat/code startup so flash remains pinned without auto escalation and the UI initializes with the correct preset label.
* fix(tools): bound search_content runtime and let ESC preempt queued tools
Three small hardening steps for the "ESC sometimes can't interrupt" complaint:
1. search_content now feeds at most 8 KiB of each line to the matcher.
A minified-JS one-liner can be MBs on a single line; both the lowercase
pass and the regex hot loop chewed through the whole thing per file, and
`throwIfAborted` only ran *between* lines so ESC was useless. Truncating
the matcher input doesn't change real-world matches (displayed slice is
already capped at 200 chars).
2. search_content honours a 15-second soft deadline across the whole walk,
checked at every directory entry. A pathological regex that wedges inside
`re.test` is still uninterruptible (V8 doesn't yield), but any sane walk
that's just slow now fails loudly instead of pinning the turn forever.
3. tools.ts central dispatch refuses to start a tool whose signal is already
aborted, returning a uniform `{ rejectedReason: "aborted" }` error. ESC
during a queued sequence (e.g. five read_file calls in flight) now stops
calls 2-5 from running to completion after the user gave up — each tool
needn't re-implement the entry-time check.
Closes#1236 — wait, #1236 is already closed; this is the follow-up the
maintainer's audit identified.
* fix(search): drop per-line truncation — accuracy regression for narrow benefit
The 8 KiB LINE_MATCH_BUDGET was the wrong axis: catastrophic regex
backtracking is exponential, so 8 KiB still hangs V8's regex engine; meanwhile
legitimate long-line files (single-line JSON dumps, source maps, generated
data) silently lost matches past the first 8 KiB. Reverts the truncation;
the 2 MiB per-file cap (pre-existing) is the real upper bound on matcher
input, and the 15 s walk deadline catches slow-but-not-infinite searches.
Catastrophic regex (`(a+)+!` shape) remains uninterruptible inside re.test —
that's a separate problem that needs a worker-thread or RE2 swap, not input
truncation.
---------
Co-authored-by: reasonix <[email protected]>
The ESC handler in App.tsx was gated on `submittingRef.current || isLoopActive()`
— neither is true during the deferred MCP bridge that runs in a mount-time
useEffect, so a server stuck in `initialize()` would pin boot for the full 60s
per-request timeout with no escape. Ctrl+C still killed the whole process, but
ESC silently swallowed.
Threads an AbortSignal from App.tsx → mcpRuntime.addSpec → McpClient.initialize
→ request, then adds an ESC condition that fires before the turn/loop branch:
when no turn is active and there are pending MCP aborters, abort them all and
log a hint pointing at /mcp for retry. The underlying client is closed in the
existing catch branch in addSpec, so the stdio child is killed cleanly.
Closes#1236
Co-authored-by: reasonix <[email protected]>
Adds remark-math + rehype-katex + katex so `$E = mc^2$` and `$$ ... $$`
blocks typeset as real equations instead of leaking raw markup. Inline
math comes from `$...$`, display math from `$$...$$`; math inside fenced
code blocks stays as code because the `pre > code` override runs first.
throwOnError: false on rehype-katex so a half-typed `$` in a mid-stream
chunk degrades to plain source instead of throwing — important because
the streaming pipeline can split tokens anywhere.
KaTeX CSS is imported once in main.tsx; Vite picks up the woff2/woff/ttf
font URLs and emits them as bundled assets, so first render is offline-
safe (no CDN fetch at runtime) — that matters for a Tauri app.
Closes#1235
Co-authored-by: reasonix <[email protected]>
The macos-universal release shard runs on an ARM64 runner, so bundle-node.mjs
was downloading darwin-arm64 Node and shipping it inside a binary advertised
as universal. Intel Macs couldn't exec the sidecar, Tauri's child spawn failed
silently, and the WebView came up blank.
Bundle script now downloads both arm64 and x64 Node distributions on darwin
and lipo's them into one universal Mach-O. CI verifies the result with
`lipo -archs` before tauri-action runs, and asserts `desktop/dist/index.html`
exists so a silent frontend build failure can't ship an empty bundle either.
Co-authored-by: reasonix <[email protected]>
International donors can send via PayPal (paypal.me/yuhuahui); domestic users
scan the WeChat Pay QR. README copy frames it as "coffee, not contract" —
donations don't buy feature priority or change issue triage, which keeps the
project's cheap-and-narrow positioning intact.
Co-authored-by: reasonix <[email protected]>
Brings the desktop's slash-command list to parity with four CLI
commands that were already in src/cli/ui/slash/commands.ts but not
plumbed through to the desktop sidecar.
Backend (src/cli/commands/desktop.ts) — three new RPC handlers
wiring to existing loop methods:
- compact_history → loop.compactHistory()
- retry → loop.retryLastUser(), emits $retry_result
- btw → side-channel loop.client.chat() with a fresh
{system, user} payload (NOT the running log),
emits $btw_result
Frontend (desktop/src/App.tsx):
- /feedback opens the GitHub new-issue URL in the system browser
- /compact, /retry fire their RPC and rely on the existing $error
event for failures
- /btw sets draft to "/btw " and the send() handler intercepts the
prefix and routes to the btw RPC. The answer appends as a status
message (UI-only, never persisted) — matches "side question, never
in context" semantics.
- $retry_result drives a retryNonce counter so the useEffect that
fills the composer fires exactly once per retry.
Refs #1220 (desktop ↔ CLI parity tracking).
The header "Export" button only copied the conversation to the
clipboard — the label promised something different than the action
delivered. Split it into two:
- Copy → full conversation Markdown to clipboard (same content
as before).
- Export → native save dialog, writes a UTF-8 .md file via a new
write_text_file Tauri command. Gated by the existing capability
system; the path comes from the OS save dialog, so it's
user-chosen.
Factor the shared Markdown rendering into formatConversationMarkdown
to drop duplication between the titlebar menu, the main-head buttons,
the command palette, and the slash-action surface.
en + zh-CN i18n updated consistently; new dialog:allow-save Tauri
capability + a copy icon added.
The desktop already persists theme / font scale / font family /
currency via localStorage, but the window itself reset to the
default 1024×720 centered bounds on every launch.
New useWindowBounds hook follows the existing useAutoScroll /
useDisableTextAssist extraction pattern: restores
reasonix.windowBounds on mount, debounces 300 ms saves on
tauri://resize + tauri://move, skips saving while maximized (that
state belongs to the OS), and gates restore on a 400×300 minimum
so corrupted data can't reopen the window in an unusable size.
App.tsx calls the hook once alongside the other persistence hooks.
decorations: false in tauri.conf.json means the WebView viewport
equals the outer window, so innerWidth/innerHeight round-trip
cleanly through setSize without frame-chrome drift.
Closes#1206
The serif font stack in theme.ts had `"Geist"` as its first entry,
but Geist is a geometric sans-serif (same one the Sans option uses).
Latin glyphs matched Geist immediately and never fell through to
Georgia — selecting Serif in Settings looked identical to Sans on
English text. CJK text changed only because neither Geist nor
Georgia covers CJK and the OS picks something up the chain.
Drop Geist from the serif stack; Georgia + Times New Roman are
built-in on macOS / Windows and widely available on Linux.
Closes#1212
The dashboard /sessions panel could only browse — to actually create,
swap, or delete a session you had to bounce to the CLI. Users got
stuck wondering why nothing was clickable.
Wire the existing onSwitchSession path through to the dashboard
context, then expose:
- POST /api/sessions/new → mint fresh
- POST /api/sessions/<name>/switch → swap into existing
- DELETE /api/sessions/<name> → unlink (409 on the active
session, 404 if missing)
GET response gains currentSession + canSwitch so the SPA degrades
gracefully in standalone mode. Panel: + New button, per-row switch
+ delete (disabled on the active row), active-session pill, falls
back to the "resume in TUI" hint when no CLI is attached.
9 new tests cover both attached + standalone paths.
Closes#1216
Two desktop UX fixes:
Per-message copy. The Ctrl+K palette only offered "copy last reply" or
"export everything"; there was no way to grab a single turn in the
middle of a long thread. UserMsg and AssistantMsg each gain a small
copy button at the bottom-right of the body. UserMsg copies raw text;
AssistantMsg concatenates `.kind === "text"` segments only (reasoning
and tool calls excluded). 1.2s "copied" indicator reuses the existing
.copy-btn pattern.
Relabel "Clear messages" → "Clear screen" (清屏). The clear action
only zeroes the local UI — session data persists on disk and reloads
from the sidebar. The "Clear messages" label implied permanent
deletion; "Clear screen" matches what the action actually does. The
hint (clearChatHint) already correctly stated "Clear the UI only —
subprocess stays alive".
Shorten preset pill labels (`deepseek-v4-flash` / `deepseek-v4-pro`
→ `v4-flash` / `v4-pro`) so they fit the composer bottom row without
truncation.
When a skill ships without a description, fall back to a localized
`{scope} skill · {runAs}` string instead of the previous hardcoded
`skill · ${s.scope}`. Both en + zh-CN get scope + runAs entries.
Add `text-overflow: ellipsis` to `.popup-item .desc` so an overly
long skill description can't dominate the slash picker.
Tauri's WKWebView on macOS 12 (Monterey) ships with WebKit older than
16.4 — no lookbehind support. Hitting (?<=...) falls into the
named-capture-group parser, sees `=` as the first character of the
name, and throws "invalid group specifier name" at script parse time
before any JS runs. User sees a black window.
Two lookbehinds were shipping:
- FILE_PATH_RE in Markdown.tsx — rewritten as a leading capture group;
splitFilePaths advances past the captured prefix to keep FilePill
boundaries unchanged.
- mdast-util-gfm-autolink-literal's email regex — the package's
previous() callback already validates the preceding character after
the match, so the lookbehind was just a fast-fail. Stripped at
build time via a small Vite transform plugin scoped to that
module's id.
Verified: zero (?< occurrences in the rebuilt bundle.
Closes#1209
The original #1179 report ("click a session, nothing happens, terminal
shows no logs") had a quieter cause than the slow-list path #1207
addressed. If loadSessionMessages returns [] (file 0 bytes,
all-malformed lines, etc.), the sidecar emits $session_loaded with
messages:[] and the renderer re-renders an empty chat — click looks
dead, stderr stays silent because nothing failed.
Three changes:
- session_load now stderr-logs empty/failed loads AND emits a new
$session_empty event with the byte count
- App.tsx renders $session_empty as a visible inline error message
in the chat ("Session 'X' loaded with no messages (N bytes)…"),
with restore-from-.bak guidance
- the rpc-dispatch unknown-tab path stops silently dropping events
(the previous emit had no tabId, so the renderer's per-tab router
ignored it) — switched to stderr.write so it's observable
Closes#1179 (follow-up to #1207)
The desktop sidebar's session list was reading every .jsonl in
~/.reasonix/sessions/ in full just to count lines, then filtering by
workspace — multi-second stalls on every list refresh once any
session got large.
Two changes:
- listSessions takes an optional workspaceFilter and reads meta.json
before statSync + countLines. Sessions outside the current
workspace skip the (potentially multi-MB) jsonl read entirely.
- countLines drops the UTF-8 decode + regex split + filter chain for
a raw Buffer byte-scan. ~10x faster on multi-MB jsonls. Still
picks up a dangling final line on hand-edited files.
Also incidentally addresses #1179 — the "click doesn't load" report
was the post-click emitSessions round-trip blocking on every-jsonl
re-read, not the click itself.
Closes#1179
Subdir AGENTS.md / REASONIX.md / AGENT.md has worked since #1033 but
only via read_file. If the agent runs list_directory pkg/foo and then
picks what to read next, the guidance in pkg/foo/AGENTS.md never
surfaces — the picking decision is blind.
Add findDirMemory(absDir, rootDir) that walks the listed dir +
ancestors innermost-first. Wire it into list_directory with the same
once-per-session dedupe as read_file. findSubdirMemoryAncestors stays
as a thin wrapper for read_file. Root REASONIX.md still excluded —
it's already in the system prompt.
7 new tests cover the new walker plus the list_directory integration.
Closes#1160
Replace hardcoded Mac-only keyboard symbols (⌘, ⇧, etc.) with a
platform-aware <Shortcut> component. macOS keeps ⌘ / ⇧; Windows and
Linux render Ctrl, Shift, etc. Platform detection in main.tsx now
recognises Windows in addition to macOS, setting data-platform on
<html>.
Adds desktop/src/ui/shortcut.tsx with:
- Shortcut component for inline kbd rendering
- shortcutText() for plain-text shortcut strings
- localizeShortcutText() to swap ⌘ inside already-translated strings
Updates every hardcoded <kbd> across App, CommandPalette, cards,
composer, jobs-pop, settings, sidebar, statusbar, workdir-pop.
Closes#1095
MCP responses cross a network boundary — TypeScript types are
compile-time only. validateResultShape() now runs at the top of
flattenMcpResult() (the single funnel every MCP result passes through
before reaching the model), and rejects malformed payloads with a
useful error string instead of letting them bubble up as opaque
`.map is not a function` or similar crashes downstream.
Covers: non-object result, missing/non-array content, non-object
block, unknown block type, non-string text, non-string image data,
non-string image mimeType. 8 unit tests in tests/mcp.test.ts cover
every rejection path plus a valid-result passthrough.
A user reported the desktop window went white when opening the right
panel's Tools tab after configuring an MCP server (#1197). With no
error boundary in place, a render error in any panel sub-tree
unmounted the whole React tree.
Add a small PanelErrorBoundary, wrap the context-panel tab body with
it (keyed by tab so switching resets), and harden the $mcp_specs
reducer against malformed payloads. Future render errors now show an
inline message with the actual error string instead of white-screening
the app — the rest of the UI stays usable and the user can copy the
error back to us.
Closes#1197
The desktop client shipped with a purple-gradient "R" placeholder
that didn't match the brand on the docs site or npm page.
Regenerate every platform icon (macOS .icns, Windows .ico, Windows
Store squares, Linux PNG sizes, Android adaptive, iOS app icon set,
master icon.png) from docs/brand/reasonix-logo-square.png via
`tauri icon`, and replace desktop/icons/source.svg so future
regenerations stay consistent.
Closes#1117
The Community section used to carry its own contrib.rocks avatar wall;
the new Acknowledgments section at the bottom now does too. Drop the
upper one, point the Community NOTE callout at the bottom wall, and
upgrade the remaining wall to the wider max=100 / 12-column layout.
Calls out nine contributors selected by both commit count and code
volume, plus separate thanks for the logo designer and the XiaoHongShu
promoter. Listed alphabetically with an explicit "no ordering of
importance" note. Also adds a contrib.rocks avatar mosaic and fixes
the footer link to the canonical esengine/DeepSeek-Reasonix path.
The desktop language switch still left some UI in hardcoded English or
Chinese — context panel tabs, sidebar relative times, status bar
labels, approval / plan / checkpoint cards, markdown copy + open
tooltips, composer footer, and exported markdown summaries.
Route the remaining user-facing strings through the existing
desktop i18n dictionaries and fill matching keys on both sides. The
zh-CN file's `typeof en` constraint locks both halves in sync.
Closes#1192
Bold the Discord nav link and add an IMPORTANT callout right before
the Install section. Drowned out among 7 nav links + 9 badges, the
Discord invite was effectively invisible on first scan; the callout
puts it at the same level as the cache-stability TIP and case-study
NOTE, with the channel layout and contributor-verify hook visible
in the first screen.
When an MCP server in config.json failed to bridge (wrong URL,
network 404, smithery streamable endpoint unreachable, missing auth
header, etc.), the dashboard showed a generic "未桥接 / unbridged" with
a "restart reasonix code" hint that didn't help — the bridge had
already run, errored, and we dropped the reason.
Track the last bridge failure per spec in mcp-runtime, expose it via
runtime.failures(), pipe through /mcp/specs, and render the actual
error reason inline in the dashboard MCP panel.
Adds 3 unit tests for the new failure tracker.
Until now, only busy→idle re-pinned to the bottom. If the user had
scrolled up earlier (un-pinned) and then sent a new message, the new
turn rendered off-screen until the turn completed.
Treat both busy edges the same: turn start = user just acted and
expects to see the new turn; turn end = settle on the final answer.
Closes#1182
Drop the `devtools` Cargo feature so the inspector is compiled out of
release builds entirely; Tauri auto-enables it on debug, so `tauri dev`
is unchanged.
Add a small prod-guard that suppresses the `contextmenu` event in
production via `import.meta.env.DEV`, exempting input / textarea /
contenteditable so native copy-paste still works.
Closes#1187
embedAllOpenAICompat sent ALL texts in a single API call. Providers like
Aliyun Bailian's text-embedding-v4 cap batch size at 10 items/request,
so files with more chunks than the cap got HTTP 400.
Split input into batches of batchSize (default 10) and thread the option
through config types, builder, semantic tool, server API, and the
dashboard form.
The command-palette `about` handler was wired to `flashToast("Reasonix · …")`,
which only flashed the version string for a second. With the new AboutModal
in place, route the palette entry to the same `setAboutOpen(true)` the
sidebar row uses.
Co-authored-by: reasonix <[email protected]>
Add an About entry in the sidebar foot (under 审批规则, above 设置)
that opens a new modal showing:
- App name + tagline.
- Current version, read at build time from desktop/package.json via
Vite's `define` and exposed as the `__APP_VERSION__` ambient
constant.
- Repository link — clicks open https://github.com/esengine/DeepSeek-Reasonix
via @tauri-apps/plugin-opener (already a dep).
- "Check for updates" button — queries the GitHub releases API,
prefers the latest `desktop-v*` tag (per the split-namespace
release scheme in #1153), falls back to bare `v*` if the desktop
track hasn't cut its own tag yet. Surfaces up-to-date / outdated /
failed states inline, and offers a "View releases" link on outdated.
EN + zh-CN strings added under `t("about.*")`.
Refs maintainer request — wire a single click-to-open About panel.
Co-authored-by: reasonix <[email protected]>
Right-clicking a session item in the sidebar opened a delete-confirmation
popover (#906). Users in #1116 hit it accidentally — right-click on a
list item doesn't read as "delete" in any standard desktop UI, and the
popover obscured the item enough that some users perceived the session
as "disappeared". One reporter explicitly asked whether right-click-to-
delete was a bug or intentional.
Remove the right-click hijack and surface deletion via a small X icon
inside each session-item, hidden by default and revealed on
hover / focus-within. Clicking the icon opens the same confirmation
popover anchored to the icon's bounding rect. stopPropagation keeps
the click from also firing the row's onClick (which loads the session).
The popover, its dismiss-on-outside-click + Esc handling, and the
auto-focused Cancel button all stay — only the entry gesture changes.
Closes#1116
Co-authored-by: reasonix <[email protected]>
Adds a Discord invite link to both READMEs (nav row + badge) so users
have a synchronous channel alongside GitHub Discussions.
Wires the CI workflow to post to the #ci-alerts Discord channel on
main-branch push failures only (PR failures stay out of Discord to
avoid noise). Reads the webhook from the DISCORD_CI_WEBHOOK repo
secret; quietly skips when the secret is unset so forks don't break.
Adds a brand asset bundle to docs/brand/ — the whale-in-R mark
contributed by @Bernardxu123 in discussion #1130. Carries the icon
(SVG / PNG / ICO) plus square-logo and wordmark variants, so the same
mark can be reused on the site, GitHub OG image, npm card, and the
Discord server avatar.
docs/logo.svg (the historical wordmark referenced from the READMEs)
stays in place; this commit only adds new files.
Pressing Enter to commit a CJK IME candidate often sends the same
Enter through the terminal as a real keystroke (Microsoft Pinyin,
Sogou, …), and a TTY program has no way to know whether that Enter
was IME commit or "send the message". The chat composer was treating
it as "send" and submitting whatever the user had typed so far.
Watch for non-ASCII input on the keystroke stream and stamp a
timestamp; when a submit action fires within 50ms of that stamp,
drop it instead of calling onSubmit. The window is wide enough to
catch the back-to-back commit-then-Enter the terminal flushes
together and tight enough that a real typed Enter after CJK input
(human key cadence ≥80ms) still sends the message.
Closes#1136
Co-authored-by: reasonix <[email protected]>
The setup wizard's API-key check hit `${baseUrl}/user/balance`, an
endpoint that exists only on DeepSeek's API. Users pointing the
config at any OpenAI-compatible third party (DashScope / Tongyi,
Moonshot, Zhipu, …) got a 404 surfaced as
`暂时无法验证 API key (DeepSeek 404)` even with a valid key — the
config was right, the probe was wrong.
Switch to `${baseUrl}/models`. It's the standard OpenAI-compat
listing endpoint, exists on every provider the client.ts loop
already talks to (`listModels` uses the same path), and 401/403
there still cleanly means "key rejected". Relabel the non-auth
failure message from `DeepSeek <status>` to `HTTP <status>` so the
surfaced error isn't misleading on non-DeepSeek backends.
Add a regression test that pins the probe URL to DashScope's
`compatible-mode/v1` base so a future revert can't quietly
re-DeepSeek-ify the validator.
Closes#1168
Co-authored-by: reasonix <[email protected]>
Each MeasuredCard registers a stdout `resize` listener via Ink's
useBoxMetrics. A long conversation legitimately keeps dozens of
cards mounted at once, so Node's default MaxListeners=10 trips
and prints a spurious "Possible EventEmitter memory leak detected"
warning the moment the user hits the 11th card.
Raise the ceiling to 200 right before render() so normal use stays
quiet while a real leak (one not bounded by card count) would still
surface above the new bar.
Refs #1157
Co-authored-by: reasonix <[email protected]>
The cache loop carried a per-turn TurnFailureTracker that flipped
flash→pro mid-turn after N repair signals (default 3, range
[1,20], configurable via `--escalate-after`, `escalation.failureThreshold`
in config). That heuristic was guess-work — three "search text not
found" or repair-storm hits doesn't reliably mean the model needs
more reasoning power, just that it hit one kind of friction.
Strip the counter entirely and rely on the two escalation paths
that don't rely on a magic number:
- `/pro` arms the next turn manually when the user wants it.
- The model self-escalates via the `<<<NEEDS_PRO>>>` marker when
it actually thinks it needs more headroom — that path stays
intact and is what `autoEscalate` continues to gate.
Removals:
- TurnFailureTracker class + FAILURE_ESCALATION_THRESHOLD constant
- CacheFirstLoop.noteToolFailureSignal + its two call sites
- `failureThreshold` option threaded through CacheFirstLoop /
chat.tsx / code.tsx / run.ts / App.tsx / index.ts
- `--escalate-after` CLI flag (3 commands)
- `escalation.failureThreshold` config field
- `loop.autoEscalation` i18n string (EN + zh-CN + types)
- Nine tests targeting the counter-based path; the marker-path
tests and `escalatedThisTurn` field tests stay.
Behavioral change: a long string of tool failures no longer flips
the model to pro mid-turn. Users who want pro for a hard turn type
`/pro` (one-shot) or `/preset max` (persistent). The model can
still self-escalate.
Co-authored-by: reasonix <[email protected]>
124 comment lines in src/cli/ui/App.tsx carried GBK→UTF-8 mis-decoded
Chinese fragments — some short (`闂?` standing in for an em-dash or arrow
separator), some destroyed Chinese paragraphs.
- Substitute the short `闂?` pattern with `—` (em-dash). For groups of
adjacent corruption that originally encoded arrow keys (`↑/↓`), restore
the arrows so the navigation-key comments read correctly again.
- Rewrite three corrupted JSDoc / inline comments where the Chinese tail
was destroyed; salvage the recoverable English prefix and drop the
unrecoverable bytes.
No code paths touched. typecheck / lint / comment-policy stay green.
Co-authored-by: reasonix <[email protected]>
CacheFirstLoop is rebuilt by App.tsx's useMemo whenever the active
session changes, and its constructor calls `stats.seedCarryover(...)`
with the resumed session's persisted totals. The TUI's `summary` state
was only ever updated at turn-end, so until the user submitted a new
turn the StatusRow kept showing the previous session's cost — or
$0 on a cold start with --resume.
Mirror `loop.stats.summary()` into summary state on every loop
rebuild so the displayed totals follow the active session immediately.
Refs #1143
Co-authored-by: reasonix <[email protected]>
Python MCP SDK servers write info logs (e.g. `INFO server.py:534
Processing request of type ListPromptsRequest`) to stderr. The stdio
transport was inheriting the child's stderr from the reasonix process,
so those lines wrote straight into the TUI's render buffer and stuck
around until a SIGWINCH triggered a full redraw.
Switch the third stdio slot from "inherit" to "pipe" and drain the
child's stderr in onStderr. Forward to our own stderr only under
REASONIX_DEBUG_MCP=1, matching the gating already used for dropped
malformed stdout lines.
Closes#1146
Co-authored-by: reasonix <[email protected]>
Sticky-bottom in useAutoScroll relied on the scroll event listener
to compute isPinned. Scroll events fire for our own scrollTo too,
and a smooth scrollTo keeps dispatching them for 200-500 ms — long
enough to misread "smooth scroll mid-flight" as "user scrolled up"
and freeze the view for the rest of the streaming turn (#1103).
Drop the scroll listener entirely. Un-pin only on real user input
(wheel / touchmove / keydown / pointerdown). ResizeObserver still
follows scrollHeight while pinned. Programmatic scrollTo no longer
has a way to flip isPinnedRef itself.
Closes#1103
Co-authored-by: YHH <[email protected]>
Pushing a CLI tag (`vX.Y.Z`) just triggered the desktop Tauri bundle
matrix — `release.yml` listened on `tags: ["v*"]`, same namespace the
npm CLI uses. Decouple them so each release surface owns its own
tag prefix.
- `release.yml` (desktop): trigger flips to `tags: ["desktop-v*"]`,
workflow_dispatch description updated; future desktop bumps are
`git tag desktop-vX.Y.Z`.
- `publish-npm.yml` (new): triggers on `tags: ["v*"]`, runs
`npm publish` against the matching tag. Verifies the tag's version
segment matches `package.json` before publishing so a forgotten
bump fails clean instead of as an opaque npm 403.
- `sync-desktop-version.mjs`: strip both `^v` and `^desktop-v` prefixes
so the desktop workflow's new tag shape flows through to
tauri.conf.json / Cargo.toml / desktop/package.json unchanged.
Net effect: npm publish stops being a manual local step (no more risk
of forgetting `npm run verify` first), and CLI tags can never again
spawn a stray desktop bundle.
Co-authored-by: reasonix <[email protected]>
* chore(chat): default to Ink — remove rust integration hooks
Drop the rust renderer setup branch in chat.tsx: warning print, stderr-
to-log redirect, null stdin/stdout, scene/trace handler wiring, the
approval/composer/mode/preset/setup-submit refs. Ink runs as the only
TUI path; render() loses the rust-vs-node ternaries.
First step of removing the rust renderer entirely — App.tsx still owns
the (now-orphan) ref effects, scene modules and crate still on disk.
* chore(ui): drop scene-driven picker bridges + integrated handlers
App.tsx loses the five isIntegratedRendererRequested() picker effects
(sessions / theme / checkpoint / model / mcp hub) — Ink modals already
handle those states without the rust bridge. Strip useSceneTrace, all
*Json memo inputs that only fed it, sceneApproval, prompt-input /
list-picker subscribe stores, and the approvalDispatchRef / rustComposer
/ modeSet / presetSet effects.
use-qq-channel.ts drops the rust prompt-overlay branch in promptLine —
readline is the only path; the `{ secret: true }` option goes with it
(no terminal-side echo masking either way under Node readline).
* chore(ui): delete scene/ directory + useSceneTrace hook + tests
Drop the rust-renderer integration surface: scene/renderer.ts (NAPI
loader), scene/trace.ts (snapshot bridge), scene/{null-stdin,null-stdout,
input-adapter}.ts (Ink-side stubs when rust owned the TTY), scene/{prompt-input,
list-picker}-store.ts (cross-process picker dispatch), hooks/useSceneTrace.ts
(scene-frame emitter), and the three companion test files.
Setup.tsx loses its submitRef forwarding too — Node's MaskedInput is the
only key source now.
* chore(rust): delete crates/, subpackages/, build scripts, release workflow
Pure tree deletion: crates/reasonix-render/ (rust ratatui sources + napi
glue), subpackages/render-*/ (the five empty per-platform optional-dep
packages — the .node binaries were CI artifacts, never committed),
scripts/dev-prepare.mjs (cargo build wrapper), scripts/sync-render-versions.mjs
(subpackage version pin syncer), .github/workflows/release-render.yml
(napi-rs CI matrix), and the matching .gitignore entries.
Cargo.toml + Cargo.lock at repo root go too — no rust code remains.
* chore(pkg): strip optionalDependencies + rust build scripts
Drop the five @reasonix/render-{platform}-{arch} optional deps (subpackages
are gone), the rust:build / render:versions:* / dev:prepare npm scripts
(scripts gone), and the corresponding render-version guards in verify /
prepublishOnly. npm install on every supported platform now resolves to the
same minimal dep tree — no platform-specific .node fetch step.
* feat(tui): pure-Ink rebuild — drop renderer patches, simplify cards
Now that the rust renderer is gone, the workarounds we layered on top
of Ink for it (or in defense against its quirks) are unmotivated dead
weight. Clear them out in one pass and adopt a single consistent glyph
vocabulary across the card vocabulary.
Renderer config:
- chat.tsx render() drops `patchConsole: false`, `incrementalRendering:
false`, `alternateScreen` toggle — Ink defaults take over
- `--no-alt-screen` / `--no-mouse` CLI flags + altScreen / mouse
ChatOptions removed; useTerminalSetup hook (hand-rolled DECSET 2004 /
>4;2 / 1007 ANSI sequences) deleted
- useCursorBlink + its issue-#728 active-guard removed; cursor stays
statically visible (no half-blink ghosting on the slow side)
Card chrome:
- Card primitive drops the left stripe + border config; settled
vs active is now identical, just a column box with a top margin
- CardHeader drops titleBg / titleColor pill background; titles
are plain bold tone-colored text
- All card / LiveRows / Setup callers stripped of pill props
Glyph vocabulary (consistent across every card):
- running / active ●
- completed ✓
- failed / error ✗
- aborted ⊘
- queued / pending ○
- warning ⚠
- child row ⎿
- progress bars █ / ░
- spinner braille
Layout:
- PromptInput wrapped in borderStyle="round" — rounded composer box
- ComposerArea reorders: suggestions → composer → loop status →
ModeStatusBar → StatusRow (bottom)
- StatusRow outer row flips to flexWrap="wrap", drops height=1; on
narrow terminals pills wrap to a new line instead of truncating
- Leading horizontal rule above StatusRow removed (it's at the bottom now)
Discoverability hints (info rows surfaced on startup):
- /dashboard once the embedded server URL is ready
- /copy permanently in startupInfoHints
Residual rust mentions cleaned: --node CLI flag, useInputRecall +
keystroke-context comments, REASONIX_RENDERER plumbing in the
chat-mcp startup-summary test.
* chore(release): 0.46.0 — Rust TUI removed, pure-Ink rebuild
CLI npm package only — the desktop Tauri client banner stays at its
own version on the download page. README drops the "Terminal renderer
(Rust by default)" section that pointed at the now-removed
optionalDependencies + REASONIX_RENDER_BIN path.
CHANGELOG 0.46.0 entry covers the rust-renderer removal, the env vars
that became no-ops, and the TUI overhaul that landed in the same arc
(rounded composer, bottom status row, /dashboard + /copy hints,
narrow-terminal pill wrapping).
* ci: drop rust job (rustfmt / clippy / cargo test) — crate is gone
---------
Co-authored-by: reasonix <[email protected]>
* fix(chat): rust TUI input — setup capture, paste burst, Ctrl+V
- Setup: rust now owns the keystroke buffer while setup_pending is
Some. Previously every event was dropped via `continue`, so Ink's
MaskedInput (which receives a null keystroke reader in integrated
mode) sat on a screen that ate every keypress — Windows users (and
any Mac user after the rc.2 eager-spawn change) couldn't enter
their API key. Buffer is forwarded to Setup.handleSubmit via a new
`setup-submit` event and a submitRef on the Setup component.
- Composer paste: track last_key_at and treat an Enter that arrives
within 15ms of the previous key as paste-as-keystrokes, inserting
'\n' literally instead of submitting. Bracketed paste is the happy
path, but Apple Terminal (macOS default) and cmd.exe pre-ConPTY
don't speak it, so multi-line pastes used to submit on the first
'\n'. The same guard short-circuits Enter inside prompt_input
(single-line, can't accept '\n') so paste bursts don't submit
half-pasted answers.
- Ctrl+V: explicit clipboard paste via arboard::get_text in both
composer and prompt_input. The only working paste path when
bracketed paste is unavailable.
* fix(test): normalize tmp cwd via realpath on macOS
mkdtemp in /var/folders/... but process.cwd() after chdir resolves
to /private/var/folders/...; the spy compared the unresolved tmp
path against the resolved one and bare-routing tests failed on
every Mac. Resolve at setup so the assertion sees one path.
* chore(release): 0.45.1
* chore: rustfmt + sync package-lock.json to 0.45.1
- rustfmt: one-line match arm in integrated.rs (CI fmt --check fixed it)
- package-lock.json: regenerate so optional-deps resolve to 0.45.1 instead
of the stale 0.44.2-rc.4 lock that was blocking `npm ci` on main
---------
Co-authored-by: yhh <[email protected]>
Co-authored-by: reasonix <[email protected]>
When `buildMessages` heals dangling assistant `tool_calls` before a request, also persist the healed log: `log.compactInPlace(healed.messages)` updates the in-memory state and `rewriteSession()` flushes it to the JSONL on disk (now crash-safe via the `.jsonl.bak` sidecar from #1101). The disk write is wrapped in try/catch — a FS failure shouldn't block the in-memory heal.
Before this, send-time healing scrubbed the outgoing request but the JSONL stayed poisoned, so the next process restart reloaded the bad state and the user got "session can't send" symptoms forever.
Refs #1079.
Replace the in-place `writeFileSync` in `rewriteSession` with: write to a sibling `*.tmp` file, snapshot the previous live transcript to `<path>.jsonl.bak`, then atomically `renameSync` the tmp into place. On error the tmp is unlinked and the error rethrown.
`loadSessionMessages` falls back to the `.bak` sidecar only when the live file has content but no valid entries — an intentionally empty live file is preserved.
`renameSession` / `deleteSession` / `archiveSession` carry the `.jsonl.bak` recovery sidecar so orphaned backups can't accumulate.
Refs #1079.
Move the scroll-history hint into an i18n-backed `InputAreaWithHistoryHint` component (`app.historyScrollHint`), and replace remaining GBK-as-UTF-8 mojibake literals (`闂?`, `濠电姷…`) in `App.tsx` with the intended ASCII separators / wording.
Adds `tests/app-visible-mojibake.test.ts` to scan source for the mojibake byte sequences so the corruption can't recur.
Closes#1082.
Extract two visual regions from `App.tsx` per #565 Phase 2:
- `LiveActivityArea` — OngoingTool, SubagentLiveStack, ThinkingRow, UndoBanner, PlanLiveRow, ToastRail
- `ComposerArea` — ModeStatusBar, LoopStatusRow, StatusRow, PromptInput, SlashSuggestions, AtMentionSuggestions, SlashArgPicker, HistoryHint
`React.memo` on both for render isolation once Phase 3 lands.
`Parameters<typeof UndoBanner>[0]['banner']` derives the undoBanner prop type from the source component, avoiding transitive imports.
Real types throughout — `EditMode`, `JobRegistry`, `Parameters<typeof LoopStatusRow>`, `SlashArgPickerProps`.
Closes#565 Phase 2.
* feat(render): in-process NAPI addon (0.45.0-rc.0)
Replaces the spawn-child + stdio/socket IPC architecture with a
native Node addon. The rust ratatui loop now runs on a std::thread
inside the Node process; scene state goes through emit() (mpsc) and
events come back via ThreadsafeFunction.
Why: the two-process model raced Ink's null-stdio composition with
rust's TTY takeover on macOS — stdin pipe closed before the seed
scene frame landed, rust hit `if stdin_closed && !have_state` and
exited at 120ms. rc.1-rc.4 patched symptoms; this rip-out removes
the structural cause. Distribution also simplifies (.node per
triple, no chmod +x, no optional-dep resolver, no UDS/named-pipe).
Also: kills the caret-blink-driven sync-update bursts every 480ms
that overwrote Windows Terminal's IME composition overlay and
produced flicker while typing CJK. Idle scenes are now flicker-free;
needs_animation gates on scene.busy.
Drops: scene_socket.rs, renderer-process.ts, renderer-resolver.ts,
input-source.ts, createRustKeystrokeReader, smoke-rust.ps1, all
REASONIX_RENDER_CMD / REASONIX_INPUT_CMD / REASONIX_SCENE_SOCK
env vars, the rust child's --integrated CLI mode, the keep-alive
setInterval, optional-dep binary resolver fallback.
Release workflow rebuilt for napi: cargo build --lib produces a
cdylib, staged as reasonix-render.<triple>.node into each subpackage.
* style(render): rustfmt
* fix(render): gate napi behind a feature so cargo test links
Without the feature, the rlib doesn't pull in `napi-*` runtime symbols
(`napi_create_reference`, `napi_call_function`, …), which the linker
can't resolve when building the standalone `reasonix-render` bin or
the integration tests under tests/ — those don't run inside Node, so
no host provides the N-API symbol table. CI's `cargo test` step on
ubuntu was failing with rust-lld undefined-symbol errors as a result.
Default features stay empty. Release CI + `npm run dev:prepare` pass
\`--features napi\` when building the cdylib that Node loads.
---------
Co-authored-by: reasonix <[email protected]>
rc.3 diagnostics confirmed: rust integrated child exits in ~118ms with
code=0 signal=null and no stderr output. Single explanation: the rust
integrated loop's early-exit branch
if stdin_closed && !have_state { return Ok(()) }
fires because Node never wrote any scene state to the child stdin pipe
before something closed it (likely Ink unmount cascade on macOS).
Fix: ensureSceneTraceReady() now writes an empty trace frame ('{type:"trace"}')
immediately after spawn. Rust decodes it as a default SceneState,
flips have_state=true, and the early-exit branch no longer triggers
even if Node's pipe later closes. Rust will keep running on its
inherited stdout + own /dev/tty input.
Subsequent React-driven state updates (when useSceneTrace's effect
fires, on platforms where it does) overwrite the seed frame normally.
Co-authored-by: reasonix <[email protected]>
rc.2 made the mac symptom flip from 'hang' to 'exit immediately' — but
~/.reasonix/rust-render-stderr.log still empty, so we have no signal
on what actually killed the rust child. Three diagnostic improvements
to make rc.3 land actionable info:
1. trace.ts: emit [trace] resolver source+command + spawn-start line
before spawning. Confirms which binary was picked.
2. renderer-process.ts: log [spawnRenderer] child exit code/signal/aliveMs.
Distinguishes startup crash (aliveMs<1s) from clean exit.
3. renderer-process.ts: log non-JSON child stderr lines (rust panics /
crossterm errors / debug output) as [rust-stderr] ... Previously
silently dropped — exactly the path that left rc.1/rc.2 undebuggable.
Also: don't synthesize an 'exit' event back to the integrated handler
when the child dies within 1.5s of spawn. Sub-second deaths are almost
always startup crashes; letting Node cascade into process.exit hides
the real cause. Hold Node alive so the user can read the log.
Co-authored-by: reasonix <[email protected]>
rc.1's keep-alive interval prevented Node from exiting, but the rust
child was never actually spawned — on macOS, the React useEffect in
useSceneTrace that normally triggers emitSceneMessage → trace.ts
ensureInitialized() → spawnRenderer() simply never fired in some npx
contexts. Result: Node held the event loop open via keep-alive,
nothing rendered, user saw 'hung'.
Three layered fixes:
1. trace.ts exports ensureSceneTraceReady() — chat.tsx calls it right
after setIntegratedEventHandler so spawn happens eagerly, before
Ink mounts. No more React-effect-timing dependency.
2. renderer-process.ts synthesizes an {event:'exit'} when the rust
child dies on its own (panic / SIGKILL / terminal close) so the
integrated handler can tear Node down. Previously Node's keep-alive
would hang forever waiting for a dead child.
3. trace.ts logs to stderr when resolveRenderer returns no usable
command instead of bailing silently — anyone hitting 'TUI never
appears' can grep ~/.reasonix/rust-render-stderr.log for the
reason.
Co-authored-by: reasonix <[email protected]>
macOS reproducer: `npx reasonix code` (default = rust + integrated TUI)
prints the startup info line then immediately exits back to shell, no
TUI ever renders. Rust binary runs fine standalone; Ink runs fine when
forced via REASONIX_RENDERER=node. The breakage is at the seam between
the two.
Root cause: makeNullStdin / makeNullStdout are pure-JS Node streams
with no underlying libuv handles. The rust trace child is spawned by a
React useEffect (useSceneTrace → emitSceneMessage), enqueued
microseconds AFTER render() returns. On macOS the event loop sees no
active handles in that window and exits before the effect runs. Linux
and Windows happen to keep the loop alive via other handles in the
boot path (timers from MCP runtime / proxy init / etc.); macOS
doesn't.
Defensive setInterval(()=>{}, 0x7fffffff) keep-alive held for the
lifetime of waitUntilExit() and cleared in finally. RC bump to
0.44.2-rc.1 for Mac smoke before promoting to stable; no other code
changes — same renderer binary as 0.44.0.
User reports on macOS: 'spawn .../node_modules/@reasonix/render-darwin-arm64/bin/reasonix-render EACCES'.
actions/download-artifact@v4 strips Unix file modes when round-tripping
the per-platform binaries through the workflow's artifact storage, so
the 0.44.0 tarballs landed without the executable bit.
Two-layer fix:
1. Each @reasonix/render-* subpackage now declares its binary in the
'bin' field of package.json. npm install chmod +x's bin-declared
files during extraction — covers the normal install path.
2. The publish workflow explicitly chmod +x's the non-Windows binaries
after staging from artifacts, so the tarball itself ships with the
right mode regardless of npm version.
Bumps to 0.44.1; no code changes — same renderer binary as 0.44.0,
just republished with correct file modes.
Co-authored-by: reasonix <[email protected]>
Windows MSI bundler rejects SemVer prerelease identifiers — Win32
installer versions must be numeric MAJOR.MINOR.BUILD.REVISION (each ≤
65535). rc.5/beta.2 etc. fail the bundle with:
failed to bundle project 'optional pre-release identifier in app
version must be numeric-only and cannot be greater than 65535 for
msi target'
Encode the prerelease's numeric tail as the 4th segment:
0.44.0-rc.5 → 0.44.0.5
0.44.0-beta.2 → 0.44.0.2
0.44.0 → 0.44.0 (unchanged)
Only tauri.conf.json gets the encoded value. Cargo.toml + desktop/
package.json keep the full SemVer (cargo + npm both accept it).
Co-authored-by: reasonix <[email protected]>
rc.4 publish failed because prepublishOnly re-ran the test suite and an
ink stdout-rendering test (tests/ui-status-row-balance.test.tsx) failed
on the publish runner with mysterious row-of-dashes output, even though
the same test passed on the build CI matrix.
Re-running tests during npm publish is doubly wasteful and one more
flakiness surface — every push already runs the full lint + typecheck +
test:coverage matrix on ubuntu + windows before merge, and the
workflow above explicitly builds dist/ via 'npm run build'. Trust
that and add --ignore-scripts to npm publish.
(prepublishOnly itself is still useful for one-off manual publishes
from a contributor's machine.)
Co-authored-by: reasonix <[email protected]>
npm publish --provenance compares package.json's repository.url against
the workflow's actual github.com path via sigstore. The canonical repo
name is esengine/DeepSeek-Reasonix; we'd been pointing at the legacy
esengine/reasonix redirect alias, which sigstore rejects with E422
'Failed to validate repository information'.
Caught by v0.44.0-rc.3 publish — auth worked but every subpackage
publish hit E422 on the provenance step.
Co-authored-by: reasonix <[email protected]>
GH's Intel-Mac runner pool was largely retired in 2025; the existing
release.yml comment notes queue waits ran to hours. rustc on macos-14
(Apple Silicon) cross-builds x86_64-apple-darwin natively when the
target is installed via dtolnay/rust-toolchain's `targets:` field —
no extra setup, no codesign step needed at build time.
Caught by the v0.44.0-rc.1 push: 4 of 5 build jobs finished in <2min,
darwin-x64 sat queued for 15+ min before I cancelled.
Co-authored-by: reasonix <[email protected]>
npm publish defaults to dist-tag 'latest' regardless of SemVer, so
publishing 0.44.0-rc.1 would replace 0.44.0 as the default for
`npx reasonix@latest` users. Detect prereleases (version contains
'-') in the workflow and use --tag 'next' for them; stable versions
keep 'latest'.
Co-authored-by: reasonix <[email protected]>
Tauri 2.x renamed the field; @tauri-apps/cli 2.11.1 rejects the old name
with a schema validation error blocking `tauri dev` startup.
Co-authored-by: reasonix <[email protected]>
- Bare `reasonix` (no subcommand) now == `reasonix code` — note that
in the command table.
- New 'Terminal renderer' subsection: rust TUI is the default since
0.44.0; `--node` flag (or REASONIX_RENDERER=node) opts back to Ink;
auto-fallback on unsupported platforms; REASONIX_RENDER_BIN for
testing custom builds.
Co-authored-by: reasonix <[email protected]>
In raw mode crossterm doesn't translate ctrl+c to SIGINT — the byte 0x03
is delivered as a key event and the existing is_quit branch handles
interactive exit cleanly. But `taskkill`, parent-process death, terminal
disconnect (SIGHUP), and external `kill` (SIGTERM) bypass the event
loop entirely; the alt-screen + raw mode stayed dirty and the next
launch rendered with an offset.
ctrlc::set_handler with the 'termination' feature covers all those paths:
SIGINT / SIGTERM on unix, ctrl-c / ctrl-break / console-close on
Windows. The handler best-effort runs disable_raw_mode +
LeaveAlternateScreen + cursor::Show and exits 130.
Wired up for both --emit-input mode (which also enters raw mode) and
the render modes. The panic hook keeps its existing cleanup for
unwinding crashes.
Co-authored-by: reasonix <[email protected]>
Stand up the npm publish pipeline for the rust renderer so a tagged release
ships pre-built binaries to every supported platform.
- subpackages/render-{win32-x64, linux-x64, linux-arm64, darwin-x64, darwin-arm64}/
package.json with name, version, os, cpu, libc, bin/ allowlist. npm sees
the cpu+os fields and installs only the one matching the user's platform.
- scripts/sync-render-versions.mjs keeps every subpackage's version + the
main package.json's optionalDependencies pins lockstep with main version.
npm scripts render:versions:sync / render:versions:check; verify and
prepublishOnly fail loudly on drift.
- .github/workflows/release-render.yml: matrix build on each target's
runner (cross gcc for linux-arm64), uploads each subpackage as an
artifact, then a single publish job downloads them, re-syncs versions
to the tag, and runs npm publish on the 5 subpackages + the main
package in order. Triggered by v* tag push (same convention as the
existing tauri release.yml) or manual workflow_dispatch with a tag input.
- Main package.json optionalDependencies enumerates all 5 subpackages.
Existing renderer-resolver locates them via @reasonix/render-${platform}-${arch}
with no further changes needed.
After this lands, the first tagged release (e.g. v0.44.0) ships the rust
binary to npm so npx reasonix@latest works on win/mac/linux out of the box
without cargo on PATH.
Co-authored-by: reasonix <[email protected]>
#1074 — clicking a history session a few times surfaces
"reasonix exited (code 1)" and reverts the UI to "connecting to
reasonix core…". That code-1 exit is Node 16+'s default for an
unhandled promise rejection, and the desktop daemon never
registered the process-level guards a long-running sidecar needs.
The most likely upstream trigger is the abort + rebuild cycle in
the `session_load` handler: replacing `tab.runtime` orphans any
in-flight fetch on the old client, which then rejects with no
awaiter. Whatever the precise leak, the right behaviour for a
daemon is to log loudly and keep serving — not exit and force a
full Tauri reconnect.
`installDesktopCrashGuards()` registers `unhandledRejection` and
`uncaughtException` listeners that forward the stack to stderr
(surfaces via `rpc:stderr` for debugging) but do NOT call
`process.exit`. Called once from `desktopCommand` after
`loadDotenv()`.
Tests: 4 cases in tests/desktop-crash-guards.test.ts cover the
listener-count assertion, Error / non-Error rejection coercion,
and the uncaughtException branch.
Fixes#1074
Co-authored-by: reasonix <[email protected]>
* feat: rust TUI as default + auto-resolver + bare reasonix→code + URL wrap
- Bare `reasonix` defaults to `code` in cwd (was: chat when not in a project dir).
- Rust TUI is the default; `--node` flag (or REASONIX_RENDERER=node) opts back to Ink.
- New `renderer-resolver.ts`: priority order REASONIX_RENDER_CMD/INPUT_CMD env →
REASONIX_RENDER_BIN env → @reasonix/render-{platform}-{arch} optional dep →
cargo run --bin reasonix-render (source tree only) → missing.
- `chat.tsx` auto-falls-back to Ink with a stderr warning when renderer is missing,
removing the old 'no API key → bypass rust' bail (Setup screen works under Rust now).
- New `paint_link_wrapped` in whole_screen/paint.rs: dashboard URL with long token
wraps across multiple rows inside the main panel instead of bleeding into sidebar.
- 9 resolver unit tests + 1 long-URL wrap test + bare-routing tests updated.
* feat: auto-resolve prebuilt rust binary + auto-build on npm dev + Ctrl+D quit
- Resolver checks source-tree target/release/reasonix-render(.exe) then
target/debug before falling back to `cargo run`. Skips cargo's per-invocation
overhead (a few hundred ms on every spawn) when a prebuilt binary exists.
- New scripts/dev-prepare.mjs runs `cargo build --release --quiet --bin
reasonix-render` ahead of tsx so contributors never spawn a stale binary
after editing rust source. Silent no-op when cargo is missing (TS-only devs).
- npm 'dev' / 'chat' scripts now chain through dev:prepare. Added
'rust:build' for explicit rebuilds.
- App.tsx wires Ctrl+D to quitProcess(); the boot banner already advertises
it but the binding was never actually wired.
* feat(scene): integrated mode is now the default when rust renderer is active
Once #1064 landed (rust integrated-mode P0 parity), there's no reason to
keep integrated as opt-in. Flipping the default:
- ctrl+d / ctrl+c: handled directly by rust event loop (main.rs:239 +
is_quit), one press exits cleanly. Non-integrated mode chained through
--emit-input → input-source.ts → KeystrokeProvider → React handler →
await stopAndSaveCpuProfile → process.exit, which sometimes took two
or three presses to fire.
- mouse-click on preset / mode / picker rows: rust handles directly and
emits {event:'preset-set'|'mode-set'|...}; non-integrated has no React
handler for mouseClick so clicks were silently dropped.
- ctrl+c terminal restore: rust returns from its loop and runs
restore_terminal (leave alt-screen + disable raw mode). Non-integrated
mode got SIGINT'd before cleanup, leaving alt-screen + raw mode dirty
→ next launch rendered with an offset.
Flag inverted: REASONIX_RENDERER_INTEGRATED=0 opts out (was: =1 to opt
in). Useful only for debugging the non-integrated split.
* chore(rust): rustfmt
* test(resolver): platform-neutral win32 .exe path assertion
The hardcoded backslash path failed on Linux CI because path.join uses
posix separators there. Assert via endsWith / regex instead.
---------
Co-authored-by: reasonix <[email protected]>
* feat(desktop): apply desktop-opt visual layer onto main
Port the style-layer changes from feat/desktop-opt while keeping main's
layout and functionality:
- Fonts: swap IBM Plex for Anthropic Sans / Geist / Inter
- Window: frameless titlebar with custom window controls + drag region
- Styles: wholesale styles.css redesign (warm-neutral dark palette)
- Splash: replace with the slimmer desktop-opt splash screen
- Restore .tabbar/.tab and recent-session-list styling dropped by the
redesign; design them in the new visual language
- YOLO notice: move from a top banner to a bottom-right toast
- Move the Review/Auto/YOLO mode switch above the composer input
- Compact thinking / tool-call / shell process cards
- Style the session right-click delete popover
* fix(desktop): drop proprietary Anthropic Sans for open-source Geist
Anthropic Sans is a proprietary typeface — bundling the woff2 carries
licensing risk. Geist (SIL OFL) is already a dependency and was the
fallback in every font stack, so promote it to primary and remove the
@font-face and the bundled font file.
* fix(desktop): correct per-mode tooltips on ModeSwitch + i18n for composer hints
* fix(i18n): update tooltips and placeholders for composer and desktop UI
#1019 — once you Tab into a subdir via @ to browse, there's no way
to back out without retyping the path. Add a synthetic ".." entry
that pops one level whenever the picker is inside a subdir; absent
at the workspace root where it'd be meaningless.
Desktop composer:
- `atItems` prepends a `{ name: "..", kind: "dir" }` mention when
`parentOfAtQuery(popup.query)` is non-null, with a dim hint
showing the parent path (or "↑ workspace root" at the top).
- `pickItem` and the Tab handler intercept `".."` before the normal
dir-drill path and rewrite the @ token to the parent's path,
then re-query so the popup repaints with the parent dir.
CLI / Ink picker:
- `useCompletionPickers` adds a `parentBrowseEntry` at the head of
the browse list when `browseDir !== ""`. The entry is flagged
`synthetic: "parent"` on `AtPickerEntry` so `pickAtMention`
always drills (otherwise Enter on ".." would commit `@<parent>`
as a literal mention).
- Rust renderer's `at_completion` already constructs `@<insertPath>/`
for any `is_dir: true` entry, so the synthetic entry naturally
drills there too — no Rust-side change needed (`#[serde(...)]`
ignores the unknown `synthetic` field).
Test plan: `tests/mention-parent-entry.test.ts` covers the
path-math helpers in both surfaces (root short-circuit, one-level
pop, multi-level nested, Windows separator normalisation).
`npm run verify`: 211 files / 3158 tests pass.
Closes#1019
Co-authored-by: reasonix <[email protected]>
#968 — users running Reasonix on a workstation wanted to open the
dashboard from a phone or another laptop on the same LAN, and to
stop the per-boot token churn that breaks bookmarks.
The HTTP server already accepted `host` and `token` in its options
struct (only tests reached them); CLI and config didn't expose
either, and the maintainer comment told users localhost-only was
the only supported mode.
Surface both knobs through the normal channels:
- `config.dashboard.host` + `config.dashboard.token`
- `--dashboard-host <host>` flag on `code` / `chat`
- `REASONIX_DASHBOARD_HOST` + `REASONIX_DASHBOARD_TOKEN` env vars
- resolver order: flag → env → config → server default
Stable tokens shorter than 16 chars are dropped with a stderr
warning (otherwise users would set "password" and call it a day).
When the bind host isn't loopback (127.0.0.1 / ::1 / localhost),
the server writes a one-line stderr warning at boot so the user
sees the trade-off: "the URL token is the only auth — keep it
secret."
Closes#968
Co-authored-by: reasonix <[email protected]>
* fix(rust): zero-width character handling + tab expansion in paint engine
1. Add char_width(ch) — returns 0 for control characters (where
unicode-width returns None) instead of the previous unwrap_or(1)
which gave spurious width-1 cells to control chars, causing them
to overwrite the next character's cell.
2. paint() now bails early on w==0 characters instead of painting
them — zero-width chars (combining marks, ZWJ, ZWNJ, variation
selectors, control codes) are skipped entirely.
3. paint_str_to() expands \t to 2 spaces (terminal convention),
skips all w==0 characters, and uses char_width() for measurement.
4. overlay_at.rs switch to char_width() to match.
* test(rust): add Unicode rendering tests — emoji, ZWJ, combining marks, tab, control chars, CJK+emoji mix
* fix: rustfmt test file
---------
Co-authored-by: Bernardxu123 <[email protected]>
Project memory only loaded REASONIX.md at the repo root. Large
monorepo users (#1033) wanted Claude-style per-subdir memory:
frontend/REASONIX.md, api/REASONIX.md, etc., scoped to their
directory and pulled in only when relevant — not at session start.
New `src/memory/subdir.ts` walks from a file's dir up to (but not
including) rootDir and collects every PROJECT_MEMORY_FILES match
(REASONIX.md / AGENTS.md / AGENT.md). The root's memory is
intentionally excluded — `applyProjectMemory` already injects it
into the system prompt, so re-emitting through tool results would
just bloat context.
`read_file` checks the walker on every call, prepends a
`[module memory: <rel-path>]\n\n<content>` block for each ancestor
that hasn't been shown yet in this session, then the file body
follows. Multiple ancestors emit outer-first (broad rules read
before specific overrides). The shown-set lives on the toolset
closure so each tab/session re-injects on first relevant read.
Respects REASONIX_MEMORY=off and reuses PROJECT_MEMORY_MAX_CHARS
truncation. The injection is best-effort — unreadable / empty
files are skipped silently.
Closes#1033
Co-authored-by: reasonix <[email protected]>
Tauri's default NSIS language file stores `{{product_name}}` in the
"app is running" / "kill app" / "failed to kill" strings and
substitutes it at installer runtime via
`nsis_tauri_utils::StrReplace`. When that DLL can't be loaded — the
user in #928 hit a "Could not load nsis_tauri_utils.dll" error,
most likely from AV intervention on the temp-dir extraction — the
raw placeholder leaks into the dialog and the user sees
"{{product_name}} is running! Click OK to kill it".
Override the affected LangStrings through `bundle.windows.nsis.\
languageFiles` so the product name is baked in at NSIS build time
and no runtime DLL substitution is needed. Provide English (the
upstream default) and SimpChinese so zh-CN users get a translated
installer too.
Regression test walks every custom .nsh and asserts no
`{{product_name}}` placeholders remain in the code (header comments
allowed) and that the three affected LangStrings still mention
"Reasonix".
Fixes#928
Co-authored-by: reasonix <[email protected]>
The EmptyState welcome screen offered a /help suggestion but onPick
piped every string straight to `send()`, so clicking it shipped
"/help" as a user message and the agent started reasoning about how
to provide help. Reported in #929.
Two changes:
- Route EmptyState's onPick through `slashCommands` first: if the
picked text starts with a known slash, run the local handler;
otherwise fall through to `send()` as before.
- Register a real /help slash command that primes the composer with
"/" so the existing slash popup lists every available command —
discoverable, no separate help surface needed.
The composer used to open the slash popup only from `handleChange`
(actual keystrokes), so a programmatic `setDraft("/")` left the
textarea showing "/" with no popup. Add a small effect that watches
for the "" → "/" draft transition and opens the popup, leaving
user-typed slashes (and Escape-dismissed popups) unaffected.
Fixes#929
Co-authored-by: reasonix <[email protected]>
Drag-drop was added in #826 but the handler lives inside TabRuntime
and subscribes per-tab to the same window-level Tauri event. With
one tab open the behaviour looked right; once #1063 restored the
full tab set on launch, a single drop appended @-mentions to every
mounted tab's draft and the focus jumped to the last one to settle.
Gate the handler on the latest `active` value through a ref so the
subscription doesn't reinstall on every tab switch, then bail on
all event types when the tab isn't active. The overlay text used a
hardcoded English string in a CSS pseudo-element; expose it as a
--drop-overlay-label custom property and set it from JS using the
existing i18n dict (added dragDrop.overlay in en + zh-CN).
Fixes#1027
Co-authored-by: reasonix <[email protected]>
* feat(rust): render doctor/memory/ctx/plan-card/task + bracketed paste
Survey turned up five Node card kinds that round-trip through scene as
{kind, summary} only (rust's default render arm = 0 height = nothing
drawn): doctor, memory, ctx, plan, task. /doctor, /memory, /context,
plan-flow updates, and tool-task tracking all looked silent in
integrated mode.
Node side: extend toSceneCard with formatters so each card carries a
multi-line body the rust renderer can lay out:
- doctor → glyph + label + detail per check (✓ / ▲ / ✕)
- memory → category-tagged entries + token count in meta
- ctx → "X / Y used (Z%)" + per-segment + top-tools breakdown
- plan (PlanCard, not todo) → glyph-prefixed step list, kind tag
"plan-card" so it doesn't collide with the existing todo-shaped
"plan" render arm
- task → step-list with status glyphs + status in meta
Rust side: wire new card kinds in cards/mod.rs (card_height arm +
render_card dispatcher arm). All five reuse render_info_card with
their own accent + glyph (OK ✚ for doctor, DS_PURPLE ◈/◆ for
memory/plan, INFO ▦ for ctx, DS_BRIGHT ▸ for task).
Bracketed paste: integrated.rs now enables EnableBracketedPaste and
handles Event::Paste:
- in the chat composer: insert pasted text at cursor, strip \r
- in a prompt-input (e.g. /qq connect's App Secret): single-line for
normal prompts, control-chars filtered for secrets
- shuts off via DisableBracketedPaste on exit alongside mouse
Test: renders_doctor_memory_ctx_plan_card_task_kinds covers all 5
arms (summary + first body line visible in the rendered buffer).
* feat(scene): list-picker overlay — /sessions and /theme work in integrated mode
Under REASONIX_RENDERER_INTEGRATED=1 the rust child owns the alt-
screen, so React modals (SessionPicker, ThemePicker, …) render into
the null-stdout — the user sees the slash command swallow their input
and nothing happen. Wire a generic scene-driven list picker.
Architecture (mirrors prompt-input-store):
- list-picker-store.ts holds the active picker and the pending Promise;
requestListPicker({title, hint, options}) → Promise<key | null>.
- App.tsx serializes the active picker as listPickerJson via
useSyncExternalStore.
- useSceneTrace ships it as scene.listPicker in the next frame.
- Rust SceneState gains list_picker: Option<ListPicker> with
{ id, title, hint, options: Vec<{key, label, sublabel, meta}> }.
- run_integrated_loop intercepts keys when list_picker is set (between
mode/preset pickers and prompt-input), routes to a new
handle_list_picker_key: Up/Down/jk navigates, digit-keys jump, Enter
posts {event:"list-picker-response", id, key}, Esc posts cancelled.
- New whole_screen/list_picker.rs renders a centered modal with title,
count, rows (label + sublabel + right-aligned meta), and a hint
footer.
- chat.tsx's integrated event handler resolves the pending Promise;
cancelAllListPickers fires on exit.
Wire the existing pendingSessionsPicker / pendingThemePicker React
states to requestListPicker via useEffect — when set AND
isIntegratedRendererRequested(), route through scene, then dispatch
the choice to onSwitchSession / saveTheme as the Ink modal would.
Test: list_picker_modal_renders_when_scene_carries_one covers title,
options, sublabel, meta, and hint visibility.
* feat(scene): list-picker bridges for /restore and /model
Same shape as the sessions/theme bridges from the previous commit —
when pendingCheckpointPicker / pendingModelPicker becomes true AND
isIntegratedRendererRequested(), route through requestListPicker and
dispatch the choice to the same handlers the Ink modals would call:
- /restore (bare): picker over reverse-time-ordered checkpoint list
with short SHA as sublabel + fmtAgo meta; on pick, restoreCheckpoint
+ push a wrote/removed/skipped summary card.
- /model (bare): picker over the loaded model list, marks loop.model
as "current"; on pick, loop.configure + agentStore session.* dispatch
+ preset infer + savePreset, all matching the Ink ModelPicker's
onChoose handler.
* feat(rust): welcome banner + activity phase label + MCP hub inventory
Three of the smaller P1 audit items in one go:
- Idle banner now lists 4 starter commands (/help · /cost · /init ·
/sessions) under the existing type-below hint so new users see the
most-likely-useful entry points without /help.
- Status-bar brand cell swaps to an activity-aware label when busy:
"reasoning…" / "streaming…" / "running tool…" / "planning…" /
"compacting context…", driven by scene.activity. Idle stays
"reasonix". Cell width changes ≤ 5 cells so the rest of the bar
layout doesn't shift catastrophically. (Test row finder switched to
a stable anchor since the brand text is no longer constant.)
- MCP hub: full Live/Marketplace tabbed modal is heavy and
interactive; under integrated mode dump a read-only inventory of
connected servers via log.pushInfo so the user can at least see
what's wired up, with a hint to drop integrated mode for install /
configure flows.
Tests: idle_banner_includes_starter_command_hints,
status_bar_shows_activity_phase_when_busy.
---------
Co-authored-by: reasonix <[email protected]>
Five `var(--...)` references in dashboard/app.css pointed at custom
properties that were never defined. The most visible (#919) was
`.md h3 { background: var(--grad-8); color: #0a0e14 }` — with no
background the near-black heading fell straight onto the dark
page background, so sub-headings vanished in rendered markdown.
The others were the same shape:
- `.md hr` and `.status-bar-mini-fill` used `var(--gradient-rule)`
with no fallback — `<hr>` separators and the mini progress bar
rendered with no fill.
- `--bg-elev-1`, `--accent` had silent fallbacks but still pointed
at undefined tokens (typos for `--bg-elev` / `--c-accent`).
- `--bg-elev-3`, `--r-sm` were referenced with fallbacks but the
intended token wasn't defined anywhere.
Define the missing surface / radius / gradient tokens in :root
(light-mode `--bg-elev-3` lives in the light overlay) and fix the
typo references to point at the real names. Replace the dead
`--grad-8` reference with `--s2` (teal) so the three heading
levels stay distinct (sky → purple → teal).
Add `tests/dashboard-css-vars.test.ts` — walks every `var(--foo)`
in `dashboard/app.css` and asserts it resolves to a defined custom
property, so this whole class of bug fails the build instead of
shipping invisible UI.
Fixes#919
Co-authored-by: reasonix <[email protected]>
* fix: MCP bridge state — record tools immediately, use live getter for Dashboard
* fix: address review — tools-ready event, warn instead of failed, post-inspect connected
The desktop client only ever booted with one tab — whatever the
default workspace was. Tabs created via Ctrl+T were tracked in React
state only, so a restart silently dropped everything except the boot
tab. Reported as #933.
Persist the list of open workspaces in `config.desktopOpenTabs` and
rebuild every tab at boot:
- `config.ts`: add `desktopOpenTabs: string[]` plus
`loadDesktopOpenTabs` / `saveDesktopOpenTabs` (clears the key when
the list is empty so we don't leave dead state around).
- `desktop.ts`: extract `bootstrapTab(initialDir?)` to share the
emit-events + `initTabToolset` chain between the boot path and the
`tab_open` RPC. Boot iterates saved dirs in order, skipping any
that no longer exist on disk; `--dir` still wins so an explicit
CLI override is authoritative. Persist after every open/close.
- The `first` fallback tab (used for legacy tabId-less messages)
rotates to the next surviving tab when the original is closed.
Tests cover the new config helpers (round-trip, ordering preserved
across saves, empty list clears the key, malformed entries
filtered).
Fixes#933
Co-authored-by: reasonix <[email protected]>
In auto edit mode the App-level interceptor for `edit_file` /
`write_file` was stripping a leading slash off the path unconditionally
to honour the model-convention "/src/foo.ts means rootDir/src/foo.ts"
shorthand. The same strip also fired on real absolute system paths
like `/Users/x/.claude/skills/foo.md`, rewriting them to
`<rootDir>/Users/x/.claude/skills/foo.md`. `applyEditBlock` then
"created" the file there and reported success, while the user looked
at the intended absolute path and saw nothing.
Match the safePath logic that the native `write_file` tool fn already
uses: when the raw path looksLikeAbsoluteSystemPath, resolve it and
only continue intercepting when it lands inside rootDir. Outside-root
absolute paths fall through to the tool fn, which routes them through
the approval gate and writes to the path the user actually meant.
Export `looksLikeAbsoluteSystemPath` and `pathIsUnder` from
`tools/filesystem.ts` for reuse, and add a regression test that
mirrors the interceptor branch.
Fixes#942
Co-authored-by: reasonix <[email protected]>
* fix(rust): Enter submits exact slash match instead of re-completing
In the rust composer, Enter while the slash overlay was active always
rewrote the buffer to "/<cmd> " via slash_completion, even when the
user had already typed the full command name. For "/cost", the first
Enter produced "/cost " (identical content + trailing space) with no
visible feedback; the command only ran on a second Enter. From the
user's seat it looked like /cost, /help, /clear etc. did nothing.
The Node-side handleSubmit already avoids this by skipping auto-
complete when there's an exact catalog hit. Mirror that on the rust
side: add slash_is_exact(query, state), and gate the Enter-completes
arm on `slash_active && !slash_is_exact`, so the exact case falls
through to the general Enter handler and submits.
Applied to both run_integrated_loop and run_demo_loop.
* feat(scene): render usage/live/warn/tip cards in integrated mode
Slash commands like /cost emit a UsageCard (or LiveCard, WarnCard,
TipCard) through log.pushInfo / ctx.postUsage. In integrated mode the
rust process owns the screen, so those cards have to round-trip
through useSceneTrace -> SceneState.cards. Two missing pieces made
the output silently disappear:
1. toSceneCard had no case for usage/live/warn/tip, so they fell into
the default branch that only set { kind, summary } — no body.
2. Rust render_card had no arm for "usage" / "info" / "warn", so even
if a body was attached, card_height returned 0 and nothing painted.
Fix:
- TS: map live -> kind "info", warn -> kind "warn", tip -> kind "info"
with a formatted body, usage -> kind "usage" with a 3-4 line cost
breakdown (turn N · this $X · session $Y / prompt/output / cache %).
- Rust: shared render_info_card helper in notify.rs taking accent +
glyph, plus dispatcher arms for "info" (INFO blue ⓘ), "warn" (WARN
yellow ▲), "usage" (DS_BRIGHT $).
Verified: /cost now surfaces the per-turn usage card in the right pane;
arbitrary log.pushInfo messages also become visible.
* feat(scene): slash catalog parity — group, i18n summary, no-match state
The rust slash overlay was missing things the Node TUI's
SlashSuggestions has had for a while:
- Group headers (SETUP / INFO / CHAT / EXTEND / SESSION / CODE / JOBS)
when the user is browsing the bare `/` menu — pre-fix, all commands
rendered as one flat list, hard to scan.
- Translated summaries. The rust side received the raw English
spec.summary; Node's React popup uses t("slash.<cmd>.description"))
with a fallback to spec.summary.
- "no command matches '<query>'" indicator. Pre-fix, an empty match
set hid the popup silently — the user couldn't tell whether they
typoed or the prefix was simply unknown.
- argCompleter values (static arrays like ["auto","flash","pro"]) —
groundwork for a future arg-level picker; not rendered yet but the
catalog now carries the data.
Changes:
- TS: enrich slashCatalogJson with { group, argCompleter, translated
summary }; serialize as JSON-safe (spread readonly arrays).
- Rust SlashMatch: new optional `group: String` and
`arg_completer: Vec<String>` fields with serde defaults.
- Rust overlay: collect_rows tags the first row of each group with
header_above when query is `/` (group mode); row_visual_height +
draw_rows_wrapped paint the group label above that row.
- Rust overlay: render_no_match shows a 3-row "▲ no command matches"
popup when collect_rows is empty.
* fix(rust): Tab in slash/@ overlays commits the highlight
Before: Tab in the slash overlay (and at-overlay) just cycled
slash_idx / at_idx. The buffer never changed, so users had to type the
full command name even with the match visibly highlighted.
After: Tab fills the buffer with the highlighted completion, matching
Node TUI's setInput(`/${sel.cmd}`) behaviour. BackTab (Shift+Tab on
most terminals) keeps the backward-cycle behaviour for users who want
to step the highlight.
Applied symmetrically to:
- slash overlay (commits "/<cmd>" without trailing space — user can
type args or press Enter)
- at-overlay (commits the file path with trailing space, via existing
at_completion which already adds it; folder vs file handling stays
in pickAtMention on the Node side once we wire arg picker through)
Up / Down still cycles the highlight.
* feat(rust): slash arg picker for static argCompleter values
When the user typed e.g. /language and pressed space, rust composer
went blank — they had to remember and type "EN" or "zh-CN" themselves.
Node TUI shows a picker via SlashArgPicker.tsx. Mirror that on the
rust side for static argCompleter arrays (the dynamic ones — "models",
"path", "mcp-resources", "mcp-prompts", "skills" — still live on the
Node side and aren't surfaced here yet).
How it fires:
- slash_arg_matches(query, scene) parses "/<cmd> <partial>", finds the
cmd in slash_catalog, returns Some(filtered values) when the cmd has
a static argCompleter and the partial hasn't crossed into a second
arg (no embedded space). Exact-match dismisses the picker so the
user can press Enter to submit.
- render_slash_arg_overlay paints a narrow popup above the dock with
the command header ("/preset <arg>"), option count, and one row per
value (highlight + greyed suffix for typed-prefix matches).
- Key handling in run_integrated_loop: Up/Down moves selection,
Tab/Enter commits to "/<cmd> <value>", BackTab cycles backward.
slash overlay still takes priority when both could be active.
WholeScreen widget grows a with_slash_arg_index builder and threads
slash_arg_idx through to the render call. Test:
slash_arg_picker_static_completer covers prefix filter, exact dismiss,
past-first-arg cutoff, unknown cmd, and completion output.
* feat(scene): dynamic slash-arg picker — models / path / mcp / skills
The previous arg picker only worked for argCompleters that are static
arrays in the spec (preset / language / mcp-tool subcommands etc.).
For the dynamic kinds — "models", "path", "mcp-resources",
"mcp-prompts", "skills" — rust had no way to enumerate the values
(can't read MCP catalogs, can't list directories, can't see the model
registry), so commands like /model, /cwd, /resource, /prompt, /skill
fell through to "type it yourself" once the user hit space.
The fix routes the picker data through Node, which already computes
exactly this list inside useCompletionPickers (slashArgMatches):
- Node side computes slashArgStateJson = { cmd, partial, matches }
whenever slashArgContext has a picker AND there are matches. This
covers ALL five completer kinds — useCompletionPickers does the
filesystem listing for "path", the model lookup for "models", and
the MCP server walks for "mcp-resources"/"mcp-prompts"/"skills".
- Scene plumbing: useSceneTrace input field + parse helper + thread
through to the emitted message.
- Rust SceneState: new optional slash_arg_state: { cmd, partial,
matches } with serde defaults. SlashArgState struct.
- Rust slash_arg_matches: prefer scene.slash_arg_state when cmd +
partial match the current composer; fall back to catalog's static
arg_completer for offline / demo paths. Cmd+partial match guards
against stale pushes from a previous keystroke leaking in.
Tests: slash_arg_state_overrides_catalog_for_dynamic_completers
asserts (1) dynamic matches surface, (2) stale partial does NOT.
* fix(qq): /qq connect bails out instead of corrupting integrated screen
connect() uses promptLine for first-time setup (App ID, App Secret),
which drops out of raw mode and writes directly to stdout/stdin via
readline.question. Under REASONIX_RENDERER_INTEGRATED=1 the rust
child owns the alt-screen and the keyboard reader on the same fd —
the prompt collided with rust's frame composition and produced a
garbled screen with no usable input.
Now promptLine throws a descriptive error when isIntegratedRenderer-
Requested() is true. The qq handler already pipes the rejection
through ctx.postInfo, so the user sees:
ⓘ QQ connect failed: interactive prompt "QQ Open Platform App ID:"
is unavailable under REASONIX_RENDERER_INTEGRATED=1. Pass the
values inline (e.g. /qq connect <appId> <appSecret> [sandbox])
or run without integrated mode for the first-time setup.
Already-configured invocations (creds in loadQQConfig) skip
promptLine entirely and work as before.
* feat(scene): scene-driven text-input prompts (qq connect, future setup flows)
Drops the previous "throw an error" workaround for /qq connect under
the integrated renderer and replaces it with a proper round-trip
through the scene state.
Flow:
- Node code that needs a one-shot text answer calls
requestPromptInput({label, defaultValue?, secret?}) — singleton
store in src/cli/ui/scene/prompt-input-store.ts holds the active
prompt and the unresolved Promise.
- App.tsx subscribes via useSyncExternalStore and serializes the
active prompt as promptInputJson; useSceneTrace ships it as
scene.promptInput in the next frame.
- Rust SceneState has a new prompt_input: Option<PromptInput>
{ id, label, defaultValue, secret }.
- run_integrated_loop's key dispatch checks scene.prompt_input first
(between mode-picker and approval handling) and routes to a
dedicated handle_prompt_input_key: char/backspace/cursor keys edit
the buffer normally, Enter posts {event:"prompt-response", id, text}
back to Node, Esc posts {cancelled:true}, all other keys are eaten
so they don't trigger slash/at overlays.
- Dock composer renders the prompt label as the placeholder, swaps
the ❯ glyph for ? in WARN color, and masks the buffer with •
bullets when secret:true so an API secret never appears on screen.
- chat.tsx's integrated event handler resolves the pending Promise
on prompt-response; cancelAllPromptInputs fires on exit.
- qq use-qq-channel's promptLine now picks between the readline path
(non-integrated) and requestPromptInput (integrated); the App
Secret prompt is marked secret:true.
Composer-text echo is suppressed while a prompt-input is active so
the password doesn't leak into Node's chat input state.
* fix(rust): // should not surface the entire slash catalog
slash_match_count and collect_rows built their needle with
query.trim_start_matches('/'), which strips ALL leading slashes.
For input "//" that gives needle "" — same as bare `/` (group mode),
so the popup exploded into every catalog entry. The user is almost
always typing literal punctuation there ("//" as in a comment, URL,
etc.), so the popup should stay closed.
Switch both call sites to query.strip_prefix('/').unwrap_or("") so
only one leading slash is consumed. "/" → needle "" (group mode,
unchanged). "//" → needle "/" → matches_query("cmd", "/") false on
every command → no popup, no match. "///" same.
Test: double_slash_does_not_match_anything covers /, //, ///.
* feat(scene): surface dashboard URL in rust boot block
The web dashboard auto-starts on port-pin or ephemeral assignment
when the TUI launches, but in integrated mode the rust renderer
showed no trace of it — users had no way to discover the URL short
of running /dashboard explicitly. Add a third line to the boot meta
("model" / "workdir" / "dashboard") that surfaces the URL right
under workdir.
Wiring:
- Hoist the dashboardUrl useState in App.tsx above useSceneTrace so
the scene frame can include it. Pass dashboardUrl through the
trace input.
- SceneTraceInput gains an optional dashboardUrl string; useSceneTrace
emits it as part of the trace message.
- Rust SceneState gains dashboard_url: Option<String> with
rename = "dashboardUrl".
- boot.rs renders the line in DS_BRIGHT + UNDERLINED so it reads as
a link. Modern terminals (Windows Terminal, iTerm2, WezTerm, gnome-
terminal ≥3.26) auto-detect the URL and make it Ctrl+click-able
without OSC 8 — ratatui's grid-buffer model doesn't pass through
raw escape sequences cleanly, so we lean on the terminal instead.
Tests: dashboard_url_renders_in_boot_block,
dashboard_line_hidden_when_url_absent.
* feat(rust): OSC 8 hyperlink for the dashboard URL
The previous version relied on terminals auto-detecting URLs — most
of them don't, or require Ctrl+click which the user couldn't find.
paint_link writes an OSC 8 escape sequence into a single cell's
symbol (open + visible text + close) and flags the next visible-width
cells as skip, so ratatui's diff layer leaves them alone. The
terminal interprets the sequence and renders a real clickable
hyperlink; non-OSC-8 terminals (older xterm, basic SSH) still see
the visible text fall back to the underlined accent style.
Used in the boot block to make the dashboard URL clickable in
Windows Terminal, iTerm2, WezTerm, gnome-terminal ≥3.26, kitty —
i.e. anything modern.
---------
Co-authored-by: reasonix <[email protected]>
The chip already renders an <I.slash /> icon, so storing the raw
"/theme" produced a duplicate `/ /theme` once the popup picked the
command. Mention chips already store the bare name — do the same
for slash so the icon doesn't double the prefix.
Fixes#930
Co-authored-by: reasonix <[email protected]>
Closes#1028
Reported: the persistent CLI status bar and the web dashboard's bottom
bar / side rail show different numbers for the SAME running session
(ctx capacity, cache-hit ratio). Two independent causes.
(1) **K unit mismatch.** `formatTokens` (src/cli/ui/primitives.tsx)
divided by 1024 — `1_000_000` rendered as `977K`. The dashboard
formats via `(ctxCap / 1000).toFixed(0)` and shows `1000K`. Same
underlying value, different K convention. DeepSeek's own docs say
"1M context" / "128K", which is base-1000, so the CLI was the
outlier. Switched to base-1000.
(2) **Cache-hit metric mismatch.** The web reads
`loop.stats.summary().cacheHitRatio` — a session-aggregate
(carryover + sum across all turns / weighted hit-miss). The CLI
status bar's `status.cacheHit` was being fed the per-turn
`stats.cacheHitRatio` from the just-completed call. Identical loop,
different semantics, no label disambiguation. Routed the aggregate
through a new optional `sessionCacheHit` on the `turn.end` event;
the reducer prefers it for `status.cacheHit` and falls back to the
per-turn value when absent (back-compat). The per-turn UsageCard
in scrollback still shows the per-turn ratio — only the persistent
status bar changes.
Verified: 203 files / 3097 tests passing. Regression coverage:
- ui-reducer: turn.end honours sessionCacheHit when present; falls
back to usage.cacheHit when absent.
- ui-status-row-balance: ctx pill renders `720K/1000K` for the
720k/1M case (was `703K/977K` under base-1024).
Co-authored-by: reasonix <[email protected]>
Closes#943
Repro: open a new session in the desktop app, send the first prompt,
then click a different session in the sidebar BEFORE the AI finishes
streaming. The new session vanishes entirely.
Cause:
- A new session writes only `<name>.meta.json` at mint time; the
`<name>.jsonl` file isn't created until the first `appendSessionMessage`
call.
- `CacheFirstLoop.step()` only called `appendAndPersist` for the user
message AFTER the first API round-trip succeeded (loop.ts:977-980).
- Switching sessions tears down the loop via `abortTurn` → the in-flight
fetch is aborted, the loop never reaches the persist line, the `.jsonl`
is never written.
- The sidebar's `listSessionsForWorkspace` globs `.jsonl` only, so the
orphan `.meta.json` is invisible and the session is gone from the UI.
Fix: persist the user message at the very top of `step()`, before the
API call. If the round-trip fails the message stays on disk and the
user can `/retry` without re-typing — same UX as ChatGPT / Claude where
a failed send leaves the bubble visible. `pendingUser` becomes null
since the log already carries it; `buildMessages(pendingUser)` keeps
working unchanged.
Regression coverage in `tests/loop-user-persist.test.ts`:
- pre-response abort still writes the user message to the JSONL on
disk (the exact #943 scenario, simulated via a never-resolving fetch
+ `loop.abort()`)
- happy path still writes exactly one user copy followed by the
assistant turn (no duplicate-user regression)
Co-authored-by: reasonix <[email protected]>
Partial mitigation for #1031 — heap creeps monotonically in long
sessions and Mark-Compact eventually gives up. Tool cards retain their
full `output` string forever in the agent store; a 7-hour session that
reads files, runs greps, fetches pages, or screenshots a browser via
Puppeteer drags every one of those payloads through the heap until
OOM, even though only the most recent few are visible at a time.
`appendCard` now runs the cards through `elideOldToolOutputs` before
attaching the new one. Tool cards that have slid past the recent
window (default 200) have their `output` replaced with a short stub
that records the original length and points the user at the session
log on disk. UI ordering is preserved — only the heavy payload field
gets stripped. Recent cards are untouched; cards already stubbed are
skipped so the elision is idempotent; small outputs are left alone.
Out of scope: this is one of several likely contributors to the OOM
the issue describes. Diagnostic suggests other heap-resident sources
(streaming buffers, MCP subprocess handles, possible closure retention
on `/mcp reconnect`) may also contribute. #1031 stays open until a
heap-snapshot repro narrows the root cause further.
Regression tests cover: below-window untouched, beyond-window stubbed,
idempotent on second-pass, small outputs skipped, non-tool cards never
modified.
Co-authored-by: reasonix <[email protected]>
Closes#1011
Node's stock 2 GiB heap cap chokes long agent turns. The reported case
hits OOM about a minute after submitting a 221-character prompt on a
WSL2 + Node v24 + dashboard setup. The streaming buffers, SSE socket
state, and accumulating message log push the heap past 1.8 GiB before
the turn finishes, then mark-compact gives up:
Mark-Compact 1830.8 (2170.2) -> 1776.7 (2172.7) MB ...
FATAL ERROR: Reached heap limit Allocation failed
Fix: re-exec the process with `--max-old-space-size=<target>` appended
to NODE_OPTIONS at startup. No-op when the user already set the flag
themselves (NODE_OPTIONS or execArgv). Target is the smaller of 4 GiB
or half of system memory, clamped against a 2 GiB floor — keeps WSL2 /
container setups with constrained RAM from accidentally being asked to
serve a heap they don't have.
Implementation:
- `src/cli/heap-limit.ts` — pure `decideHeapTargetMb` (testable).
- `src/cli/heap-limit-launch.ts` — side-effect module that reads
`v8.getHeapStatistics().heap_size_limit`, calls the decision fn, and
`spawnSync`'s a child with the bumped NODE_OPTIONS, then `process.exit`s
with the child's status. A `REASONIX_HEAP_REEXEC=1` env sentinel
prevents infinite re-exec if Node ignores the flag.
- `src/cli/index.ts` imports `./heap-limit-launch.js` first so the
re-exec fires before commander / dashboard server / DeepSeek client
modules load — the bumped heap covers the full lifecycle.
Out of scope: the underlying leak (issue #1031 also OOM'd at 4 GiB).
Identifying that requires a reproducer + heap snapshot and stays open.
Co-authored-by: reasonix <[email protected]>
* feat(shell): sensitive-path pattern guard for run_command args (#259)
Path-argument scanner on top of the existing allowlist gate. When a
run_command or run_background call matches the allowlist but one of its
argv tokens resolves into a sensitive prefix or matches a sensitive
filename pattern, the call is demoted to the confirm gate — same code
path as RISKY_ARGS.
Default blocklist:
- Path prefixes: ~/.ssh, ~/.aws, ~/.gnupg, ~/.kube, /etc/shadow,
/etc/sudoers
- Filename patterns (case-insensitive): *.env, *.env.*, *.key, *.pem,
id_rsa*, id_ed25519*, *credentials*, *secret*
User-configurable via ReasonixConfig.sensitivePaths (prefixes + patterns).
Refs: OWASP AI Agent Cheat Sheet §1, §8
* fix: wire up user sensitivePaths config and use pathMod.sep for Windows
1. Read config.sensitivePaths in registerRooted and forward to
registerShellTools so the YAML override actually takes effect.
2. Use pathMod.sep in pathStartsWithPrefix instead of hardcoded '/'
so Windows backslash paths match correctly.
---------
Co-authored-by: KuaaMU <[email protected]>
Co-authored-by: reasonix <[email protected]>
Partial fix for #1031 — web typing lag, especially under Chinese / Japanese
/ Korean IMEs.
Two changes in `dashboard/src/panels/chat.ts`:
- Extract a memo'd `ChatInput` subcomponent that owns `input`,
`popoverKind`, `popoverItems`, `popoverSel` plus the input + popover
handlers. The parent `ChatPanel` no longer re-evaluates its full chrome
JSX (mode pickers, status bar, side rail, message feed) on every
keystroke; `ChatInput` re-renders alone. Parent callbacks (`onSubmit`,
`onNew`, `onClear`) are stabilised via refs for live values (`busy`,
`messages.length`) so the memo barrier actually holds.
- Handle IME composition with `onCompositionStart` / `onCompositionEnd`.
Browsers fire `input` events for every intermediate code point during
IME composition (one per pinyin keystroke for Chinese), and previously
each one triggered a slash / mention regex pass plus a popover state
update. The new gate stores composition state in a ref, skips the
popover work while composing, and ignores the Enter that IMEs use to
commit a candidate (otherwise we'd swallow the chosen character and
submit the half-composed input).
Out of scope: the OOM half of the issue (Puppeteer MCP / message-log
retention) — that needs a reproducer + heap snapshot and will be tracked
separately.
Co-authored-by: reasonix <[email protected]>
* refactor(mcp): implement configuration normalization and object-based server declarations
Introduces a robust configuration system for MCP servers that supports both legacy string-based specs and a new canonical `mcpServers` object format. This allows for advanced configurations including custom HTTP headers for SSE and Streamable HTTP transports.
- Adds `mcpServers` to `ReasonixConfig` to support structured server definitions.
- Implements `normalizeMcpConfig` to merge legacy `mcp` strings with the new object format, ensuring `mcpServers` takes precedence.
- Enhances `buildTransportFromSpec` to support passing `headers` for non-stdio transports.
- Updates CLI commands (`acp`, `mcp-inspect`, `mcp-runtime`, `run`) and internal resolution logic to use normalized configurations.
- Adds `specToRaw` for serializing normalized specs back to legacy string formats.
- Updates documentation to reflect the new configuration schema and examples.
- Adds unit tests for configuration normalization logic.
* feat(mcp): refine spec construction logic for different transport types
Implements transport-specific property assignment when merging parsed MCP specifications with normalized configuration. This ensures that environment variables are only applied to `stdio` transports, while HTTP headers are correctly scoped to `sse` and `streamable-http` transports, preventing invalid configuration leakage between types.
- Update `mcp-inspect` and `mcp-runtime` to use conditional spec building based on transport type.
- Refactor `reconnectMcpServer` to decouple transport-specific properties from the base specification.
- Improve type safety by explicitly typing the constructed `McpServerSpec`.
* refactor(mcp): centralize spec overlay logic into `overlayMatchedSpec`
Extracts the complex conditional logic for merging parsed MCP specifications with configuration into a dedicated utility function. This simplifies the command implementations in `mcp-inspect` and `mcp-runtime` and cleans up the reconnection logic.
- Add `overlayMatchedSpec` to `src/mcp/spec.ts` to handle transport-specific property merging.
- Replace inline switch statements in `mcp-inspect.ts` and `mcp-runtime.ts` with the new utility.
- Simplify `reconnectMcpServer` in `src/mcp/reconnect.ts` by removing redundant spec reconstruction.
Closes#1034
undici's `ProxyAgent` ctor calls `new URL(input)`, and Windows users
routinely set `HTTPS_PROXY=127.0.0.1:10888` (no scheme). Without a
scheme the URL ctor throws — the throw escapes the top-level
`installProxyIfConfigured()` call in `src/cli/index.ts:22`, killing
startup before any UI renders:
TypeError: Invalid URL code: 'ERR_INVALID_URL'
input: '127.0.0.1:10888'
at new URL (node:internal/url:818:25)
at #getUrl (.../ProxyAgent)
at installProxyIfConfigured
Two changes in `src/net/proxy.ts`:
- New `normalizeProxyUrl` auto-prefixes `http://` when the env value has
no `scheme://` and validates via `new URL`. Bare host:port becomes
`http://host:port/`; already-prefixed values pass through unchanged;
unparseable values return null.
- `installProxyIfConfigured` wraps the `setGlobalDispatcher(new ProxyAgent)`
call in try/catch and emits a stderr warning on either normalization
failure or ProxyAgent ctor failure instead of throwing — proxy misconfig
should never block startup.
Regression coverage in `tests/proxy.test.ts`: bare host:port auto-prefix,
existing prefixed URLs preserved, malformed values warn + return null
without throwing.
Co-authored-by: reasonix <[email protected]>
Tighten the 2-line // comment from #1046 to a single 1-line /** ... */
to match the repo's trailing-comment cap.
Co-authored-by: reasonix <[email protected]>
* perf(tokenizer): cache renderTools output via WeakMap
toolSpecs arrays are reference-stable across turns (ImmutablePrefix
returns the same _toolSpecs array). A WeakMap keyed on the array
pointer avoids re-JSONifying 20-40 schema objects and re-allocating
the ~1.5 KB tools template string on every decidePreflight call.
* fix: shorten tools cache comment to pass comment-policy lint
---------
Co-authored-by: Bernardxu123 <[email protected]>
Closes#1042
DeepSeek thinking-mode contract: every assistant message round-tripped
to the API must carry `reasoning_content` (even empty-string). When
`ContextManager.fold` synthesized its history-summary assistant turn it
built a bare `ChatMessage` literal — `reasoning_content` was never set.
On the next API call the persisted log replayed that turn and the
provider 400'd:
The `reasoning_content` in the thinking mode must be passed back
to the API.
Two changes in `context-manager.ts`:
- `summarizeForFold` now returns `{ content, reasoningContent }` so the
summarizer's own reasoning is preserved.
- `fold` builds the synthetic message via `buildAssistantMessage`, with
the SESSION's model as the producing model — so even if the summarizer
somehow emits no reasoning, the empty-string stamp lands on thinking-
mode sessions and the next call no longer 400s.
Regression coverage: `tests/context-manager-thinking-mode.test.ts`
asserts (1) summarizer's reasoning is carried through, (2) thinking-mode
sessions get empty-string stamping when the summarizer omits it,
(3) non-thinking sessions stay clean (no spurious `reasoning_content`).
Co-authored-by: reasonix <[email protected]>
* refactor(scene): move the entire scene producer from TS to Rust
Stage A of the user's "build the foundation right first" architectural
pivot. The JS side no longer builds a SceneFrame layout tree; it just
serializes the latest input state. Rust deserializes the state and
runs the full layout / palette / row-shape logic against the *real*
terminal area.
## Why
The TS scene producer was a recurring source of "things don't look
right" bugs because:
- JS reads its idea of terminal size from Ink's `useStdout()`, which
is the **null stream** under `REASONIX_RENDERER=rust` mode. Cols
and rows fell back to 80 × 24 every render, so layout decisions
(boot block size, card cap, dock thickness) were divorced from the
actual terminal — even though the renderer rendered against the
real area. Producer + renderer disagreed on dimensions.
- Two languages held the same constants (palette hexes, row counts,
glyphs). Every visual tweak required keeping both sides in sync.
- Each behavior change required `npm run build` + restart and a
fresh `cargo build` if either side drifted.
Moving the producer to Rust makes the renderer authoritative for
layout. Single source of truth, single rebuild target.
## What
New Rust modules under `crates/reasonix-render/src/`:
- `state.rs` — `SceneState` / `SceneCard` / `SlashMatch` /
`SessionItem` / `SetupState` / `Message` (tagged enum
`{ type: "trace" | "setup", ... }`).
- `theme.rs` — `palette::{bg, bg2, fg, fg1..3, ds, ds_bright,
ds_purple, ok, warn, err}` matching the v1 mock's oklch tokens.
- `producer.rs` — `build_trace_frame(&state, cols, rows)` +
`build_setup_frame(&state, cols, rows)`. Ports the boot block
(REASONIX ASCII banner), card kinds (`user` / `reasoning` /
`streaming` head+body, `tool` rich row, generic single-line for
others), composer / meta / status dock, slash overlay, sessions
picker, approval modal — all from the old TS producer.
`main.rs` reads messages from stdin: tries `Message`, falls back to
bare `SceneState`, then `SetupState`, then legacy `SceneFrame` for
back-compat with any pre-rolling-out builds. Each frame calls
`terminal.size()` to get the real cols/rows and feeds them into the
producer.
## JS side
`useSceneTrace.ts` shrunk from ~700 LOC to ~270 LOC — purely state
shaping now. The hook builds a plain object (`{ type: "trace", ...
state }`) and emits it via the renamed
`emitSceneMessage(message: unknown)`. Same for `useSetupSceneTrace`.
Helpers that survived (still used to serialize wire-format payloads):
`toSceneCard`, `parseRecentCards`, `parseSlashMatches`,
`parseSessions`, `summarizeCard`.
Gone (moved to Rust): `buildTraceFrame`, `buildSetupFrame`, all the
row builders (`composerRow`, `metaRow`, `statusBarRow`, `slashRow`,
…), the kind-glyph / color / label tables, `PALETTE`, `listWindow`,
`slashWindow`, `cardsForHeight`.
## Tests
- Rust (`crates/reasonix-render/tests/producer.rs`) — 14 new cases
covering boot block, card kinds, composer cursor, dock rows,
approval / slash / sessions overlays, status bar segments, edit
mode color, rich tool format, setup frame, body line cap.
- TS (`tests/scene-trace-frame.test.ts`) — pared down to the
20 wire-format tests that still apply (`summarizeCard`,
`toSceneCard`, `parseRecentCards`, `parseSlashMatches`,
`parseSessions`).
\`cargo test -p reasonix-render\` — 51 / 51 green (23 render +
14 producer + 6 decode-only + 6 input + 2 round-trip).
\`npm run verify\` — 3071 / 3074 green via prepush gate (3 pre-existing
skipped).
## Migration notes
- Rust binary **must** be rebuilt for users running off the prebuilt
`target/release/reasonix-render.exe` — the new producer is the
binary's job now.
- The legacy `SceneFrame` JSON shape is still accepted by Rust as a
fourth-tier fallback, so a stale JS bundle paired with a fresh
Rust binary keeps working until both roll forward.
Refs #868
* fix(rust): enable raw mode and drop scroll-area inner padding
Two suspected causes of the "底部 / 左右 / 上下 都有点没顶全" gap
that survives Stage A:
1. `main.rs` never called `enable_raw_mode()` for the render path.
In cooked mode the terminal driver treats a write to the last
row × last column as an implicit newline / scroll, which leaves
the bottom row visually empty under ratatui + alt-screen.
`run_emit_input` (the keystroke-only branch) already enables raw
mode for its own loop; the render branch was missing it.
2. `scroll_area` carried `padding_x: 2, padding_y: 1` inside the
producer, eating 2 cells off each horizontal edge of the scroll
area and 1 row off the top/bottom. The outer box's bg drew the
right color underneath, so it didn't read as a true "gap" — but
on a terminal whose own cell-edge padding is non-zero the
compounded effect looked like all four sides were short.
Also added a one-shot debug log gated on REASONIX_RENDER_DEBUG=1 that
writes `terminal.size()` at startup + the first frame's `area` to
stderr (which under rust mode is the ~/.reasonix/rust-render-stderr.log
file). Useful for verifying the renderer is seeing the real terminal
dimensions, not 80×24.
Refs #868
* fix(rust): debug log writes to a file instead of stderr
Stderr from the rust child inherits Node's OS-level fd (stdio:
"inherit"); the parent's process.stderr.write override is only
JS-level and doesn't catch native writes from the rust binary, so
the previous eprintln-based diagnostic vanished into the parent
terminal (where ratatui's alt screen masked it).
Switched to writing the diagnostic to a file —
REASONIX_RENDER_DEBUG=1 enables, REASONIX_RENDER_DEBUG_LOG overrides
the path; default is ~/.reasonix/rust-render-debug.log.
* fix(rust): drop outer background fill, let terminal bg show through
User feedback: \"为什么其他他们都能自动顶满,我们还要设置 WT padding?\"
Answer: we were painting a #0f1018 dark bg on the outer box, which
makes the cell grid contrast with the terminal's own background. The
WT pixel padding between window frame and cell grid then renders in
the terminal's default bg — visually a colored frame around our
drawing area.
vim / less / claude / etc. don't paint a bg color. Their cells render
in the terminal's default bg, so the WT padding ring matches and
disappears.
Same treatment here: outer + scroll_area now use BoxLayout::default()
(no bg). The dock's composer / status rows keep their bg2 tint —
that's a deliberate panel-strip effect inside the content flow, not
a full-screen wash.
Setup frame also drops its bg for the same reason.
Refs #868
* fix(rust): restore outer background fill, drop "no bg" variant
User report: dropping outer bg caused ghosting. Diagnosis: ratatui's
diff renderer compares cells frame-to-frame and only writes cells
that changed. When the outer box paints a solid bg every frame, every
cell of the frame is touched with that bg → any leftover content
from a prior frame gets overwritten cleanly.
When outer bg was removed, cells with no current-frame writes
(default Cell = space + Color::Reset) didn't necessarily appear as a
change vs the previous frame, and stale characters / fg colors stuck.
Restoring outer + setup-frame background = palette::bg(). The cost
is the WT pixel-padding ring showing the terminal's default bg
instead of ours, which is the same trade-off vim / lazygit / btop /
zellij all make. Recommend the WT 0-padding setting in the README
rather than try to eliminate the bg layer.
Also added terminal.autoresize() at startup so the very first frame
already knows the actual terminal size — defensive in case the
backend's cached size lags the first draw on Windows.
Refs #868
* chore(rust): bump ratatui 0.29 → 0.30 + crossterm 0.28 → 0.29, modernize main
Two upstream releases pulled in:
- ratatui 0.30.0 (2025-12-26): `Alignment` → `HorizontalAlignment`
alias, `Color::from_crossterm/into_crossterm` replacing
From/Into, `Flex::SpaceAround` semantics now match CSS. None of
the breaking surface touches our code (we don't use those
identifiers).
- crossterm 0.29.0: KeyModifiers Display fix; no API change at our
call sites.
Meanwhile, three modern idioms we were missing:
1. **BufWriter around stdout** — ratatui docs flag unbuffered
stdout as the #1 perf footgun. Per-cell write syscalls in the
diff loop add up fast on Windows. Wrapping with BufWriter
collapses each frame into one flush.
2. **Panic hook that restores the terminal** — without it, a Rust
panic leaves the user stuck in raw mode + alt-screen with no
keyboard echo and a broken prompt. We now install a hook that
disables raw mode and leaves the alt-screen before chaining to
the previous hook (so backtraces still print).
3. **Factored init / restore helpers** — `init_terminal()` does
`enable_raw_mode` + `EnterAlternateScreen` + new BufWriter
backend; `restore_terminal()` is the matching teardown. Same
shape as `ratatui::init` / `ratatui::restore` (which we'd use
directly if we didn't need the BufWriter / custom backend
variant).
Renamed local terminal type to `RenderTerminal` for clarity
(`Terminal<CrosstermBackend<BufWriter<Stdout>>>` is unwieldy at
every call site).
All 51 Rust tests still pass. JS-side npm verify untouched.
Refs #868
* fix(rust): wrap each draw in synchronized output + clear on resize
Two stability strategies that modern TUI apps use to eliminate
tearing / partial-frame flicker / cross-frame ghosting:
## Synchronized Output Mode (DCS 2026)
Every `terminal.draw()` is now bracketed by
ESC[?2026h (BeginSynchronizedUpdate)
ESC[?2026l (EndSynchronizedUpdate)
Supported by Windows Terminal 1.18+, kitty, foot, alacritty, ghostty,
iTerm2 3.5+, recent VS Code terminal. Terminals that don't recognize
the sequences silently ignore them — zero downside.
What it does: the terminal app stops flushing pixels mid-frame.
Whatever ANSI bytes arrive between BSU and ESU are buffered; one
atomic display update happens at ESU. Eliminates:
- Visible cursor "scanning" across the screen during a draw
- Partial-frame artifacts when the diff updates two adjacent rows
that haven't been ESC-positioned together
- Cross-frame ghosting that survives a diff miss (the next frame's
paint lands atomically over the previous, no in-between state)
ratatui doesn't auto-wrap draws in BSU/ESU (probably because the
escape sequences are still terminal-specific), so we do it
ourselves around each call via `crossterm::execute!`.
## Force terminal.clear() on terminal resize
Each iteration of the stream loop reads `terminal.size()` and
compares to the previous frame's size. On change → `terminal.clear()`
which marks the next frame as a full redraw (no diff). Prevents
stale cells from showing through after a window resize.
ratatui already auto-resizes on `terminal.draw`, but auto-resize
preserves the diff state which can leave the OLD-dimensions content
in cells that no longer belong to the new layout.
## Borrow-checker note
`Terminal::draw` returns a `CompletedFrame<'_>` that borrows the
terminal. We discard it with `.err()` so the second
`crossterm::execute!` (for `EndSynchronizedUpdate`) can re-borrow
the terminal mutably.
Refs #868
* refactor(rust): rewrite view layer on top of ratatui widgets, drop custom scene tree
The previous architecture had two layers of abstraction stacked on top
of ratatui — `SceneNode` (the protocol type) and `BoxNode` (our own
flex layout engine). The Rust render code wrote cells via
`buf[(x,y)].set_char()` directly, bypassing ratatui's widget system.
That bypass was the root cause of every \"shouldn't ratatui handle this\"
class of bug we kept hitting:
- ghosting from diff misses when our cell-direct writes didn't match
ratatui's expected mutation pattern
- CJK / emoji width counted twice (once by our `unicode-width` advance,
once by ratatui internally)
- no layout cache; full re-layout every frame
- ~1500 LOC of producer + render + scene-tree we maintained ourselves
instead of using ratatui's tested Layout + Paragraph + Block
This PR throws all of that out and uses ratatui's widgets directly.
## What's gone
Deleted from the Rust crate:
- `src/scene.rs` (SceneFrame / SceneNode / BoxLayout / TextRun /
TextStyle / BorderStyle / Dim / FillToken / FlexDirection /
FlexAlign / FlexJustify — 178 LOC)
- `src/producer.rs` (the entire 1,387-LOC scene-tree builder)
- `src/render.rs` (the 389-LOC manual cell-writing renderer with our
own flex algorithm)
- `tests/render.rs` (557 LOC of tests against the deleted renderer)
- `tests/producer.rs` (335 LOC against the deleted producer)
- `tests/round_trip.rs` (107 LOC against the deleted SceneFrame
protocol type)
Deleted from the JS side (no longer used now that JS only emits raw
state):
- `src/cli/ui/scene/build.ts` (the `box` / `text` / `frame` helpers)
- `src/cli/ui/scene/types.ts` (SceneNode / BoxLayout etc. — protocol
types are Rust's now)
- `src/cli/ui/scene/theme.ts` (palette moved to Rust)
- `src/cli/ui/scene/lower.ts` (the abandoned Ink-tree-to-scene
conversion from the original Stage 0 plan)
- 4 test files that exercised the deleted modules
Total: -3,806 LOC across deleted files.
## What's new
`src/view.rs` (779 LOC) — a single `render_trace(state, frame)` +
`render_setup(state, frame)` entry point that uses ratatui widgets
directly:
- `Layout::default().direction(Direction::Vertical).constraints([...])`
for the scroll-area / dock split (instead of our `compute_axis_sizes`)
- `Paragraph::new(Text::from(lines))` with `Wrap { trim: false }` for
the scroll content (instead of our line-by-line `set_char` loop)
- `Block::default().style(Style::default().bg(...))` for the dock and
status bg tints (instead of our custom bg fill path)
- `Line::from(Vec<Span>)` for every styled row; ratatui handles wide
characters / emoji widths internally
- `render_row_split` helper for left-aligned + right-aligned spans on
the meta and status rows
`tests/view.rs` (288 LOC) — 15 cases using `ratatui::backend::TestBackend`
to render into an in-memory grid and assert the symbol stream. Every
behavior the deleted producer.rs tests covered (boot block, card
kinds, composer cursor, dock rows, approval / slash / sessions
overlays, status bar segments, edit mode color, rich tool format,
setup frame) is re-tested against the new view.
`theme.rs` absorbed `Color` / `NamedColor` (previously in scene.rs);
palette is unchanged.
`decode_only.rs` switched from `serde_json::from_str::<SceneFrame>`
(no longer exists) to `serde_json::Value` — it's a dev helper that
just counts valid JSON-line frames, doesn't validate their shape.
## Pipeline shape (unchanged, still JS → JSON state → Rust)
```
JS state change
↓ useSceneTrace useEffect
↓ emitSceneMessage({ type: "trace", model, cards, ... })
↓ child.stdin.write(json + "\n")
↓ Rust child reads line
↓ decode_message → Payload::Trace(SceneState)
↓ render_trace(state, frame) ← new
↓ ratatui widgets emit cell ops
↓ ratatui diff vs previous frame
↓ BufWriter → stdout → terminal
```
Sync-output mode (begin/end synchronized update) and the resize
clear-on-change guard from the previous commits are still in place.
`cargo test -p reasonix-render` — 24 / 24 green
(15 view + 6 input + 3 decode_only).
`npm run verify` — 3039 / 3042 green (3 pre-existing skipped).
Refs #868
* fix(rust): scroll area padding via Block, not by shrinking the area
The previous render_scroll manually carved a `Rect` 2 cells in from
each edge of the scroll area and rendered the Paragraph into that
inner Rect. The OUTER 2-cell horizontal margin + 1-row top/bottom
margin were never touched by the Paragraph and the canvas-block at
the start of render_trace only sets style (bg) on cells, not their
symbol. So when boot block → cards transitioned, the boot block's
LOGO chars at the very edge of the scroll area persisted as ghosts.
Switched to `Paragraph::new(...).block(Block::default()
.padding(Padding::new(2, 2, 1, 1)).style(...))`. The Block paints
its bg over the full scroll-area rect (including the padding ring)
and indents the inner content via Padding — so every cell is fresh
each frame, no ghosting.
Refs #868
* fix(rust): set bg on every Paragraph + bottom-anchor cards in scroll
Two real bugs the ratatui source dive (paragraph.rs:407-413) caught:
## 1. Paragraph paints its own style over the OUTER area first
The render order inside Paragraph::render is:
1. buf.set_style(area, self.style) ← outer paint
2. self.block.render(area, buf) ← block paint (covers
only border / bg
cells controlled by
the block style)
3. render text into inner(area)
If Paragraph has no style set, step 1 paints style=default (no bg),
WIPING any bg that a separate Block widget rendered over the same
area beforehand. We were doing exactly that — render_status painted
a Block with bg=bg2 over the status area, then called render_row_split
which used Paragraph::new(left/right) with no style. The Paragraphs
painted their default "no bg" over the left and right chunks,
overwriting the bg2 strip the Block had just laid down. Net effect:
status bar bg2 only survived in cells the Paragraphs didn't touch,
which is a fragmented mess after a diff.
Fix: set `.style(Style::default().bg(...))` on every Paragraph that
needs a bg, instead of relying on a separate Block widget.
Applied to:
- render_scroll (Paragraph.style + Block.style both = palette::bg())
- render_composer (bg2)
- render_approval (bg2)
- render_meta (bg, via render_row_split bg arg)
- render_status (bg2, via render_row_split bg arg)
- render_slash_overlay (bg)
- render_sessions_picker (bg)
- render_setup (bg)
render_row_split now takes a `bg: Color` parameter and applies it to
both half-paragraphs.
## 2. Cards anchor at the bottom of the scroll area, not the top
Paragraph has no vertical-alignment setter — content always starts
at the top row of the area (paragraph.rs:449-458). For chat we want
the latest message adjacent to the composer, not the brand banner.
scroll_lines() now pads the line list at the TOP with empty Lines
when content is shorter than the available height, so cards drift
down to sit just above the dock. Boot block (empty cards path) is
unchanged — stays at the top of scroll.
Together these two fixes address every "didn't fill / ghost / partial
bg" complaint that survives the architectural rewrite.
Refs #868
* feat(rust): rewrite trace renderer as cell-level WholeScreen widget
Replace the ratatui Paragraph + Layout-based render_trace with a
single cell-level Widget that hand-paints every (x, y) in the
frame. The whole layout splits into the whole_screen/ module:
- theme + paint primitives (paint, paint_str, fill_bg, truncate,
format_ts) with CJK width handled via unicode-width + set_skip
on continuation cells
- boot block (REASONIX logo + model/cwd/git/tools/hint rows)
- dock: bordered input box, kbd hint row, status bar with ctx bar
segments and threshold colors
- sidebar: Mission Control header + PLAN / JOBS / CHANGES /
SESSION sections, auto-binding to todo + tool cards in state
- cards/ subdir, one file per kind: message (user/reasoning/
assistant), todo, tool, diff, output (cmd/fileview/search),
notify (subagent/confirm/await/error). 13 kinds total.
- slash + @file autocomplete overlays as bordered popups above
the dock, with arrow-key navigation and Enter to complete
- row-level scrolling via virtual buffer + thumb scrollbar on the
right edge; mouse wheel, PgUp/PgDn, Home/End
- mouse drag selection with cards-area clamping, scroll-anchor
tracking (selection follows content under scroll), auto-scroll
when dragging past edges, auto-copy to system clipboard via
arboard on mouse-up
- tick loop (80ms) drives spinner frames on Running tool cards,
composer caret blink, streaming text reveal on the assistant
card body
Stream-loop now multiplexes JSON state from stdin (in a reader
thread feeding an mpsc channel) with crossterm events. Keyboard
stays with Node (no protocol change needed for typing); rust
captures mouse only and updates local UI state (scroll, selection)
independently of incoming state.
A new --demo flag drives an interactive playground state with
all card kinds populated.
32 new tests in tests/whole_screen.rs cover overlays, card kinds,
selection, scrolling, animation. view::render_trace is no longer
reached from main.rs (deleted in a follow-up commit).
* refactor(rust): drop view::render_trace and its 13 tests
stream-loop has rendered Trace payloads through WholeScreen since
the previous commit; view::render_trace and its 28 helpers are no
longer reachable. Delete them.
Keep view::render_setup — that's the API-key entry screen (Setup
payload), a separate UI path that WholeScreen doesn't cover.
view.rs: 796 → 98 lines
tests/view.rs: 15 → 2 tests (kept the 2 setup tests)
* feat(rust): composer editing — cursor movement, word-nav, insert at point
Track composer cursor index in the demo loop instead of always
appending to the buffer. Char keys insert at cursor (not just push
to end). Cursor moves through the text:
Left / Right one character
Ctrl+Left / Right one word
Home / End start / end of buffer
Backspace delete char before cursor
Ctrl+Backspace delete word before cursor
Delete delete char after cursor
Home / End used to scroll cards top / bottom; that was reassigned
to PgUp / PgDn (which were already there). Cursor is the more
natural binding for editing.
Word boundary uses char::is_whitespace transitions. CJK runs are
treated as one word since is_whitespace is false for them; matches
typical terminal editing intuition.
The caret ▮ renders at composer_cursor in dock.rs — text before
cursor + caret + text after cursor, so the caret visually sits
between characters when mid-string.
* feat(rust): idle empty-state banner + composer cursor + prompt mode hint
When state.cards is empty, the cards area now renders a 2-row idle
banner (OK rail) instead of leaving the middle blank:
▎ ● idle ready for next task
▎ type below · / commands · @ file refs · ! shell
Matches the React mock's Idle component. Shown on first launch and
after /clear when production reasonix wires state.cards to empty.
dock composer paints the caret ▮ at composer_cursor instead of
always at end-of-text, so the caret can sit between characters.
The ❯ prompt now signals what mode the user is in by color:
default ds-bright (chat)
/... ds-bright (slash command — paired with overlay)
@... ds-purple (attach file — paired with overlay)
!... ok-green (shell mode)
3 new tests: idle banner content, caret at cursor index, !shell
prefix doesn't accidentally trigger slash/at overlays.
* feat(rust): multi-line composer with Shift+Enter, scroll-to-cursor, line nav
Composer now grows from 1 to 5 content rows as the buffer gains
newlines (DOCK_HEIGHT + lines - 1, capped at 5+MAX_COMPOSER_ROWS-1
= 9 rows total). Cards area shrinks accordingly; selection cards
layout reads the same dock height so mouse coords stay aligned.
Shift+Enter inserts \n at cursor
Enter submits the whole buffer (newlines preserved)
Up / Down when no overlay is active, move cursor between
lines preserving column; otherwise navigate the
overlay match list (existing behavior)
Beyond 5 content rows the box scrolls vertically so the cursor
line is always visible. ↑ and ↓ glyphs appear at the box edge to
indicate hidden lines above or below the visible window.
Slash and @file completion now place the cursor at end of the
substituted buffer instead of leaving it stale.
* feat(rust): Tab / Shift+Tab cycles slash and @file overlay matches
Standard shell-completion gesture. Tab moves selection forward and
wraps to top when at end. Shift+Tab moves back and wraps to bottom.
Updates the navigate hint in both overlays to show "↑↓/Tab navigate".
Up/Down still work as before; Tab is just an extra binding.
* feat(rust): --integrated mode — full UI ownership with event proto to Node
A new mode flag that combines the demo loop's interactive composer
with the stream loop's stdin-driven scene state. Designed to let
production reasonix hand the entire UI (typing, slash/@ overlays,
scroll, selection, all keybindings) over to the rust renderer
instead of splitting input between Node's Ink composer and rust's
mouse-only capture.
Architecture:
stdin Node → rust line-delimited SceneState JSON
stderr rust → Node line-delimited event JSON
stdout rust → tty rendered frames
controlling rust ↔ tty keyboard + mouse via crossterm
rust owns composer state locally (buffer, cursor, slash_idx,
at_idx, scroll, selection, dragging, tick). On each frame, it
overlays composer_text + composer_cursor onto the incoming
SceneState clone, then renders WholeScreen as usual. Local UI
state never round-trips to Node.
Events emitted to stderr:
{"event":"submit","text":"…"} plain Enter with non-empty buffer
{"event":"interrupt"} Ctrl+C while scene.busy
{"event":"exit"} Ctrl+C when idle, or Ctrl+D
Setup payloads from Node fall through to render_setup with no
keyboard capture for that frame; Node-side Ink can keep handling
the API-key entry if needed.
Plumbing change: Payload + decode_message moved from main.rs to
state.rs so integrated.rs can use them. Composer editing helpers
(insert_char_at, cursor math, word boundaries, line nav) moved to
a new editor module shared between demo and integrated loops.
Node side is unchanged — needs a follow-up PR there to spawn rust
with --integrated, pipe stderr, parse events, and disable Ink's
own composer.
* feat(scene): wire REASONIX_RENDERER_INTEGRATED=1 to spawn rust --integrated
The rust renderer's --integrated mode (lands on the
whole-screen-prototype branch in the reasonix-render crate) lets
it own keyboard + composer state and report submit/interrupt/exit
events back to Node via stderr. This wires the Node side to it.
When REASONIX_RENDERER=rust and REASONIX_RENDERER_INTEGRATED=1:
- spawnRenderer adds --integrated to the child args
- the child's stderr is piped (was inherit) and parsed
line-by-line as JSON events
- the keystroke input child is skipped — rust captures the
terminal directly via crossterm
- trace exposes setIntegratedEventHandler so chat.tsx can
register a single dispatcher before the first scene frame emits
Events handled:
submit routed to qqSubmitRef.current — same code path the QQ
channel uses to feed text into App's queuedSubmit
effect, then through handleSubmit
exit clean shutdown via stopAndSaveCpuProfile + process.exit
interrupt no-op for now (terminal SIGINT already reaches Node);
wiring loop.abort is a follow-up
Backwards compatible: without the env var the existing rust mode
(Ink composer + RustKeystrokeReader input child) keeps working.
* chore(rust): add pulldown-cmark for markdown rendering
Pulls in pulldown-cmark 0.13 (+ unicase) so the renderer crate can
parse markdown bodies from assistant messages.
* feat(rust): render markdown bodies in assistant message cards
Parses message/notify/output card bodies as markdown (headings,
code, lists, tables, blockquotes, inline emphasis) and renders them
cell-by-cell within the card body width. Adds shared wrap_visual
helper in cards/mod.rs so wrap math stays in one place.
* feat(rust): integrated-mode polish — approvals, pickers, completion, sidebar toggle
Round of feature work on top of the --integrated runner:
- Approval prompts (plan / shell / path / edit / choice / checkpoint)
rendered as a full-screen overlay above the dock, with key handlers
on the rust side and an event protocol back to Node.
- Mode picker (review/auto/yolo) and preset picker (auto/flash/pro)
triggered from clicking the pills in the status bar.
- Dynamic slash and @file overlays — both now drive from a catalog
pushed in scene state (slash_catalog / at_state) instead of hardcoded
command and path lists.
- Multiline composer wrap + cursor positioning across visual lines.
- Live session stats in the right sidebar (model, ctx, ↑/↓ tokens,
cache %, cost, balance, last turn) read straight from scene state.
- Integrated event loop split into stdin / terminal reader threads
with a unified Evt channel.
- Sidebar Ctrl+B toggle (was an unimplemented "⌘. toggle" hint);
long PLAN / JOBS labels now wrap multi-line inside the sidebar
instead of being truncated.
- Bounded paint_str_to() so the boot hint, cwd, logo etc. clip to
the main-panel width instead of bleeding into sidebar columns.
Tests: full sidebar/toggle/wrap regression suite + new dynamic
slash/at catalog coverage.
* feat(ts): wire React UI to integrated-mode rust events
Bridges the rust --integrated runner back to the Node UI layer:
- App.tsx routes approval-response / mode-set / preset-set / composer
events from the rust child to the existing React handlers via refs.
- useSceneTrace pushes the additional scene fields the rust side now
consumes (preset, session/last-turn tokens + cost, cache_hit_ratio,
slash_catalog, prompt_history, approval, at_state).
- State + reducer track session input/output tokens and last turn ms
for the new sidebar SESSION block.
- Composer text echoed from the rust side feeds useInputRecall so the
recall popover sees the live buffer.
- renderer-process gains a composer event type; chat.tsx forwards the
integrated flag so REASONIX_RENDERER_INTEGRATED=1 spawns rust with
--integrated.
* chore: demo-utils sample + probe-fanout debug script + tau-bench db tweak
- src/demo-utils.ts + tests: tiny sample module used as the target for
risk:med submit_plan dogfooding.
- scripts/probe-fanout.mts: headless probe that measures tool-call
fan-out and ordering for the run_skill flow (issue #675).
- benchmarks/tau-bench/db.ts: minor adjustment to test data.
* chore: drop demo-utils file header to meet comment-policy
5-line header tripped the ≤2-line rule. Names are doc enough here.
* chore(rust): cargo fmt across reasonix-render
CI's cargo fmt --check failed on the new test bodies (long single-line
strings and asserts). Ran cargo fmt to bring everything in line.
* chore(rust): satisfy clippy -D warnings
CI runs `cargo clippy --all-targets -- -D warnings`; the integrated-mode
polish landed lints on:
- too_many_arguments — paint_str_to, paint_cell, paint_entry,
render_block, render_table, render_card_header (renderer helpers with
many style/geometry params; #[allow(clippy::too_many_arguments)])
- manual_clamp — overlay.rs / overlay_at.rs: use .clamp() directly
- needless_range_loop — md_render.rs table rows: switch to
col_widths.iter().enumerate()
- large_enum_variant — state::Message / Payload: SceneState dwarfs
SetupState; #[allow] on both
- needless_lifetimes — overlay_at::entries_for
- question_mark — integrated::cycle_or_pick: let-else → `?`
- dead_code — markdown::MdBlock::Code lang field (kept for parser
fidelity)
- field_reassign_with_default — three test fixtures; use struct init
- unused assignment / parentheses / loop counter — trivial cleanups
* chore(rust): reflow message.rs use line after clippy import prune
cargo clippy --fix removed unused imports but left the remaining
use {...} braces on too many lines for rustfmt's check.
* chore(rust): collapse Event::SoftBreak | HardBreak match arm into guard
clippy 1.95 added collapsible_match — fold the inner `if !in_code`
into a match guard on the outer SoftBreak/HardBreak arm.
---------
Co-authored-by: reasonix <[email protected]>
The 64-call per-turn iter cap was a stateless-completion-era backstop
that long-running tasks kept tripping into. Multiple users have reported
it blocks legitimate work; the comment that called it a "last-resort
backstop" already acknowledged the primary stop is the token-context
guard, so the field is pure footgun. Same goes for subagents — their
8/20-call defaults pushed real explore/verify work into pause-resume
cycles for no functional reason.
What's left as the real stops:
- token-context guard (ContextManager.decidePreflight + decideAfterUsage):
folds history when prompt pressure rises, force-summarizes when fold
no longer helps. Still in place, untouched.
- storm breaker: catches repeated identical tool calls.
- parent abort cascade: subagent dies when parent aborts.
- user Esc.
Deletions:
- CacheFirstLoopOptions.maxToolIters + the field on the class.
- For-loop iter cap → unbounded; loop exits only via return statements
(no more tools / context-guard / abort / fatal error).
- 70% in-step warning, result-augmenter "wrap up soon" injection.
- onIterBudgetExhausted opt + post-loop "budget exhausted" handler.
- subagent pause/resume mechanism (was iter-cap-tied): SpawnSubagent /
SubagentTool no longer take maxToolIters; spawn_subagent tool drops
max_iters parameter; SubagentResult drops paused / pausedSession /
partialSummary; LoopEvent drops paused role + pausedAtIter +
partialSummary; force-summary.ts drops summarizePartialProgress and
the "budget" reason in reasonPrefixFor/errorLabelFor.
- Skill frontmatter `max-iters` field + matching install_skill arg.
- SubagentTypeSpec.maxToolIters (explore=20, verify=8 caps gone).
- Distillation telemetry drops `paused` + `pausedSpawnCount`.
- i18n: toolBudgetWarning, reasonBudget, labelBudget; abortedAtIter no
longer carries `{cap}`.
Net -743 lines across 20 files; 1 dead test file deleted.
Co-authored-by: reasonix <[email protected]>
The 200-line head+tail preview was actively hurting model reasoning:
a 500-line source file dumped a stitched fragment of 80 + outline + 40
instead of the actual code, so follow-up reasoning ran on a half-blind
view. Replace the line-threshold gate with a byte-threshold gate that
trusts the prompt cache.
- Files ≤ 512 KiB → full content. No more "auto-preview" stitching.
- Files > 512 KiB → outline mode: metadata + first 80 lines + symbol
outline + concrete next-step commands (search_content / range / head).
- Files > 32 MiB → refuse load; same next-step menu.
- NUL-byte sniff over first 8 KiB rejects mislabeled binaries cleanly
instead of dumping UTF-8 garbage.
Extend the outline extractor so non-code users aren't blind in outline
mode:
- .proto: top-level message / service / enum + nested rpc.
- .txt: Chinese (第N章/节/回, 卷N, 楔子, 番外 …) and English
(Chapter N, Part N) chapter markers — usable for the novel
/ long-document workflow.
Renames `FilesystemToolsOptions.maxReadBytes` to `outlineThresholdBytes`
to reflect the new semantic (was hard truncate, now outline trigger).
Co-authored-by: reasonix <[email protected]>
Three layered fixes for the streaming-card jitter feedback loop (refs #549 / #700):
- MeasuredCard reports height only on growth for unsettled cards, suppressing Yoga's transient shrink measurements that fed back into virtual-window oscillation. Settled cards still report the exact final height.
- useIncrementalWrap debounces lineCells changes by 120ms via useEffect + useState, holding the previous width during a terminal resize so the incremental wrap stays on its monotonic path until the new width settles.
- Rust render loop adds FrameCache: skip JSON deserialization, scene render, and ratatui diff when consecutive raw frames are byte-identical. Trace scene only changes on card/model/activity updates, so most frames between streaming deltas are duplicates.
- New `banner?: boolean` field on `ReasonixConfig` (default true preserves existing behavior)
- When set to false, `bootReady` starts true and the 1.4s whale-spout timer is skipped — main UI appears as soon as React mounts
Supersedes the symptom-only fix from #895 — that one shipped `WEBKIT_DISABLE_DMABUF_RENDERER=1` but the abort fires before DMABUF init, so it never touched the failing path.
Root cause: AppImages bundle `libwayland-client.so.0` from the Ubuntu CI runner; distros with a divergent libwayland ABI (Tumbleweed / Fedora / Arch on some weeks) make `eglGetDisplay()` return `EGL_BAD_PARAMETER` and WebKitGTK 2.42+ aborts unconditionally.
Fix: at main() entry, when we detect AppImage (`APPDIR`) + Wayland (`WAYLAND_DISPLAY`) on Linux, set `LD_PRELOAD` to the first existing host libwayland (`/usr/lib64/...` then Debian-multiarch). WebKitWebProcess is fork+exec'd from us and inherits the env, linking against the host libwayland instead of the bundled one. Also forces `WEBKIT_DISABLE_COMPOSITING_MODE=1` on the same code path. The DMABUF disable from #895 stays as an always-on helper for Mesa stacks that don't need the libwayland swap.
Refs #892 — leaving open until huangsijun17 confirms on real hardware via a workflow_dispatch AppImage build.
- New `[data-theme="light"]` block overrides every `:root` CSS variable with an Element Plus palette (4.5:1 contrast target)
- ~35 targeted fixups for hex/rgba values that bypass CSS variables in the dark theme
- Sun/moon toggle in the sidebar footer, persisted to `localStorage.rx.theme` with `prefers-color-scheme` as the first-visit fallback
- i18n strings (en + zh-CN) for themeToggle / themeLight / themeDark
Closes the gap between our generic single-line tool cards and the
design mock's tool rows. Where before a tool call showed up as just
`▸ bash`, the scene now matches the mock layout:
▸ Read (src/parser.ts) ✓ 0.12s #a4f1
▸ Grep (parseStream) ✓ 7 matches 0.08s #a4f2
▸ Bash (false) ✗ 10ms #f00a
## Schema
\`SceneTraceCard\` gains four optional fields — \`args\`, \`status\`
("ok" / "err" / "running"), \`elapsed\` (preformatted "0.12s" or
"120ms"), and \`id\` (shortened "#xxxx"). Non-tool cards keep just
\`kind\` + \`summary\`, so the existing tests and JSON shape are
backward compatible.
\`parseRecentCards\` accepts the new optional fields when present,
ignores them when absent.
## App side serializer (\`toSceneCard\`)
New export replaces the inline \`{ kind, summary }\` shorthand in
App.tsx's \`recentCardsJson\`. For tool cards:
- \`status\` derives from \`done\` + \`rejected\` + \`aborted\` +
\`exitCode\` — non-zero exit / rejected / aborted → "err",
done → "ok", otherwise "running".
- \`elapsed\` formats ms < 1000 as "Nms", else "N.NNs".
- \`args\` extracts a primary display string from the tool's args
object — tries \`path\` / \`file\` / \`command\` / \`cmd\` /
\`pattern\` / \`query\` / \`url\` in that order, then falls back to
the first string value in the object.
- \`id\` shortens \`Card.id\` to "#" + last 4 alphanumerics.
Behavioral choices match the mock: primary arg goes in parens, ✓/✗
glyph picks status color (ok teal / err pink), elapsed in fg2 muted,
id in fg3 dim trailing.
## Renderer side (\`toolCardBlock\`)
Special-cased in \`cardBlock\` for kind === "tool". Other kinds keep
the simple glyph + label + summary path.
## Tests
\`tests/scene-trace-frame.test.ts\` — 9 new cases:
- \`toSceneCard\` plain pass-through for non-tool kinds
- enriched tool card with args/status/elapsed/id
- running tool: status="running", no elapsed
- failed (exit ≠ 0) and rejected → status="err"
- elapsed >= 1000ms formatted as seconds
- primary-arg extraction order (path > pattern, etc.)
- toolCardBlock renders the rich ▸ name (args) ✓ elapsed #id row
- ✗ for err status
- … for running status
\`npm run verify\` green via prepush gate (47 scene-trace tests pass).
Refs #868
Co-authored-by: reasonix <[email protected]>
Addresses the user's "empty space" feedback on the v1 layout — the
empty-state scroll area was mostly bg fill. The boot block now
carries actual visual weight:
- 6-row REASONIX ASCII block-letter banner (the exact ANSI Shadow
art from the v1 mock), drawn in PALETTE.ds blue + bold.
- Tagline row: "DeepSeek code agent · terminal-native, cache-first ·"
underneath the logo.
- Key/value rows widened from 8 → 10 cell key width: model · workdir
· mcp · tools.
- Tools row enumerates the actual tool kinds (read · write · edit ·
bash · grep · fetch · todo) so users see what's actually wired.
- Hint row gets Ctrl+C / Ctrl+D added to the existing / @ ! glyphs;
rendered with ds-blue glyphs and fg2-muted labels — same kbd-chip
pattern the meta row uses.
- scroll-area padding bumped 1 → 2 horizontally so the wide banner
doesn't sit flush against the left edge.
The vertical empty between boot block and dock is unchanged on
purpose — that's the design's behavior too (the v1 mock fills the
middle with chat cards once a turn starts; an empty fresh session
has space below the boot block).
## Tests
The existing "renders a boot block in the scroll area" test was
asserting on the literal string `REASONIX` — now switched to the
banner's first row (`██████╗`) + the tagline + the `tools` field
so we keep coverage on the new shape.
\`npm run verify\` green via prepush gate.
Refs #868
Co-authored-by: reasonix <[email protected]>
- Apply V4 chat template (BOS/EOS, USER/ASSISTANT specials, generation suffix) so countTokens tracks the API's prompt_tokens
- Render assistant tool_calls in DSML, merge tool results into the next user turn
- Render tool specs via TOOLS_TEMPLATE in estimateRequestTokens instead of raw JSON
- Refresh bundled tokenizer.json.gz to V4 vocab (added-token IDs shift accordingly)
- Switch context-manager per-message fold ordering to content-only counts
Closes#982
The user supplied a new design mock (reasonix-v1 / "Reasonix TUI v1.html")
that's a complete shape change from the desktop-style mock we had
before:
- Single-column terminal stream (cards + boot block), no permanent
sidebar / context pane.
- Fixed bottom dock: composer input row → meta row (kbd shortcuts)
→ status bar (multi-segment).
- Each card identified by a colored prefix glyph + label, no
enclosing boxes (mock's explicit "design rule: NO enclosing boxes,
every block uses a left-rail" — borders out, glyphs in).
This PR replaces \`buildTraceFrame\` end-to-end to match.
## Palette swap (theme.ts)
Old palette tokens (bg / bg2 / panel / card / border / borderStrong
/ fg / fg2 / muted / accent / accentStrong / success / warning /
danger / violet) → v1 oklch-derived hex set:
bg #0f1018 bg2 #161824
fg #e8e9f3 fg1 #a8aabd
fg2 #6b6e85 fg3 #3d4055
ds #6b85ff dsBright #8b9fff dsPurple #a78bfa
ok #5eead4 warn #fbbf24 err #fb7185 info #60a5fa
Single source of truth — every styled run reads from PALETTE.
## Layout
Outer column (background bg):
- scroll area (height fill): boot block when no cards, otherwise
one row per card with kind-colored glyph + label + summary.
- dock (intrinsic height): composer row → meta row → status bar.
Approval, slash overlay, and sessions picker fold in above the
composer row when active.
Three-pane sidebar/ctxpane code is gone — was the wrong shape for
the v1 mock. The "MISSION CONTROL" right rail in the mock is a
toggleable secondary view; we'll wire it as an opt-in render mode
later, not as the default layout.
## Specific row shapes
- Boot block (empty state): \`● REASONIX DeepSeek code agent\`
banner, then \`model\` / \`cwd\` / \`mcp\` rows, then a hint line
with kbd-colored glyphs for \`/\` \`@\` \`!\`.
- Card row: \`<glyph> <LABEL> <summary>\` per kind — YOU (blue),
THINKING (purple), reasonix streaming (teal), tool (muted),
diff (purple), error (err), warn (warn), plan/task (purple).
- Composer row: \`❯ <text> ▮ <text>\` on a bg2 line, fixed height 1.
- Meta row: left segments (\`↵ send · ⇧↵ newline · / cmd · @ file ·
! shell\`), spacer, right (\`esc cancel · ↑ history\`). Each kbd
glyph in ds blue, label in fg2 muted — matches the mock's hint
row exactly.
- Status bar: \`● reasonix · model X · mode review · busy/idle\` on
the left; spacer; \`wallet ¥X · cwd ~/path\` on the right.
Bg-tinted, fixed height 1.
## What still falls short of v1
- No ASCII REASONIX banner art (the 6-row block-letter logo). Too
big for 80-col terminals; the compact \`● REASONIX …\` banner
ships instead, and a follow-up can add the art for wide terminals.
- Card head/body separation — each card is still one summary line.
The mock has multi-line bodies (THINKING italic body, diff hunks,
bash output). Wiring full bodies through to scene needs richer
card payloads in \`SceneTraceCard\`, separate PR.
- Status bar ctx / tokens / cost / turn / git segments — need
telemetry + git status wiring not yet exposed to scene.
- MISSION CONTROL right rail (PLAN / JOBS / CHANGES) — separate
toggleable view.
## Tests
\`tests/scene-trace-frame.test.ts\` rewritten end-to-end against the
new structure (38 cases, all green) — shape tests use
\`scrollOf\` / \`dockOf\` / \`composerRowOf\` / \`statusRowOf\` /
\`metaRowOf\` helpers instead of fixed indices, so future row
reorderings don't churn the whole file.
\`RESERVED_ROWS\` (used by \`cardsForHeight\`) bumped 3 → 4 to reflect
the new dock: composer + meta + status = 3 rows; boot block adds 1
more on the cold-start path.
Closes-out #1007 (which was building on the wrong shape).
Refs #868
Co-authored-by: reasonix <[email protected]>
Closes the most obvious "placeholder" in the three-pane layout. The
sidebar previously read \`use /sessions to browse\` — accurate but
visually empty. Now it shows the actual saved sessions for the
current workspace with the active one highlighted, matching the
sidebar in the design mock.
## Wiring
- \`App.tsx\` initializes \`sessionsPickerList\` from
\`listSessionsForWorkspace(currentRootDir)\` on mount (was \`[]\` —
only populated when the picker opened).
- A \`useEffect\` re-reads the list whenever \`currentRootDir\` changes
(\`/cwd\` switching).
- New \`SceneTraceInput.sidebarSessionsJson\` + \`sidebarActiveSession\`
scalars — same primitive-deps pattern as the picker overlay's
\`sessionsJson\`. \`sidebarSessionsJson\` carries \`{ title, meta:
branch }\` per session; \`sidebarActiveSession\` is the active
session name for highlighting.
## Sidebar rendering
- Empty case: \`no saved sessions / type to start one\` (one accurate
hint instead of the previous \`/sessions to browse\` instruction
that didn't tell the user what was actually going on).
- Non-empty: one row per session, \`▸\` accent marker on the active
one, others dimmed. Caps at \`MAX_SIDEBAR_SESSIONS\` (8) with an
\`…N more\` overflow row.
- Meta line (\`branch\`) is intentionally omitted in this PR — the
24-cell sidebar gets cramped fast once you add a second line per
row. Showing meta inline alongside the name is a follow-up if it
matters.
## Tests
\`tests/scene-trace-frame.test.ts\` — 4 new cases:
- list rendered into sidebar when \`sidebarSessions\` is given
- active session row marked with \`▸\` and accent color
- placeholder when \`sidebarSessions\` is \`[]\`
- overflow row when > 8 sessions
\`npm run verify\` green via prepush gate.
Refs #868
Co-authored-by: reasonix <[email protected]>
Closes the visual gap between the structural three-pane layout from
#1003 and the user's design mock. Previously every cell defaulted to
the terminal's stock bg/fg; now the trace frame honors a small
palette derived from the mock's oklch tokens, panes carry rounded
borders, and title / status rows sit on a panel-tinted bar.
## Schema + Rust render
- `BoxLayout.background?: Color` — new field, same shape as
`borderColor`. Schema added in both TS (types.ts) and Rust
(scene.rs).
- `render_box` now runs `apply_decoration(layout, buf, area)` before
laying out children:
- if `background` is set, fills every cell of the box area with
that bg (via ratatui Block's style).
- if `borderStyle` is set, draws ratatui's box-drawing perimeter
(Plain/Double/Rounded/Thick) in `borderColor`, shrinking inner
area by 1 cell on each side for children.
- both are independent — bg without border (title/status bars)
works, border without bg (debug outlines) works too.
ratatui's `Block` widget already does the right thing for the
combined case (fill then draw border on top), so we lean on that
rather than rolling perimeter-drawing by hand.
## Design palette (`src/cli/ui/scene/theme.ts`)
oklch tokens from the mock converted to hex once, frozen as
`PALETTE.{bg, bg2, panel, card, border, borderStrong, fg, fg2,
muted, accent, accentStrong, success, warning, danger, violet}`.
Single source of truth — components don't pick raw colors anymore.
## Producer side
- Outer frame: `background: PALETTE.bg` (dark blue-grey base, sits
behind every pane).
- Title row: `background: PALETTE.panel`, brand prefix glyph in
`accent`, model name in `violet` (matches the gradient brand mark
in the mock).
- Sidebar + ctx pane: `borderStyle: round` + `borderColor: border`
+ `background: bg2`. Reads as two soft cards flanking the main
pane, same shape as the mock's panel/card style (modulo CSS
gradients which ratatui can't do).
- Status bar: `background: PALETTE.panel`, busy/idle in
warning/success hexes from the palette, wallet segment in
success when present.
- Section headers (`SESSIONS`, `CONTEXT`) drop the dash decoration
and use bold accent — cleaner now that bordered panes provide the
framing.
## Tests
- Rust (6 new): box-drawing chars at perimeter for Single / Round /
Double border styles, border color applied to perimeter cells,
background fills every cell, border shrinks inner area by 1
on each side.
- JS: existing 61 tests adjusted to the new shapes (status row is
now always a box for its bg tint, busy/idle assert hex colors via
PALETTE rather than named "green"/"yellow"). 2 new shape
assertions: title/status carry a background; side/ctx panes
carry borderStyle=round + background.
`cargo test -p reasonix-render --test render` → 23/23.
`npm run verify` → green via prepush gate.
## What's still aspirational
Real CSS gradients, drop shadows, border-radius smoothness, custom
fonts, hover states — ratatui can't do any of these and won't.
That's the floor for "TUI-native faithful to the mock"; everything
above is what we ship.
Refs #868
Co-authored-by: reasonix <[email protected]>
Stage 1 toward the user's design mock — restructure from a flat
column of rows to the classic IDE three-pane shape:
┌───────────── title (full width) ─────────────┐
│ SIDEBAR (24) │ MAIN (fill) │ CTX (32) │
└───────────── status (full width) ────────────┘
The middle band is a `direction: "row"` box with `height: "fill"`,
made possible by the flex-sizing infra from #1000. Sidebar and ctx
pane have fixed cell widths; main pane fills the remainder. Both
side panes auto-hide on narrow terminals — sidebar below 60 cols,
ctx pane below 100 cols — so an 80-col terminal still works the way
it did before, just with a sessions-rail on the left.
## Main pane content (unchanged)
The cards stack, composer / approval / sessions-picker takeover,
slash overlay — exactly the same nodes as before, now living inside
the main pane's column instead of inline in the root.
## Sidebar (stage-1 placeholder)
Just a `─ SESSIONS ─` header + `use /sessions to browse` hint. The
real session list goes here in stage 2 once App.tsx surfaces a
permanently-loaded list (today it's loaded only when the picker is
open).
## Context pane (uses what's wired)
`─ CONTEXT ─` + `model · cards · wallet`. Wallet moves from the
status row into the ctx pane when both are visible — avoids
duplicating it. At cols < 100 the ctx pane is hidden and wallet
stays on the right of the status row (as in #1001).
## Test rewrite
The flat-children shape was load-bearing in 15 tests. Added two
helpers — `mainOf(f)` / `statusOf(f)` / `titleOf(f)` — and rewrote
each test to drill through the new structure. Coverage is identical
in spirit (still asserts behavior of card rows, composer, approval
modal, sessions picker, slash overlay, status segments) but
expressed in terms of the new hierarchy.
3 new shape tests:
- root is now `[title, middle, status]` (3 children, not 4-7)
- sidebar hidden below 60 cols
- ctx pane hidden below 100 cols
Refs #868
Co-authored-by: reasonix <[email protected]>
First concrete consumer of the new flex layout primitive (#1000) and
the smallest visible step toward the multi-segment status bar the
design mock points at. Wallet balance is the most direct visible
signal of reasonix's cheap-positioning claim — users see how slowly
the number goes down across a session.
- New SceneTraceInput.walletBalance + walletCurrency scalars,
primitives so effect deps stay stable.
- statusRow upgrades from a single text node to a row box only when
the balance is present: left segments (cardCount · busy/idle · activity)
+ fill spacer + right segment (`wallet ¥184.20`). When balance is
null/undefined the row stays a single text node — back-compat with
the existing test that asserts `kind === "text"` on the status row.
- Currency rendering: ¥ for CNY/RMB/JPY, $ for USD, € EUR, £ GBP;
unknown codes fall back to `CODE 5.00` so nothing silently looks
like the wrong currency.
- App.tsx forwards `balance.total` and `balance.currency` from
useSessionInfo — both null until the first successful
getBalance() call, so the wallet segment appears once the
endpoint responds and stays hidden offline.
Cache-hit %, branch, spent (this session), jobs count all also belong
in this row; each is a small isolated wiring step from here.
Refs #868
Co-authored-by: reasonix <[email protected]>
Schema already had `width` / `height` as `Dim::Cells(n) | Dim::Fill`
on box children, but the Rust render layer ignored both — every row
child fell back to its intrinsic width and every column child to its
intrinsic height. That made the schema's `direction: row` only useful
for content-packed rows, never for sized panes.
## Algorithm
Walk children once; classify each:
- explicit `Dim::Cells(n)` → reserve exactly n cells (capped at the
remaining axis space, in source order)
- explicit `Dim::Fill` → defer
- unsized → reserve intrinsic size, capped at remaining
After the first pass, split whatever's left equally among the deferred
Fill children, distributing any pixel remainder to the leading ones
so the total adds up to exactly the gap-adjusted axis budget. Gaps
between siblings come off the top.
## Visible use
`titleRow` is now a row box: brand on the left, model name on the
right, with a `width: "fill"` spacer between them. Sets up the
producer-side pattern that the upcoming three-pane layout PR
(Sidebar / Main / ContextPanel) will reuse — sidebar gets a fixed
cell width, main gets `Dim::Fill`, ctx panel gets its own fixed.
## Tests
9 new Rust cases on the layout algorithm (fixed reservation order,
single Fill, multiple Fill, uneven remainder distribution, fixed
clamped at remaining, intrinsic fallback for unsized, gap subtraction,
column height variants).
2 new JS cases on the producer-side titleRow restructure (row box
with brand + fill spacer + model; spacer-only row when no model).
Refs #868
Co-authored-by: reasonix <[email protected]>
Closes the keystroke half of the rust-renderer Setup gap (visible
mirror landed in the previous PR). Under REASONIX_RENDERER=rust the
JS process runs Ink with a null stdin (src/cli/ui/scene/null-stdin.ts);
MaskedInput used Ink's useInput, which subscribes to that null stream,
so the masked input received nothing and the fresh-user path was a
hard dead end.
- chat.tsx: the pre-App <Setup> branch is now wrapped in
<KeystrokeProvider reader={keystrokeReader}> — same reader the App
tree already uses, so under rust mode keys come from the spawned
reasonix-render --emit-input child, and under default mode they
come from the stdin reader singleton.
- MaskedInput.tsx: useInput → useKeystroke. The hook already falls
back to useInput when no provider is mounted, so non-rust callers
(none today, but future ones) keep working unchanged.
Refs #868
Co-authored-by: reasonix <[email protected]>
First step toward un-blocking the fresh-user path under
REASONIX_RENDERER=rust. The Setup screen rendered to the null Ink
stdout and was completely invisible; a user with no saved key saw
nothing at all and had no way to know the loop was waiting on input.
The scene producer now emits a parallel setup frame:
✦ reasonix · welcome
Enter your DeepSeek API key:
get one at https://platform.deepseek.com
❯ •••••▮
✗ <error> (only when error is set)
Ctrl+C to exit · /exit to quit
- New buildSetupFrame(input, cols, rows) — completely separate from
buildTraceFrame; the setup screen never coexists with cards / status
/ composer so a shared layout would only constrain both.
- New useSetupSceneTrace hook — Setup.tsx calls it with bufferLength
and the current error string. Only the buffer LENGTH crosses the
scene boundary; raw key material never gets serialized into the
scene stream.
- No keystroke change in this PR — MaskedInput keeps using Ink's
useInput. That gap (stdin is the null stream under rust mode, so
useInput receives nothing) becomes a real interactive Setup in a
follow-up.
Refs #868
Co-authored-by: reasonix <[email protected]>
Under REASONIX_RENDERER=rust the Ink-side SessionPicker rendered to
the null stdout, so a user opening /sessions saw nothing but the
"awaiting input" composer they couldn't actually type into. The scene
producer now mirrors the picker:
- New SceneSessionItem ({ title, meta? }) surfaced via useSceneTrace
as a JSON-encoded array plus a primitive sessionsFocusedIndex.
- buildTraceFrame: when sessions is non-empty, replace composer (and
any approval / slash overlay) with a header row + one focused
windowed row per session (cap 8, with a "…N more" tail when the
list is longer) + a hint footer.
- listWindow extracted as a generic so the same centering logic
serves the slash and sessions blocks.
- SessionPicker gains a tiny onFocusChange callback (useEffect
publishes the local focus state); App.tsx mirrors it into a useState
and into the scene input. No restructuring of SessionPicker beyond
the prop — its useKeystroke handling stays exactly as is.
- App.tsx builds sessionsJson via useMemo from sessionsPickerList
with `${branch} · ${turns} turns` as the meta line; gated on
pendingSessionsPicker so the overlay only appears while the picker
is actually open.
Refs #868
Co-authored-by: reasonix <[email protected]>
Under REASONIX_RENDERER=rust the various pending* confirmation modals
(shell command, sandbox path, edit review, free-form choice, plan
approval) had no scene representation, so the user saw the composer
prompt while the loop was actually waiting on a y/n. The composer is
now replaced with a `❓ [kind] <prompt> [y/n]` row whenever any of
those states is set:
- New SceneTraceInput.approvalKind / approvalPrompt scalar pair —
primitives keep effect deps stable.
- buildTraceFrame: when approvalPrompt is set, push approvalRow in
place of composerRow and suppress the slash overlay.
- Prompt clipped to 60 chars with a trailing ellipsis so long
shell commands stay readable.
- App.tsx derives the pair via useMemo from pendingShell / pendingPath
/ pendingEditReview / pendingChoice / pendingPlan, in that priority
order.
Per-modal refinement (selected option for choice, diff preview for
edits, full plan text, etc.) lives in later sub-PRs — this is the
"smallest visible win" stub.
Refs #868
Co-authored-by: reasonix <[email protected]>
Under REASONIX_RENDERER=rust the slash overlay was an Ink-only feature
— typing `/` showed nothing in the Rust-drawn scene, so the user
couldn't see what command they were about to fire. The scene producer
now mirrors the overlay:
- New SceneSlashMatch type ({ cmd, summary, argsHint? }), surfaced
through useSceneTrace as a JSON-encoded array + a primitive
slashSelectedIndex (keeps effect deps stable).
- buildTraceFrame appends one row per match below the composer with
a ▸ on the selected one; a tail "…N more" line shows when the
match list exceeds MAX_SLASH_ROWS (6).
- slashWindow keeps the selected row inside a centered 6-row window
for long match lists.
- App.tsx moves useSceneTrace below useCompletionPickers so it can
read slashMatches / slashSelected, and JSON-encodes a minimal
view-model via useMemo so array refs don't churn the deps.
Group headers / advanced footer / no-match warning live in the Ink
overlay only — the scene version stays flat and minimal, per the
"each B-line step is the smallest visible win" plan.
Refs #868
Co-authored-by: reasonix <[email protected]>
The scene producer painted ▮ after the full composer text regardless
of where the cursor actually was, so left/right arrows under
REASONIX_RENDERER=rust looked like they did nothing. PromptInput now
publishes its cursor through an onCursorChange callback; App.tsx
mirrors it into useSceneTrace, and composerRow() splits the text
around the block (clamped to [0, text.length]).
Refs #868
Co-authored-by: reasonix <[email protected]>
App.tsx had five JSX blocks that each repeated the same nine
`!pendingShell && !pendingPath && !pendingPlan && !pendingReviseEditor
&& !pendingSessionsPicker && !pendingCheckpointPicker && !pendingMcpHub
&& !stagedInput && !pendingEditReview` chain — gating which "live
activity" rows render while a take-over modal is up. Defining the
chain once as `noTakeoverOverlay` next to the existing `modalOpen`
collapses ~35 lines and makes the JSX scan in one tick.
The five blocks consolidated:
- OngoingToolRow (line ~3922)
- SubagentLiveStack
- ThinkingRow (statusLine variant)
- ThinkingRow (activityLabel variant)
- PlanLiveRow
UndoBanner intentionally NOT consolidated — its visibility rule is a
different (overlapping but not equal) set that also excludes
pendingChoice, stagedChoiceCustom, pendingRevision,
stagedCheckpointRevise, pendingCheckpoint. Pulling those into
`noTakeoverOverlay` would change visibility for the other rows; a
separate constant for UndoBanner is a follow-up if it ever needs
more callers.
Why "noTakeoverOverlay" not "modalOpen": `modalOpen` already exists
for the broader "any modal owns the screen" check used by global
hotkey gates. It includes model/theme/copy-mode pickers that overlay
on top without claiming the bottom rows. The live rows should still
render under those. Keeping the two constants distinct preserves
that distinction.
App.tsx: 4368 → 4333 (-35 lines).
First sub-PR of #565 phase 2. Non-extraction yet — pure dedupe; the
sub-component split comes after the helper boolean exists for the
component to use.
Refs #565#868
Co-authored-by: reasonix <[email protected]>
A fresh install hitting `REASONIX_RENDERER=rust reasonix` cold lands
on the Setup screen — and Setup is invisible. It renders to Ink's
stdout (the null stream under the Rust path) and reads stdin
directly via Ink's `useInput` (also the null stream). The user
types the API key blind, never sees the prompts, never sees their
input.
Stage 2's keystroke adapter doesn't help: Setup isn't wrapped in
`KeystrokeProvider`, and even if it were, the visual still wouldn't
appear because the trace frame is built from app state — Setup
isn't in the state.
This PR sidesteps the problem for now: if no saved API key, ignore
the env flag this launch. The session runs entirely in Ink (real
stdio), Setup works as it always did, the user enters their key,
the session continues. Next launch with the key persisted, the
Rust path engages.
stderr gets a one-line notice so the user understands why the flag
they set was ignored:
REASONIX_RENDERER=rust ignored for this launch: no saved API key.
Complete Setup once, then re-launch with the flag.
What this is NOT: a real fix for the Setup-in-Rust-mode UX. Stage 3
(flip default) will need Setup to render through the scene frame
plus take input through KeystrokeProvider. That's a bigger
refactor — Setup.tsx swaps `useInput` for `useKeystroke`, and the
scene producer extends to cover the Setup phase. Tracked for that
PR, not this one.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
The render loop did `x += 1` for every char. East-Asian wide chars
(CJK 测/试/中, fullwidth punctuation, some box-drawing) are 2 cells
wide, so the next char got written at the cell that was already
covered by the wide char's right half. ratatui's flush logic then
silently dropped one of them — the user saw `测试123` come out as
`测 23` (the `试` and `1` both lost to overlap).
Fix: use `unicode-width::UnicodeWidthChar` for `display_width(ch)`
and advance `x` by that width. Zero-width chars (combining marks,
control codes that survive past the input parser) skip without
consuming a cell; multi-cell chars consume the full width and leave
the continuation cell blank, which is what ratatui expects.
Same fix on `intrinsic_width` for box layout — was counting
codepoints, now counts display cells.
Test: `cjk_chars_advance_by_their_display_width_so_neighbors_dont_overlap`
renders `测试123` into a buffer and asserts each char lands at its
correct column (0, 2, 4, 5, 6 — not 0, 1, 2, 3, 4).
Caught during the 2026-05-15 manual smoke pass: user typed 测试123
in the composer, scene frame showed `测 23▮` instead.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
Two cousins of one screen-corruption bug:
- Ink subscribes to its stdout's `resize` event from every component
that calls `useStdout` — the App tree has 11+ such consumers, which
trips Node's default 10-listener leak warning. The warning text
then writes to stderr.
- Under REASONIX_RENDERER=rust the alt-screen is owned by the Rust
child. Any stderr write from the Node parent overwrites whatever
ratatui drew at the same cells and stays visible until the next
frame redraws. The user sees garbage mid-row.
Fix both ends:
- `makeNullStdout()` calls `setMaxListeners(50)` on its return value
so the realistic Ink subscriber count fits under the cap and the
warning never fires.
- `chatCommand` redirects `process.stderr.write` to
`~/.reasonix/rust-render-stderr.log` for the duration of the
session when the Rust path is active. Restored in the `finally`
block alongside the other cleanup.
Even with `setMaxListeners`, library code or future warnings could
still hit stderr — the log-file redirect catches all of them. The
log persists across sessions so a user noticing missing output can
tail it.
What this does NOT do:
- Rust child's stderr is still `"inherit"` — its errors (rare) still
print to the terminal and corrupt the screen. Routing the Rust
child's stderr to a separate file is a follow-up if it ever bites.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
The trace frame had one row for the latest card and a status row
underneath. Under REASONIX_RENDERER=rust this meant the user could
only see the *current* moment of the conversation, not the history
— typing a follow-up question lost the prior assistant reply from
view. The Ink card stream is invisible behind the null stdout.
After this PR, the scene frame stacks one row per card between the
title and status rows, capped at `min(rows - 3, 24)` so a 24-row
terminal shows up to 21 cards.
Architecture choice: pass cards from App.tsx as a JSON-encoded
string, not a plain array. Reason: the `useSceneTrace` effect deps
must be primitive — an array selector returning a new ref every
render would re-fire the effect on every keystroke even when the
cards themselves haven't changed. JSON.stringify of a small
projection (kind + summary) is shallow-equal-stable inside zustand
without needing custom comparators.
Splits:
- `SceneTraceCard` type — narrow `{kind, summary}` shape sent over
the React boundary.
- `parseRecentCards(json)` — defensive deserializer; bad JSON or
malformed items drop silently.
- `cardsForHeight(cards, rows)` — clamps the slice to terminal height
with a 24-card hard cap. Pure function, easy to test.
- `buildTraceFrame` now takes `cards: ReadonlyArray<...>` directly,
not the old `lastCardKind`/`lastCardSummary` pair. Tests updated.
App.tsx selector hashes the last 24 cards to JSON; previous
`lastCardKind` + `lastCardSummary` selectors removed (replaced by
the one JSON selector — fewer store reads per render).
Tests: 4 new `parseRecentCards` cases + 4 new `cardsForHeight`
cases + a "stacks one row per card" frame assertion. Existing
buildTraceFrame tests updated to the new input shape (no test
intent changed, just plumbing).
Refs #868#947
Co-authored-by: reasonix <[email protected]>
The trace frame had three rows: title, last card, status. Under
REASONIX_RENDERER=rust this meant a typing user saw nothing change
until they hit Enter — the composer is in Ink, which renders to
the null stream in that mode. The user had to type blind.
Fourth row, always present:
❯ (type a message) # empty, dim placeholder
❯ what's the weather▮ # non-empty, typed text + cursor block
useSceneTrace's input gains a `composerText` field; App.tsx wires
its existing `input` state into it. The composer state was already
re-rendering App on every keystroke (it's a normal useState), so
hooking the trace frame in is just one extra dep — no new
performance characteristic.
Why "❯" (U+276F) + "▮" (U+25AE):
- "❯" is a single-cell prompt glyph that renders consistently across
Windows Terminal, iTerm2, kitty, VSCode terminal. The ASCII ">" is
ambiguous with the user-card icon in the row above; using a
different glyph keeps the rows visually distinct.
- "▮" is the same vertical-bar cursor block Ink-rendered terminals
show; it gives the user a place to "look at" while typing without
needing a real blinking cursor (which would require timer-driven
scene frame updates that we don't want to pay for yet).
What this still does NOT solve:
- The cursor block is positioned at the end of the input; cursor
movement (Ctrl+A / arrow keys) inside the buffer isn't reflected.
Showing in-line cursor position needs the composer's cursor
offset state, which lives one component down from where the
trace input is assembled. Follow-up if anyone notices.
- Slash-command autocomplete, history-prev preview, paste-marker
visualization — none of those show. They're separate panels in
Ink. Same lowering-pass-blocked-on-#565 story.
Tests: two new buildTraceFrame cases (empty / typed) plus updating
the existing "three children" expectation to four.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
The renderer child has REASONIX_RENDER_CMD (from #961) for swapping
in a pre-built binary instead of going through `cargo run`. The
input child had no such override — when REASONIX_RENDERER=rust is
set, it always invokes `cargo run --bin reasonix-render --
--emit-input`, which incurs a multi-second cold-compile on first
launch even when a release binary already exists.
Symmetric env var: REASONIX_INPUT_CMD (JSON array of strings) takes
the same shape as REASONIX_RENDER_CMD, overrides the default
spawnInputSource command in chat.tsx. Production users won't set
it; smoke-test scripts and dev wrappers point both env vars at the
same release binary (with `--emit-input` arg for the input one) so
launch is fast.
Caught during the 2026-05-15 manual smoke pass on Windows Terminal:
without the override, the first run of `REASONIX_RENDERER=rust
reasonix` hangs on a black screen for 30+ seconds while the input
child compiles in the dev profile, which is indistinguishable from
"broken" without instrumentation. Pre-building the dev binary helps
but still pays cargo's per-invoke staleness-check cost.
No production behavior change when the env var is unset; the
default command is unchanged.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
- Update flash/pro USD price constants to current official rates
- Fall back to prompt_tokens - cache_hit when API omits prompt_cache_miss_tokens
- Reset SessionStats and status-bar spend on /new so new chats don't inherit old totals
Stage 2 polish. The Rust input child now enables xterm mouse capture
and forwards click / drag / release / scroll events as JSONL. The JS
adapter translates them to a KeyEvent with the existing mouse fields
(mouseClick / mouseDrag / mouseRelease / mouseScrollUp /
mouseScrollDown plus row+col), matching what the Ink path's
StdinReader produces from raw SGR mouse reports.
This is the #867 fix the RFC promised — mouse-wheel SGR escape
sequences no longer leak into the composer because the Rust child
captures + decodes them; JS receives a structured event with
mouseRow / mouseCol set.
Rust:
- `EnableMouseCapture` before the loop, `DisableMouseCapture` on
cleanup. crossterm's default (mode 1000 + SGR 1006) matches what
the JS StdinReader's SGR mouse parser was decoding from raw bytes.
- `translate_mouse(MouseEvent) -> Option<MouseInputEvent>`. Maps:
Down(Left) → "click"
Drag(Left) → "drag"
Up(any) → "release"
ScrollUp → "scroll-up"
ScrollDown → "scroll-down"
Right/middle clicks, Moved, ScrollLeft/Right drop to None — the
JS KeyEvent has no slot for them; better silent than fake-filling.
crossterm rows/cols are 0-based; bumped to 1-based on the wire
so the JS side keeps the VT mouse-report convention it already
uses for Ink-path mouse events.
JS:
- `MouseInputEvent` type + `onMouse()` on InputSource. The
discriminator + kind narrow in `isMouseEvent` so unknown future
event variants drop silently.
- `translateMouse(rust) -> KeyEvent` sets the appropriate mouse
flag plus mouseRow / mouseCol; the rest of KeyEvent stays empty
(input: "") so the composer's mouse-click handlers see exactly
what they got from the Ink path.
Tests: 7 new translation cases (each kind + row/col preservation)
plus an end-to-end via the Node stub mixing click + scroll + drag.
Refs #868#947#867
Co-authored-by: reasonix <[email protected]>
The Rust input child now enables DECSET 2004 (bracketed paste) and
emits multi-byte paste bursts as a distinct event rather than as a
flood of Char events. The JS adapter translates those to a KeyEvent
with `paste: true` — matching what the existing StdinReader produces
on the Ink path, so the composer's paste-suppress logic (don't
interpret \n as submit) just works under REASONIX_RENDERER=rust too.
Rust:
- `EnableBracketedPaste` before the read loop, `DisableBracketedPaste`
on cleanup. Both are best-effort — terminals that don't support
bracketed paste keep working, individual chars just keep arriving
as Char events.
- `Event::Paste(text)` handled in the same match arm; emits
`{"event":"paste","text":"..."}` JSON.
- `PasteEvent` struct + `paste_event()` factory in input.rs.
JS:
- `PasteInputEvent` type + `onPaste()` on InputSource. `dispatch()`
routes JSONL lines to either bus by the `event` discriminator;
unknown event kinds get dropped (forward-compat for resize, mouse).
- `translatePaste()` runs the text through `sanitizePasteText()` —
the same bidi/zero-width strip the stdin path uses (#849) — and
emits `{ input: <clean>, paste: true }`.
Tests:
- end-to-end paste round-trip through the Node stub, mixed with
regular key events to confirm both buses fire in order
- `translatePaste` strips invisibles like `\u200B`, `\u202E`
- existing adapter tests unchanged
Refs #868#947
Co-authored-by: reasonix <[email protected]>
Closes the input loop for REASONIX_RENDERER=rust. The Rust input
child (`reasonix-render --emit-input` from #969 → #966) now feeds
keystrokes back into the React tree via KeystrokeProvider's existing
`reader` slot, the same slot tests use for synthetic stdin.
End-to-end with #962 + #971 + this PR:
- JS produces SceneFrames (already)
- Rust child renders alt-screen TUI (already)
- Ink writes go to a null stream (already)
- Ink reads stdin from a null stream (already, #971)
- Rust child emits keystroke events (already, #966)
- JS forwards them to composer / picker ← this PR
Pieces:
- `KeystrokeReader` interface in keystroke-context.tsx — the minimum
shape KeystrokeProvider already required from a reader (start +
subscribe). StdinReader satisfies it; the prop type was tightened
to it. No behavior change for existing callers.
- `createRustKeystrokeReader()` in scene/input-adapter.ts. Spawns
the input source, translates `KeyInputEvent` → Reasonix's
`KeyEvent` shape, fans out to subscribers. Translation map:
Char → input + (ctrl/shift/meta) modifier flags
Enter → return: true (+ modifiers)
Esc/Up/Down/Left/Right/Backspace/Tab/BackTab/Home/End/PageUp/
PageDown/Delete → corresponding KeyEvent field set
F-keys + unrecognized → null (KeyEvent has no slot; better to
drop than to fake-fill a different field)
Alt → meta — Reasonix uses Ink's vocabulary on the JS side.
- chat.tsx: when REASONIX_RENDERER=rust, build the reader once
before `render()`, forward it through Root → both
KeystrokeProvider instances (picker + main App). Close it in the
`finally` block so the input child doesn't linger.
24 tests in `tests/scene-input-adapter.test.ts`: every translation
branch (single chars, modifier combinations, Shift+Enter, every
named code, F-key/unknown rejection) plus end-to-end via the Node
stub — events round-trip through the spawned-child path into
subscriber callbacks.
What this does NOT yet do:
- Input still goes through the same composer / picker / approval
handlers that the Ink stdin reader fed before, so all existing
shortcuts work. But the Rust side is single-source-of-truth for
modifier resolution — modifyOtherKeys / Kitty / ConPTY-stripped
variants the JS StdinReader handles by sniffing escape sequences
are not all reproduced in the Rust translation yet. Stage 3 is
where those get tightened against real terminal traces.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
* feat(scene): silence Ink's stdin reader when REASONIX_RENDERER=rust
Cut A from #962 wired Ink to a null stdout so the spawned Rust child
owns the visible terminal. This PR closes the matching gap on the
input side: when the env var is set, Ink mounts with a stdin that
never emits data.
Why this matters now:
- Without it, both processes read from the same controlling terminal.
The Node parent reads through process.stdin (fd 0); the Rust child
reads /dev/tty directly via crossterm. One keystroke goes to
whichever does read() first — a race the user sees as missed or
duplicated input depending on timing.
- Cut B (validator mode) was unaffected because the Rust child only
decoded; nothing competed for keys. Streaming mode (#962) made the
race observable. Silencing Ink resolves it.
makeNullStdin() is a Readable that never push()es, plus the tty-side
methods Ink calls during mount (`isTTY`, `setRawMode`, `pause`,
`resume`, `isPaused`, `setEncoding`, `ref`, `unref`). Each is a no-op
that returns the stream so chained calls stay safe.
Symmetric to makeNullStdout() — same cast pattern (`unknown as
NodeJS.ReadStream`), same tests-against-the-shape style. 6 cases
cover no-data emission and every shape method Ink touches.
What this does NOT do: it doesn't yet wire the spawned input-source
(#969) into App.tsx state. So today, with REASONIX_RENDERER=rust,
the Rust render shows but typing reaches no one. That hookup is the
next PR; this one removes the race so the hookup has a clean seam.
Refs #868#947
* fix(server,tests): strip GIT_* env vars around git ls-files & test setup
Two cousins of the same root cause, fixed together so the test that
exposes the bug also passes once the production fix is in place:
- `src/server/api/checkpoint-create.ts` runs `git ls-files` via
execSync with a cwd, but git resolves the repo via GIT_DIR env
first with cwd as fallback. When the dashboard runs inside a
context that pre-set GIT_DIR (e.g. a pre-push hook spawning
reasonix to take a snapshot), ls-files reports files from the
outer repo instead of rootDir. Strip every GIT_*-prefixed env var
before the execSync so cwd is the only thing left for git.
- `tests/server-dashboard.test.ts` beforeEach does the same shape of
thing: `execSync("git init/config/add/commit", { cwd })` in a
temp dir. Same env-inheritance problem; under a pre-push hook
it would (a) "git commit" into the outer repo and fail because
the repo is mid-push, and (b) silently rewrite the outer repo's
user.email to "[email protected]" via the test's "git config" line.
Strip GIT_* there too.
Repro: any `git push` of this branch — the pre-push hook ran the
dashboard checkpoint tests with inherited GIT_DIR, producing 6
cascading test failures and (worse) silently changing the
committer identity in .git/config. Standalone `npm test` passed
because there was no parent git operation setting GIT_DIR.
Other production callsites with the same shape — git-diffs handler,
slash commit helpers, session branch detection — aren't exercised
by tests that run inside a hook, so they stay as-is for a follow-up
PR rather than expanding this one's scope.
---------
Co-authored-by: reasonix <[email protected]>
Stage 2 PR-2. spawnInputSource() runs the Rust binary with
--emit-input, reads its JSONL stdout, parses each line into a
KeyInputEvent, and dispatches to registered onKey handlers. No
production callers wire it in yet — that's the next PR.
API shape:
const source = spawnInputSource();
source.onKey((event) => { ... });
// later: source.close() to signal + await, or source.wait() to
// just await natural exit.
Two methods, not one, because the use cases differ:
- close() sends SIGINT and awaits exit. Production needs this so
the child doesn't linger after JS shuts down — the Rust binary
reads /dev/tty directly, so there's no stdin pipe to close.
- wait() just awaits exit without signaling. Used by tests where
the stub finishes naturally; without it, the SIGINT in close()
would race against the stub's writes and kill it mid-emit.
Line parser is forgiving:
- Malformed JSON: skip and keep going. Don't drop later valid
events. A Rust panic might emit a stderr trace that bleeds into
stdout briefly; one bad byte shouldn't take down the input
stream for the rest of the session.
- JSON that isn't a key event: skip. Future event kinds (resize,
mouse) ride on the same channel; isKeyEvent() narrows.
Tests: 6 cases via a Node stub that replays a JSONL fixture file to
stdout. Covers ordered delivery, multi-handler dispatch, unsubscribe,
malformed-line tolerance, non-key-event filtering, empty-command
rejection. The stub stands in for the binary so vitest stays
Rust-toolchain-free.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
Stage 2 PR-1. The Rust binary gains a third mode (alongside the
default streaming renderer and --decode-only): --emit-input reads
keys from the terminal and writes one JSON line per press to
stdout. Nothing wires this to JS yet — that's the next PR — but the
keyboard-to-event mapping is isolated, tested, and stable.
Event shape:
{"event":"key","code":"Enter"}
{"event":"key","code":"Char","char":"a"}
{"event":"key","code":"Char","char":"c","modifiers":["ctrl"]}
{"event":"key","code":"F5"}
`translate_key()` lives in input.rs. It returns Option<InputEvent>
so non-press events (Release / Repeat on Windows-style key events)
and unsupported codes (Media keys, capslock, etc.) collapse to None
rather than emitting noise. The caller skips Nones.
Why semi-pre-mapped, not raw key bytes:
- Bytes are ambiguous across terminal encodings (xterm vs
modifyOtherKeys vs Kitty protocol). The translation absorbs
that — JS gets a canonical event shape and never has to know
which protocol the user's terminal speaks.
- We do not pre-map to *semantic* events (submit, history-prev)
yet because the mapping is contextual (composer vs picker vs
approval). That mapping lives JS-side in the next PR, where
the active context is known.
Modifiers serialize in canonical order: ctrl, alt, shift, super.
Ctrl+C is recognized via `is_quit()` so --emit-input exits cleanly
on the standard interrupt sequence.
Tests: 10 cases in tests/input.rs covering plain chars, Enter,
Ctrl-prefixed, multi-modifier order, function keys, release-event
suppression, and the three JSON serialization shapes (plain,
char, char+modifiers).
Refs #868#947
Co-authored-by: reasonix <[email protected]>
The frame produced by useSceneTrace was a one-liner: "reasonix · N
cards · busy/idle · activity". Useful as a wiring proof but
uninformative as a render target — when REASONIX_RENDERER=rust the
Rust binary just drew that one line forever.
This PR makes the frame mean something. Three rows in a column box:
Row 1: title — "reasonix · deepseek-chat"
Row 2: last card — kind icon + first line of content
Row 3: status — count · busy/idle · activity
`summarizeCard()` reads the most recent card and returns a clipped
first-line summary; tools show their name with a running marker
when not done. Icons + colors per card kind let the Rust render
distinguish user from streaming from tool at a glance.
The hook signature gains `model`, `lastCardKind`, `lastCardSummary`.
App.tsx pulls the last two via dedicated useAgentState selectors so
they survive shallow-equality checks — selecting `.kind` and a
short string keeps deps primitive instead of an array ref that'd
re-fire the effect every render.
What this does NOT solve:
- Input visibility — the composer is still in Ink which renders to
/dev/null when REASONIX_RENDERER=rust. That's Stage 2 territory
(semantic input events from Rust back to JS).
- Multi-card scrollback — only the last card is summarized. Showing
the full stream needs either real Ink-tree lowering or a bounded
ring buffer of card summaries; both are bigger pieces.
Tests:
- 11 cases in tests/scene-trace-frame.test.ts. Five for
summarizeCard (first-line extraction, clipping with ellipsis,
tool name + running marker, done-state, undefined input), six
for buildTraceFrame (structure, model in title, placeholder
card row, user-card cyan+bold, idle/busy color, activity suffix).
Refs #868#947
Co-authored-by: reasonix <[email protected]>
REASONIX_RENDERER=rust now actually flips the renderer. The spawned
Rust process takes the user-facing terminal (alt-screen + ratatui);
Ink keeps running for state, hooks, and the SceneFrame producer but
writes to a null sink whose columns/rows still proxy the real tty.
End-to-end: state in JS → frames over stdin → ratatui on screen.
Three parts:
1. Rust streaming. The non-decode-only path is now a tight
stdin-line / parse / draw loop with no pre-load and no keyboard
handling. crossterm reads its own keys from /dev/tty, so we
skip enable_raw_mode and event::poll entirely — Ink (in the
parent process) keeps stdin and raw-mode ownership unchanged.
Exits on stdin EOF, which fires when the parent closes the pipe
during shutdown.
2. Null Ink stdout. `makeNullStdout(real)` returns a Writable that
discards bytes but reports `real.columns` / `real.rows` and
re-emits `resize`. Yoga still computes correct layouts; the user
just doesn't see Ink's render. Cast to NodeJS.WriteStream is
honest about the gap — `unknown as` not `any as`.
3. Default command no longer carries --decode-only. The validator
mode from #961 is still reachable via REASONIX_RENDER_CMD; the
default for REASONIX_RENDERER=rust is now the streaming TUI.
Known limitations (Stage 2 territory):
- No input wiring. The user can see Rust's render and type keys
(Ink receives them and updates state, which produces new
frames), but Ink's composer / completions / pickers are
invisible since Ink itself isn't drawn. Stage 2 (Rust input
layer + semantic events back to JS) is what closes this.
- Initial blank moment. Spawning the child has a small startup
cost; until the first frame arrives the alt-screen is empty.
- alt-screen disabled on the JS side when the flag is on, so the
Rust child's alt-screen entry is the only one in flight.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
Cut B of the runtime switch. When the env var is set, useSceneTrace
spawns the Rust binary with --decode-only and pipes frames to its
stdin instead of writing to a file. The binary stays headless — no
alt screen, no raw mode, no terminal takeover — so Ink keeps owning
the visible TUI while the Rust process consumes frames in the
background.
This is the intermediate stop, not the full flip. It proves the
producer → consumer loop end-to-end during a real session without
fighting Ink for the terminal. The "Rust process owns the visible
TUI" version (cut A) comes when Ink can be mounted to a null-stdout
backend; that refactor is its own design problem and lands separately.
What changed:
Rust:
- `decode_only::run_decode_only<R, W>` — generic over input/output,
reads JSONL, deserializes, emits "frame N" lines. Three tests
covering count, blank-line skipping, and error line context.
- `main.rs` checks argv for `--decode-only` before touching ratatui.
When set, calls run_decode_only and exits. Otherwise the existing
alt-screen render path runs unchanged.
JS:
- `trace.ts` now has three modes: off / file / child. Selection by
env var: `REASONIX_RENDERER=rust` wins over `REASONIX_SCENE_TRACE`.
- `flushSceneTrace()` (async) awaits the child's exit. Needed by
tests and by future graceful-shutdown code; `resetSceneTrace()`
stays sync for the existing call sites.
- `REASONIX_RENDER_CMD` (JSON array of strings) overrides the
default `cargo run --bin reasonix-render -- --decode-only`
command. Used by tests to point at the Node stub; production
users have no reason to set it.
`spawnRenderer`'s `DEFAULT_COMMAND` is now exported so trace.ts can
build the decode-only command on top of it rather than duplicating
the dev-build prefix.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
JS-side plumbing for the REASONIX_RENDERER=rust runtime switch.
spawnRenderer() starts the reasonix-render binary, returns an
emit(frame) that writes one JSONL line to the child's stdin and a
close() that resolves with the child's exit code.
No app integration yet — this is the wire. The flip-the-flag PR
that decides between Ink and the spawned Rust process lands once
Ink can be mounted to a non-stdout backend, which is its own design
problem (Stage 1's mid-cut).
Why the test uses a Node stub:
- The real binary takes over the terminal (alt screen + raw mode).
Running it in a CI process would be hostile to the test runner.
- The contract we want to test is the JS-side plumbing: spawn
succeeds, frames pipe in order as JSONL, stdin closes cleanly,
exit code surfaces, post-close emit is a no-op. None of that
needs a real terminal — a Node script that echoes stdin lines
to a file is sufficient.
- This also keeps tests Rust-toolchain-free. Future CI doesn't
need to build the crate just to run the JS suite.
The DEFAULT_COMMAND points at `cargo run --bin reasonix-render` so
that future smoke tests / dev usage works without installing the
binary; release tooling will swap that to the installed binary
path when distribution is wired up.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
First visible Rust output. reasonix-render now reads JSONL frames
from stdin, sets up an alt-screen TUI, and renders each frame
through a recursive walker that paints into ratatui's Buffer.
Layout model:
- Text nodes paint runs left-to-right; styles map to ratatui's
fg/bg + Modifier bits. Overflow truncates at the right edge of
the area (single-line for now; wrap modes come when we hit a
real wrapped Text node).
- Box nodes apply paddingX/paddingY symmetrically, then split the
inner rect by direction. Column direction stacks children
vertically using each child's intrinsic height (1 for Text, sum
of children + gap + 2·paddingY for Box). Row direction lays out
horizontally with intrinsic width.
- Gap is added between siblings, not after the last one.
- Hex colors round-trip to ratatui::Color::Rgb (truecolor); named
colors map 1:1; "default" → Reset.
Binary controls:
- Frames advance on 'n' / Right-arrow or after the 800ms dwell.
- 'p' / Left-arrow goes back.
- 'q' / Esc exits cleanly (raw mode disabled, alt screen left,
cursor shown) even on panic-free error paths.
Tests:
- 7 render tests in tests/render.rs covering plain text, styled
runs, column stacking with gap, row layout, padding offset,
text overflow truncation, and hex truecolor.
- Existing 6 round-trip tests still pass.
- Buffer assertions use buf[(x,y)].symbol() / .style() so the
tests fail at the cell level if styling regresses, not just on
visual diffs.
Deps added: ratatui 0.29, crossterm 0.28, anyhow 1. These are
the canonical TUI dependency triple and we will live with them
through Stage 3.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
Closes the last open Stage 0 item from #947 — a real session running
with REASONIX_SCENE_TRACE=path/to/frames.jsonl now writes one frame
per state change to the trace file. The Rust binary from #953 can
read this trace and replay decoded SceneFrames end-to-end.
The frame today is a one-line summary (card count, busy/idle,
activity label), not a full lowering of the Ink tree. That's
intentional: lowerInkToScene only handles Ink primitives, and the
App tree is mostly stateful components. A full automatic lowering
is blocked on either (a) finishing #565 so the render tree is
decomposable, or (b) adding a function-component expansion helper —
both bigger pieces of work.
What this PR gets us anyway: a wired producer, the boundary proven
on real data, and a stable shape for the Rust side to test against.
When the lowering matures, only the body of useSceneTrace changes;
the call site in App stays the same.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
Locks in formatting and lint for the reasonix-render crate before
the second Rust PR adds anything substantial. Without this gate, the
Rust side drifts silently — JS contributors don't run cargo, and the
crate's existing serde annotations are exactly the kind of code
where one missed rename rots the boundary.
What runs:
- `cargo fmt --all -- --check` — formatting matches what rustfmt
produces on stable.
- `cargo clippy --all-targets -- -D warnings` — warnings are errors.
No clippy allowlist; if we want to silence something, the suppression
goes next to the offending code with a one-line reason.
- `cargo test --manifest-path Cargo.toml` — the round-trip suite
from #953. Tests run only at the workspace root, so the Tauri
shell at `desktop/src-tauri` (its own excluded workspace) is
untouched.
Linux-only for now. macOS and Windows runners come when actual
rendering work needs cross-platform terminal behavior gated; today
all the Rust code is serde + std and would just burn CI minutes
elsewhere.
Also applies rustfmt to the existing crate — two cosmetic line
wraps in `scene.rs` and one in `round_trip.rs` that `cargo fmt`
wants. The behavior change is zero; this is just the diff rustfmt
produces.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
First Rust code in the tree. Stage 1 spike per #868: prove the
scene-graph contract round-trips JS → Rust through the JSONL trace
written by REASONIX_SCENE_TRACE (#947 / #952).
What's in this PR:
- Cargo workspace at the repo root. `desktop/src-tauri` stays its
own workspace via `exclude` — the Tauri shell does not roll into
the renderer build.
- `crates/reasonix-render` binary + library. Library exposes the
serde-derived scene types; binary reads JSONL from stdin and
debug-prints decoded frames. Six round-trip tests cover named
colors, hex colors, nested boxes, full-frame serde symmetry, and
rejection of unknown node kinds.
- `target/` ignored at the workspace root. `Cargo.lock` committed
because this is a binary crate.
What's not in this PR:
- ratatui. Rendering comes once the trace path actually feeds real
app frames; printing the decoded debug form is enough to prove
the boundary.
- A `cargo test` step in CI. Will land alongside the next Rust PR
so the toolchain install only pays its cost once we have more
than one round-trip suite to gate on.
- Any change to the JS side. The contract type (`schemaVersion: 1`)
is the load-bearing piece both sides agree on; if a future field
is added on either side, schemaVersion bumps and the boundary
breaks loudly.
Refs #868#947
Co-authored-by: reasonix <[email protected]>
* feat(scene): define JSON scene-graph contract for Stage 0
Lays down the SceneFrame / SceneNode types the Rust renderer will
consume over stdio (per #868 Stage 0). No producer or consumer yet —
this is the contract that subsequent lowering / Rust-render PRs will
implement against.
Two primitives only (text + box), mirroring Ink. Layout fields are
hints; Rust does the actual layout (Yoga is what we're getting rid of).
schemaVersion=1 reserves room to evolve.
Refs #868
* feat(scene): builders for SceneFrame + JSON round-trip test
Authoring helpers for the contract introduced in #946 — `frame()`,
`box()`, `text()`, `run()`. Callers don't construct discriminated-
union literals by hand; the builders carry the `kind` tag and omit
empty optional fields so `JSON.stringify` produces clean output.
Round-trip test pins the JSON shape: anything we build serializes
and parses back as deep-equal. This is the cheapest invariant that
catches accidental non-JSON-able fields creeping in (functions,
Maps, BigInt, etc.) before the Rust side is wired up.
Refs #868#947
* feat(scene): walker that lowers Ink Text/Box to SceneNode
Handles the two Ink primitives directly — anything else (function
components, intrinsic host elements, unsupported props) throws with a
named error. Strict on purpose: the contract grows only when a real
use case forces it, not when someone defensively adds untested fields.
Behavior:
- Nested Text flattens into a single TextNode with multiple runs.
Parent styles inherit; child styles win on conflict.
- Ink prop vocabulary normalizes to scene vocabulary (`dimColor` →
`dim`, `alignItems: flex-start` → `align: start`, `wrap: end` →
`truncate`, `width: "100%"` → `"fill"`, etc.).
- Symmetric padding/margin only — Ink's per-side `paddingLeft` etc.
aren't supported until something needs them.
- Falsy children (null / undefined / false / true) skip cleanly.
14 unit tests cover the happy paths and every throw site.
Refs #868#947
* test(scene): lowering snapshot for Bar (real Ink primitive component)
First proof that lowerInkToScene works on a real component out of
primitives.tsx — not just synthetic React.createElement fixtures.
Bar is hook-free, so calling it as a plain function returns the
React element tree directly. Four cases cover the boundary
conditions:
- Mid-range ratio: filled + empty runs both non-empty.
- ratio=0 / ratio=1: one run is an empty string (lowering preserves
these as runs with the parent style; downstream normalizers can
filter if needed).
- dim=true: parent dim merges into the filled run alongside its
own color.
Refs #868#947
* feat(scene): stdio trace harness gated by REASONIX_SCENE_TRACE
Side-channel for capturing scene frames during a real session. Off
unless the env var is set; when set, every emitSceneFrame() call
appends one JSON object per line to the path.
Why JSONL: trivial to tail, trivial for tests on either side of the
boundary, no length-prefix framing decisions baked in before we know
what the Rust side wants. We can swap encodings later — the harness
is one module.
File is truncated on first emit, so a stale trace from a previous
run does not bleed into the new one. That trade-off (clobber on
init) matches how we expect this to be used: debugging a single
session at a time, not aggregating across runs.
No producer wires this up yet. The follow-up PR threads it through
one render site in App.tsx as a proof point.
Refs #868#947
---------
Co-authored-by: reasonix <[email protected]>
* feat(scene): define JSON scene-graph contract for Stage 0
Lays down the SceneFrame / SceneNode types the Rust renderer will
consume over stdio (per #868 Stage 0). No producer or consumer yet —
this is the contract that subsequent lowering / Rust-render PRs will
implement against.
Two primitives only (text + box), mirroring Ink. Layout fields are
hints; Rust does the actual layout (Yoga is what we're getting rid of).
schemaVersion=1 reserves room to evolve.
Refs #868
* feat(scene): builders for SceneFrame + JSON round-trip test
Authoring helpers for the contract introduced in #946 — `frame()`,
`box()`, `text()`, `run()`. Callers don't construct discriminated-
union literals by hand; the builders carry the `kind` tag and omit
empty optional fields so `JSON.stringify` produces clean output.
Round-trip test pins the JSON shape: anything we build serializes
and parses back as deep-equal. This is the cheapest invariant that
catches accidental non-JSON-able fields creeping in (functions,
Maps, BigInt, etc.) before the Rust side is wired up.
Refs #868#947
* feat(scene): walker that lowers Ink Text/Box to SceneNode
Handles the two Ink primitives directly — anything else (function
components, intrinsic host elements, unsupported props) throws with a
named error. Strict on purpose: the contract grows only when a real
use case forces it, not when someone defensively adds untested fields.
Behavior:
- Nested Text flattens into a single TextNode with multiple runs.
Parent styles inherit; child styles win on conflict.
- Ink prop vocabulary normalizes to scene vocabulary (`dimColor` →
`dim`, `alignItems: flex-start` → `align: start`, `wrap: end` →
`truncate`, `width: "100%"` → `"fill"`, etc.).
- Symmetric padding/margin only — Ink's per-side `paddingLeft` etc.
aren't supported until something needs them.
- Falsy children (null / undefined / false / true) skip cleanly.
14 unit tests cover the happy paths and every throw site.
Refs #868#947
* test(scene): lowering snapshot for Bar (real Ink primitive component)
First proof that lowerInkToScene works on a real component out of
primitives.tsx — not just synthetic React.createElement fixtures.
Bar is hook-free, so calling it as a plain function returns the
React element tree directly. Four cases cover the boundary
conditions:
- Mid-range ratio: filled + empty runs both non-empty.
- ratio=0 / ratio=1: one run is an empty string (lowering preserves
these as runs with the parent style; downstream normalizers can
filter if needed).
- dim=true: parent dim merges into the filled run alongside its
own color.
Refs #868#947
---------
Co-authored-by: reasonix <[email protected]>
* feat(scene): define JSON scene-graph contract for Stage 0
Lays down the SceneFrame / SceneNode types the Rust renderer will
consume over stdio (per #868 Stage 0). No producer or consumer yet —
this is the contract that subsequent lowering / Rust-render PRs will
implement against.
Two primitives only (text + box), mirroring Ink. Layout fields are
hints; Rust does the actual layout (Yoga is what we're getting rid of).
schemaVersion=1 reserves room to evolve.
Refs #868
* feat(scene): builders for SceneFrame + JSON round-trip test
Authoring helpers for the contract introduced in #946 — `frame()`,
`box()`, `text()`, `run()`. Callers don't construct discriminated-
union literals by hand; the builders carry the `kind` tag and omit
empty optional fields so `JSON.stringify` produces clean output.
Round-trip test pins the JSON shape: anything we build serializes
and parses back as deep-equal. This is the cheapest invariant that
catches accidental non-JSON-able fields creeping in (functions,
Maps, BigInt, etc.) before the Rust side is wired up.
Refs #868#947
* feat(scene): walker that lowers Ink Text/Box to SceneNode
Handles the two Ink primitives directly — anything else (function
components, intrinsic host elements, unsupported props) throws with a
named error. Strict on purpose: the contract grows only when a real
use case forces it, not when someone defensively adds untested fields.
Behavior:
- Nested Text flattens into a single TextNode with multiple runs.
Parent styles inherit; child styles win on conflict.
- Ink prop vocabulary normalizes to scene vocabulary (`dimColor` →
`dim`, `alignItems: flex-start` → `align: start`, `wrap: end` →
`truncate`, `width: "100%"` → `"fill"`, etc.).
- Symmetric padding/margin only — Ink's per-side `paddingLeft` etc.
aren't supported until something needs them.
- Falsy children (null / undefined / false / true) skip cleanly.
14 unit tests cover the happy paths and every throw site.
Refs #868#947
---------
Co-authored-by: reasonix <[email protected]>
* feat(scene): define JSON scene-graph contract for Stage 0
Lays down the SceneFrame / SceneNode types the Rust renderer will
consume over stdio (per #868 Stage 0). No producer or consumer yet —
this is the contract that subsequent lowering / Rust-render PRs will
implement against.
Two primitives only (text + box), mirroring Ink. Layout fields are
hints; Rust does the actual layout (Yoga is what we're getting rid of).
schemaVersion=1 reserves room to evolve.
Refs #868
* feat(scene): builders for SceneFrame + JSON round-trip test
Authoring helpers for the contract introduced in #946 — `frame()`,
`box()`, `text()`, `run()`. Callers don't construct discriminated-
union literals by hand; the builders carry the `kind` tag and omit
empty optional fields so `JSON.stringify` produces clean output.
Round-trip test pins the JSON shape: anything we build serializes
and parses back as deep-equal. This is the cheapest invariant that
catches accidental non-JSON-able fields creeping in (functions,
Maps, BigInt, etc.) before the Rust side is wired up.
Refs #868#947
---------
Co-authored-by: reasonix <[email protected]>
Lays down the SceneFrame / SceneNode types the Rust renderer will
consume over stdio (per #868 Stage 0). No producer or consumer yet —
this is the contract that subsequent lowering / Rust-render PRs will
implement against.
Two primitives only (text + box), mirroring Ink. Layout fields are
hints; Rust does the actual layout (Yoga is what we're getting rid of).
schemaVersion=1 reserves room to evolve.
Refs #868
Co-authored-by: reasonix <[email protected]>
User card was the only card using fg.meta + a near-black pill, so
once the active-card border stripe disappears in scrollback the
"You" row blends straight into surrounding meta text. Switch the
card tone to tone.brand (themed) and give the title pill a
brand-blue tint, matching the visual weight other cards carry.
Refs #910 (visibility half; @-mention issue stays open pending repro).
Co-authored-by: reasonix <[email protected]>
The ws @types are declared in package.json but the message/error
handlers used implicit any callback params, which trips the strict
typecheck gate on every pre-push run. Annotate raw as RawData and err
as Error — same shape ws emits, no runtime change.
Co-authored-by: reasonix <[email protected]>
* feat(qq): add QQ channel support to chat and code sessions
* refactor(qq): extract remote channel flow from app
---------
Co-authored-by: test <[email protected]>
Inline-code-heavy content like tree structures (each segment wrapped
in backticks, one entry per line) collapsed into a single wrapped
paragraph because soft breaks became spaces. Add remark-breaks so
single newlines render as <br/>, matching chat-UI expectations and
preserving line-by-line layout for tree views, ASCII tables, etc.
Co-authored-by: reasonix <[email protected]>
* fix(repair): prevent silent execution with empty args on truncation failure, fix POSIX process-group kill
Add fallback flag to TruncationRepairResult to distinguish between
successful repairs and hard fallback to {}. When repair fails completely,
keep the original truncated args so tools.ts rejects them with an
informative JSON parse error rather than silently running with {}.
Also add detached: true on POSIX spawn so children become their own
process-group leaders, allowing killProcessTree to terminate the whole
subtree instead of only the direct child.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
* fix(repair): correct changed detection in truncation repair, restore React import
- Use s !== input instead of notes.length > 0 for changed detection,
since brace/bracket closing doesn't produce notes but does change the JSON.
- Revert import type React back to import React in plan-confirm test,
as tsconfig uses classic JSX transform that requires runtime React.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
* chore: remove unused biome suppression
Co-Authored-By: Claude Opus 4.7 <[email protected]>
---------
Co-authored-by: Claude Opus 4.7 <[email protected]>
* feat(typeahead): mid-turn steer injection and queue with Esc recall
- loop.steer() method + steerConsumed getter (private fields, no public mutable state)
- "steer" EventRole replaces string-parsed "steer:" prefix
- Typeahead queue: Enter during busy appends, Esc recalls, drain with steerConsumed gate
- steer(newText) resets steerConsumed to prevent subsequent drain from being blocked
- Merged two drain effects into one to eliminate double-submit race
- Single drain effect: if steerConsumed, skip handleSubmit (message already in log)
- PromptInput stays enabled during busy; typeahead indicator shows staged count
- i18n: composer.typeaheadStaged (EN + zh-CN)
- 5 tests covering steer API, consumption, reset, and regression
* fix(tui): capture Ctrl+V paste while scrolled up
HistoryTypingCapture was returning early on ev.paste, discarding the
pasted content. Now it appends ev.input to the buffer, matching the
behaviour of normal key input.
---------
Co-authored-by: rokyplay <[email protected]>
* feat(skills): auto-discover .agents/skills as a default root
Closes#870. The configurable-paths system from #925 lets users point at
any directory, but a user with existing skills already sitting in
`~/.agents/skills` or `<project>/.agents/skills` still has to find that
setting and configure it — which is exactly the friction the original
issue asked us to avoid.
Append `.agents/skills` to the default discovery list in
`SkillStore.roots()` at both project and global scope, alongside the
existing `.reasonix/skills` entries. Anything sitting in the
skills.sh-style convention now just works on first launch.
* test(settings): make skillPaths absolute-path assertion platform-agnostic
The combined-POST test from #925 asserts `resolved: "/opt/skills"` for an
input of `/opt/skills`, which only holds on POSIX. On Windows `/opt/skills`
isn't an absolute path — `path.resolve` rebases it against the current
drive and returns `F:\opt\skills` (or whatever `CWD`'s drive is). Same
behavior as the production code, just the test forgot to mirror it.
Wrap the expected `resolved` in `resolve(absolute)` so both the
production resolver and the test compute the value through the same
function. Linux output unchanged.
(This would have been caught by the matrix CI from #926, but #925's PR
build ran a few minutes before that landed.)
---------
Co-authored-by: reasonix <[email protected]>
The /cwd slash command now exposes \`argCompleter: "path"\`, a new
completer type that async-lists the filesystem via \`listDirectory()\`.
Tab drills into directories (trailing '/'), Enter commits. Matches
are capped at SEARCH_RESULT_CAP (200) to match @-mention search.
- types.ts: add "path" to argCompleter union
- commands.ts: wire /cwd to argCompleter: "path"
- useCompletionPickers.ts: new usePathCandidates hook; update pickSlashArg
for dir drill-down; expose slashArgPathCandidates
- App.tsx: Tab handler checks candidate.isDir for drill vs. commit
- SlashArgPicker.tsx: optional pathCandidates prop, renders trailing /
on directory rows
Recent PRs hit Windows-specific bugs that Ubuntu CI couldn't catch —
literal forward-slash separators in path comparisons (#911) and
`partial.startsWith("/")` as an "is absolute path" heuristic (#922) both
sailed through `ubuntu-latest` while shipping broken on the platform
that most of the user base actually runs.
Add `windows-latest` to the existing matrix so every PR exercises the
Windows code paths (taskkill tree-kill, MS Store node-shim detection,
path separator handling, etc.) before review. Job name now includes the
OS so the two runs are distinguishable in branch protection.
Also swap the hardcoded `/tmp/tau-dry.json` in the τ-bench dry-run for
`${{ runner.temp }}` — RUNNER_TEMP is set on every GitHub Actions runner
including Windows, where `/tmp` isn't a path.
Co-authored-by: reasonix <[email protected]>
* fix(desktop): always show the jobs segment in the status bar
The segment was gated on `jobs.length > 0`, so users who hadn't yet
triggered a `run_background` call had no visible entry point and
assumed the feature wasn't wired up. ⌘J still worked but wasn't
discoverable.
Render the segment unconditionally; the running count uses the muted
`.v` color when zero and the accent `.v acc` color when something's
live, so an idle workspace still reads as idle without disappearing
from the bar.
* fix(desktop): jobs popover live-refresh, always-visible segment, run_background cwd
Three related fixes that turn the jobs popover from "polled and silently
dropped" into a real surface.
1. **`$jobs` events were never delivered.** `emitJobs()` emits without a
`tabId` (the snapshot is cross-tab by design), but the desktop event
router at `App.tsx:2446` only delivers events when `tabId` is set —
anything untagged was thrown away. Both the 1.5s popover poll and the
turn-complete one-shot fetch were sending requests to the agent and
then dropping the response. Add a broadcast branch for `$jobs` that
fans out to every registered tab dispatcher.
2. **Status-bar segment was hidden until a job existed**, so users with
no prior `run_background` calls had no visible entry point and
assumed the feature wasn't wired up (the ⌘J shortcut still worked but
wasn't discoverable). Render unconditionally; show `0` in the muted
`.v` color when idle, accent when something's live.
3. **`run_background` rejected `cd X && cmd`** patterns (correctly — the
JobRegistry needs single processes for tree-kill to work), and the
model fell back to `run_command` which doesn't go through the
registry and so doesn't show up in the popover at all. Add an
optional `cwd` param to `run_background`: workspace-relative or
absolute, must stay inside the workspace root (path-traversal check).
Tool description updated to point at `cwd` instead of `cd X && cmd`.
Plumb a new `onJobsChanged` callback from `ShellToolsOptions` through
`CodeToolsetOpts` so the desktop CLI re-emits `$jobs` after
`run_background` / `stop_job` / `wait_for_job` (when it returned because
the child exited). That gives the popover sub-second updates without
relying on the 1.5s poll for state changes that just happened.
---------
Co-authored-by: reasonix <[email protected]>
Followup to #912: orphaned dev servers are now killed on app exit, but
users still had no way to see what Reasonix had spawned in the first
place. Wires the JobRegistry to a popover anchored at the status bar.
Node side
- desktop.ts publishes a `$jobs` snapshot (id, command, pid, running,
exit code, started-at, tailed output, plus the per-tab session
label). Three new commands: `jobs_list`, `jobs_stop`, `jobs_stop_all`.
All aggregate across tabs — the popover is a workspace-wide view,
not a per-tab one.
- Stop handlers re-emit `$jobs` on settle so the UI doesn't have to
refetch to see the row flip to `exited`.
Desktop UI
- `ui/jobs-pop.tsx` renders the design's two-section layout (running
above, exited below) with per-row expand for pid / elapsed /
tailed output. Cuts the design's CPU/RAM/progress meters and the
awaiting-approval / queue sections — JobRegistry doesn't track
that data and the desktop's approval flow lives on different
surfaces. shell is the only `kind` we actually spawn.
- Status-bar `jobs` segment appears only when ≥1 job exists, shows
running count, click toggles the popover. Cmd/Ctrl-J does the same.
- App.tsx polls `jobs_list` every 1.5s while the popover is open and
once per `turn_complete` so the badge reflects fresh state without
being chatty when nothing's open.
- Styles in `styles.css` adapted from the supplied design: same panel
chrome (`.jobs-pop`, `.jobs-head`, `.jr-main`, `.jr-detail`,
`.jr-log`), simplified row grid (status / kind / body / time /
actions — no meter column since there's no progress to show).
i18n strings under `statusbar.jobs*` + `jobs.*` for both en and zh-CN.
Co-authored-by: reasonix <[email protected]>
Two visible breaks in how assistant messages displayed code blocks.
1. Fenced blocks WITHOUT a language tag fell through the `code` override
as inline `<code>`, because the override only branched on a
`language-*` className. Combined with the `pre` handler stripping its
wrapper to a fragment, the result lost both block layout AND
whitespace — multi-line ``` blocks rendered on one line as pills.
Move the dispatch to `pre`: detect the inner `<code>` child, pull lang
off the className if present, fall back to `"text"`. Anything without
a recognized language still goes through `CodeBlock` + `CodeView`, so
whitespace and the copy button survive. `code` is now purely the
inline path.
2. The CodeBlock chrome (`.codeblock`, `.codeblock-head`, `.codeblock-lang`,
`.copy-btn`) and the prism-rendered `<pre>` (`.codeview`,
`.codeview-line`, `.codeview-line-num`, `.codeview-line-content`)
had zero CSS — they were emitted to the DOM but never styled. Code
blocks rendered as a column of prism-colored tokens with no border,
no background, no header, and the copy button as a browser default.
Add the missing rules under `.markdown …` so they only target our
md-rendered tree (cards and elsewhere keep their own pre/code styles).
Inline `<code>` retains its existing `.msg-text code` pill style since
the new selectors are all scoped to `.markdown .…` and CodeBlock's
output contains no nested `<code>` element to collide with.
Co-authored-by: reasonix <[email protected]>
Reasonix-spawned background jobs (vite, http-server, npm run dev, etc.)
were outliving the desktop app — the user could quit Reasonix and the
preview URL at http://localhost:8080 stayed reachable, with no surface
to discover or stop the orphans.
Two reasons. (1) The Node CLI's cleanup hook was `process.once("exit",
…)`, but Node ignores async work inside `exit` listeners, so the
`jobs.shutdown()` promise was created and dropped on the floor. (2)
The Rust side called `child.kill()`, which on Windows is
`TerminateProcess` and only reaps the direct Node child — grandchildren
get reparented and survive.
Wire both layers:
- desktop.ts gains a real `gracefulShutdown` that awaits each tab's
`jobs.shutdown(1500)` (tighter than the 5s default — desktop is
going down, dev servers don't get etiquette) and then exits. It
fires on SIGTERM, SIGINT, and stdin readline `close` (Rust EOF).
The old `process.once("exit", …)` is gone — it was a no-op.
- rpc.rs now shares the `Child` between the natural-exit watcher and
`rpc_kill`. On Tauri ExitRequested we close Node's stdin (trips the
readline close → graceful path above), poll the child for up to 3s,
then `taskkill /F /T` (Windows) or `kill -KILL` + `pkill -KILL -P`
(Unix) so anything still standing — descendants included — goes
down with us.
Closes#907
Co-authored-by: reasonix <[email protected]>
Pressing the interrupt button (or Esc) only flipped tab.aborter — a
controller checked between events yielded by rt.loop.step(). When the
underlying DeepSeek stream was stuck waiting for a network read, no
events yielded, so the aborted flag never got read and the turn never
unwound. The "Reasoning" timer kept ticking forever.
The loop has its own AbortController (_turnAbort) that IS threaded into
client.stream({ signal }), so aborting it unblocks the fetch directly.
The TUI has always called loop.abort(); the desktop transport just
never wired it up.
Introduce abortTurn(tab) which fires both — the tab-level controller
(still used by the for-await guard) AND the loop-level one — and route
the five sites that needed cancellation through it: abort cmd, new_chat,
session_load, switchWorkspace, closeTab. The TUI's existing reset of
_turnAbort inside step()'s aborted path keeps subsequent turns clean.
Closes#905
Co-authored-by: reasonix <[email protected]>
When the floating "Reasoning" interrupt-bar was removed (PR #898), its
animation keyframe was left in place because three other modals
(settings, cmdk, plan modal) and now the session-delete popover all
reference `animation: rise`. The keyframe still carried the
interrupt-bar-specific `translate(-50%, ...)` baseline, which the
bar needed to stay centered while animating. For every other
consumer, that -50% horizontal offset is unwanted: the popover
animates in shifted half its width to the left, then snaps to its
real position the instant the animation completes. The eye reads
that as a horizontal pop, not a clean fade-up.
Switch the keyframe to a pure Y translate. All current users want
the same vertical slide-up + fade-in, none have a baseline
horizontal transform that depended on the keyframe preserving it.
Co-authored-by: test <[email protected]>
Right-clicking a session in the sidebar fired a `window.confirm()` —
a native modal that visually breaks the dark UI and traps the user
the moment a misclick lands the cursor over a session row. Users
flagged this as too easy to fire by accident.
The right-click gesture stays, but the action surface is now an
in-app popover anchored at the cursor with explicit cancel/delete
buttons. Misclicks are recoverable: clicking anywhere outside the
popover or hitting Esc dismisses without touching the session. The
cancel button is autofocused, so Enter on an accidental popover
cancels rather than deletes. The confirm button uses the existing
--danger color so the destructive option is visually distinct.
useLayoutEffect measures the popover and clamps it inside the
viewport so right-clicking a session near the window edge doesn't
push the popover off-screen.
Co-authored-by: test <[email protected]>
`/cwd ../tmp-b` re-pointed the filesystem / shell / memory / hook
tools at the new directory but left the in-memory chat log, on-disk
session transcript, system prompt, and status-bar session label all
referencing the OLD workspace. Two real problems:
- The model kept reasoning over messages that referenced paths from
tmp-a — cross-workspace contamination on every follow-up.
- The status bar still showed `code-tmp-a` after switching to tmp-b,
so users couldn't tell which workspace the active session belonged
to.
This patch wires the missing follow-through:
- `CacheFirstLoop.switchWorkspace({ sessionName })` archives the old
session transcript (same path as `/new`), drops the in-memory log,
repoints `sessionName`, and re-runs the system-prompt builder so
the new workspace's REASONIX.md / memory takes effect immediately.
- `code.tsx` now wraps `rootDir` and `semantic.enabled` in `let`
bindings and exposes `onRootChange` on `codeMode`, so the
rebuilder closure resolves the live workspace at call time.
- `App.tsx`'s `switchCwd` callback now calls `onRootChange` +
`loop.switchWorkspace` + dispatches a new
`session.workspace.change` event so the agent store's
`SessionInfo.id` and `.workspace` update — that's what the status
bar reads. The slash handler propagates `clear: true` so
`applySlashResult` mirrors `/new`'s UI reset (scrollback, pending
edits, modals).
- New event `session.workspace.change` + reducer case in the agent
store.
Closes#902
Co-authored-by: test <[email protected]>
Before: while the agent was generating, pressing Enter aborted the
current turn — there was no way to leave a follow-up without
interrupting (and discarding) in-progress reasoning. You had to wait
out the whole turn before typing the next thing.
After: while busy, Enter on a non-empty draft enqueues the text and
clears the textarea; the messages render as removable chips above the
composer, and drain FIFO when `$turn_complete` fires. esc remains the
canonical abort. Empty-draft Enter is a no-op (it used to silently
abort, which was confusing).
Implementation lives entirely above the loop / streaming layer:
- `state.queuedSends: string[]` in the TabRuntime reducer, plus
`enqueue_send` / `dequeue_send` / `shift_queued_send` actions.
- A small useEffect watches `(busy, ready, queuedSends.length)` —
when busy flips false with a non-empty queue, it shifts the head
and routes it through the existing `send(override)` path. Reuses
every code path a manual send already touches (user-message card,
sendRpc, prefix cache, etc.).
- Composer accepts `queuedSends`, `onQueueWhileBusy`, `onDequeueSend`
props. Enter-while-busy with a non-empty draft now routes to the
queue instead of abort. The hint-row right side becomes
`⏎ 排队 · esc 中断` so the new behavior is discoverable.
- The queue is cleared on `clear`, `rpc_exit`, and `$session_loaded`
(queued text from session A shouldn't auto-send into session B).
Closes#894
Co-authored-by: test <[email protected]>
The "Reasoning Xs / 中断 esc" pill floated absolutely 88px above the
bottom, centered over the input — it covered the top edge of the
textarea AND duplicated the stop affordance the composer already
shows (the send button flips to a red 中断 button while busy).
Collapse the indicator into the existing hint-row above the textarea:
animated pip + label + elapsed timer on the left, ⏎/esc 中断 hint on
the right. No floating overlay, no overlap, single canonical stop
button (composer's own send→stop transform). The hint-row stays at the
same height — the busy state morphs in place when state.busy flips.
`InterruptBar` and the `.interrupt-bar` CSS block are removed; the
`@keyframes rise` definition is kept since other modals (settings,
cmdk) still reference the animation name.
Closes#896
Co-authored-by: test <[email protected]>
WebKitGTK 2.42+ ships a new DMABUF-based renderer that SIGABRTs the
WebKitWebProcess at launch on several Wayland + Mesa combos (Intel UHD
+ KDE Plasma 6 on openSUSE Tumbleweed was the reported case in #892,
but the same crash shows up in many Tauri / WebKit2GTK apps in the
wild). The window opens black, the parent process keeps running.
Setting WEBKIT_DISABLE_DMABUF_RENDERER=1 before WebKitWebProcess
spawns falls back to the older shared-memory texture path, which is
slower but reliably renders. We only force this on Linux, and only
when the user hasn't set the var themselves — that keeps the door
open for users on working stacks who want the newer fast path.
Closes#892
Co-authored-by: test <[email protected]>
* feat(skills): add install_skill tool for AI-authored playbooks
A new tool that lets the agent create reusable skills mid-session.
Writes <project>/.reasonix/skills/<name>.md (or ~/.reasonix/skills/<name>.md
for global scope), assembles the frontmatter, and returns the path.
The newly installed skill is callable immediately via run_skill in the
same turn — run_skill reads the file fresh from disk. The pinned Skills
index in the system prompt only refreshes on /new (same precedent as
remember: keep the prefix cache stable).
For the desktop client, a new onSkillInstalled hook on CodeToolsetOpts
threads through to registerSkillTools; the desktop tab wires it to
emitSkills(tab) so the sidebar pushes the new skill without a tab
reload. TUI mode leaves the hook unset since it surfaces skills via
/skill list (always reads disk on demand).
Permissions ride the existing tool-permission tiers: default mode
shows the call args (name + body) for approval, acceptEdits auto-
approves like write tools, yolo skips the prompt — no special install
path needed.
* test(memory): thread homeDir override so /memory tests don't read real ~/.reasonix
Two pre-existing tests were silently reading the developer's real
~/.reasonix/memory/ during test runs, failing whenever the dev had any
global memory pinned locally.
The fix is a clean opt-out: applyMemoryStack and the /memory slash
context now accept an optional homeDir. Production callers still
default to os.homedir(); the two failing tests pass a tmpdir.
- applyMemoryStack(base, root, { homeDir }) — threads to
applyGlobalReasonixMemory, applyUserMemory, applySkillsIndex.
- SlashContext.homeDir — wired through to MemoryStore in the
/memory handler.
No behavior change in production; only test isolation.
---------
Co-authored-by: test <[email protected]>
Hardcoded `0.42.0-3` was scattered across 8 files (3 static HTML pages
+ 5 JSX modules). The JSX side now reads `window.REASONIX_VERSION` set
once in i18n.jsx (loaded first on every page), so future bumps are a
one-line edit. Static HTML pages still need manual touch — they don't
load any JS.
Side effects:
- Footer / nav strip shows "stable" instead of "prerelease" — desktop
is GA in 0.43.0.
- Mirror grid file sizes refreshed from the actual v0.43.0 assets
(universal.dmg 53 → 52 MB, AppImage 122 → 128 MB).
- Roadmap drops "(prerelease)" from the shipped Tauri item; in-progress
column key advances v0.42.x → v0.44.x (0.43.x is now in Shipped
territory).
Co-authored-by: test <[email protected]>
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.
2026-05-09 00:04:33 +08:00
1084 changed files with 186575 additions and 19371 deletions
<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/>
<h3 align="center">ターミナルで動く DeepSeek ネイティブの AI コーディングエージェント。</h3>
<img src="docs/assets/hero-terminal.svg" alt="Reasonix code mode — assistant proposes a SEARCH/REPLACE edit; nothing on disk until /apply" width="860"/>
> **This is the legacy TypeScript line (Reasonix 0.x), in maintenance mode.**
> Active development moved to the **Go rewrite** — see the [`main-v2`](https://github.com/esengine/DeepSeek-Reasonix/tree/main-v2) branch (the new default) and the [migration guide](https://github.com/esengine/DeepSeek-Reasonix/blob/main-v2/docs/MIGRATING.md). Only bug fixes land here.
<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/>
@@ -44,90 +63,132 @@
> [!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.
<br/>
## Web search
Reasonix includes `web_search` and `web_fetch` tools. By default it uses **Mojeek** (no setup required). You can switch to a **self-hosted SearXNG** instance — a metasearch engine that aggregates whatever upstream engines your instance is configured for.
### Switching engines (persists to disk)
The `/search-engine` slash command (alias `/se`) writes your choice to `~/.reasonix/config.json` immediately — it survives restarts:
```
/search-engine mojeek # default, no external deps
/search-engine searxng # SearXNG at http://localhost:8080
The tool picks up the change on the next call — no restart needed.
### Starting SearXNG
```sh
podman run -d --replace --name searxng -p 8080:8080 docker.io/searxng/searxng
# or: docker run -d -p 8080:8080 searxng/searxng
```
Verify it's running:
```sh
curl http://localhost:8080/search?q=test
# → HTML search results page
```
> **Note:** The endpoint must include the protocol (`http://`). `localhost:8080` alone will fail — the tool will show a clear error telling you to install SearXNG if the server is unreachable.
> [!IMPORTANT]
> **Community · 加入社区** — bilingual Discord with channels for setup help (`#help` / `#求助`), workflow showcases, feature ideas, and contributor-only PR coordination. Verify your GitHub in-server to get the **Contributor** role automatically. → **<https://discord.gg/XF78rEME2D>**
<br/>
## Install
```bash
Requires Node ≥ 22. Works on macOS · Linux · Windows (PowerShell · Git Bash · Windows Terminal).
Install Reasonix globally if you want the `reasonix` command available on your `PATH`:
~~~bash
npm install -g reasonix
reasonix code my-project # paste a DeepSeek API key on first run; persists after
~~~
Or run it once without installing globally:
~~~bash
cd my-project
npx reasonix code # paste a DeepSeek API key on first run; persists after
```
npx reasonix code # always uses the latest package by default
~~~
Requires Node ≥ 22. Tested on macOS · Linux · Windows (PowerShell · Git Bash · Windows Terminal). Get a [DeepSeek API key →](https://platform.deepseek.com/api_keys) · `reasonix code --help` for flags.
Grab a [DeepSeek API key →](https://platform.deepseek.com/api_keys) · `reasonix code --help` for flags.
`npx` is the recommended path — no global install, always picks up the latest version. If you'll use Reasonix daily and want `reasonix` on your `PATH`, run `reasonix update` once and it'll do the `npm install -g` for you.
If you use Reasonix daily, global install is the simplest path. If you just want to try it, use `npx`.
### Subcommand cheatsheet
**Prefer fewer keystrokes?** The shorter `dsnix` alias resolves to the same CLI:
| Command | When to use |
~~~bash
npm install -g dsnix # exposes `dsnix` on PATH, depends on reasonix
npx dsnix@latest code # one-shot via the shorter command
~~~
A global `npm install -g reasonix` also drops a `dsnix` shim on PATH, so the two are interchangeable.
Bare `reasonix` (no subcommand) launches `code` in the current directory — typing `reasonix` and `reasonix code` are equivalent.
| Command | When |
|---|---|
| `reasonix code [dir]` | Coding agent rooted at a project. **Start here.** |
| `reasonix chat` | Plain chat — no filesystem tools, just a conversation with persisted history. |
| `reasonix run "task"` | One-shot, streams the answer to stdout. Good for shell pipes. |
| `reasonix doctor` | Environment health check (Node version, API key, MCP wiring). |
| `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 listed in `reasonix --help` and on the [CLI reference](https://esengine.github.io/DeepSeek-Reasonix/#cli).
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).
**Working in a different folder:** Reasonix scopes filesystem tools to the launch directory. To work elsewhere, pass `--dir`:
### QQ channel
```bash
npx reasonix code --dir /path/to/project # or use a relative path
```
QQ can extend an existing `chat`, `code`, or desktop session as a remote channel. It is part of the current session flow, not a separate runtime mode.
Mid-session switching isn't supported by design (the message log + memory paths get tangled with stale roots). Quit and relaunch with a new `--dir` to retarget. `/status` always shows the current pinned workspace.
- CLI: start a session, then run `/qq connect`
- Desktop: open `Settings -> General -> QQ Channel`
**Author your first skill:** Skills are markdown playbooks the model can invoke (`/skill <name>`). There's no remote registry yet — you author them directly:
Once connected, QQ messages can enter the current session, assistant replies route back to QQ, and follow-up interactions can continue remotely.
```bash
/skill new my-skill # scaffolds <project>/.reasonix/skills/my-skill.md
/skill new my-skill --global # or under ~/.reasonix/skills for cross-project use
```
For full setup, desktop quick start, and troubleshooting, see [QQ channel setup](./docs/qq-connect.md).
Edit the file (`description:` frontmatter + body), then `/skill list` to see it. Add `runAs: subagent` to the frontmatter to spawn an isolated subagent loop instead of inlining the body.
### 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
~~~
**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.
**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
~~~
**Claude-format skills also load.**`<project>/.claude/skills/<name>/SKILL.md` and `~/.claude/skills/` are read alongside Reasonix's native paths, so tooling that emits Claude-format skills works out of the box. Example — drop OpenSpec workflows in without an upstream adapter:
~~~bash
npx openspec init --tools claude # writes .claude/skills/openspec-*/SKILL.md
/skill openspec-propose <task> # then invoke from Reasonix
~~~
</details>
<br/>
## Configuration
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) | Bing by default; switch to Baidu AI Search, self-hosted SearXNG, Metaso, Tavily, Perplexity, Exa, Brave, or Ollama with `/search-engine`. |
| [Semantic index](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#index) | `reasonix index` — local Ollama or any OpenAI-compatible embedding endpoint. |
<br/>
@@ -163,7 +224,7 @@ Click through to the full architecture writeup → [Pillar 1 — Cache-first loo
| Web search (Bing + Baidu + SearXNG + API engines) | yes | yes | yes | yes |
| 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.
@@ -173,6 +234,8 @@ For live cache-hit rates, costs, and methodology, see [`benchmarks/`](./benchmar
## Documentation
- [**Architecture**](./docs/ARCHITECTURE.md) — three pillars: cache-first loop, tool-call repair, cost control
- [**CLI Reference**](./docs/CLI-REFERENCE.md) — every shell subcommand, every slash command, every keybinding
- [**QQ channel setup**](./docs/qq-connect.md) — CLI first-connect flow, desktop entry, and QQ Open Platform credentials
@@ -183,7 +246,7 @@ For live cache-hit rates, costs, and methodology, see [`benchmarks/`](./benchmar
## Community
> [!NOTE]
> Reasonix is open source and community-developed. The contributors wall below isn't decoration — every avatar is a real PR that shipped.
> Reasonix is open source and community-developed. Every avatar in the Acknowledgments wall at the bottom of this file 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.
@@ -203,12 +266,6 @@ Scoped starter tickets — each with background, code pointers, acceptance crite
**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 alt="Star History Chart" src="https://api.star-history.com/chart?repos=esengine/DeepSeek-Reasonix&type=date&legend=top-left" />
</picture>
</a>
<br/>
## Support
If Reasonix has been useful and you'd like to say thanks, you can. It stays a coffee, not a contract — donations don't buy feature priority or change how issues get triaged.
name:"Context fold preserves pinned constraints from system prompt",
category:"context",
requiresApi: false,
run:()=>
withTiming(async()=>{
constsystemPrompt=`You are a coding assistant.
# HIGH PRIORITY constraints
- DO NOT use npm install without asking.
- Never delete files without confirmation.
# User memory
The user prefers TypeScript over JavaScript.
# Project memory
This project uses pnpm instead of npm.`;
constlog=newAppendOnlyLog();
// Fill log with synthetic long history to trigger a fold boundary > 0.
for(leti=0;i<40;i++){
log.append({
role:"user",
content:`Turn ${i}: Please review the codebase and tell me what you found.`,
});
log.append({
role:"assistant",
content:`Turn ${i} summary: I reviewed the codebase and found several issues including unused imports, missing type annotations, and inconsistent formatting.`,
});
}
constclient=newMockDeepSeekClient("Summary of all prior turns.");
conststats=newSessionStats();
constctx=newContextManager({
client: clientasany,
log,
stats,
sessionName: null,
getAbortSignal:()=>newAbortController().signal,
getCurrentTurn:()=>1,
getSystemPrompt:()=>systemPrompt,
});
// Use a tiny tail budget so almost everything becomes head and gets summarized.
/** tau-bench in-memory DB helpers — pure functions over a nested-table WorldState. */
importtype{WorldState}from"./types.js";
/** Deep-clone a WorldState — `structuredClone` is enough since the type is JSON-shaped by contract. */
/** Deep-clone a WorldState — `structuredClone` is enough since the type is JSON-shaped by contract. Idempotent: calling cloneDb N times on the same input yields identical copies. */
exportfunctioncloneDb(db: WorldState):WorldState{
returnstructuredClone(db);
}
/** Get a row by table name and id. Lookup is `db[table][id]` — two-level nested dictionary. Returns the row object or `undefined` if not found. */
exportfunctiongetRow(
db: WorldState,
table: string,
@@ -13,6 +15,7 @@ export function getRow(
returndb[table]?.[id];
}
/** Set a single field on a row. Mutates `db` in-place — caller should `cloneDb` first if isolation is needed. Returns `true` if the row was found and updated, `false` if not. */
editGateTitle:"edit gate — Shift+Tab cycles in TUI",
editReviewTitle:"review — both edits and non-allowlisted shell ask first",
editAutoTitle:"auto — edits auto-apply, shell still asks",
@@ -214,12 +529,19 @@ export const en = {
dailyMeta:"cost · cache saved · turns",
noData:"No usage data yet — run a turn in reasonix chat / code / run and refresh.",
windows:"Rolling windows",
colWindow:"window",
colTurns:"turns",
colCacheHit:"cache hit",
colCost:"cost (USD)",
colCacheSaved:"cache saved",
colVsClaude:"vs Claude",
colSaved:"saved",
axisTime:"time",
axisUsd:"USD",
axisTurns:"turns",
seriesCost:"cost",
seriesCacheSaved:"cache saved",
seriesTurns:"turns",
mostUsed:"Most used models",
colModel:"model",
},
@@ -236,6 +558,16 @@ export const en = {
loadingTranscript:"loading transcript…",
emptyTranscript:"empty transcript.",
messages:"{count} message{s}",
newBtn:"New session",
newHint:"Archive the current conversation and start a fresh one",
switchBtn:"Switch to this session",
deleteBtn:"Delete",
deleteConfirm:"Delete session \"{name}\"? This removes the transcript file and cannot be undone.",
cantDeleteActive:"Switch to a different session before deleting this one.",
attachRequired:
"Live session operations need an attached CLI session. Launch via reasonix chat or open the dashboard from inside a TUI session.",
activeChip:"active",
activePill:"active",
},
tools:{
loading:"loading tools…",
@@ -248,6 +580,74 @@ export const en = {
readOnly:"read-only",
write:"write",
flat:"flat",
desc:{
web_search:
"Search the public web. Returns ranked results with title, url, and snippet. Call this when the answer depends on current state — events, prices, releases, real-world status.",
web_fetch:
"Download a URL and return its visible text content (scripts/styles/nav stripped). Use after web_search when a snippet isn't enough.",
run_command:
"Run a shell command in the project root; returns combined stdout+stderr. Allowlisted read-only commands run immediately; mutations are gated by user confirmation.",
run_background:
"Spawn a long-running process and detach. Returns a job id for tailing logs, waiting for completion, or killing. Use for dev servers, watchers, and one-shot long jobs.",
job_output:
"Read the latest output of a background job. Returns the tail of the buffer and tells you whether the job is still running.",
wait_for_job:
"Block server-side until a background job finishes, bounded by timeout. Use instead of polling job_output in a loop.",
stop_job:
"Stop a background job. SIGTERM first, SIGKILL after a grace period. Safe to call on an already-exited job.",
list_jobs:
"List every background job started this session — running and exited — with id, command, pid, and status.",
remember:
"Save a memory for future sessions. Use when the user states a preference, corrects your approach, shares a non-obvious fact, or asks you to remember something.",
forget:
"Delete a memory file and remove it from MEMORY.md. Use when the user asks to forget something or a remembered fact is now wrong.",
recall_memory:
"Read the full body of a memory file when its one-line summary isn't enough detail.",
read_file:
"Read a file under the sandbox root. Supports head/tail/range scoping to save context. Auto-returns a preview for files over 200 lines.",
list_directory:
"List entries in a directory. Returns one line per entry, marking directories with a trailing slash.",
directory_tree:
"Recursively list entries in a directory as an indented tree. Budget-aware with auto-collapse for large subtrees.",
search_files:
"Find files whose NAME matches a substring or regex. Case-insensitive. Skips dependency/build directories by default.",
search_content:
"Recursively grep file CONTENTS for a substring or regex. Returns matches in path:line:text format. The right tool for finding references.",
glob:"List files matching a glob pattern, sorted by mtime. Default limit 200, max 1000. Skips node_modules/.git/dist by default.",
get_file_info:"Stat a path under the sandbox root. Returns type, size in bytes, and mtime.",
write_file:
"Create or overwrite a file with the given content. Parent directories are created as needed.",
edit_file:
"Apply a SEARCH/REPLACE edit to an existing file. The search must match exactly and be unique in the file.",
multi_edit:
"Apply N SEARCH/REPLACE edits across one or more files atomically. If any edit fails, no files are written.",
create_directory:"Create a directory (and any missing parents) under the sandbox root.",
move_file:"Rename or move a file or directory under the sandbox root.",
delete_file:
"Delete one file under the sandbox root. Refuses directories — use delete_directory for those.",
delete_directory:
"Recursively delete a directory under the sandbox root. Pass recursive:false to refuse non-empty directories.",
copy_file:
"Copy a file or directory under the sandbox root. Refuses to overwrite an existing destination.",
submit_plan:
"Submit one concrete plan for a review gate. Use for multi-file refactors, architecture changes, or anything expensive to undo.",
mark_step_complete:
"Mark one step of the approved plan as done. Call exactly once after finishing each step.",
revise_plan:
"Surgically replace the remaining steps of an in-flight plan. Done steps are never touched.",
run_skill:
"Invoke a playbook from the Skills index. Pass the bare skill name. Subagent-tagged skills spawn an isolated subagent.",
spawn_subagent:
"Spawn an isolated subagent for a self-contained subtask. Use for parallel fan-out or when the work needs many file reads.",
todo_write:
"In-session task tracker for multi-step work. Replaces the entire list every call. No approval gate or file writes.",
ask_choice:
"Present 2-6 alternatives to the user. Use when the user asks for options or you need a preference decision.",
create_skill:
"Scaffold a new skill the user can invoke later via /skill. Supports inline and subagent run modes.",
add_mcp_server:
"Register a new MCP server in the user's config. Takes effect on the next session. Supports stdio, SSE, and streamable-http.",
},
},
permissions:{
loading:"loading permissions…",
@@ -295,6 +695,10 @@ export const en = {
whyUnbridgedDesc:
"This spec lives in your config.json but isn't bridged into the live session. MCP servers attach when reasonix code starts; the dashboard alone can't spawn the child process.",
whyUnbridgedHint:"To activate: restart reasonix code, then refresh this dashboard.",
bridgeFailed:"Bridge failed",
bridgeFailedTitle:"bridge failed · in config",
bridgeFailedHint:
"Reasonix tried to bridge this server and the attempt errored. Common causes: wrong URL, missing auth header, upstream 404/5xx, missing local command. Fix and restart reasonix code to retry.",
pickHint:"Pick an MCP server on the left to inspect tools / resources / prompts.",
toolsTitle:"Tools · {count}",
resourcesTitle:"Resources · {count}",
@@ -367,6 +771,7 @@ export const en = {
loading:"loading skills…",
filterPlaceholder:"filter skills",
project:"project",
custom:"custom",
global:"global",
builtin:"builtin",
newSkill:"new skill",
@@ -374,6 +779,7 @@ export const en = {
runs7d:"runs · 7d",
pickHint:"Pick a skill on the left, or create a new one above.",
readOnlyBuiltin:"read-only · builtin",
readOnlyCustom:"read-only · custom path",
builtinDesc:
"Built-in skills ship with Reasonix; the model picks them up automatically. To customize, create a project- or global-scoped skill with the same name.",
saved:"saved {scope}/{name}",
@@ -458,7 +864,8 @@ export const en = {
lastBuild:"last build",
builtWith:"built with",
currentTarget:"current target",
incompatibleHint:"This on-disk index was built for a different provider or model. Run Rebuild to replace it.",
incompatibleHint:
"This on-disk index was built for a different provider or model. Run Rebuild to replace it.",
runIndexHint:"Run an index to enable semantic_search.",
reIndex:"Re-index",
build:"Build",
@@ -475,6 +882,7 @@ export const en = {
customRequestBodyMustBeObject:"Custom request body must be a JSON object.",
saveBeforeIndex:"Save semantic settings before starting an index.",
extraBody:"extra body",
batchSize:"batch size",
keepExistingKey:"leave blank to keep existing key",
remoteProvider:"Remote embedding provider",
remoteProviderDesc:
@@ -540,6 +948,12 @@ export const en = {
shellBgTitle:"background process",
shellSubtitle:"model wants to run a shell command",
shellBgSubtitle:"long-running — keeps running after approval",
pathTitle:"file outside sandbox",
pathSubtitle:"{intent} via {tool}",
pathRead:"read",
pathWrite:"write",
pathSandboxLabel:"sandbox",
pathAllowPrefixLabel:"allow prefix",
runOnce:"Run once",
alwaysAllow:'Always allow "{prefix}"',
deny:"Deny",
@@ -587,4 +1001,343 @@ export const en = {
pickerNewPlaceholder:"Name (leave blank for default)",
viewerClose:"Close",
},
error:{
title:"Something broke in the dashboard",
body:"The TUI is unaffected — only this browser tab tripped. You can dismiss and keep working, or report it so we can fix the underlying cause.",
conststub=`---\nname: ${newName.trim()}\ndescription: TODO — one-line description that helps the model match this skill\n---\n\n# ${newName.trim()}\n\n`;
// macOS Chinese IME fires compositionend before the confirm keydown.
constcomposingRef=useRef(false);
constcompositionEndedAtRef=useRef(0);
// Programmatic draft transitions to "/" (e.g. /help suggestion in EmptyState, #929) must open the slash popup, since handleChange only fires on actual user input.
return`${ELIDED_PREFIX}${TRANSCRIPT_RECENT_MESSAGE_WINDOW} messages; ${chars.toLocaleString()} chars dropped to keep long sessions responsive. Full content remains in the session log.]`;
Loaded 100 of 1084 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.