Compare commits

...
545 Commits
Author SHA1 Message Date
reasonix 50b1bf4a50 fix(cli): don't crash session hydration on a tool_call missing its function
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.
2026-06-03 03:05:05 -07:00
esengine 8907573f09 docs(v1): mark the TypeScript line as legacy, point to the Go rewrite (main-v2) 2026-05-31 01:29:19 -07:00
512e3dd66e chore(cache): localize /status cache-detail line and make tool sort locale-independent (#2320)
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]>
2026-05-29 17:44:02 -07:00
Sivan fccea10236 Cache Efficiency Guardrails and Diagnostics / 缓存效率守卫与诊断 (#2314)
* feat(cache): add cache efficiency guardrails

* fix(cache): hash sent tool snapshot for diagnostics
2026-05-29 17:29:40 -07:00
HUQIANTAOandHUQIANTAO 72e89ff7c3 fix(desktop): clean up animations — remove breathing lights, fix broken keyframes (#2267)
- Fix undefined @keyframes 'caret' → 'stream-caret' (shell running caret was broken)
- Fix undefined @keyframes 'fade' → 'fade-in' (about modal mask was broken)
- Remove shimmer animation from 'Running' label and ThinkingPill text (double animation with dots)
- Remove pulse-soft breathing from PendingUserMsg background
- Remove yolo-pulse breathing from YOLO mode border
- Unify duplicate @keyframes shimmer-bg into shim
- Remove dead keyframes: pulse-soft, yolo-pulse
- Wire tab status dots to actual busy/idle state (was hardcoded to 'running')

Co-authored-by: HUQIANTAO <[email protected]>
2026-05-29 02:26:38 -07:00
nianyi(likai) d83a0bd630 fix(web): apply 15s timeout to all search engines (#2252 follow-up) (#2259)
#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.
2026-05-29 01:56:24 -07:00
Porun b1f7d1ab15 feat(weixin): render ilink qr in terminal (#2246) 2026-05-29 01:43:58 -07:00
YapuandClaude Opus 4.7 bd98ef3fe3 fix(web): 给 searchBing 添加 15s 超时防止无限挂起 (#2252)
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]>
2026-05-29 01:10:12 -07:00
621aad4d87 fix(desktop): increase sidebar minimum drag width from 160px to 200px (#2248)
侧边栏拖拽最小宽度从 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]>
2026-05-29 01:09:51 -07:00
J. F. Zhang 4e4faf2eae fix(desktop): persist prompt history across sessions (#2068)
* fix(desktop): persist prompt history across sessions

* fix(desktop): use session logs for prompt history
2026-05-29 00:56:56 -07:00
nianyi(likai) c0f2320224 feat(session): add /session-persist to toggle auto-resume on launch (#2238) (#2243)
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
2026-05-29 00:53:42 -07:00
TulgaandTulga Battogtokh b58c505c84 fix: restore browser dashboard file mentions (#2242)
Co-authored-by: Tulga Battogtokh <[email protected]>
2026-05-29 00:51:31 -07:00
QiuYa e57ca88473 feat(cli): split-pane plan panel in TUI (#2227)
## 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
2026-05-29 00:20:50 -07:00
e3b31be66c fix(ui): apply themed background to input area and app surface (#2182)
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]>
2026-05-28 23:47:45 -07:00
Porun f3082b91d0 feat(weixin): add trusted iLink channel (#2240)
* feat(weixin): add trusted iLink channel

* fix(weixin): constrain ilink endpoint
2026-05-28 23:42:08 -07:00
Xy 08eaac5ed4 fix(loop): keep headless NEEDS_PRO escalation one-shot (#2236) 2026-05-28 23:36:51 -07:00
nianyi(likai) 744d1f93eb feat(permissions): global shell allowlist that cascades with per-project (#2059) (#2091)
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).
2026-05-28 23:34:46 -07:00
nianyi(likai) 893c1c7f9f fix(desktop): follow streaming output when user is at bottom (#2159) (#2235)
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.
2026-05-28 23:33:29 -07:00
nianyi(likai) e95c93f2dc feat(mcp): expand ${VAR} env vars in mcpServers header values (#2148) (#2233)
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.
2026-05-28 23:33:06 -07:00
YHHandyhh bdbafa7b7c fix(test): skip #2137 symlink skill tests on Windows (EPERM without admin) (#2239)
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]>
2026-05-28 23:25:45 -07:00
nianyi(likai) 868b61b4ac feat(skills): inline references/ files at load time for Anthropic Skills compat (#2214) (#2230)
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.
2026-05-28 22:50:01 -07:00
nianyi(likai) 991ad37959 fix(proxy): hint for corporate firewalls where DeepSeek requires proxy (#2215) (#2229)
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.
2026-05-28 22:43:28 -07:00
nianyi(likai) 4811857f6b fix(session): warn when system prompt changes on session resume (#2212) (#2228)
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
2026-05-28 22:43:05 -07:00
QiuYa 1739231050 fix(desktop): abort agent loop on plan_response cancel (#2225)
## 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
2026-05-28 22:42:43 -07:00
CVEngineerandwufengfan 0a7f9ed4a1 fix(desktop): Virtuoso initial scroll to bottom + JumpBar onScrollToTurn callback (#2056 hotfix) (#2073)
* feat(desktop): collapse intermediate reasoning + group consecutive tool calls

* fix: open tool cards inside group when expanded

* fix: independent collapse state per tool group

* fix: lift ToolGroupShell to module scope, preserve shell live-streaming, rename defaultOpen prop

* perf(desktop): replace messages.map with backwards-walk index replace in streaming handlers

* perf(desktop): reduce transcript window 120->60 to halve rendered message nodes

* perf(desktop): virtual list with Virtuoso for message thread — only render visible messages

* Revert "perf(desktop): reduce transcript window 120->60 to halve rendered message nodes"

This reverts commit 6d90d659ed.

* perf(core): windowed AppendOnlyLog (200 msg) with lazy file fallback; add readTailMessages for backward JSONL scan

* style: fix biome formatting + comment cleanup

* fix: use fstatSync after openSync to avoid TOCTOU race (CodeQL)

* fix: sort import order (biome)

* fix: remove existsSync before openSync (TOCTOU race, CodeQL)

* fix: toMessages() returns window only, add toFullHistory(); restore length to entries.length; update callers

* style: method chain formatting

* fix: add toFullHistory mock to ctx-breakdown test

* fix: replace useAutoScroll with Virtuoso followOutput + scrollToIndex for scroll handling

* fix: proper Virtuoso height via CSS height:0 + flex; move jump button outside thread; use position:fixed instead of sticky

* Revert "fix: proper Virtuoso height via CSS height:0 + flex; move jump button outside thread; use position:fixed instead of sticky"

This reverts commit c061398079.

* Revert "fix: replace useAutoScroll with Virtuoso followOutput + scrollToIndex for scroll handling"

This reverts commit ffd48d60b8.

* fix: replace useAutoScroll with Virtuoso followOutput + scrollToIndex; fix JumpBar onScrollToTurn callback

* fix: initial scroll to bottom on session load with proper dep

* fix: position absolute Virtuoso inside relative thread to fix height calc in flex layout

* fix: move jump button outside .thread for correct positioning

* fix: add minHeight 0 to Virtuoso; set thread height 100%

* fix: use Virtuoso initialTopMostItemIndex + scrollerRef for scroll-to-bottom and persistence

* fix: add key to Virtuoso assistant item for correct DiffStats re-render

* fix: initialTopMostItemIndex for Virtuoso initial scroll to bottom

* restore to upstream/main with single initialTopMostItemIndex fix

* fix(jumpbar): onScrollToTurn callback uses Virtuoso scrollToIndex instead of querySelector (broken with virtual list)

* fix: replace Virtuoso followOutput with atBottomRef + scrollToIndex for reliable streaming auto-scroll

* Revert "fix: replace Virtuoso followOutput with atBottomRef + scrollToIndex for reliable streaming auto-scroll"

This reverts commit 6060719365.

* fix: move error/warning render + pending-approval Footer back inside Virtuoso

* Revert "fix: move error/warning render + pending-approval Footer back inside Virtuoso"

This reverts commit a2477d7c7b.

* sync hotfix

---------

Co-authored-by: wufengfan <[email protected]>
2026-05-28 22:31:13 -07:00
Yapu b5f884a61d fix(ink): scroll jitter on rapid mouse wheel (#2076) (#2095)
* 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
2026-05-28 22:29:41 -07:00
DawnCloud1213 5f03643efd feat(prompt): prefer MCP search tools over built-in defaults (#2066)
* 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
2026-05-28 22:29:19 -07:00
249e18f425 fix(server): convert sync fs I/O to async across server API and session memory (#2219)
* 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]>
2026-05-28 22:24:29 -07:00
9b1e01bea9 fix(ui): replace ANSI dim with explicit FG.faint colors; WCAG contrast fixes (#2221)
* 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]>
2026-05-28 22:10:21 -07:00
Sivan e472735144 feat: cache diagnostics v1 — /cache-miss-report, doctor --cache, prefix hash evidence | 缓存诊断 v1 (#2188)
* feat(cache): add prompt cache diagnostics

* fix(cache): hash sent tool snapshot in diagnostics

* perf(cache): memoize prefix diagnostic hashes
2026-05-28 22:01:59 -07:00
Porun 583054feaf fix(telegram): bind callback confirmations (#2222)
* fix(telegram): bind callback confirmations

* docs(telegram): explain remote setup
2026-05-28 22:00:59 -07:00
a6613c6708 fix(i18n): convert ja.ts files to spread-fallback pattern across all three layers (#2216)
- 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]>
2026-05-28 21:59:50 -07:00
88114f2f78 perf(i18n): replace regex in t() with replaceAll (#2176)
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]>
2026-05-28 21:49:36 -07:00
Sivan 0a5bc5402b feat(tools): add AST-aware delete_symbol (#2191) 2026-05-28 21:48:24 -07:00
df5776c5a4 feat(i18n): add Russian (ru) locale to desktop and dashboard (#2217)
- 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]>
2026-05-28 21:35:39 -07:00
Zeng Renchao 2e7ff04711 fix(desktop): resolve FilePill click path against session-tracked files (#2186)
* 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.
2026-05-28 21:34:35 -07:00
nianyi(likai) 0711fada71 fix(skills): follow symlinked entries in SkillStore.readEntry (#2104) (#2124)
`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.
2026-05-28 21:31:59 -07:00
7704b77344 perf: skip healing pipeline and token count when log is unchanged (#2180)
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]>
2026-05-28 21:29:53 -07:00
Sivan 02d0ece98a feat: expand Reasonix theme palettes / 扩展 Reasonix 主题配色 (#2134)
* 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
2026-05-28 21:08:58 -07:00
Porun 17bc1aa4ab feat(telegram): improve remote rendering and ingress (#2213)
* fix(telegram): preserve Markdown rendering in replies

* feat(telegram): use buttons for remote confirmations

* feat(telegram): register slash commands with bot

* test(telegram): update expectations for remote commands

* fix(telegram): harden remote ingress
2026-05-28 21:04:51 -07:00
Sivan c3670c973c feat(cli): add ssh remote dry-run RFC (#2192) 2026-05-28 20:55:03 -07:00
nianyi(likai) 96199134e7 feat(loop): /max-tokens slash command to cap output tokens per turn (#2196) (#2207)
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
2026-05-28 20:50:44 -07:00
Sivan 55fbb3338d feat(mcp): canonicalize tool schemas for cache stability (#2189) 2026-05-28 20:50:22 -07:00
4980ecdf7f fix(ui): theme Pill component colors via ThemeTokens proxy (#2183)
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]>
2026-05-28 20:49:39 -07:00
jimmy 7336a112b1 fix: classify Baidu and Metaso HTTP errors before JSON parse (#2206) 2026-05-28 20:47:53 -07:00
TaoMu 6b5ae1ea40 fix(lifecycle): show plan suggestion once per session (#2208) 2026-05-28 20:46:31 -07:00
Sivan 7cf019559d feat(tools): add anchor-based delete_range (#2190) 2026-05-28 20:43:36 -07:00
Sivan 84fb462b6d feat: enrich MCP features with cc-switch migration / 丰富 MCP 功能,支持 cc-switch 迁移 (#2135)
* feat: enrich MCP features with cc-switch migration

* fix: address mcp review feedback

* fix: resolve mcp preflight cwd paths

* test: cover desktop MCP import reconciliation

* fix(desktop): refocus MCP tools tab on repeated status
2026-05-28 20:40:31 -07:00
TaoMu 96ae010fac fix(ui): show mention filenames before paths (#2170) 2026-05-28 19:52:15 -07:00
nianyi(likai) 28ea853730 fix(tests): sync assertions broken by #2173 and #2168 (#2200)
- 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.
2026-05-28 19:24:30 -07:00
wade1999 119d880575 fix(qq): polish busy ingress and setup reminders (#2178) 2026-05-28 19:00:10 -07:00
Bernardxu123andBernardxu123 745a7e54c8 fix(desktop): render write_file results as DiffCard in thread view (#2177)
Co-authored-by: Bernardxu123 <[email protected]>
2026-05-28 18:48:46 -07:00
Bernardxu123andBernardxu123 8131e24102 feat(cli): unified diff display for edit_file / write_file / multi_edit (#2173)
Add configurable diff display mode for file-editing tools in CLI,
addressing issue #1251 (edit_file/write_file diff without git).

## Changes

### Tool output enhancement
- write_file now returns unified diff format matching edit_file:
  - New file: \created path (N chars)\
  - Overwrite: \edited path (old→new chars)\ + unified diff
  - Large file (>5000 lines / >100KB): summary only, no diff
- All three edit tools (edit_file, write_file, multi_edit) now produce
  consistent output that Desktop's parseEditResult can also parse

### /diff command
- \/diff\ — show current mode (default: summary)
- \/diff full\ — render unified diff with +/- colors in ToolCard
- \/diff summary\ — show path + stats line (edited path +N -M)
- \/diff none\ — show only tool name and checkmark

### Config
- New DiffDisplay type in config.ts (\summary | full | none\)
- Persisted to ~/.reasonix/config.json via /diff command
- loadDiffDisplay / saveDiffDisplay functions

### ToolCard renderer
- In full mode, parse diff from tool output and render with colored
  +/- lines, hunk headers, and file stats in the card meta
- Summary and none modes preserve existing behavior

### Files modified
- src/tools/fs/edit.ts — add generateWriteDiff()
- src/tools/filesystem.ts — write_file uses generateWriteDiff
- src/config.ts — DiffDisplay type + load/save
- src/cli/ui/cards/ToolCard.tsx — diff-aware rendering
- src/cli/ui/slash/handlers/diff.ts — new /diff handler
- src/cli/ui/slash/commands.ts — register /diff command
- src/cli/ui/slash/dispatch.ts — import diffHandlers
- src/i18n/EN.ts — diff handler + slash translations
- src/i18n/zh-CN.ts — Chinese translations

Co-authored-by: Bernardxu123 <[email protected]>
2026-05-28 18:20:19 -07:00
4cf52b3653 perf: eliminate sync I/O from agent loop hot paths (#2162)
* 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]>
2026-05-28 18:09:10 -07:00
Porun 7854d42410 feat: add Telegram channel support (#2168) 2026-05-28 18:08:00 -07:00
Sivan 823ae7ffca fix(desktop): keep sessions alive when closing window (#2144)
* fix(desktop): keep sessions alive when closing window

* fix(desktop): make close-to-tray opt-in

* chore: ignore local agent notes
2026-05-28 18:07:37 -07:00
bf69ccbd8c perf: optimize tokenizer hot paths and prompt builder (#2163)
* 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]>
2026-05-28 18:01:51 -07:00
AtmoOmen a6b32c0638 fix(desktop): composer inline mentions, command chips, and text highlighting (#2143)
* 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
2026-05-28 17:54:10 -07:00
TaoMu 58b01976ae fix(tools): enforce auto git rollback checkpoints (#2169)
* fix(tools): enforce auto git rollback checkpoints

* fix(tools): require explicit rollback marker
2026-05-28 17:46:32 -07:00
TaoMuandReasonix Test 1bcec032a6 fix(cli): commit settled cards to native scrollback (#2151)
* fix(cli): commit settled cards to native scrollback

* fix(cli): freeze verbose state for static history

---------

Co-authored-by: Reasonix Test <[email protected]>
2026-05-28 17:46:10 -07:00
Yapu 47f6ba2fa5 fix: batch store notifications to prevent React max update depth (#2123) (#2133)
* 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
2026-05-28 17:41:13 -07:00
Yapu 03a3ae2a58 fix(ink): reduce VS Code terminal lag by throttling drain and debouncing damage (#2080) (#2130)
* 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.
2026-05-28 17:40:50 -07:00
AtmoOmen 00ae400175 fix(desktop): auto-switch to new session after deleting active session (#2127)
* 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.
2026-05-28 17:40:28 -07:00
Tianjiu 0678972729 fix(desktop): use native macOS fullscreen zoom (#2164) 2026-05-28 08:21:38 -07:00
AtmoOmen 638f230f40 feat(desktop/dashboard): show cache percentage with 2 decimal places + details on hover (#2158)
- 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/.
2026-05-28 08:12:05 -07:00
jimmy 8e9b7d4689 Add Baidu AI Search backend (#2147) 2026-05-28 08:01:30 -07:00
TaoMu b063966b92 feat(lifecycle): suggest plan rails for high-risk tasks (#2119) 2026-05-28 07:30:58 -07:00
Yapu 55a8f62c4d fix: load skills from symlinked directories (#2104) (#2137)
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
2026-05-28 07:09:27 -07:00
Yapu 0b64723128 feat: add contextTokens config for custom model context window (#2075, #2074) (#2085)
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
2026-05-28 07:02:51 -07:00
nianyi(likai)andYapu 17725071e5 fix(shell): demote allowlisted commands when path args escape workspace (#2081) (#2089) (#2138)
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]>
2026-05-28 06:57:53 -07:00
wade1999 2eec3a9f53 feat(desktop): extend QQ remote commands with model and mode controls (#2062)
* 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
2026-05-28 06:52:33 -07:00
Yapu 5c3ba5313a feat: configurable maxIterPerTurn per-turn iteration cap (#2037) (#2046)
* 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
2026-05-28 06:52:07 -07:00
Yapu 984e830df4 fix(shell): demote allowlisted commands when path args escape workspace (#2081) (#2089)
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.
2026-05-27 19:14:39 -07:00
TaoMu abb1088d3d feat(lifecycle): detect explicit plan-first intent (#2070) 2026-05-27 19:06:40 -07:00
lightfrontandXingbo Zhao 08883ce211 fix(i18n): add missing sendFeedback/skipFeedback/cancelFeedbackLabel/refineFeedbackLabel keys to ja locale (#2069)
Co-authored-by: Xingbo Zhao <[email protected]>
2026-05-27 19:04:46 -07:00
reasonix 3e6cee2a6a fix(desktop): drop debug stderr log left in #2025 recentWorkspaces handler
Caused biome lint failure on main.
2026-05-27 18:50:52 -07:00
Harlans 0a83ed0937 feat: 工作目录增加删除按钮 (#2025) 2026-05-27 18:48:22 -07:00
nianyi(likai) 9569024c9b fix(i18n): i18n-ify Ollama errors, add missing ollama to engine hints, flatten ternaries (#1992) 2026-05-27 18:45:34 -07:00
CVEngineerandwufengfan dc4a5dcfcf perf(core): windowed AppendOnlyLog (200 messages) with lazy file fallback (#2057)
* perf(core): windowed AppendOnlyLog (200 msg) with lazy file fallback; add readTailMessages for backward JSONL scan

* style: fix biome formatting + comment cleanup

* fix: use fstatSync after openSync to avoid TOCTOU race (CodeQL)

* fix: sort import order (biome)

* fix: remove existsSync before openSync (TOCTOU race, CodeQL)

* fix: toMessages() returns window only, add toFullHistory(); restore length to entries.length; update callers

* style: method chain formatting

* fix: add toFullHistory mock to ctx-breakdown test

---------

Co-authored-by: wufengfan <[email protected]>
2026-05-27 07:59:53 -07:00
CVEngineerandwufengfan fa66bc4d21 perf(desktop): virtual list with Virtuoso for message thread — only render visible messages (#2056)
Co-authored-by: wufengfan <[email protected]>
2026-05-27 07:59:47 -07:00
J. F. Zhang 7cbedd0b6a fix(release): split macOS dmg by arch (#2050) 2026-05-27 07:24:26 -07:00
Murasameand王锦坤 b13bcbcd77 fix(todo): hide completed items from rendered output (#2049)
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]>
2026-05-27 07:24:05 -07:00
wade1999 6a5d5b1a13 feat(desktop): support desktop QQ remote commands (#2058) 2026-05-27 07:23:58 -07:00
AtmoOmen 9ec2ecae02 feat(desktop): add feedback text input for plan cancel/refine actions (#2053)
* feat(desktop): add feedback text input for plan cancel/refine actions

Desktop 端 PlanApprovalCard 在用户点击「取消」或「细化」时,
展示文本输入框允许用户写下反馈原因再发送,与 CLI 端保持一致。

- PlanApprovalCard 新增 feedbackMode 状态,点击 Cancel/Refine
  后切换到文本输入模式,支持 Enter 发送、Escape 跳过
- PlanVerdict.feedback 字段现在通过 onRefine/onCancel 回调正确传递
- i18n 新增 sendFeedback / skipFeedback / cancelFeedbackLabel /
  refineFeedbackLabel 键值(en/de/ja/zh-CN)
- 同步更新 modal.planFeedbackPlaceholder / choiceCustomPlaceholder
  文本至四种语言
- 补全 ja/de 缺失的 toolCalls / oneToolCall i18n 键值
- styles.css 新增反馈输入模式下的 approval 卡片样式

* fix(desktop): typo
2026-05-27 07:23:52 -07:00
CVEngineerandwufengfan 7f67bc29ce perf(desktop): replace messages.map with backwards-walk index replace in streaming handlers (#2055)
Co-authored-by: wufengfan <[email protected]>
2026-05-27 07:21:50 -07:00
lightfrontandXingbo Zhao 280ef69cd1 fix(i18n): add missing toolCalls/oneToolCall keys to ja locale (#2048)
Co-authored-by: Xingbo Zhao <[email protected]>
2026-05-27 07:21:44 -07:00
arata dbaefa766c fix(desktop): polish sidebar for narrow widths (#2034)
- New-chat button: preserve #2016 layout, hide shortcut/label at compact widths

- Search row: consistent padding/gap, placeholder ellipsis

- Session items: meta truncation, absolute action buttons
2026-05-27 07:21:38 -07:00
reasonix e19d4df68e fix(i18n): backfill ja keys missed by recent merges
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.
2026-05-27 05:21:20 -07:00
Bernardxu123andBernardxu123 909b5cced5 fix(desktop): CSP connect-src and Porcelain theme accent color (#2038)
* 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]>
2026-05-27 05:14:03 -07:00
QiuYa 6960630283 feat(desktop): 计划正文和内存正文支持 Markdown 渲染 (#2042)
- PlanBanner / PlanApprovalCard 中的计划正文和摘要从原始 <div>/<pre>
  改为 <Markdown> 渲染,支持标题、代码块、列表、行内样式等 GFM 语法。
- CtxMemory 中的内存正文(REASONIX.md)从 <pre> 改为 <Markdown> 渲染。
- 上下文面板布局重构为 flex column,内存详情区域自动撑满侧边栏剩余高度。
2026-05-27 05:13:56 -07:00
TaoMu 7042722fb0 fix: keep compact sidebar new chat label visible (#2016)
* fix compact sidebar shortcut fallback

* fix desktop compact sidebar shortcut fallback
2026-05-27 05:13:50 -07:00
nianyi(likai) ad6ecf0dda feat(desktop): grant pending tool/path approval with Enter key (#2015)
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
2026-05-27 05:13:45 -07:00
wade1999 db651d51da feat(skill): add builtin qq helper (#2004) 2026-05-27 05:13:18 -07:00
CVEngineerandwufengfan e54a99df7b feat(desktop): collapse intermediate reasoning, group consecutive tool calls (#1929)
* feat(desktop): collapse intermediate reasoning + group consecutive tool calls

* fix: open tool cards inside group when expanded

* fix: independent collapse state per tool group

* fix: lift ToolGroupShell to module scope, preserve shell live-streaming, rename defaultOpen prop

---------

Co-authored-by: wufengfan <[email protected]>
2026-05-27 05:13:12 -07:00
nianyi(likai) 0d3c6e20e2 fix(hooks): add last_assistant_message to Stop payload for ecosystem compat (#1989) 2026-05-27 05:13:05 -07:00
nianyi(likai) a0bd169cd0 feat(web-search): add bing-intl engine for international index (#1990) 2026-05-27 05:12:21 -07:00
TaoMu b51cb03a23 fix(desktop): bound long-session transcript payloads (#2019) 2026-05-27 05:12:14 -07:00
zhangyapu1 d8e896a8b5 fix: include subagent token usage in session stats (#2008) (#2041)
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.
2026-05-27 05:12:07 -07:00
zhangyapu1 69f5147629 feat(mcp): support requestTimeoutMs per-server config (#2023) (#2036)
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.
2026-05-27 05:12:00 -07:00
paradoxSCHandClaude Sonnet 4.6 f0a831b931 fix(mcp): bridge mcpServers in Desktop and unify cfg.mcp reads across CLI (#2024)
- 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]>
2026-05-27 05:11:30 -07:00
Ikko Eltociear Ashimine 547228ae8c docs: add Japanese README (#2011) 2026-05-27 05:11:23 -07:00
enderzcx ef40665371 fix(cli): preserve bundled CLI version metadata (#1997) 2026-05-27 05:11:16 -07:00
nianyi(likai) 9df95d75e7 fix(desktop): backfill missing keys in Japanese (ja) locale (#2018)
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.
2026-05-27 05:11:09 -07:00
lightfrontandXingbo Zhao c4a0dc5121 fix(desktop): replace | with \vert in math to avoid GFM table breakage (#2017)
* 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]>
2026-05-27 05:10:49 -07:00
cwatanabandreasonix a0816a02f5 feat(i18n): add Japanese (ja) locale (#1915)
* 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]>
2026-05-27 00:18:18 -07:00
YHHandreasonix 3b4fd7dca0 fix(ink): defer useBoxMetrics measure off the React commit batch (#2003)
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]>
2026-05-27 00:02:10 -07:00
YHHandreasonix 1095f5ff52 fix(loop): force-summary uses active model, not hard-coded flash (#1986)
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]>
2026-05-26 21:52:09 -07:00
Weikeng Chenandreasonix c3e0ccf99c feat(desktop): 余额显示支持多币种(同时展示人民币和美元) (#1930)
* 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]>
2026-05-26 21:47:26 -07:00
wade1999 16904ce664 feat(qq): default to markdown replies (#1941) 2026-05-26 21:47:06 -07:00
YHHandreasonix 54c3792085 fix(desktop): fire hooks (Pre/PostToolUse, UserPromptSubmit, Stop) per tab (#1984)
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]>
2026-05-26 21:45:03 -07:00
YHHandreasonix dac635ed45 fix(desktop): clear pending assistant on error so the spinner stops (#1660) (#1985)
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]>
2026-05-26 21:16:36 -07:00
YHHandreasonix 691bd03201 fix(config): saveApiKey overrides stale env so UI save takes effect (#1982)
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]>
2026-05-26 21:04:16 -07:00
YHHandreasonix 4837165227 fix(loop): force-summary uses active model, not hard-coded flash (#1979)
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]>
2026-05-26 21:03:27 -07:00
YHHandreasonix 49e9d9e04a fix(desktop): wire /skill and /skills slash commands (#1969) (#1978)
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]>
2026-05-26 21:01:36 -07:00
YHHandreasonix ec9788d8ed fix(truncated-result-saver): fall back to ~/.reasonix when rootDir is fs root (#1974)
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]>
2026-05-26 20:51:52 -07:00
YHHandreasonix 58f28d61aa fix(truncate): align slice boundaries to UTF-16 codepoint (#1970) (#1976)
`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]>
2026-05-26 20:47:17 -07:00
AtmoOmenandreasonix 857951ac83 fix(web_fetch): fallback to DoH when system DNS returns fake internal IPs (#1944)
* 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]>
2026-05-26 20:44:17 -07:00
enderzcx 3f66304eb4 fix(cli): accept models endpoint in doctor (#1972) 2026-05-26 20:33:36 -07:00
enderzcx 7fc3c526f1 fix(desktop): refresh context token meter (#1964) 2026-05-26 20:28:03 -07:00
TaoMu b1ee3ff327 fix: sanitize lone surrogates in chat payloads (#1939) 2026-05-26 20:06:15 -07:00
TaoMu 8ede8830fa fix(desktop): preserve context on abort (#1938) 2026-05-26 20:04:26 -07:00
TaoMu 7e03aca713 Fix generated-script shell cwd guidance (#1937)
* fix: clarify shell cwd guidance for generated scripts

* fix: soften generated script cwd guidance

* test: stabilize regex worker restart check
2026-05-26 20:02:37 -07:00
lightfrontandXingbo Zhao 2f2ddf5d06 fix(desktop): support \[ \] and \( \) math delimiters in markdown (#1923)
* 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]>
2026-05-26 19:59:14 -07:00
TaoMu 3c08f600a9 fix: keep dashboard New Chat label on one line (#1924)
* fix dashboard new chat button wrapping

* test dashboard new chat localized label

* fix compact sidebar new chat layout
2026-05-26 19:52:15 -07:00
YHHandreasonix bfcf333222 chore(errors): tighten errorDetail propagation (#1965)
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]>
2026-05-26 19:52:14 -07:00
YHHandreasonix 82c016b193 fix(tui): break CardStream measure→render→measure loop (#1958)
* 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]>
2026-05-26 19:45:34 -07:00
paradoxSCH 28990641b1 fix(acp): propagate structured error details through loop, transcript, ACP
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.
2026-05-26 19:45:11 -07:00
YHHandreasonix 0c837dda91 chore(dashboard): type the new server-snapshot helpers (#1961)
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]>
2026-05-26 19:36:45 -07:00
TaoMu 964ee5a0e6 fix dashboard session refresh (#1917) 2026-05-26 19:33:04 -07:00
Hermito Kattandhermitokatt 04694eae65 feat(web): add Brave Search API as web_search backend (#1916)
Add Brave Search (api.search.brave.com) as a new web search engine
alongside bing, searxng, metaso, tavily, perplexity, exa, and ollama.

Core:
- searchBrave(): GET api.search.brave.com/res/v1/web/search with
  X-Subscription-Token header, i18n error handling, 1–20 topK clamp
- loadBraveApiKey(): env chain BRAVE_SEARCH_API_KEY → BRAVE_API_KEY
  → config.braveApiKey; exported in public API
- /search-engine brave CLI handler + /se alias; argCompleter updated
- braveApiKey config field; webSearchEngine('brave') dispatcher

Integration:
- Desktop: dropdown option, API key credential UI, protocol types,
  SettingsPatch, webSearchApiKeys prefix, i18n labels (en/de/zh-CN)
- Dashboard: dropdown option, protocol type, i18n label (en)
- Server: VALID_WEB_SEARCH_ENGINES, error message, cast type
- Desktop RPC: incoming/outgoing types, collectWebSearchApiKeyPrefixes,
  persistence guard + save logic for braveApiKey

i18n:
- 5 new webErrors keys: braveMissingKey, braveUnauthorized,
  braveRateLimit, braveServerError, braveParseError
- Handler labels: usageBrave, switchedBraveNote (EN, de, zh-CN, ru)
- |brave added to ~40 engine suggestion strings (EN, de, zh-CN)
- de.ts additionally adds |ollama to suggestion strings (pre-existing
  omission in German locale)

Tests:
- web-tools.test.ts: 6 searchBrave test cases (happy path, 401/403,
  429, parse error, empty results, topK clamp)
- config.test.ts: 4 loadBraveApiKey tests (env chain fallback)
- config.test.ts: brave in webSearchEngine round-trip array
- public-api.test.ts: loadBraveApiKey in snapshot

Closes #1763

Co-authored-by: hermitokatt <[email protected]>
2026-05-26 19:25:08 -07:00
YHHandreasonix 65dbd122f6 docs(readme): add AtomGit star badge (#1954)
Co-authored-by: reasonix <[email protected]>
2026-05-26 19:07:04 -07:00
Bernardxu123andBernardxu123 89235a20bb fix(desktop): normalize path separators for Windows file opening (#1914)
* 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]>
2026-05-26 19:00:24 -07:00
enderzcx 2ee56515da feat(desktop): expose workspace switcher in sidebar (#1908) 2026-05-26 18:47:23 -07:00
CVEngineerandwufengfan e83a106c64 fix(desktop): allow clearing base URL and editor (#1905)
Co-authored-by: wufengfan <[email protected]>
2026-05-26 18:44:10 -07:00
YHHandreasonix 182d41eb87 refactor(ink): inline ink runtime as workspace package (#1947)
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]>
2026-05-26 18:08:51 -07:00
reasonix 25988eb175 fix(desktop): bump app bundle version to 0.52.0 2026-05-26 04:09:20 -07:00
reasonix 171e10f69e chore(dsnix): bump to 0.52.0 + sync lockfile 2026-05-26 03:46:33 -07:00
reasonix cb3e6189d6 chore(release): 0.52.0 2026-05-26 03:39:52 -07:00
enderzcx 651779ae93 feat(web): add Ollama cloud search backend (#1900)
* feat(web): add Ollama cloud search backend

* fix(web): format Ollama web tool test
2026-05-26 03:24:26 -07:00
Tianjiu c634341883 fix(desktop): separate ctx scrollbar from resize handle (#1856)
* 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
2026-05-26 03:20:02 -07:00
enderzcx 0510873412 fix(desktop): bump app bundle version to 0.51.0 (#1891) 2026-05-26 02:57:36 -07:00
YHHandreasonix f2e0b1f6d8 refactor(desktop): harden clipboard image paste path (#1897)
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]>
2026-05-26 02:57:10 -07:00
enderzcx 421fff2263 feat(desktop): import local AI app sessions (#1894) 2026-05-26 02:55:38 -07:00
enderzcx 660dcc662f feat(desktop): paste clipboard images into composer (#1889) 2026-05-26 02:39:00 -07:00
Odisseyandreasonix a44bbae18a i18n: add Russian (ru) language pack (#1879)
* 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]>
2026-05-26 02:35:35 -07:00
enderzcx de0d1fb19a fix(client): parse Ollama usage token fields (#1886) 2026-05-26 02:30:21 -07:00
YHHandreasonix 210781f88d refactor(desktop): pull JumpBar dot styling back into a helper (#1892)
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]>
2026-05-26 02:22:34 -07:00
Hermito Kattandhermitokatt c86383934a fix(i18n): German corrections — capitalization, terminology, and coverage (#1878)
- 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]>
2026-05-26 02:17:20 -07:00
CVEngineerandwufengfan 33d03ef099 feat(desktop): highlight active message bar in JumpBar; follow latest message (#1813)
Co-authored-by: wufengfan <[email protected]>
2026-05-26 02:13:47 -07:00
YHHandreasonix c14d8a3a8a feat(config): accept DEEPSEEK_API_BASE_URL as a base-URL env alias (#1876) (#1887)
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]>
2026-05-26 01:59:11 -07:00
YHHandreasonix dc1779e8da feat(proxy): accept proxy.url from config.json (#1881)
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]>
2026-05-26 01:46:39 -07:00
YHHandreasonix 585a243b0b fix(desktop): unit-suffix CSS vars during drag, use canonical thread-width helper (#1875)
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]>
2026-05-26 01:24:59 -07:00
TaoMu c96a524742 fix(tui): guard ASCII IME enter commits (#1874) 2026-05-26 01:17:56 -07:00
TaoMu 71065f34bd test(jobs): wait for tail output before asserting (#1872) 2026-05-26 01:17:17 -07:00
TaoMu 74e138c472 test(tui): cover prompt incremental repaint (#1873) 2026-05-26 01:13:49 -07:00
YHHandreasonix f226ad2508 fix(dashboard): sync TUI and Web modal state (#1831) (#1866)
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]>
2026-05-26 01:10:09 -07:00
CVEngineerandwufengfan df0507fbb8 perf(desktop): direct DOM CSS vars during sidebar drag, disable CSS transition, content-visibility for messages (#1812)
* fix(desktop): drag perf — direct DOM + disable CSS transition during drag; fix test types

* fix: restore export on applyIncoming (test imports it)

* fix: revert resize handle to 5px (1px was ungrabbable per review)

---------

Co-authored-by: wufengfan <[email protected]>
2026-05-26 01:05:06 -07:00
YHHandreasonix 85668b0130 fix(desktop): float update banner above the thread (#1865)
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]>
2026-05-26 01:02:31 -07:00
Tianjiu 6a2b78f5c0 fix(ui): highlight active plan edit mode (#1863) 2026-05-26 00:49:53 -07:00
YHHandreasonix 31acf1e232 fix(desktop): add search-engine API key UI + intercept slash command (#1867)
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]>
2026-05-26 00:28:17 -07:00
YHHandreasonix da25e37b1d chore(desktop): split kind/length effects in @ popup, drop redundant guard (#1859)
- 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]>
2026-05-26 00:14:07 -07:00
YHHandreasonix d0643eebb2 chore(i18n): drop zh-CN /qq argsHint, fall back to source (#1862)
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]>
2026-05-26 00:13:53 -07:00
YHHandreasonix ab04288066 fix(mcp): drop LSP-only fields from initialize params (#1861)
`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]>
2026-05-26 00:05:38 -07:00
Bernardxu123andBernardxu123 fd32b56535 fix(i18n): /qq command hints now use i18n, argsHint and description localized to Chinese (#1857)
Co-authored-by: Bernardxu123 <[email protected]>
2026-05-26 00:00:26 -07:00
Tianjiu 4163217919 fix(desktop): keep mention popup stable (#1850) 2026-05-25 23:53:01 -07:00
YHHandreasonix cb4b2be38e chore(ui): drop undo-context re-exports through useEditHistory (#1854)
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]>
2026-05-25 23:49:35 -07:00
TaoMu f10267038b fix(tui): preserve undo state in session context (#1810) 2026-05-25 23:22:45 -07:00
YHHandreasonix 6b015c0559 refactor(ink): extract vendored renderer to @esengine/ink + tui polish (#1847)
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]>
2026-05-25 22:42:17 -07:00
reasonix 6c8650d2be fix(desktop): wire memoryDetail/onReadMemory through test fixtures
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.
2026-05-25 09:42:15 -07:00
reasonix 98dec4a401 chore(dsnix): bump to 0.51.0 + sync lockfile 2026-05-25 09:31:23 -07:00
reasonix 8a56afd571 chore(release): 0.51.0 2026-05-25 09:22:58 -07:00
YHHandreasonix 10dccac9b0 chore(deps): bump ink 7.0.2 -> 7.0.4, drop patch-package machinery (#1791 follow-up) (#1809)
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]>
2026-05-25 09:05:28 -07:00
YHHandreasonix 95f5df07e6 fix(tui): demote stuck running plan step on turn end (#1784) (#1806)
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]>
2026-05-25 08:51:12 -07:00
YHHandreasonix 25eefbbdec perf(search): bypass regex worker for literal patterns (#1748) (#1804)
`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]>
2026-05-25 08:50:20 -07:00
TaoMu c53535946a fix(loop): trim long-session retained payloads (#1799)
* fix(loop): prune stale plain reasoning

* fix(loop): trim retained tool-call payloads
2026-05-25 08:49:03 -07:00
YHHandreasonix 3218500736 fix(stdin): refuse ESC-less CSI recovery when followed by typed text (#1771) (#1800)
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]>
2026-05-25 08:12:18 -07:00
YHHandreasonix 65e833f6e8 fix(tui): hide max effort on non-DeepSeek endpoints (#1798)
#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]>
2026-05-25 08:10:22 -07:00
Hermito Kattandhermitokatt 4a6be7dc50 fix(i18n): German (de) corrections and completions (#1797)
- /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]>
2026-05-25 08:08:57 -07:00
YHHandreasonix b224b7bf42 fix(cli): replace BEL with ST on Windows stdout so cmd doesn't beep on every frame (#1795)
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]>
2026-05-25 07:26:59 -07:00
Bernardxu123andBernardxu123 a0a723109a fix(ui): patch Ink to reduce terminal flicker on overflow frames (#1791)
* 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]>
2026-05-25 06:51:54 -07:00
Tianjiu c4641ec7f0 fix(desktop): recalc thread width on resize (#1789) 2026-05-25 06:35:07 -07:00
YHHandreasonix ff705c1dc6 fix(dashboard): replay active modal on SSE connect so web confirm gate isn't stuck (#1770) (#1792)
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]>
2026-05-25 06:34:08 -07:00
ForeverYoungPp a65f1062fc fix: normalizeSemanticEmbeddingUserConfig drops timeoutMs field (#1788) 2026-05-25 06:33:33 -07:00
arata 48cc3f4cb2 fix(docs): polish docs responsive spacing (#1785)
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.
2026-05-25 06:32:09 -07:00
YHHandreasonix d85f9387a6 fix(dashboard): expose new memory browser to web mode (followup to #1766) (#1779)
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]>
2026-05-25 04:33:17 -07:00
TaoMu 5165a54658 fix(tui): coalesce prompt cursor sync (#1768) 2026-05-25 04:28:16 -07:00
Tianjiu 582b440967 feat(i18n): add German (de) language support (#1773)
* 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).
2026-05-25 04:20:20 -07:00
TaoMu 3d9a0de38b fix: restore scroll and memory visibility (#1766) 2026-05-25 04:18:31 -07:00
YHHandreasonix b9ecc4efe0 fix(config): EXDEV fallback for atomic write on OneDrive / NTFS reparse points (#1778)
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]>
2026-05-25 04:08:07 -07:00
YHHandreasonix 95913f1cf6 fix(dashboard): bootstrap mcp/skills/memory panels in web mode (#1775)
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]>
2026-05-25 03:50:17 -07:00
YHHandreasonix 7df5d8b58e fix(loop): drain steer queue on /new + /cwd so prior intent doesn't leak (#1774)
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]>
2026-05-25 03:44:36 -07:00
Bernardxu123andBernardxu123 1d6a30d11b fix(desktop): fix right panel scrollbar not draggable (#1765)
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]>
2026-05-25 03:03:22 -07:00
Tianjiu 603600bf02 fix(desktop): verify bundled node TCC inheritance (#1749) 2026-05-25 03:00:59 -07:00
YHHandreasonix e6a175e138 perf(ui): index-backed mutateCard + O(n) plan.drop + elide cursor (#1769)
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]>
2026-05-25 02:55:13 -07:00
TaoMu bb9415a457 fix(tui): avoid Apple Terminal mouse reset crash (#1764) 2026-05-25 02:39:43 -07:00
TaoMu 5f661b932a Show desktop startup failures (#1759) 2026-05-25 02:30:31 -07:00
TaoMu bfef3c3e73 Guard CLI startup on unsupported Node (#1757) 2026-05-25 02:30:03 -07:00
Bernardxu123andBernardxu123 eb065799c7 fix(tui): sync system cursor for IME candidate window alignment (#1754)
* fix(tui): sync system cursor for IME candidate window alignment

* fix: satisfy biome exhaustive-deps lint rule

---------

Co-authored-by: Bernardxu123 <[email protected]>
2026-05-25 02:27:12 -07:00
Ethanandannon dba8a49e88 feat(ui): configurable cost display currency with click-to-toggle (#1710)
* 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]>
2026-05-25 02:23:04 -07:00
YHHandreasonix a683234090 perf(ui): progressive Static mount — session restore 4.5s → 430ms first paint (#1761)
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]>
2026-05-25 02:20:46 -07:00
TaoMu 0fe5041ccd fix(ui): reduce Windows terminal repaint cadence (#1750) 2026-05-25 02:00:16 -07:00
douglarek b5096d1278 feat(memory): support CLAUDE.md and ~/.claude/CLAUDE.md for Claude Code migration (#1694)
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
2026-05-25 01:57:13 -07:00
dacec354 618ed36b2a feat: preserve full tool results when truncated (#1615) (#1703)
* 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
2026-05-25 01:54:02 -07:00
YHHandreasonix 3781904b11 test(edit-blocks): skip symlink-preservation test when symlink syscall fails (#1753)
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]>
2026-05-25 01:50:47 -07:00
YHHandreasonix aa539fdd55 chore(ui): render-trace readStats API + large-session probe with real numbers (#1751)
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]>
2026-05-25 01:34:46 -07:00
YHHandreasonix e826984619 chore(ui): add per-component render trace gated by REASONIX_TRACE_RENDERS (#1747)
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]>
2026-05-25 01:16:20 -07:00
YHHandreasonix 558d471113 refactor(core): extract LruCache + TtlLruCache + lazy(), replace ad-hoc duplicates (#1746)
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]>
2026-05-25 00:58:50 -07:00
Bernardxu123andBernardxu123 38d88abcc0 fix(tui): show plan mode [PLAN]/[计划] badge in input bar footer (#1742)
* 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]>
2026-05-25 00:34:09 -07:00
Kagura 8a7c83435e fix(tui): implement forward-delete for Delete key (#1735)
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
2026-05-25 00:29:39 -07:00
YHHandreasonix 81249ec581 perf(markdown): memoize CodeBlock syntax highlight (#1743)
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]>
2026-05-25 00:22:39 -07:00
YHHandreasonix d6aeafa984 perf(tokenizer): cache BPE + per-content bounded counts, fast-path truncate (#1741)
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]>
2026-05-25 00:11:38 -07:00
TaoMu 1768cf4d58 fix(desktop): contain long mcp specs (#1736) 2026-05-24 23:32:08 -07:00
CVEngineerandwufengfan 5290275857 feat(desktop): add JumpBar message navigation dock (#1729)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 23:26:16 -07:00
TaoMu f00f238b66 fix(desktop): sync slash setting commands (#1724) 2026-05-24 23:23:13 -07:00
Bernardxu123andBernardxu123 395ffdb6d5 feat(acp): support REASONIX_ACP_SYSTEM_APPEND env var for system prompt injection (#1737)
Co-authored-by: Bernardxu123 <[email protected]>
2026-05-24 23:18:29 -07:00
YHHandreasonix 3a05934db0 refactor(loop): extract stream aggregator + chunked dispatch from step() (#1739)
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]>
2026-05-24 23:00:08 -07:00
CVEngineer 6b5bf7ac2f feat(desktop): add JumpBar message navigation dock (#1725)
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.
2026-05-24 20:58:49 -07:00
TaoMu 5467670146 fix(tui): drop ESC-stripped legacy X10 mouse reports (#1723)
#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.
2026-05-24 20:25:03 -07:00
YoungDan-hero b40a5692ec fix(code): make edit-block writes crash-safe via atomic rename (#1721)
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.
2026-05-24 20:20:20 -07:00
FriendsHL 7d49171a28 docs: sync ARCHITECTURE.md and benchmark pricing to match code (#1720)
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.
2026-05-24 20:00:13 -07:00
bluedevil947 e4259d3543 fix(index): skip .devenv and .direnv in glob, search, and directory_tree (#1706)
.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.
2026-05-24 19:19:51 -07:00
paradoxSCH 5af0f1661f fix(plan): archive completed plans instead of letting them persist (#1700)
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
2026-05-24 19:00:06 -07:00
YHHandreasonix 0df09f32cb fix(loop): don't show DeepSeek-specific 5xx hints when host is not DeepSeek (#1716)
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]>
2026-05-24 18:56:20 -07:00
YHHandreasonix 56f3ffe968 fix(desktop): self-heal stale model id + expose plan as 4th editMode (#1699)
* 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]>
2026-05-24 08:33:35 -07:00
TaoMu 38e6d2cf8c fix(desktop): restore aborted prompt drafts (#1693) 2026-05-24 08:30:00 -07:00
TaoMu d2f62d4561 fix(tui): drop stale copy startup hint (#1692) 2026-05-24 08:28:12 -07:00
CVEngineerandwufengfan 03fb6582ed feat(desktop): show collapsible file-change summary after each assistant turn (#1691)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 08:19:38 -07:00
reasonix 5e757bd372 chore(dsnix): bump to 0.50.1 + sync lockfile 2026-05-24 07:39:33 -07:00
reasonix 2e7bdec3a8 fix(install): use execSync, not execFileSync, in postinstall
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.
2026-05-24 07:33:07 -07:00
reasonix 05b47947a1 fix(install): postinstall no-ops outside a git checkout (0.50.1)
#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.
2026-05-24 07:25:20 -07:00
reasonix 4188ddf007 chore(dsnix): bump to 0.50.0 + sync lockfile 2026-05-24 07:08:48 -07:00
reasonix be60c9539e fix(release): build before test in prepublishOnly so dashboard smoke tests find dist/
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`.
2026-05-24 07:01:55 -07:00
reasonix 28d95059c7 chore(release): 0.50.0 — CLI-hosted dashboard for desktop, presets removed, persisted usage stats, plan dispatch gate
Headline themes:
- Desktop: bundle the CLI-hosted React dashboard, retire Tauri+Preact duplicate (#1418)
- Config: drop preset abstraction; flash/pro are direct model selections (#1657, #1630)
- Stats: persist cumulative usage to session meta + auto-restore on startup (#1667, #1680, #1643, #1628)
- Plans: editMode="plan" enforced at the ToolRegistry dispatch gate (#1681); step advance fix (#1629)
- Context: fold once at turn start, drop pre-flight + byte-ceiling (#1642, #1646); collapsible compacted card (#1649)
- Subagents: per-skill flash/pro override + Settings UI (#1632)
- Desktop polish: sidebar drag-resize (#1688), responsive collapse (#1585), copy/edit overlay + msg-history nav (#1645), Esc closes modal not turn (#1685), QQ tab isolation (#1672), DiffCard for edits (#1662), theme-aware highlighting (#1655), system events toggle (#1654/#1650), macOS TCC inheritance (#1614), dashboard.enabled (#1612)
- Dashboard polish: persistent session URL (#1586, #1589, #1599), theme-aware highlighting (#1664), IME confirm-enter guard (#1689), code-fence lang fix (#1677), vendor chunk split (#1587), markdown table h-scroll (#1562)
- TUI: Alt+S input stash/recall; static history isolated from input rerenders (#1635); legacy mouse drop (#1637, #1648); multi-edit gated in review (#1647)
- Diff: SplitDiff column border holds under CJK (#1686)
- MCP: workspace roots passed to servers (#1625); codeCommand honors mcpServers (#1603)
- Config plumbing: (baseUrl, apiKey) resolved as a tuple (#1658); stale model id self-heal (#1663)

See CHANGELOG for the full list.
2026-05-24 06:55:16 -07:00
TaoMu 217a9d1804 fix(dashboard): ignore IME confirm enter (#1689) 2026-05-24 06:34:51 -07:00
TaoMu 0c0e800520 fix(desktop): discard explicitly aborted turns (#1687) 2026-05-24 06:29:56 -07:00
CVEngineerandwufengfan be4e619dd3 feat(desktop): draggable sidebar resize + responsive conversation panel width (#1688)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 06:16:39 -07:00
66c5b5107e fix(diff): SplitDiff renders CJK without misaligning the column border (#1686)
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]>
2026-05-24 05:55:14 -07:00
YHHandreasonix bf18fd648b fix(dashboard): mirror code fence lang detection fix from #1661 (#1677)
#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]>
2026-05-24 05:44:29 -07:00
YHHandreasonix 3555d36b57 chore(ui): drop redundant overflow-wrap from inherited descendants (#1675)
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]>
2026-05-24 05:26:32 -07:00
wade1999 a6c2fb6115 fix(desktop): isolate QQ turn routing by tab (#1672) 2026-05-24 05:15:39 -07:00
4ecfd877fc fix(desktop): Esc closes the open modal instead of aborting the model (#1685)
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]>
2026-05-24 05:13:14 -07:00
4068b9d3b5 feat(plan): wire editMode="plan" into the ToolRegistry dispatch gate (#1681)
`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]>
2026-05-24 04:33:32 -07:00
YHHandreasonix f297fe0a26 fix(stats): carry totalCompletionTokens across resumes (#1667 follow-up) (#1680)
#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]>
2026-05-24 04:11:08 -07:00
CVEngineerandwufengfan 56a3efd93e fix(cli,desktop): persist cumulative usage stats to session meta + auto-restore on startup (#1667)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 04:03:45 -07:00
YHHandreasonix 1c3cfba15b chore(theme): finish theme rename follow-up after #1666 (#1678)
#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]>
2026-05-24 03:57:14 -07:00
Bernardxu123andBernardxu123 860ae56633 fix(ui): optimize prompt input styling with theme simplification and history indicator (#1666)
- 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]>
2026-05-24 03:52:43 -07:00
CVEngineerandwufengfan 326e657bf9 feat(dashboard): code block syntax highlighting follows light/dark theme (#1664)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 03:45:03 -07:00
CVEngineerandwufengfan 36228c72a8 feat(desktop): render edit_file/multi_edit results as DiffCard (#1662)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 03:30:31 -07:00
YHHandreasonix 8686c91b45 fix(dashboard): tool cards no longer stuck spinning forever (#1676)
`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]>
2026-05-24 03:26:31 -07:00
CVEngineerandwufengfan 7219a20cb7 fix(desktop): code block lang detection + overlay header + icon-only copy button (#1661)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 03:25:47 -07:00
YHHandreasonix 340760feb1 fix(dashboard): composer queue-count label was passing wrong var name (#1674)
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]>
2026-05-24 03:16:26 -07:00
Yvoneandkoge_yvone 1dc54dfc78 fix: 修复长路径撑开聊天气泡 (#1590)
Co-authored-by: koge_yvone <[email protected]>
2026-05-24 03:15:03 -07:00
YHHandreasonix 2a45ac45af fix(dashboard): don't synthesize $turn_complete from per-iter assistant_final (#1673)
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]>
2026-05-24 03:04:36 -07:00
YHHandreasonix 4610d54743 fix(model): self-heal stale model id on load; drop v3 ids from picker fallbacks (#1663)
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]>
2026-05-23 23:24:01 -07:00
YHHandreasonix f11e2188b9 chore(loop): drop redundant abort warning, keep only synthetic final (#1659)
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]>
2026-05-23 23:13:45 -07:00
YHH d2b5d0542e fix(config): resolve (baseUrl, apiKey) as a tuple, not two independent fields (#1658)
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
2026-05-23 23:05:10 -07:00
YHHandreasonix 88fc19d962 refactor(config): drop preset abstraction, expose model + effort directly (#1657)
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]>
2026-05-23 22:37:02 -07:00
YHHandreasonix 8aba0e2c78 chore(cli): drop dead i18n helper + variable from #1617 (#1656)
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]>
2026-05-23 22:19:09 -07:00
Fengfan Wu 267c4901dc feat(desktop): code block syntax highlighting follows light/dark theme (#1655)
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.
2026-05-23 22:17:50 -07:00
YHH bac58aedd0 feat(ui): desktop system events + show/hide toggle (#1654)
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.
2026-05-23 22:13:58 -07:00
YHHandreasonix bf77bba995 chore(desktop): extract useAutoCollapse hook, tidy sidebar logic (#1652)
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]>
2026-05-23 22:07:49 -07:00
Evan-Pycraft 341dc83f3c feat(i18n): localize edit approval/discard messages and events errors with zh-CN (#1617) 2026-05-23 22:06:26 -07:00
Tianjiu e02d0984c3 fix(desktop): add responsive sidebar collapse (#1585)
* fix(desktop): add responsive sidebar collapse

* fix(desktop): preserve composer menus in responsive layout
2026-05-23 21:54:34 -07:00
YHHandreasonix 5a9a5db4e7 feat(dashboard): surface system events as quiet inline dividers, drop chatty ones (#1650)
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]>
2026-05-23 21:52:17 -07:00
YHHandreasonix f78beded5c chore(desktop): #1645 follow-ups + isolate flaky server-dashboard test (#1651)
* 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]>
2026-05-23 21:48:52 -07:00
Fengfan Wuandwufengfan e170db3ec2 feat(desktop): copy/edit overlay, msg history nav, IME guard, card collapse (#1645)
* 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]>
2026-05-23 21:21:21 -07:00
TaoMu 5116d11198 test(tui): cover legacy mouse report flood (#1648) 2026-05-23 21:17:11 -07:00
YHH 106255be72 feat(ui): render compacted history as a collapsible card on all three surfaces (#1649)
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).
2026-05-23 21:05:14 -07:00
TaoMu c848df3fa3 fix(tui): gate multi-edit in review mode (#1647)
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
2026-05-23 20:25:51 -07:00
YHH 421e412658 refactor(context-manager): drop preflight, fold once at turn start (#1646)
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.
2026-05-23 20:23:37 -07:00
TaoMu b3e868135d fix(desktop): surface file paths and completion feedback (#1644)
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
2026-05-23 20:16:24 -07:00
YHHandreasonix 6ca6219513 fix(desktop): show current context size, not cumulative cache totals (#1643)
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]>
2026-05-23 19:51:03 -07:00
YHH 3c8cc8c477 refactor(context-manager): preflight folds first, drop obsolete byte ceiling (#1642)
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.
2026-05-23 19:49:36 -07:00
TaoMu bfb6d8e289 fix(ui): preserve code operators in code blocks (#1640)
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
2026-05-23 19:44:20 -07:00
YHHandreasonix a00ea34411 fix(desktop): block right-click context menu (#1641)
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]>
2026-05-23 19:42:57 -07:00
TaoMu c5debed4da fix(tui): drop legacy mouse reports (#1637) 2026-05-23 19:03:37 -07:00
TaoMu 31998dfe93 fix(tui): isolate static history from input rerenders (#1635) 2026-05-23 19:00:19 -07:00
ForeverYoungPp 3d150437a2 fix(api): normalize preset in settings/overview endpoints to prevent badge crash (#1633) 2026-05-23 18:58:29 -07:00
YHHandreasonix 7d817f8a8e feat(subagents): per-skill flash/pro override + Settings UI (#1632)
* 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]>
2026-05-23 09:53:56 -07:00
Bernardxu123andBernardxu123 f12e10db62 fix(memory): cap SessionStats turns at 200 with cost carryover (#1628)
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]>
2026-05-23 09:53:34 -07:00
TaoMu 12a9a518ef fix(ui): advance active plan steps (#1629) 2026-05-23 08:24:46 -07:00
TaoMu 84952744f8 fix(mcp): pass workspace roots to servers (#1625) 2026-05-23 08:18:18 -07:00
TaoMu f38100ed44 fix(ui): replace repeated live hints (#1624) 2026-05-23 08:15:57 -07:00
YHHandreasonix 161d6ec78f feat(presets): drop auto + /pro — flash/pro are the only knobs now (#1630)
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]>
2026-05-23 07:45:09 -07:00
YHHandreasonix dc1acf7526 fix(theme): composer + user card bg use theme tokens, not hardcoded #1e1e1e (#1623)
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]>
2026-05-23 07:14:49 -07:00
TaoMu f459dbf268 test(lifecycle): cover npm package aliases (#1621) 2026-05-23 05:47:35 -07:00
Bernardxu123andCI Fix 9372b3a316 fix(memory): JobRegistry self-cleanup for completed jobs (#1620)
- 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]>
2026-05-23 05:44:18 -07:00
YHHandreasonix b16f614368 fix(settings): restore search-engine switcher in dashboard + desktop (#1618)
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]>
2026-05-23 05:39:34 -07:00
YHHandreasonix 9e541658c8 fix(desktop): macOS bundled node inherits parent TCC grants (#1614)
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]>
2026-05-23 04:57:30 -07:00
douglarek 7d90606f8e feat(config): add dashboard.enabled setting to suppress auto-start (#1612)
* 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
2026-05-23 04:55:41 -07:00
Bernardxu123andCI Fix f67fcd261f fix(desktop): prevent stale events from corrupting UI after session switch (#1582)
* 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]>
2026-05-23 04:49:10 -07:00
dacec354 a6afeabd05 feat(tui): add Alt+S input stash/recall hotkey
Empty input + stash exists → recall into input, clear stash.
Empty input + no stash → "Nothing to stash" hint.
Non-empty input + stash exists → true exchange.
Non-empty input + no stash → stash input, clear buffer.

Gated behind busy + modal guard. No dead i18n keys.
2026-05-23 04:47:23 -07:00
Irene Luoandllr-selfgit 96c91279a8 fix(tui): surface failed shell command output (#1608)
Co-authored-by: llr-selfgit <[email protected]>
2026-05-23 03:37:26 -07:00
Bernardxu123andCI Fix 3daafde4a7 fix(mcp): use normalizeMcpConfig in codeCommand to support mcpServers (#1568) (#1603)
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]>
2026-05-23 03:27:03 -07:00
Tianjiu 019a852be5 fix(desktop): preserve compact composer default (#1594)
* fix(desktop): preserve compact composer default

* fix(desktop): widen chat when rails collapse
2026-05-23 03:23:56 -07:00
Tianjiu d1ca21f545 fix(ui): preserve user message newlines (#1588) 2026-05-23 03:11:57 -07:00
TaoMu 018aa2e76e test(lifecycle): cover deterministic policy corpus (#1574) 2026-05-23 02:12:19 -07:00
YHHandreasonix ff4032c7db feat(dashboard): cross-session stability, persistent URL, polish pass (#1599)
* 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]>
2026-05-23 01:00:28 -07:00
YHHandreasonix 4689ea42e8 fix(dashboard): include current session in CLI-printed URL (#1589)
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]>
2026-05-22 21:19:45 -07:00
YHHandreasonix cb0851c4cc perf(dashboard): split heavy vendor libs into separate chunks (#1587)
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]>
2026-05-22 21:10:42 -07:00
YHHandreasonix 790949c8f1 feat(dashboard): persist active session in URL for shareable / refresh-safe links (#1586)
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]>
2026-05-22 20:52:19 -07:00
Tianjiu 595a83ee74 fix(ui): add horizontal scroll for markdown tables (#1562) 2026-05-22 20:17:39 -07:00
YHHandreasonix 6e8cad791e chore(install): include desktop deps in root postinstall (#1584)
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]>
2026-05-22 19:46:57 -07:00
462b79b15e feat: port desktop dashboard from Tauri+Preact to CLI-hosted React Web app (#1418)
* 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]>
2026-05-22 19:36:08 -07:00
YHHandreasonix fe141e069d fix(presets): drop stale "5/31 discount" framing in pro cost copy (#1583)
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]>
2026-05-22 19:27:48 -07:00
YHHandreasonix cf148a1285 chore(dsnix): bump to 0.49.0 + sync lockfile (#1570)
Co-authored-by: reasonix <[email protected]>
2026-05-22 10:23:35 -07:00
YHHandreasonix 6ea352fdd8 chore(changelog): document #1563 + #1565 under 0.49.0 (#1569)
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]>
2026-05-22 10:11:59 -07:00
YHHandreasonix 544714b2ba fix(context): align fold summary prefix with main agent for cache reuse (#1565)
* 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]>
2026-05-22 09:20:25 -07:00
YHHandreasonix 7ae935335e feat(edit): enforce read-before-edit at the dispatch gate (#1563)
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]>
2026-05-22 08:36:09 -07:00
YHHandreasonix 77a7cd9c61 fix(approval-prompts): translate Shell/Path confirm title and action labels (#1560) (#1561)
`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]>
2026-05-22 08:26:21 -07:00
TaoMu 615cc81fce refactor(lifecycle): extract risk policy (#1557) 2026-05-22 08:07:14 -07:00
YHHandreasonix 65c0d641ef feat(web-search): default to Bing, drop Mojeek, dashboard engine switcher (#1558)
* 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]>
2026-05-22 07:57:50 -07:00
YHHandreasonix 4e136aad4e fix(config): atomic write + restore preset-write diagnostic trace (#1555)
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]>
2026-05-22 07:16:53 -07:00
YHHandreasonix 4de6321b10 fix(client): wire timeoutMs to fetch when caller passes a signal (#1535) (#1553)
`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]>
2026-05-22 06:54:42 -07:00
wby 152477205f fix(tui): restrict @mention file search to current directory prefix (#1548)
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
2026-05-22 06:40:27 -07:00
paradoxSCH 6ac18cfbce fix(code-system): add Task integrity guardrail preventing objective simplification (#1516)
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.
2026-05-22 06:31:53 -07:00
YHH fc85376c3f chore(context): capture all pinned-constraint blocks in fold tail (#1552)
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.
2026-05-22 06:29:49 -07:00
paradoxSCH 736deb1321 fix(context): preserve memory constraints across context folds (#1515)
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.
2026-05-22 06:22:09 -07:00
paradoxSCH fa5f3a01c6 fix(tools): discourage shell-based file edits in run_command description (#1514)
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.
2026-05-22 06:14:58 -07:00
TaoMu b5a2175c6e test(lifecycle): rename lifecycle harness fixtures (#1532)
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.
2026-05-22 05:59:42 -07:00
Shaun Xiao c7368be722 feat(chat): queued mid-turn steer handling (#1501)
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
2026-05-22 05:47:04 -07:00
TaoMu 6ca3c94d21 test(lifecycle): cover stop and cancel recovery (#1499)
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.
2026-05-22 05:40:35 -07:00
Bernardxu123 900c68d638 fix(tui): remove misleading ^O expand from paste sentinel label; update shortcut panel descriptions (#1517)
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.
2026-05-22 05:36:33 -07:00
wade1999 7eecebe3ea feat(desktop): add approval and completion notifications (#1519)
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.
2026-05-22 05:32:19 -07:00
YHH b43dd4bb91 chore(changes): gate @mention popover on MODE === "attached" (#1549)
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.
2026-05-22 05:08:48 -07:00
ForeverYoungPp ca68ba07f9 fix(changes): add @mention file picker popover to ChatPane (#1546)
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.
2026-05-22 04:40:26 -07:00
Tianjiu f0f1ac60a5 fix(web): block SSRF in web_fetch (#1544)
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.
2026-05-22 04:35:12 -07:00
Evan-Pycraft 72f2478f35 feat(i18n): localize CLI command output strings (MCP, sessions, prune, theme) (#1524)
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.
2026-05-22 02:34:42 -07:00
YHH 57a3624d13 fix(web): bridge path-access approval modal to the dashboard (#1538)
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.
2026-05-22 02:28:40 -07:00
YHH cd8def12b6 refactor(tui): drop the byte-virtual frame layer (stage 4 of #1529)
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.
2026-05-22 02:10:48 -07:00
YHH b465b73178 refactor(tui): drop viewport-budget row allocator (stage 3 of #1529)
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).
2026-05-22 01:50:23 -07:00
YHH 8a8d7655e6 refactor(tui): make Static the only history renderer; drop virtual-viewport machinery (stage 2 of #1529)
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.
2026-05-22 01:36:21 -07:00
YHH bb76851f95 feat(tui): static-history path behind REASONIX_STATIC_HISTORY (stage 1 of #1529)
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.
2026-05-22 01:12:45 -07:00
Bernardxu123 78e7327ead fix(tui): Ctrl+Enter inserts newline and update shortcut panel (#1513)
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
2026-05-21 23:37:26 -07:00
YHHandreasonix c9f8bc1507 fix(client): translate DeepSeek 429 into a concurrency-limit hint (#1526)
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]>
2026-05-21 23:30:32 -07:00
YHHandreasonix 1024a0cc44 fix(edit): preserve file encoding on read/edit/restore (GB18030, UTF-8 BOM) (#1518)
* 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]>
2026-05-21 22:36:06 -07:00
YHHandreasonix 002a97fe91 feat(tui): add mouseWheelRows config knob for per-terminal scroll tuning (#1511)
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]>
2026-05-21 20:59:14 -07:00
YHHandreasonix 45f9a65fd4 fix(proxy): allow opting out of the DeepSeek direct-route default (#1507)
`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]>
2026-05-21 20:14:46 -07:00
TaoMu 3cc72075f2 feat(plans): surface lifecycle evidence summaries (#1500) 2026-05-21 19:38:30 -07:00
TaoMu d807c1f9b8 test(lifecycle): cover failed verification revise flow (#1498) 2026-05-21 19:27:10 -07:00
YoungDan-hero acb1dca762 fix: constrain shell redirects to sandbox boundaries (#1457)
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.
2026-05-21 19:11:08 -07:00
YoungDan-hero e5bb6b4a24 fix: prevent edit snapshots from reading outside workspace (#1454)
* fix: resolve root-relative edit block paths

* fix: prevent edit snapshots from reading outside workspace
2026-05-21 18:59:52 -07:00
Irene Luoandllr-selfgit 4e8a49408e feat(tools): limit tool dispatch rate (#1356)
Co-authored-by: llr-selfgit <[email protected]>
2026-05-21 18:45:35 -07:00
reasonix 245e13b245 fix(desktop): tsc errors blocking desktop bundle build
- 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.
2026-05-21 06:36:05 -07:00
reasonix be414940cb fix(desktop): drop workspace:* protocol for core-utils — desktop isn't a workspace member
`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).
2026-05-21 06:25:41 -07:00
reasonix b6492b2677 chore(dsnix): bump to 0.48.1 + sync lockfile 2026-05-21 06:20:55 -07:00
reasonix c404bfe60e chore(release): 0.48.1 — dsnix alias, lifecycle observability, composer redesign
Headline themes:
- dsnix: short alias package + lockfile/readme sync
- Lifecycle: strict observability + multi-file refactor and config-migration corpus tests
- Approval prompt: unified PauseRequest data model across ACP/CLI/Desktop (#1322 Phase 3)
- i18n: builtin skill descriptions + MCP error toasts + status labels (zh-CN)
- UI: composer redesign with Ctrl+P shortcut help modal
- Security: drop baked metaso key + trust project hooks
- Perf: fold thresholds 50→75% / 70→78%

See CHANGELOG for the full list.
2026-05-21 06:16:16 -07:00
Tianjiu d7fb4daca5 fix(security): remove baked metaso key and trust project hooks (#1488) 2026-05-21 06:05:18 -07:00
YHHandreasonix fa916e8603 fix(yolo): auto-resolve run_command + run_background gates in YOLO mode (#1489)
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]>
2026-05-21 05:43:10 -07:00
YHHandreasonix 8429754d1c fix(desktop): make error cards dismissable + tone-down recoverable ones (#1487)
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]>
2026-05-21 05:27:32 -07:00
sorghum 9e46fe4746 feat: optimize java tool (#1485)
* feat: make jarKeyword a required parameter[2]

* feat: Optimize Java Tool.
2026-05-21 05:05:20 -07:00
YHHandreasonix 99281682a6 fix(tui): keep SGR mouse on Windows — alternate-scroll breaks wheel on WT (#1486)
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]>
2026-05-21 05:04:38 -07:00
Bernardxu123andReasonix Dev 19430d225d feat(ui): redesign input area and integrate Ctrl+P shortcut help modal (#1483)
* 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]>
2026-05-21 04:51:15 -07:00
YHHandreasonix 330a75b8fb fix(desktop): clear orphaned pause-gate modals on \$turn_complete (#1484)
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]>
2026-05-21 04:21:15 -07:00
YHHandreasonix a91faab615 fix(cost): show session-aggregate cache hit so /cost matches the status bar (#1482)
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]>
2026-05-21 04:12:36 -07:00
Evan-Pycraft 962774be14 feat(i18n): localize MCP error toasts and status labels with zh-CN (#1481) 2026-05-21 03:50:09 -07:00
YHHandreasonix 2821aeb95f fix(plan): Accept executes immediately when the plan has no open questions (#1480)
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]>
2026-05-21 03:25:17 -07:00
TaoMu 604ab2451e test(lifecycle): cover config migration corpus (#1473) 2026-05-21 03:07:36 -07:00
Tianjiu 8ccb0f575c feat(desktop): allow renaming session titles from sidebar (#1478)
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.
2026-05-21 02:46:36 -07:00
YHHandreasonix 29608dfe78 fix(tui): switch default mouse mode to alternate-scroll (?1007h) (#1477)
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]>
2026-05-21 02:33:47 -07:00
YHHandreasonix 09406f2932 fix(desktop): make /btw visibly work — echo input, surface busy, use side-question prompt (#1472)
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]>
2026-05-21 01:35:31 -07:00
Evan-Pycraft 6bc7a7cdba feat(i18n): localize builtin skill descriptions with zh-CN (#1468) 2026-05-21 01:06:39 -07:00
YHHandreasonix 9a156e88fe fix(tests): bump chat-mcp-startup timeout to 30s for Windows + coverage (#1471)
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]>
2026-05-21 00:44:06 -07:00
YoungDan-hero 50f38c77c7 fix: resolve root-relative edit block paths (#1452) 2026-05-21 00:20:17 -07:00
TaoMu 68449b81fc fix(desktop): autosize composer for multiline input (#1439) 2026-05-21 00:19:21 -07:00
TaoMu 485a18ee51 test(lifecycle): cover multi-file refactor corpus (#1427) 2026-05-21 00:18:24 -07:00
TaoMu 6e68735e0a feat(lifecycle): surface strict lifecycle observability (#1426) 2026-05-21 00:17:23 -07:00
paradoxSCHandClaude Sonnet 4.6 3a09a2b9c5 feat(approval-prompt): unified PauseRequest→UI data model for ACP, CLI, Desktop (#1322 Phase 3) (#1443)
* 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]>
2026-05-21 00:14:57 -07:00
YHHandreasonix 1090980452 perf(fold): raise normal threshold 50%→75%, aggressive 70%→78% (#1461)
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]>
2026-05-20 20:41:47 -07:00
YHHandreasonix cdb4b1c7b2 fix(preflight): also gate on JSON body bytes, not just tokens (#1451)
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]>
2026-05-20 18:28:41 -07:00
YHHandreasonix 77e9c69a9d fix(dsnix): sync package-lock for new workspace + document alias in README (#1442)
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]>
2026-05-20 09:25:00 -07:00
YHHandreasonix ce61452e45 feat(dsnix): add shim package for shorter CLI command (#1440)
`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]>
2026-05-20 09:18:35 -07:00
reasonix 90d2c33d3a chore(release): 0.48.0 — NO_PROXY, code intelligence, lifecycle round two
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.
2026-05-20 07:32:30 -07:00
Evan-Pycraft 7fdd219c0e feat(i18n): extract remaining hardcoded strings in edit history and MCP browse (#1433) 2026-05-20 07:28:54 -07:00
YHHandreasonix 8061478f87 feat(slash): add /about — version, website, GitHub, license (#1434)
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]>
2026-05-20 07:08:50 -07:00
YHHandreasonix af1e52bed1 fix(config): tolerate BOM in config.json + retire preset-trace diagnostic (#1431)
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]>
2026-05-20 06:45:07 -07:00
YHHandreasonix a99b120902 fix(ui): elide reasoning + streaming + diff content beyond the recent window (#1432)
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]>
2026-05-20 06:36:03 -07:00
YHHandreasonix 3f1db467ee fix(desktop): swallow F5 / Ctrl+R in packaged builds (#1430)
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]>
2026-05-20 06:07:23 -07:00
YHHandreasonix a654c97279 debug(preset): trace writeConfig + savePreset + dashboard preset writes (#1429)
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]>
2026-05-20 05:57:13 -07:00
YHHandreasonix 5517a3af78 fix(desktop): make rpc_spawn idempotent + add desktop_resync rehydrate path (#1428)
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]>
2026-05-20 05:33:01 -07:00
YHHandreasonix a7c1640e7a fix(settings): allow clearing baseUrl from the dashboard (#1425)
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]>
2026-05-20 05:12:23 -07:00
TaoMu 3e8cf9440c test(lifecycle): add strict e2e harness (#1424) 2026-05-20 05:01:50 -07:00
YHHandreasonix edb90cd7e4 fix(ui): less-sensitive wheel scroll + collapse per-card stdout resize listeners (#1423)
* 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]>
2026-05-20 04:59:23 -07:00
YoungDan-heroandCursor f339f668ad fix: reject ambiguous search-replace edit blocks (#1414)
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]>
2026-05-20 04:47:31 -07:00
YHHandreasonix d304a7607d feat(subagent): live byte progress + top-level explore/research/review tools (#1422)
* 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]>
2026-05-20 04:46:11 -07:00
YHHandreasonix 8d82bb573d fix(loop): reset _turnAbort in finally so consumer break can't lock the session (#1421)
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]>
2026-05-20 04:43:28 -07:00
TaoMu 32674bdd48 fix(lifecycle): keep strict rails cache-neutral (#1407) 2026-05-20 03:21:48 -07:00
YHHandreasonix e5b6f817b0 chore(desktop): document writeAllSync + drop redundant optional chain on caught err (#1412)
Co-authored-by: reasonix <[email protected]>
2026-05-20 03:20:06 -07:00
Xingxing Zhouand粥 5161dd3c84 Fix desktop stdout partial writes (#1405)
Co-authored-by: 粥 <[email protected]>
2026-05-20 02:55:56 -07:00
YHHandreasonix f7a5b5a79a chore(docs,scripts): drop obsolete MCO RFC + spawn-cost probes (#1411)
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]>
2026-05-20 02:51:19 -07:00
TaoMu bae312ce7a feat(lifecycle): gate mutations during checkpoints (#1389)
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.
2026-05-20 02:37:19 -07:00
YHH 0f7a0beac7 fix(test): switch vitest to forks pool to stop heap OOM on many-core hosts (#1408)
`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.
2026-05-20 02:30:33 -07:00
YHH 633984124a test(shell-tools): raise run_background dispatch test timeout to 15s (#1406)
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.
2026-05-20 02:15:53 -07:00
TaoMu cc7a2bf71e fix(tools): guard repeated gate rejections (#1392)
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.
2026-05-20 01:59:57 -07:00
TaoMu 5a46f7277b feat(plan): surface step evidence summaries (#1391)
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.
2026-05-20 01:59:15 -07:00
TaoMu d5ac6a3cef feat(lifecycle): preserve state across plan revisions (#1388)
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.
2026-05-20 01:54:37 -07:00
TaoMu f0eb2a474c fix(lifecycle): let slash plan off release rails (#1386)
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
2026-05-20 01:53:58 -07:00
wade1999 5be617e513 docs(qq): add desktop quick start and trim README surface (#1401)
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`.
2026-05-20 01:46:04 -07:00
paradoxSCH 661fbd2bd9 fix(desktop): sync context token meter after /compact (#1399)
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.
2026-05-20 01:43:36 -07:00
YHH 3a7c15a4bb chore(shell): trim run_command param description (saves 119 tokens of cached prefix) (#1403)
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`.
2026-05-20 01:40:32 -07:00
YHH 5adce512d4 chore(scripts): measure per-tool token cost end-to-end (#1402)
`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`.
2026-05-20 01:40:23 -07:00
YHH 6a3d9c15af test(tools): close dispatch-level E2E gaps for shell jobs, web, and scaffold (#1400)
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.
2026-05-20 00:58:54 -07:00
sorghum 9ac2294bec feat(java-source): strip javap noise + raise buffer to save tokens (#1390)
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.
2026-05-20 00:17:52 -07:00
YHH e5580e4d30 refactor(config): sanitize string[] fields at readConfig boundary (#1396)
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
2026-05-20 00:16:11 -07:00
paradoxSCH ba9fb3c8d2 fix(desktop): prevent React #31 when MCP config contains non-string items (#1394)
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.
2026-05-20 00:02:23 -07:00
YHHandreasonix 401c6b8cb0 feat(code-query): tree-sitter get_symbols + find_in_code (TS/JS/Python/Go/Rust/Java) (#1387)
* 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]>
2026-05-19 23:39:22 -07:00
YHHandreasonix dc979239c0 fix(desktop): surface /btw usage hint on empty payload instead of dropping the keystroke (#1383)
`/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]>
2026-05-19 21:46:16 -07:00
YHHandreasonix 51832e9661 feat(doctor): surface resolved NO_PROXY + per-host routing decisions (Tier 3) (#1375)
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]>
2026-05-19 21:10:59 -07:00
summerandSummer Su 2b87a6e10d feat(desktop): 添加自定义字体与文件链接优化 (#1376)
Co-authored-by: Summer Su <[email protected]>
2026-05-19 21:09:51 -07:00
YHHandreasonix aa8c82a606 feat(net): --no-proxy CLI flag + REASONIX_NO_PROXY env + cfg.proxy field (Tier 2) (#1374)
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]>
2026-05-19 19:58:40 -07:00
YHHandreasonix 2a5e24848b feat(net): honor NO_PROXY + bake DeepSeek bypass into default whitelist (Tier 1) (#1373)
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]>
2026-05-19 19:45:21 -07:00
YHHandreasonix c26a5500cf fix(tools): walk .reasonix/ from FS tools so user skills stay reachable (#1371)
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]>
2026-05-19 19:24:00 -07:00
YHHandreasonix e1f144d743 fix(desktop): apply USD→CNY conversion to cost meter and session-cost card (#1369)
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]>
2026-05-19 19:01:17 -07:00
YHHandreasonix eb06c32366 test(web): cover Perplexity + Exa backends; strip section-banner comments (#1366)
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]>
2026-05-19 18:32:41 -07:00
dacec354 db3a0d0d7e Feat/web-search perplexity exa (#1350)
* feat: add Perplexity and Exa as web_search engines

* fix: biome lint errors and update public API snapshot
2026-05-19 18:24:39 -07:00
YHHandreasonix 6cc7a8ea66 chore(java): clean up comment style + isolate searchProject tests (#1363)
* 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]>
2026-05-19 18:23:07 -07:00
J3y0r 71b0ffa80e fix(cli): add opt-out for terminal mouse tracking (#1345)
Closes #1337.
2026-05-19 18:21:58 -07:00
sorghum b0d8fea64c feat: Add Java source code search and decompilation tools. (#1344) 2026-05-19 18:02:46 -07:00
YHHandreasonix 95864a9cc7 fix(desktop): restore augmentProcessPath() lost in #1334 rebase (#1361)
#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]>
2026-05-19 17:58:36 -07:00
wade1999 18ee05d0f1 feat(desktop): make QQ sessions usable from desktop (#1334)
Closes #1317.
2026-05-19 17:51:54 -07:00
reasonix c41c9ed0cf fix(release): move @reasonix/core-utils to devDependencies (0.47.2)
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.
2026-05-19 06:12:21 -07:00
reasonix 08008a02ea chore(release): 0.47.1 — desktop shakeout + prompt budget round one 2026-05-19 05:44:10 -07:00
YHH a5654c5af1 fix(skill): surface /skill in welcome hints + drop stale built-ins line (#1333)
Closes #1213
2026-05-19 05:20:20 -07:00
Tianjiu 3f80f74208 fix(ui): highlight selected picker rows in light themes (#1330)
Closes #1311

Co-authored-by: T1anjiu <[email protected]>
2026-05-19 05:05:40 -07:00
paradoxSCHandparadoxSCH 4b5b7a2927 feat(core-utils): introduce @reasonix/core-utils workspace package (Phase 1) (#1328)
Closes #1322 (Phase 1)

Co-authored-by: paradoxSCH <[email protected]>
2026-05-19 05:04:27 -07:00
YHH 8355c6f37b fix(desktop): inherit login-shell PATH so nvm/asdf/fnm reach run_command (#1331)
Closes #1252
2026-05-19 04:58:19 -07:00
YHH 8735359f14 fix(desktop): stop claiming "Connected" — desktop QQ is config-editor-only (#1326)
Closes #1317
2026-05-19 04:37:57 -07:00
YHHandT1anjiu 5f13757d7a fix(multi_edit): roll back files that may have been modified on write failure (#1325)
Co-authored-by: T1anjiu <[email protected]>
2026-05-19 04:36:45 -07:00
YHHandreasonix fd162a3636 feat(read_file): lower outline threshold 512 KiB → 64 KiB (#1324)
#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]>
2026-05-19 04:11:45 -07:00
YHHandreasonix e7fb66996f refactor(prompt): compress codeSystemPrompt (-51%, ~3.1k tokens/request) (#1323)
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]>
2026-05-19 04:10:16 -07:00
YHHandreasonix 6e5fa83fa3 refactor(tools): compress tool spec descriptions (-28%, ~2.7k tokens/request) (#1321)
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]>
2026-05-19 04:09:36 -07:00
YHHandreasonix 548568b5e3 test(prompt-budget): lock cache-prefix byte budget (#1320)
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]>
2026-05-19 04:05:45 -07:00
paradoxSCH 1e6b28f7e4 fix(client): skip extra_body for Azure endpoints (#1316)
Closes #1299
2026-05-19 03:59:43 -07:00
reasonix e105394f67 feat(desktop): re-enable devtools and context menu in release builds
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.
2026-05-19 02:32:03 -07:00
paradoxSCH 6cdc59ffca fix(permissions): strip literal '*' from always-allow prefix in Desktop/ACP (#1312) 2026-05-19 02:29:33 -07:00
Tianjiu 0c765e0f49 fix(desktop): prevent browser Select All when composer is not focused (#1314) 2026-05-19 02:26:51 -07:00
TaoMu 2bb40b2704 feat(lifecycle): add opt-in engineering lifecycle (#1306) 2026-05-19 02:24:44 -07:00
reasonix 0097cde077 fix(search): honor tavily engine + read engine at call time
`/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
2026-05-19 02:06:34 -07:00
reasonix 6df5791fc5 fix(tui): drop spinner + stream tick rate on legacy Windows conhost
`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
2026-05-19 01:20:00 -07:00
Tianjiu a0622c776f fix(desktop): use updater plugin for update check to bypass CSP (#1298)
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.
2026-05-19 01:09:36 -07:00
TaoMu fbc38dd0cc fix(cli): resolve heap reexec entrypoint (#1303)
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.
2026-05-19 01:08:09 -07:00
TaoMu 27e8137f88 feat(plan): persist step evidence metadata (#1302)
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.
2026-05-19 01:06:45 -07:00
TaoMu 89e9c752aa feat(tools): add ordered interceptor chain (#1301)
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.
2026-05-19 01:04:22 -07:00
Orchard eaae901d27 style(desktop): add unified button:disabled style (#1304)
Thanks @Orchardxyz — neat one-rule fix, and the local opacity:1 override keeps the composer-attach visual intact. Merging.
2026-05-19 00:59:42 -07:00
reasonix 7965801689 style(i18n): join helpShellGate onto one line for biome formatter 2026-05-19 00:35:54 -07:00
Dimas D. Angga ac2c5cee88 fix(tui): surface per-call shell-exec approval flow on first run (#1278)
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.
2026-05-19 00:35:17 -07:00
Richie 424838c00d feat(desktop): add selectable theme styles (#1291)
Thanks @lisniuse — the style/mode split is a clean abstraction and the four palettes look great. Merging.
2026-05-19 00:26:47 -07:00
Tianjiu f94de83550 fix(slash): reject // line-comment input as slash command (#1288)
Thanks @T1anjiu — clean fix with a focused test. Merging.
2026-05-19 00:24:21 -07:00
reasonix 8973327ebb fix(docs): point download mirrors at desktop-v* tag namespace
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.
2026-05-18 23:29:40 -07:00
reasonix 520ed5c933 chore(release): 0.47.0 2026-05-18 22:39:47 -07:00
reasonix a6fb3a2608 fix(docs): guard mirror result lookup before probe results land
results is empty on the first render after the version resolves, so
results.find() returned undefined and reading .done crashed the page.
2026-05-18 22:33:22 -07:00
YHHandreasonix c636332251 chore(docs): pull version from the R2 mirror, drop the manual bump (#1280)
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]>
2026-05-18 22:18:22 -07:00
YHHandreasonix f0f5799880 chore: drop pr-preview screenshot from repo root (#1281)
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]>
2026-05-18 22:17:26 -07:00
Bernardxu123 414b915f58 feat(tui): add background fill to input box and user card left stripe (#1274)
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.
2026-05-18 22:14:27 -07:00
Orchard 219afe8f79 style(desktop): replace pill-tag status labels with compact icons (#1277) 2026-05-18 21:52:44 -07:00
YHHandreasonix 080b385feb feat(desktop): show download progress in the update banner (#1276)
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]>
2026-05-18 21:49:25 -07:00
YHHandreasonix 06e449b277 chore(desktop): point updater at R2 mirror so CLI releases can't break it (#1275)
`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]>
2026-05-18 21:37:17 -07:00
YHHandreasonix 48d2d9dd0c fix(tui): gate u undo to the 5s banner window so stale taps can't revert (#1272)
`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]>
2026-05-18 21:15:17 -07:00
YHHandreasonix 34f44540eb fix(tui): sync system cursor after ink render so IME popups track ▌ (#1270)
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]>
2026-05-18 20:59:21 -07:00
wade1999 402e7fd2e7 docs(qq): tighten setup guide and readmes (#1269) 2026-05-18 20:51:48 -07:00
YHHandreasonix fba0b421f9 feat(tui): ctrl+r verbose toggle + esc-esc rewind picker (#1268)
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]>
2026-05-18 20:44:21 -07:00
YHHandreasonix 86b7a8a4ae docs(readme): note Claude-format skill paths load, with OpenSpec example (#1267)
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]>
2026-05-18 20:34:16 -07:00
Bernardxu123 03812d9f65 fix(tui): center WelcomeBanner vertically when chat is empty (#1264)
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
2026-05-18 20:11:59 -07:00
YHHandreasonix fac3046495 feat(tui): align composer keys + visuals with Claude Code (#1263)
* 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]>
2026-05-18 20:11:11 -07:00
YHHandreasonix e4a2c9fa5e feat(tui): re-enable SGR mouse wheel by default (revisit #514) (#1262)
#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]>
2026-05-18 19:12:25 -07:00
YHHandreasonix 607839b4b3 feat(search): add Tavily as web_search backend — escape hatch for Mojeek 403s (#1260)
* 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]>
2026-05-18 18:04:30 -07:00
YHHandreasonix 1d867554b4 feat(compat): read Claude .mcp.json + .claude/skills; alias type/context/agent fields (#1259)
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]>
2026-05-18 17:31:16 -07:00
wade1999 e4f77af083 fix(qq): improve first-connect onboarding and i18n (#1257) 2026-05-18 17:03:21 -07:00
Xie'Sheng 315acfc461 ui(composer): scroll active slash command into view (#1255)
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.
2026-05-18 16:56:56 -07:00
YHHandreasonix e9a7890950 chore(search): bump regex worker timeout 5s → 60s, walk deadline 15s → 120s (#1254)
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]>
2026-05-18 16:55:31 -07:00
Richie af44361eab feat(desktop): restore window, tabs, sessions and scroll on relaunch (#1253)
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
2026-05-18 16:51:39 -07:00
YHHandreasonix 9f9af5e3c5 feat(search): isolate regex in a worker thread so ReDoS can be terminated (#1250)
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]>
2026-05-18 09:28:39 -07:00
Richie 91231eb436 test(code-prompt): bound .gitignore truncation against a baseline (#1248)
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.
2026-05-18 09:27:47 -07:00
Xie'Sheng 5f1a710d9b fix(desktop): enable skill execution via slash command syntax (#1247)
- 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
2026-05-18 09:25:52 -07:00
wade1999 f9d56f7cc3 feat(desktop): add QQ settings entry (#1241) 2026-05-18 09:23:00 -07:00
J3y0r 3ae7dad3dc fix(cli): preserve flash preset auto-escalate semantics (#1240)
Pass resolved preset metadata through chat/code startup so flash remains pinned without auto escalation and the UI initializes with the correct preset label.
2026-05-18 09:20:13 -07:00
YHHandreasonix 85face1624 fix(tools): walk-level deadline for search_content + ESC preempts queued tools (#1246)
* 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]>
2026-05-18 08:44:57 -07:00
YHHandreasonix 6c1d7e91fe fix(mcp): let ESC abort hung MCP handshakes during startup (#1243)
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]>
2026-05-18 08:03:50 -07:00
YHHandreasonix 124c1ac4a8 feat(desktop): render LaTeX math via KaTeX in chat messages (#1239)
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]>
2026-05-18 07:48:03 -07:00
YHHandreasonix 426366131f fix(desktop): bundle universal Node on macOS so Intel Macs don't blank-screen (#1237)
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]>
2026-05-18 07:45:25 -07:00
YHHandreasonix 473c62e83e chore: add Support section with PayPal + WeChat Pay donation channels (#1238)
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]>
2026-05-18 07:37:22 -07:00
Bernardxu123 87428159d7 feat(desktop): add /compact, /retry, /btw + /feedback slash commands (#1231)
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).
2026-05-18 06:05:10 -07:00
Orchard a24ea7298f feat(desktop): split export into dedicated copy and file-export actions (#1229)
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.
2026-05-18 05:52:27 -07:00
Tianjiu 87961386d8 feat(desktop): persist window size and position across sessions (#1224)
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
2026-05-18 05:24:00 -07:00
Bernardxu123 0b5df530e4 fix(desktop): remove Geist sans-serif from serif font stack (#1223)
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
2026-05-18 05:21:55 -07:00
YHH 77895624e8 feat(dashboard): new / switch / delete sessions in-place, no CLI bounce (#1226)
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
2026-05-18 05:18:48 -07:00
YHH 150b8b6d65 chore(desktop): i18n the per-message copy button tooltips (#1221)
Two hardcoded title attributes from #1208 routed through thread.copyMessage / thread.copyResponse so the tooltips swap with the rest of the UI.
2026-05-18 04:59:53 -07:00
Tianjiu ffd5294f73 fix(desktop): per-message copy button + relabel "Clear messages" → "Clear screen" (#1208)
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".
2026-05-18 04:52:44 -07:00
wade1999 1ea15305b9 fix(desktop): tighten slash picker labels (#1195)
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.
2026-05-18 04:47:05 -07:00
YHH 0f19a88be4 fix(desktop): drop regex lookbehind so the bundle parses on macOS Monterey WKWebView (#1215)
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
2026-05-18 04:23:58 -07:00
YHH e8df4b46d5 fix(desktop): surface "session loaded empty" instead of looking like a no-op click (#1210)
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)
2026-05-18 04:01:07 -07:00
YHH f26c39333d perf(session): skip cross-workspace jsonls + byte-scan line count, ~10× faster sidebar list (#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
2026-05-18 03:47:22 -07:00
YHH dbcd2f2271 feat(memory): inject ancestor AGENTS.md into list_directory, not just read_file (#1203)
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
2026-05-18 03:25:52 -07:00
Richie 3378b0e221 feat(desktop): add platform-aware keyboard shortcut rendering (#1199)
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
2026-05-18 02:49:44 -07:00
Tianjiu ee15e9fe0d fix(mcp): add runtime schema validation for MCP server responses (#1198)
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.
2026-05-18 02:47:37 -07:00
YHH 2a890c5061 fix(desktop): catch context-panel render errors instead of white-screening the app (#1200)
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
2026-05-18 02:42:59 -07:00
YHH 9288fb2a93 chore(desktop): swap placeholder R icon for the repo brand mark (#1196)
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
2026-05-18 02:08:09 -07:00
reasonix 8638530792 docs: dedupe contributors wall, keep one in Acknowledgments
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.
2026-05-18 01:51:33 -07:00
reasonix 05705dcb97 docs: add Acknowledgments section thanking top contributors
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.
2026-05-18 01:41:15 -07:00
Richie e3a56c14e9 fix(desktop): localize remaining hardcoded UI copy (#1194)
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
2026-05-18 01:39:10 -07:00
reasonix 3ef9dde09c docs: surface Discord community link in README hero
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.
2026-05-18 01:28:10 -07:00
YHH f65677e070 fix(mcp): surface actual bridge-failure reason in dashboard, not just "restart" (#1191)
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.
2026-05-18 01:25:28 -07:00
YHH bf64097412 fix(desktop): also re-pin auto-scroll on turn start, not just turn end (#1189)
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
2026-05-18 00:54:47 -07:00
Richie 87f233a389 feat(desktop): disable right-click and DevTools in production builds (#1188)
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
2026-05-18 00:39:50 -07:00
LeekJay 7856ac9172 feat(embedding): batch OpenAI-compat embedding requests to respect provider batch limits (#1175)
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.
2026-05-18 00:37:20 -07:00
YHHandreasonix 601dd4c8d4 fix(desktop): Ctrl+K → About opens the modal, not a one-line toast (#1186)
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]>
2026-05-17 23:56:21 -07:00
YHHandreasonix 0188d05a62 feat(desktop): add About modal with version, repo link, and update check (#1183)
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]>
2026-05-17 23:36:48 -07:00
YHHandreasonix 329f6c96c6 fix(desktop): replace right-click-to-delete with a discoverable hover X (#1177)
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]>
2026-05-17 22:19:08 -07:00
reasonix d308b471a1 chore(release): 0.46.1
Bug-fix release rolling up the fixes that landed since 0.46.0:

- IME composition guards (dashboard #1145, TUI prompt #1170)
- desktop auto-scroll pin during streaming (#1114)
- pricing overrides + RPM rate-limit support (#1121)
- desktop macOS text-assistance disabled for inputs (#1124)
- changes-panel InflightRow elapsed/tool/abort + global Esc (#1144)
- pure-Ink TUI Ctrl+C / Esc interrupt routing (#1154)
- MCP stdio child stderr piped + gated, no longer corrupts the TUI (#1158)
- session-discovery / `reasonix sessions` listing + `/` search (#1108)
- workspace picker, bare `/cwd` opens it (#1119)
- session-cost StatusRow refresh on session switch (#1161)
- App.tsx mojibake comments cleaned up (#1162)
- drop hardcoded failure-count auto-escalation (#1163)
- QQ chunked C2C msg_seq + UTF-8 byte-aware splitting (#1131)
- QQ private-channel owner binding + allowlist (#1141)
- `/search-engine` adds metaso (#1159)
- TUI stdout MaxListeners raised so long chats stay quiet (#1166)
- wizard validates API key against `/models` (third-party endpoints) (#1169)
2026-05-17 21:28:30 -07:00
reasonix 5905a3b857 docs: link Discord community + wire CI failure alerts
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.
2026-05-17 21:24:08 -07:00
reasonix 56b54044f6 feat(brand): add Reasonix logo / icon assets
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.
2026-05-17 21:23:48 -07:00
YHHandreasonix ec1fa7db89 fix(tui): drop the IME-commit Enter in the prompt input (#1170)
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]>
2026-05-17 21:15:40 -07:00
YHHandreasonix fb9c7b9bbc fix(wizard): validate key against /models, not /user/balance (#1169)
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]>
2026-05-17 21:00:47 -07:00
YHHandreasonix 5c500becfa fix(tui): raise stdout MaxListeners ceiling for long chats (#1166)
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]>
2026-05-17 20:45:53 -07:00
Zhao XiaohongandZhao Xiaohong ff1ef4f23a fix: add metaso to /search-engine argCompleter, argsHint, and summary (#1159)
Co-authored-by: Zhao Xiaohong <[email protected]>
2026-05-17 20:36:06 -07:00
wade1999 e97f8dd3d1 fix(qq): harden private channel ownership binding (#1141)
* feat(qq): add owner binding and allowlist controls

* refactor(qq): keep access binding off the slash surface
2026-05-17 20:31:15 -07:00
wade1999 5b6d5be7ef fix(qq): add msg_seq for chunked c2c replies (#1131) 2026-05-17 20:26:15 -07:00
YHHandreasonix 41f480e921 refactor(loop): drop hardcoded failure-count auto-escalation (#1163)
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]>
2026-05-17 20:24:31 -07:00
YHHandreasonix 0d0fbc5f28 chore(app): clean mojibake out of App.tsx comments (#1162)
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]>
2026-05-17 20:12:02 -07:00
YHHandreasonix 98202d21ac fix(ui): refresh status-row summary on session switch (#1161)
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]>
2026-05-17 19:55:04 -07:00
TaoMu d9643e005c fix(workspace): add workspace picker (#1119)
* fix(workspace): add workspace picker

* chore: format pricing override files after main rebase
2026-05-17 19:44:49 -07:00
TaoMu 4511e50cd6 fix(session): improve session discovery (#1108) 2026-05-17 19:43:49 -07:00
YHHandreasonix 68e4f439cc fix(mcp): pipe child stderr instead of inheriting (#1158)
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]>
2026-05-17 19:38:35 -07:00
TaoMu eb575ffcf1 Fix pure-Ink TUI turn interrupts (#1154)
* Fix pure Ink turn interrupts

* Sync main and satisfy CI formatting
2026-05-17 19:27:14 -07:00
ForeverYoungPpandYHH f84a47d0a5 feat(changes): enhance InflightRow with elapsed time, tool summary, and Esc interrupt (#1144)
* feat(changes): enhance InflightRow with elapsed time, tool summary, and Esc interrupt

* feat(changes): supplement ChatPane input disable on busy

---------

Co-authored-by: YHH <[email protected]>
2026-05-17 19:25:40 -07:00
OrchardandYHH eba919d2e9 fix(desktop): disable macOS text assistance for inputs (#1124)
Co-authored-by: YHH <[email protected]>
2026-05-17 19:19:21 -07:00
J3y0randYHH b5ade39c6d feat(config): support pricing overrides and rpm limits (#1121)
Allow custom model pricing for third-party endpoints and throttle chat requests with configurable RPM limits.

Co-authored-by: YHH <[email protected]>
2026-05-17 19:17:43 -07:00
凌小添andYHH fc314c6eef fix(desktop): keep auto-scroll pinned during streaming (#1114)
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]>
2026-05-17 19:10:09 -07:00
YHHandreasonix aeeefa0ec5 ci: split desktop + npm releases into separate tag namespaces (#1153)
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]>
2026-05-17 19:07:25 -07:00
ForeverYoungPpandYHH 1115a029d7 fix(changes): add IME composition guard to ChatPane input (#1145)
Co-authored-by: YHH <[email protected]>
2026-05-17 19:04:16 -07:00
YHHandreasonix 12b84c226b feat(tui): remove Rust renderer, return to pure-Ink TUI (0.46.0) (#1151)
* 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]>
2026-05-17 18:49:48 -07:00
YHHandreasonix 04fa3793b9 docs(jsx): bump REASONIX_VERSION to 0.45.1 (#1135)
* docs: bump version banner to v0.45.1

* docs(jsx): bump REASONIX_VERSION to 0.45.1

---------

Co-authored-by: reasonix <[email protected]>
2026-05-17 08:55:12 -07:00
YHHandreasonix 5754f8274f docs: bump version banner to v0.45.1 (#1134)
Co-authored-by: reasonix <[email protected]>
2026-05-17 08:45:28 -07:00
fd06db5f6e fix(chat): rust TUI input — setup capture, paste burst, Ctrl+V (#1129)
* 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]>
2026-05-17 08:26:59 -07:00
TaoMu 67149fd51e fix(loop): persist send-time session healing (#1106)
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.
2026-05-17 08:15:18 -07:00
TaoMu 13f3acecee fix(session): crash-safe rewrites with .jsonl.bak recovery sidecar (#1101)
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.
2026-05-17 08:10:25 -07:00
TaoMu c8964e45b7 fix(ui): remove mojibake from scroll history hints (#1094)
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.
2026-05-17 08:08:42 -07:00
Bernardxu123 3908744234 refactor(ui): extract LiveActivityArea + ComposerArea from App.tsx (#1073)
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.
2026-05-17 07:51:36 -07:00
YHHandreasonix d2051a49ab chore(release): 0.45.0 (#1125)
Co-authored-by: reasonix <[email protected]>
2026-05-17 07:39:35 -07:00
YHHandreasonix 07d9595cf7 feat(render): in-process NAPI addon (0.45.0-rc.0) (#1123)
* 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]>
2026-05-17 07:22:17 -07:00
YHHandreasonix f562b2073a fix(scene): seed empty trace frame on rust child spawn (0.44.2-rc.4) (#1113)
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]>
2026-05-17 20:25:04 +08:00
TaoMu a27856e59e fix(session): auto-name conversations (#1112)
* fix(session): auto-name conversations

* fix(ci): sync package lock
2026-05-17 20:22:31 +08:00
YHHandreasonix 5e3b425487 fix(release): surface rust child diagnostic logging (0.44.2-rc.3) (#1111)
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]>
2026-05-17 20:11:05 +08:00
YHHandreasonix 30b3398ef9 fix(chat): eager rust child spawn for mac (0.44.2-rc.2) (#1110)
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]>
2026-05-17 20:02:14 +08:00
YHH 1d6fddfb34 fix(chat): hold event loop open while rust integrated child spawns (0.44.2-rc.1) (#1107)
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.
2026-05-17 19:42:45 +08:00
1030 changed files with 121327 additions and 42543 deletions

No files matched your search

+6
View File
@@ -1,4 +1,10 @@
DEEPSEEK_API_KEY=sk-your-key-here
DEEPSEEK_BASE_URL=https://api.deepseek.com
# DEEPSEEK_API_BASE_URL is accepted as an alias of DEEPSEEK_BASE_URL.
REASONIX_LOG_LEVEL=INFO
REASONIX_TRANSCRIPT_DIR=./transcripts
# Optional Telegram remote channel
# TELEGRAM_BOT_TOKEN=123456:botfather-token
# TELEGRAM_OWNER_USER_ID=123456789
# TELEGRAM_ALLOWLIST=123456789,987654321
+2
View File
@@ -1 +1,3 @@
github: esengine
custom:
- https://paypal.me/yuhuahui
Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

+14 -25
View File
@@ -33,6 +33,9 @@ jobs:
- name: Typecheck
run: npm run typecheck
- name: Build (tsup + dashboard)
run: npm run build
- name: Test (vitest + coverage)
run: npm run test:coverage
@@ -40,9 +43,6 @@ jobs:
if: always()
run: node scripts/coverage-summary.mjs
- name: Build (tsup)
run: npm run build
# Smoke-test the bench harnesses themselves. --dry skips all LLM
# calls, so this catches wiring regressions (task factories, CLI
# parsing, file IO, checker determinism) without needing a
@@ -51,25 +51,14 @@ jobs:
- name: τ-bench harness dry-run
run: npx tsx benchmarks/tau-bench/runner.ts --dry --out "${{ runner.temp }}/tau-dry.json"
rust:
name: rust (ubuntu-latest)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Rust (stable)
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Cargo cache
uses: Swatinem/rust-cache@v2
- name: rustfmt
run: cargo fmt --all -- --check
- name: clippy
run: cargo clippy --all-targets -- -D warnings
- name: cargo test
run: cargo test --manifest-path Cargo.toml
- name: Notify Discord on main failure
if: failure() && github.event_name == 'push' && github.ref == 'refs/heads/main'
shell: bash
env:
WEBHOOK_URL: ${{ secrets.DISCORD_CI_WEBHOOK }}
run: |
test -n "$WEBHOOK_URL" || { echo "DISCORD_CI_WEBHOOK unset, skipping"; exit 0; }
RUN_URL="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
curl -sS -X POST -H "Content-Type: application/json" \
-d "{\"content\":\"❌ CI failed on \`${{ github.ref_name }}\` (${{ matrix.os }}) — ${{ github.actor }}\n${RUN_URL}\"}" \
"$WEBHOOK_URL"
+63
View File
@@ -0,0 +1,63 @@
name: Publish dsnix
# Tag namespace: `dsnix-v<semver>` triggers npm publish for the
# dsnix shim package only. Plain `v<semver>` tags publish the main
# `reasonix` CLI (see publish-npm.yml); the two are decoupled so the
# alias can be released independently when the shim itself changes.
on:
push:
tags: ["dsnix-v*"]
workflow_dispatch:
inputs:
tag:
description: "Tag to publish (e.g. dsnix-v0.48.0). Required when running manually."
required: true
type: string
permissions:
contents: read
id-token: write
jobs:
publish:
name: publish dsnix to npm
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.tag || github.ref }}
- name: Setup Node 22
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
registry-url: https://registry.npmjs.org/
- name: Verify tag matches packages/dsnix/package.json version
shell: bash
run: |
tag="${{ github.event.inputs.tag || github.ref_name }}"
tag_version="${tag#dsnix-v}"
pkg_version=$(node -p "require('./packages/dsnix/package.json').version")
if [ "$tag_version" != "$pkg_version" ]; then
echo "::error::tag $tag (version $tag_version) does not match packages/dsnix/package.json version $pkg_version"
exit 1
fi
echo "tag $tag matches packages/dsnix/package.json $pkg_version"
- name: Verify reasonix@<version> is already published on npm
shell: bash
run: |
dep_version=$(node -p "require('./packages/dsnix/package.json').dependencies.reasonix")
if ! npm view "reasonix@${dep_version}" version >/dev/null 2>&1; then
echo "::error::dsnix depends on reasonix@${dep_version} but that version is not published yet"
exit 1
fi
echo "reasonix@${dep_version} is published — safe to publish dsnix"
- name: Publish dsnix to npm
run: npm publish --access public
working-directory: packages/dsnix
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+66
View File
@@ -0,0 +1,66 @@
name: Publish npm
# Tag namespace: plain `v<semver>` triggers npm publish for the
# reasonix CLI package. Desktop Tauri releases use `desktop-v*`
# (see release.yml) — pushing one of those never reaches this
# workflow, so the two release tracks are fully decoupled.
on:
push:
tags: ["v*"]
workflow_dispatch:
inputs:
tag:
description: "Tag to publish (e.g. v0.47.0). Required when running manually."
required: true
type: string
permissions:
contents: read
# `id-token: write` is the npm provenance handshake — harmless if we
# don't enable provenance, required if we ever do.
id-token: write
jobs:
publish:
name: publish to npm
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
# workflow_dispatch lets a maintainer publish an older tag
# without re-pushing it; tag pushes already point HEAD at the
# right ref so the fallback is a no-op.
ref: ${{ github.event.inputs.tag || github.ref }}
- name: Setup Node 22
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
registry-url: https://registry.npmjs.org/
# Fail-fast if someone tags without bumping package.json. npm itself
# would reject the duplicate publish, but the error there is
# opaque ("403 You cannot publish over the previously published
# versions") and CI is the place to catch it cleanly.
- name: Verify tag matches package.json version
shell: bash
run: |
tag="${{ github.event.inputs.tag || github.ref_name }}"
tag_version="${tag#v}"
pkg_version=$(node -p "require('./package.json').version")
if [ "$tag_version" != "$pkg_version" ]; then
echo "::error::tag $tag (version $tag_version) does not match package.json version $pkg_version"
exit 1
fi
echo "tag $tag matches package.json $pkg_version"
- name: Install dependencies
run: npm ci
# `npm publish` runs the prepublishOnly hook (lint + typecheck +
# test + build) automatically, so no separate verify step here.
- name: Publish to npm
run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+29
View File
@@ -41,6 +41,35 @@ jobs:
-R "${{ github.repository }}" \
-D assets
# Rewrite bundle URLs inside latest.json (Tauri updater manifest)
# so the desktop pulls bundles from R2, not GitHub. Without this the
# updater fetches the small JSON from R2 but still downloads the
# heavy installer from github.com — defeating the mirror.
# No-op when latest.json is absent (CLI-only releases).
- name: Rewrite latest.json URLs → R2
if: env.HAS_R2 == 'true'
env:
R2_PUBLIC_BASE: https://pub-147fb53b9c1e4bbf891a257968619ea7.r2.dev
TAG: ${{ steps.tag.outputs.name }}
run: |
file=assets/latest.json
if [ ! -f "$file" ]; then
echo "no latest.json in release — skipping rewrite"
exit 0
fi
# GitHub URLs look like:
# https://github.com/<owner>/<repo>/releases/download/<TAG>/<file>
# Rewrite to:
# <R2_PUBLIC_BASE>/<TAG>/<file>
jq --arg base "$R2_PUBLIC_BASE" --arg tag "$TAG" '
.platforms |= with_entries(
.value.url |= sub("https://github.com/[^/]+/[^/]+/releases/download/[^/]+/"; "\($base)/\($tag)/")
)
' "$file" > "$file.new"
mv "$file.new" "$file"
echo "rewrote latest.json:"
cat "$file"
- name: Configure AWS CLI for R2
if: env.HAS_R2 == 'true'
run: |
-161
View File
@@ -1,161 +0,0 @@
name: Release render binaries
on:
push:
tags: ["v*"]
workflow_dispatch:
inputs:
tag:
description: "Tag to publish (e.g. v0.44.0). Required when running manually."
required: true
type: string
permissions:
contents: read
id-token: write
jobs:
build:
name: build (${{ matrix.target.label }})
strategy:
fail-fast: false
matrix:
target:
- { label: "win32-x64", rust: "x86_64-pc-windows-msvc", os: "windows-latest", bin: "reasonix-render.exe" }
- { label: "linux-x64", rust: "x86_64-unknown-linux-gnu", os: "ubuntu-22.04", bin: "reasonix-render" }
- { label: "linux-arm64", rust: "aarch64-unknown-linux-gnu", os: "ubuntu-22.04", bin: "reasonix-render", cross: true }
# darwin-x64 cross-built from Apple Silicon — GH's macos-13 Intel pool was retired
# in 2025 and queues run to hours. rustc on macos-14 supports x86_64-apple-darwin
# natively via the `targets:` install; no codesign or runtime needed at build time.
- { label: "darwin-x64", rust: "x86_64-apple-darwin", os: "macos-14", bin: "reasonix-render" }
- { label: "darwin-arm64", rust: "aarch64-apple-darwin", os: "macos-14", bin: "reasonix-render" }
runs-on: ${{ matrix.target.os }}
steps:
- uses: actions/checkout@v4
- name: Setup Rust (${{ matrix.target.rust }})
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target.rust }}
- name: Install cross-compile linker (linux-arm64 only)
if: matrix.target.label == 'linux-arm64'
run: |
sudo apt-get update
sudo apt-get install -y gcc-aarch64-linux-gnu
- name: Rust cache
uses: Swatinem/rust-cache@v2
with:
key: render-${{ matrix.target.label }}
- name: Build reasonix-render
env:
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
run: cargo build --release --target ${{ matrix.target.rust }} --bin reasonix-render
- name: Stage subpackage binary
shell: bash
run: |
mkdir -p subpackages/render-${{ matrix.target.label }}/bin
cp target/${{ matrix.target.rust }}/release/${{ matrix.target.bin }} subpackages/render-${{ matrix.target.label }}/bin/${{ matrix.target.bin }}
- name: Upload subpackage artifact
uses: actions/upload-artifact@v4
with:
name: subpackage-${{ matrix.target.label }}
path: subpackages/render-${{ matrix.target.label }}/
if-no-files-found: error
retention-days: 7
publish:
name: publish
needs: build
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Resolve tag
id: tag
shell: bash
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
raw="${{ inputs.tag }}"
else
raw="${GITHUB_REF_NAME}"
fi
# Strip leading v so npm sees a clean SemVer.
version="${raw#v}"
echo "version=${version}" >> "$GITHUB_OUTPUT"
# Prereleases (0.44.0-rc.1, 0.44.0-beta.2, ...) ship under
# dist-tag 'next' so `npx reasonix@latest` keeps pointing at
# the most recent stable. Stable versions get 'latest' (npm's
# default — leave the flag empty).
if [[ "$version" == *-* ]]; then
echo "dist_tag=next" >> "$GITHUB_OUTPUT"
else
echo "dist_tag=latest" >> "$GITHUB_OUTPUT"
fi
- name: Setup Node 22
uses: actions/setup-node@v4
with:
node-version: "22"
registry-url: "https://registry.npmjs.org"
- name: Install dependencies
run: npm ci
- name: Sync subpackage + optionalDependencies versions to tag
run: node scripts/sync-render-versions.mjs ${{ steps.tag.outputs.version }}
- name: Verify versions are in sync
run: node scripts/sync-render-versions.mjs --check
- name: Download all subpackage artifacts
uses: actions/download-artifact@v4
with:
path: artifacts/
- name: Stage subpackage binaries back into tree
shell: bash
run: |
for d in artifacts/subpackage-*; do
label="${d#artifacts/subpackage-}"
mkdir -p subpackages/render-${label}/bin
cp -r "$d"/bin/* subpackages/render-${label}/bin/
done
# actions/download-artifact@v4 strips Unix file modes — restore +x
# on the non-Windows binaries so users hitting them via spawn() (not
# via npm's bin symlink) don't EACCES. The bin field in each
# subpackage's package.json is a second layer for the normal
# install path.
for bin in subpackages/render-{linux,darwin}-*/bin/reasonix-render; do
[ -f "$bin" ] && chmod +x "$bin"
done
ls -la subpackages/*/bin/
- name: Build main package dist/
run: npm run build
- name: Publish subpackages
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
shell: bash
run: |
set -e
for d in subpackages/render-*; do
echo "↑ publishing $d under dist-tag ${{ steps.tag.outputs.dist_tag }}"
(cd "$d" && npm publish --access public --provenance --tag ${{ steps.tag.outputs.dist_tag }} --ignore-scripts)
done
- name: Publish main reasonix package
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# --ignore-scripts: the explicit `npm run build` step above already
# produces dist/, and CI's build job already ran the full test +
# typecheck + lint matrix on every push. Re-running prepublishOnly's
# entire pipeline here just doubles latency and re-exposes us to
# flaky tests (ink stdout rendering, etc.) that have nothing to do
# with publishability.
run: npm publish --access public --provenance --tag ${{ steps.tag.outputs.dist_tag }} --ignore-scripts
+43 -9
View File
@@ -1,12 +1,16 @@
name: Release
name: Release desktop
# Tag namespace: `desktop-v<semver>` triggers desktop Tauri bundles.
# Plain `v<semver>` tags are reserved for the npm CLI release (see
# publish-npm.yml) — they intentionally do NOT trigger this workflow.
# Bump the desktop with: `git tag desktop-vX.Y.Z && git push origin desktop-vX.Y.Z`.
on:
push:
tags: ["v*"]
tags: ["desktop-v*"]
workflow_dispatch:
inputs:
tag:
description: "Tag to publish (e.g. v0.40.0). Required when running manually."
description: "Tag to publish (e.g. desktop-v0.47.0). Required when running manually."
required: true
type: string
@@ -20,13 +24,11 @@ jobs:
fail-fast: false
matrix:
target:
# `rust` is the comma-separated list installed by dtolnay/rust-toolchain;
# `tauri` is what we pass to `cargo tauri build --target`. They differ
# only for the universal Mac shard, which produces one fat binary from
# two real Rust targets via lipo. Intel-only macos-13 runner is dropped
# — GH retired most of that pool, queue waits ran to hours.
# macOS now ships two single-arch shards so Apple Silicon and Intel
# users get separate DMGs. `rust` and `tauri` stay aligned per shard.
- { os: ubuntu-22.04, label: "linux-x64", rust: "x86_64-unknown-linux-gnu", tauri: "x86_64-unknown-linux-gnu" }
- { os: macos-14, label: "macos-universal", rust: "aarch64-apple-darwin,x86_64-apple-darwin", tauri: "universal-apple-darwin" }
- { os: macos-15-intel, label: "macos-x64", rust: "x86_64-apple-darwin", tauri: "x86_64-apple-darwin" }
- { os: macos-14, label: "macos-arm64", rust: "aarch64-apple-darwin", tauri: "aarch64-apple-darwin" }
- { os: windows-latest, label: "windows-x64", rust: "x86_64-pc-windows-msvc", tauri: "x86_64-pc-windows-msvc" }
runs-on: ${{ matrix.target.os }}
# secrets.* isn't accessible from step-level if:, so expose presence as a
@@ -92,6 +94,28 @@ jobs:
working-directory: desktop
run: npm run bundle:node
- name: Verify bundled Node matches host arch (macOS)
if: startsWith(matrix.target.os, 'macos-')
working-directory: desktop
run: |
expected_arch=$(uname -m)
archs=$(lipo -archs src-tauri/binaries/node)
echo "node archs: $archs"
echo "expected arch: $expected_arch"
if [ "$archs" != "$expected_arch" ]; then
echo "Expected $expected_arch Node, got: $archs" >&2
exit 1
fi
codesign -d --entitlements :- src-tauri/binaries/node 2>&1 | grep -q "com.apple.security.inherit"
- name: Build & verify desktop frontend
working-directory: desktop
shell: bash
run: |
npm run build
test -f dist/index.html
ls dist/assets/*.js >/dev/null
# tauri-action signs OS bundles whenever the corresponding env vars are
# defined — including when they're defined to the empty string, which is
# what `secrets.UNSET` evaluates to. Gate each signing block on its
@@ -151,3 +175,13 @@ jobs:
releaseDraft: true
prerelease: false
args: --target ${{ matrix.target.tauri }}
- name: Verify app Node inherits TCC grants (macOS)
if: startsWith(matrix.target.os, 'macos-')
working-directory: desktop
shell: bash
run: |
node_bin=$(find src-tauri/target -path '*/release/bundle/macos/*.app/Contents/Resources/node' -type f | head -n 1)
test -n "$node_bin"
codesign -vvv --strict "$node_bin"
codesign -d --entitlements :- "$node_bin" 2>&1 | grep -q "com.apple.security.inherit"
+5 -3
View File
@@ -25,12 +25,15 @@ sessions/
.turbo/
# Local-only Claude Code settings — personal overrides, never committed.
.claude/settings.local.json
# Local agent notes — personal workflow reminders, never committed.
agent.md
# Per-user Reasonix state under .reasonix/ — committable team-level
# files (settings.json, skills/) stay tracked, but the user-private
# bits (semantic index, sessions, opt-out markers) never should.
.reasonix/semantic/
.reasonix/sessions/
.reasonix/semantic-skip
.reasonix/truncated-results/
# Scratch entry regenerated each time scripts/bundle-codemirror.mjs runs.
scripts/.cm-entry.mjs
# Personal bun lockfile — project uses npm officially.
@@ -45,9 +48,8 @@ desktop/src-tauri/target/
desktop/src-tauri/gen/
desktop/src-tauri/binaries/
# Cargo build artifacts for the workspace at the repo root.
/target/
# Design mock-up reference (local, not part of repo)
.design-ref/
*.cpuprofile
.probe-snapshots/
+718
View File
@@ -3,6 +3,724 @@
All notable changes to Reasonix. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.52.0] — 2026-05-26
**Ink renderer in-tree as `@esengine/ink`.** The vendored Ink fork now
lives as a workspace package (#1847), unblocking TUI-specific
renderer tweaks (focus, IME, Static append) without forking upstream.
TUI polish lands on top: guard ASCII IME enter commits so JP/CN IME
atomic commits don't double-submit (#1874), preserve undo state across
session context switches (#1810), incremental repaint coverage
(#1873).
**Desktop — clipboard image paste.** Paste screenshots / copied images
directly into the composer (#1889); paste path hardened against
oversized + non-image clipboard payloads (#1897). Sessions exported by
other local AI apps can be imported into Reasonix (#1894).
**Desktop — JumpBar polish + drag perf.** JumpBar now highlights the
active message bar and follows the latest one as the thread grows
(#1813); dot styling pulled into a shared helper (#1892). Sidebar drag
writes CSS vars directly to the DOM with `content-visibility` on
messages (#1812) and unit-suffixes the vars to dodge a Chromium
recompute storm (#1875).
**Desktop — smaller fixes.**
- Search-engine API key UI + slash command interception (#1867)
- Mention `@` popup stays stable while filtering (#1850); split
kind/length effects in the popup (#1859)
- Update banner floats above the thread instead of pushing layout
(#1865)
- `memoryDetail` / `onReadMemory` wired through test fixtures so the
desktop memory browser is exercisable in unit tests
**Config — base URL + proxy.** `DEEPSEEK_API_BASE_URL` accepted as an
env alias to the existing base-url override (#1876, #1887), and
`proxy.url` is now a first-class field in `config.json` (#1881). MCP
`initialize` no longer leaks LSP-only fields that some servers reject
(#1861).
**Providers.** Ollama usage parsing tolerates the field-name variants
recent Ollama versions emit (#1886).
**i18n.**
- Russian (`ru`) language pack added (#1879)
- German corrections — capitalization, terminology, coverage (#1878)
- `/qq` command hints + argsHint localized; English fallback for
zh-CN (#1857, #1862)
**Dashboard / UI.**
- Sync TUI and Web modal state so confirm gate doesn't desync between
surfaces (#1831, #1866)
- Highlight active plan edit mode (#1863)
- `useEditHistory` no longer re-exports undo-context through itself
(#1854)
## [0.51.0] — 2026-05-25
**First paint — session restore 4.5s → 430ms.** Progressive `<Static>`
mount streams scrollback in chunks instead of mounting the full history
synchronously (#1761). Combined with index-backed `mutateCard` + O(n)
`plan.drop` + cursor elide (#1769) and the bump to `[email protected]` (which
ships the flicker fix we'd been carrying as a patch — patch-package
machinery is gone, #1809), large session restores no longer block the
event loop on startup.
**Perf — tokenizer + markdown + search.** BPE tokenizer caches its
table + bounds per-content counts with a fast-path truncate (#1741),
so long sessions don't re-tokenize the world on every turn. CodeBlock
syntax highlight is memoized (#1743). Literal-pattern search bypasses
the regex worker entirely (#1748). Windows terminal repaint cadence is
throttled (#1750) and a BEL → ST swap on Windows stdout stops `cmd.exe`
from beeping on every render frame (#1795).
**Cross-platform robustness.**
- `EXDEV` fallback for atomic config writes on OneDrive / NTFS reparse
points (#1778) — config saves no longer fail on Windows + cloud-sync
- Apple Terminal mouse-reset crash guarded (#1764); legacy X10 mouse
reports without ESC are dropped (#1723); `ESC`-less CSI recovery is
refused when followed by typed text (#1771)
- CLI startup gates on unsupported Node versions with a clear error
instead of crashing in the middle of bootstrap (#1757)
- Desktop bundled Node inherits parent TCC grants on macOS (#1749) so
file / microphone permission prompts attach to the app, not the helper
- Crash-safe atomic rename for edit-block writes (#1721); completed
plans archive instead of persisting across sessions (#1700)
- `.devenv` and `.direnv` are skipped by glob / search / directory_tree (#1706)
**Memory — CLAUDE.md import for Claude Code migration.** Loading
`CLAUDE.md` and `~/.claude/CLAUDE.md` alongside the existing
`REASONIX.md` (#1694) lets Claude Code users carry their project /
user memory directly into Reasonix without rewriting it.
**i18n — German.** Full German (`de`) locale added (#1773) with a
follow-up correction pass (#1797).
**Desktop polish.**
- JumpBar message navigation dock (#1725, #1729)
- File-change summary card after each assistant turn (#1691)
- Self-heal stale model id; expose plan as 4th editMode (#1699)
- Restore aborted prompt drafts on relaunch (#1693)
- Recalc thread width on resize (#1789); right panel scrollbar
draggable (#1765); contain long MCP spec strings (#1736)
- Sync slash setting commands across surfaces (#1724)
- Surface desktop startup failures instead of silent exit (#1759)
**TUI polish.**
- Plan-mode `[PLAN]` / `[计划]` badge in input bar (#1742)
- Forward-delete for `Delete` key (#1735)
- IME candidate window cursor alignment (#1754)
- Coalesce prompt cursor sync to reduce flicker (#1768)
- Demote stuck `running` plan step on turn end (#1784)
- Hide `max` effort on non-DeepSeek endpoints (#1798)
- Drop stale "press Cmd-C to copy" startup hint (#1692)
**Dashboard / web mode.**
- Bootstrap mcp / skills / memory panels in web mode (#1775)
- Expose new memory browser to web (#1779)
- Replay active modal on SSE connect so confirm gate isn't stuck (#1770)
- Restore scroll and memory visibility (#1766)
- Docs responsive spacing polish (#1785)
**Smaller fixes.**
- Preserve full tool results when truncated (#1615)
- Trim long-session retained payloads to bound memory growth (#1799)
- Drain steer queue on `/new` + `/cwd` so prior intent doesn't leak (#1774)
- Suppress DeepSeek-specific 5xx hints when host isn't DeepSeek (#1716)
- `normalizeSemanticEmbeddingUserConfig` preserves `timeoutMs` (#1788)
- `REASONIX_ACP_SYSTEM_APPEND` env var for system-prompt injection (#1737)
- Configurable cost-display currency with click-to-toggle (#1710)
**Refactors / internals.**
- Extract `LruCache` + `TtlLruCache` + `lazy()` helpers from ad-hoc
duplicates (#1746)
- Split stream aggregator + chunked dispatch out of `step()` (#1739)
- Per-component render trace gated by `REASONIX_TRACE_RENDERS` (#1747);
`readStats` API on render trace + real-numbers large-session probe (#1751)
## [0.50.1] — 2026-05-24
**Install fix — `postinstall` no longer crashes on `npx`.** The
`postinstall` hook added in 0.50.0 (#1584) ran `npm ci` inside
`dashboard/` and `desktop/` to set up the dev workspace, but those
directories aren't shipped in the published tarball. Result: `npx
reasonix@0.50.0 code` failed during install with a `dashboard/package.json
not found` error and the CLI never started. `postinstall` now delegates
to `scripts/postinstall.mjs`, which exits 0 when `dashboard/package.json`
is missing (i.e. anywhere except a git checkout). 0.50.0 is deprecated
on npm.
## [0.50.0] — 2026-05-24
**Desktop dashboard — unified on the CLI-hosted React surface.** The
old Tauri+Preact dashboard inside the desktop bundle is gone (#1418).
Desktop now embeds the same CLI-hosted dashboard the browser surface
already uses, so there's one React app rendering chat across all
three surfaces (CLI, browser, desktop) instead of two divergent
implementations drifting apart. Cuts the duplicate rendering paths
that caused tool cards, code blocks, and compacted history to look
subtly different depending on where you opened the same session.
**Presets — flash/pro are the only knobs now.** The preset abstraction
is removed (#1657, #1630): config now exposes `model` + `effort`
directly instead of indirecting through `preset: auto | flash | pro`.
The `/pro` switch is dropped too — flash and pro remain as direct
model selections. Per-skill flash/pro override lands with a Settings
UI (#1632) so subagents can opt into a heavier model without
reconfiguring the parent.
**Cumulative usage stats — persisted + auto-restored.** Session token
totals and accumulated cost now write to the session meta on each
turn and reload on startup (#1667, #1680 follow-up). Cost telemetry
survives a CLI restart or desktop relaunch instead of resetting to
zero, and the context-size readout shows the current window, not the
all-time cumulative cache count (#1643). `SessionStats` caps at 200
turns with cost carryover so long-lived sessions don't unbound (#1628).
**Plans — `editMode="plan"` enforced at the dispatch gate.** Plan
mode now blocks write tools at the `ToolRegistry` dispatch layer
(#1681), not as a per-tool soft check. Plan steps also advance
correctly when intermediate actions are skipped (#1629), so the
"current step" indicator no longer stalls on a step the model already
completed.
**Context — fold once at turn start.** The pre-flight fold pass is
gone — context folding now happens once at the start of each turn
instead of being threaded through mid-turn checks (#1642, #1646). The
obsolete byte-ceiling check is dropped too. Compacted history renders
as a single collapsible card on all three surfaces (#1649), so the
fold is visible without dominating the scrollback.
**Desktop polish.**
- Draggable sidebar resize + responsive conversation panel width (#1688)
- Responsive sidebar collapse on narrow windows (#1585)
- Copy/edit overlay, message-history navigation, IME guard, card collapse (#1645)
- `Esc` closes the open modal instead of aborting the model turn (#1685)
- QQ turn routing isolated by tab so cross-tab messages don't bleed (#1672)
- Discard explicitly aborted turns instead of replaying them on resume (#1687)
- Render `edit_file` / `multi_edit` results as DiffCard, matching CLI (#1662)
- Code-block syntax highlighting follows light/dark theme (#1655)
- System events surface as a show/hide toggle (#1654, #1650)
- File paths + completion feedback surface in tool results (#1644)
- Block right-click context menu in release builds (#1641)
- Preserve code operators when rendering inline code (#1640)
- Compact composer default preserved across relaunches (#1594)
- Stale events no longer corrupt UI after a session switch (#1582)
- macOS bundled Node inherits parent TCC grants so file/microphone
permission prompts attach to the desktop app, not the helper (#1614)
- New `dashboard.enabled` config to suppress auto-start when the
dashboard isn't wanted (#1612)
- Localize edit approval/discard messages + event errors with zh-CN (#1617)
**Dashboard polish.**
- Persistent active-session URL — shareable + refresh-safe (#1586,
#1589, #1599)
- Code-block syntax highlighting follows light/dark theme (#1664)
- IME confirm-enter no longer submits mid-composition (#1689)
- Code-fence language detection fix mirrored from desktop (#1677, #1661)
- Heavy vendor libs split into separate chunks for faster cold load (#1587)
- Tool cards no longer stuck spinning when the turn ends without an
explicit completion event (#1676)
- Markdown tables get a horizontal scrollbar instead of overflowing
the chat column (#1562)
- Search-engine switcher restored in dashboard + desktop settings (#1618)
- Composer queue-count label was reading the wrong variable name (#1674)
- Long file paths stop stretching the chat bubble width (#1590)
- Don't synthesize `$turn_complete` from per-iter `assistant_final` —
let the real completion event fire (#1673)
**TUI.**
- New `Alt+S` hotkey stashes the current input buffer and recalls it
later, like a one-slot clipboard for the composer
- Static history is isolated from input re-renders, so typing during
a model turn doesn't repaint the whole scrollback (#1635)
- Legacy mouse reports (X10) are dropped so terminals that emit them
by default no longer flood the input stream (#1637, #1648)
- `multi_edit` is gated in review mode to match the single-edit
approval flow (#1647)
- Shell command failure output is surfaced to the user instead of
silently truncated (#1608)
**Diff rendering — CJK column-border alignment.** `SplitDiff` no
longer misaligns the column border when CJK characters appear in
either side of the diff (#1686). The width math now accounts for
double-width graphemes when laying out the gutter.
**Subagents — per-skill model override.** Each named skill
(`/explore`, `/research`, `/review`, `/security-review`) can now
override flash/pro independently (#1632), with a Settings UI to
manage the overrides. Defaults flow from the parent session.
**MCP.**
- Workspace roots are passed to MCP servers on connect (#1625), so
servers that scope by root see the right project
- `codeCommand` honors the full `normalizeMcpConfig` pipeline including
inline `mcpServers` blocks (#1603, follow-up to #1568)
**Config.**
- `(baseUrl, apiKey)` is resolved as a tuple instead of two
independent fields (#1658), so a partial override on one no longer
silently falls through to the env value of the other
- Stale model IDs self-heal on load; v3 IDs are dropped from the
picker fallback list (#1663)
- Theme rename follow-up from #1666 closes out the prompt-input + user
card token migration (#1678, #1666, #1623)
**Memory.** `JobRegistry` self-cleans entries for completed jobs
(#1620), so long sessions don't accumulate dead job records that
never release their references.
**Other.**
- `chore(loop)` drop redundant abort warning, keep only the synthetic
final event (#1659)
- `chore(theme)` finish theme rename follow-up after #1666 (#1678)
- `chore(ui)` drop redundant `overflow-wrap` from inherited
descendants (#1675)
- `fix(presets)` drop stale "5/31 discount" framing in pro cost copy
(#1583)
- `chore(install)` include desktop deps in root postinstall (#1584)
- `test(lifecycle)` cover deterministic policy corpus + npm package
aliases (#1574, #1621)
## [0.49.0] — 2026-05-22
**TUI — Static-history renderer.** The history pane is now rendered
exclusively through Ink's `<Static>` (#1529, stages 1–4). The previous
virtual-viewport machinery — viewport-budget row allocator, byte-virtual
frame layer, manual scroll math — is gone. Net: less code on the hot
path, no more "frame drift" on very long sessions, and the rewrite stays
Ink-native instead of fighting it. Behind `REASONIX_STATIC_HISTORY` at
stage 1, default-on by stage 2, scaffolding removed by stage 4.
**Chat — queued mid-turn steers.** Typing while the model is mid-turn
no longer fights the live render or drops the keystroke. New input
queues, surfaces a small "queued" hint, and feeds into the next user
turn cleanly (#1501). Pairs with the static-history switch so the
queued line stays visible across re-renders.
**Web search — Bing default, dashboard engine switcher.** Default web
backend switches from Mojeek to Bing (#1558); the dashboard gains a
visible engine switcher so you can flip between configured backends
without editing config. Mojeek is dropped from the bundled set entirely
in this release.
**Plans — lifecycle evidence summaries.** Plan acceptance now surfaces
the evidence captured at each lifecycle step (#1500), so the "why this
plan is ready to accept" question has a structured answer instead of
implicit trust. Builds on the strict-lifecycle observability that
landed in 0.48.1.
**Desktop — approval + completion notifications.** Native OS
notifications for approval prompts and turn-complete events (#1519),
so a long-running turn can land in the background and still surface.
Uses `tauri-plugin-notification`.
**i18n — CLI command output.** `/mcp`, `/sessions`, `/prune`, `/theme`
output is now translated (#1524), closing the remaining English-only
gap in CLI command surfaces. Approval-prompt confirm titles and action
labels also get zh-CN (#1560/#1561).
**Security.**
- `web_fetch` now blocks SSRF — private/loopback/link-local targets are
rejected at the boundary (#1544)
- Edit snapshots can no longer read outside the workspace (#1454)
- Shell redirects (`>`, `>>`, `<`) are constrained to the sandbox
boundary (#1457)
- New Task integrity guardrail catches objective simplification — i.e.
the model trying to redefine a hard requirement away (#1516)
**Tools.** `run_command` description now actively discourages
shell-based file edits in favor of the structured `edit` tool (#1514).
A per-turn dispatch-rate limit lands for tool calls (#1356), keeping
runaway loops from burning a quota slice in one turn.
**TUI polish.**
- `Ctrl+Enter` now inserts a newline (#1513) — matching how every
modern composer treats the modifier
- `mouseWheelRows` config knob tunes scroll velocity per terminal
(#1511) so trackpad vs. wheel mouse don't fight the default
- `@mention` file search is restricted to the current directory prefix
(#1548) so the picker doesn't dump the whole repo
- Paste-sentinel label no longer claims `^O` expands the paste — the
shortcut never existed (#1517)
**Context.** Pinned-constraint blocks are now preserved across context
folds (#1515) and the fold tail captures all of them, not just the last
(#1552). Memory constraints survive the fold instead of silently
dropping out under pressure.
**Client.**
- DeepSeek 429s are translated into an actionable "concurrency limit
hit" hint instead of a raw HTTP error (#1526)
- `timeoutMs` is now wired to `fetch` when the caller passes an
`AbortSignal` (#1535) — previously the timeout was silently ignored
- `--no-proxy` / `REASONIX_NO_PROXY` opt-out is honored for the
DeepSeek direct-route default (#1507)
**Files.** Read/edit/restore now preserve the source file's encoding
(GB18030, UTF-8 BOM, etc.) instead of normalizing to UTF-8 on write
(#1518). Important for CJK Windows projects.
**Web/Dashboard.**
- Path-access approval modal is bridged to the dashboard (#1538) so
the browser surface can resolve the same prompts as CLI/Desktop
- `@mention` file picker popover lands in the dashboard ChatPane
(#1546), gated on attached mode (#1549)
**Config.** Atomic config writes restore the preset-write diagnostic
trace (#1555), so when a preset write goes wrong you can actually see
why.
**Refactor.** `lifecycle` extracts a standalone risk policy module
(#1557), shrinking the orchestrator and unblocking risk policy reuse
from non-lifecycle callers.
**Edit safety.** `read-before-edit` is now enforced at the dispatch
gate, not as a per-tool check (#1563) — `edit` / `multi_edit` refuse
to fire on a file the model hasn't read this session, closing the
race where a SEARCH block could match stale bytes after an external
write.
**Cache.** Fold-summary requests now reuse the live agent's system
prompt + tool list as their prefix, so the cached bytes the main
agent just paid for carry over to the summary call (#1565). Measured
on a 48.7K-token fold: 0% → 99.6% cache hit, ~89% input cost
reduction per fold.
**Other:**
- `fix(desktop)` drop `workspace:*` protocol for core-utils — desktop
isn't a workspace member
- `fix(desktop)` tsc errors blocking desktop bundle build
## [0.48.1] — 2026-05-21
**`dsnix` — short alias.** A new `dsnix` shim package lands alongside
`reasonix` (#1440), so `npx dsnix` is now equivalent to `npx reasonix`
for users who'd rather type five characters than eight. The shim is
just a forwarding binary — same CLI, same release cadence — and ships
on npm with the same version pinning (#1442). The root README documents
the alias.
**Lifecycle — observability + corpus tests.** Strict lifecycle now
surfaces step-level evidence and rail decisions through a structured
observability channel (#1426), so what the loop is doing at each step
is legible instead of inferred. Two corpus tests lock the behavior in:
multi-file refactor flow (#1427) and config-migration replay (#1473).
**Approval prompt unification.** Phase 3 of the pause-request work
(#1322) lands a single `PauseRequest` → UI data model shared by ACP,
CLI, and Desktop (#1443) — the three surfaces now render the same
prompt from the same payload instead of each translating in their own
way. Net: pause prompts stay in sync across surfaces when fields are
added.
**i18n.** Builtin skill descriptions are now translated (#1468), and
MCP error toasts + status labels carry zh-CN (#1481). The remaining
hardcoded English surface in skill picker and MCP error toasts is gone.
**Composer redesign + Ctrl+P shortcut modal.** The input area is
rebuilt with a denser layout, a clearer affordance for multi-line
input, and a Ctrl+P shortcut-help modal that lists every key binding
in one place (#1483). The desktop composer also autosizes for
multi-line input properly (#1439).
**Java tool — cheaper.** The Java source/decompile tool description
and output are pruned (#1485), shaving cached prefix tokens. Pairs with
the #1390 buffer raise from 0.48.0.
**Security.** `metaso` web-search no longer ships with a baked API
key — it now requires the user-configured key like every other backend
(#1488). Project-level hooks are trusted without an extra prompt
provided they live inside the working directory.
**YOLO mode polish.** `run_command` and `run_background` approval
gates now auto-resolve in YOLO mode (#1489) so power users don't get a
modal for every shell call after explicitly opting in.
**Perf — folding thresholds.** Normal fold threshold raised 50% → 75%,
aggressive 70% → 78% (#1461) — the loop now spends less time folding
context that didn't need to be folded.
**Preflight.** The cap that previously only counted tokens now also
gates on raw JSON body bytes (#1451), catching oversized payloads that
weren't reflected in the token count.
**Desktop.** Error cards are dismissable and recoverable variants
toned down (#1487); orphaned pause-gate modals are cleared on
`$turn_complete` so a stale gate can't block the next turn (#1484);
session titles are renameable from the sidebar (#1478); `/btw` now
echoes input, surfaces busy state, and routes through the side-question
prompt instead of silently dropping the keystroke (#1472).
**TUI.** SGR mouse mode stays on for Windows Terminal (#1486) —
alternate-scroll silently breaks the wheel there. The default for
non-WT terminals switches to alternate-scroll (`?1007h`) (#1477) to
avoid the click-eats-selection problem on conhost-class hosts.
**Other:**
- `fix(cost)` show session-aggregate cache hit so `/cost` matches the
status-bar number (#1482)
- `fix(plan)` Accept executes immediately when the plan has no open
questions instead of waiting on a non-existent answer (#1480)
- `fix` resolve root-relative edit-block paths (#1452)
- `fix(tests)` bump chat-mcp-startup timeout to 30s for Windows test
matrix (#1471)
## [0.48.0] — 2026-05-20
**Proxy-aware networking.** `NO_PROXY` is now honored end-to-end and
the DeepSeek host is baked into the default bypass whitelist so a
machine-wide `HTTPS_PROXY` no longer routes API traffic through an
unwanted proxy (#1373). A `--no-proxy` CLI flag, `REASONIX_NO_PROXY`
env, and `cfg.proxy` field give per-invocation control (#1374), and
`/doctor` surfaces the resolved `NO_PROXY` value plus the routing
decision Reasonix made for each host (#1375). If proxy behavior ever
looks wrong, `/doctor` will tell you why in one screen.
**Code intelligence boost.** Two new tree-sitter–powered tools land:
`get_symbols` and `find_in_code` cover TS/JS/Python/Go/Rust/Java
(#1387), giving Reasonix structural code navigation instead of plain
grep. Java gets a dedicated `java_source` tool that reads `.java`
sources and decompiles `.class` / inner jar entries via `javap`
(#1344), with output stripped of noise and the read buffer raised so
large classes fit in one round (#1390). Web search adds Perplexity
and Exa backends alongside the existing Mojeek / Tavily set (#1350).
**Lifecycle round two.** Checkpoints now gate mutating tools during
restore so an in-flight edit can't race a rollback (#1389), state is
preserved across plan revisions (#1388), and step evidence is
summarized at the plan card so progress is legible without expanding
each step (#1391). `/plan` is excluded from the strict-rails cache
constraint that would otherwise force a re-prefix on every revision
(#1407, #1386), and a strict end-to-end harness covers the whole
lifecycle path (#1424).
**Subagent UX.** Long-running `explore` / `research` / `review` are
now top-level slash commands with live byte-progress in the status
row instead of a frozen spinner (#1422). The agent loop is hardened:
`_turnAbort` resets in `finally` so a consumer break can't lock the
session (#1421), ambiguous search-replace edit blocks are rejected
instead of silently miss-applying (#1414), repeated gate rejections
no longer ping-pong (#1392), and FS tools walk `.reasonix/` so user
skills are reachable from any subdir (#1371).
**Desktop.** QQ sessions are now usable from the desktop app — the
QQ Adapter routes events through the same RPC bridge as CLI tabs
(#1334). Custom font support + file-link rendering improvements ship
(#1376). Reliability fixes: `rpc_spawn` is idempotent and a
`desktop_resync` rehydrate path recovers cleanly after a renderer
reload (#1428); F5 / Ctrl+R are swallowed in packaged builds so a
stray refresh can't wipe the chat (#1430); React error #31 with
non-string MCP config items is fixed (#1394); the context-token
meter syncs after `/compact` (#1399); the cost meter and session
cost card apply USD→CNY conversion (#1369); `augmentProcessPath()`
lost in the #1334 rebase is restored (#1361); desktop stdout partial
writes are handled (#1405); `/btw` on empty payload now surfaces a
usage hint instead of dropping the keystroke (#1383).
**TUI / UI.** `/about` is a new slash command showing version,
website, GitHub, and license (#1434). Remaining hardcoded strings in
edit history and MCP browse are now i18n'd (#1433). Reasoning,
streaming, and diff content beyond the recent window are elided so
long sessions don't tank scroll perf (#1432). Wheel scroll is less
sensitive and per-card stdout resize listeners collapse to one (#1423);
terminal mouse tracking now has a CLI opt-out for users on
mouse-hostile terminals (#1345).
**Settings / config.** `config.json` with a UTF-8 BOM is tolerated
instead of crashing the loader (#1431); preset-trace diagnostic
retired (#1431). The dashboard can now clear `baseUrl` to fall back
to the bundled default (#1425). `string[]` config fields are
sanitized at the `readConfig` boundary so a malformed entry can't
propagate into the running session (#1396).
**Other:**
- `fix(test)` switch vitest to forks pool to stop heap OOM on
many-core hosts (#1408)
- `chore(shell)` trim `run_command` param description (saves 119
tokens of cached prefix) (#1403)
- `chore(scripts)` measure per-tool token cost end-to-end (#1402)
- `test(tools)` close dispatch-level E2E gaps for shell jobs, web,
and scaffold (#1400)
- `test(shell-tools)` raise `run_background` dispatch test timeout
to 15s (#1406)
- `test(web)` cover Perplexity + Exa backends (#1366)
- `docs(qq)` add desktop quick start and trim README surface (#1401)
## [0.47.2] — 2026-05-19
**Hotfix — `npx reasonix@latest` install.** `0.47.1` shipped with
`@reasonix/core-utils` listed under runtime `dependencies` as
`workspace:*`. Because the workspace package is `private: true`,
`npm publish` did not rewrite the protocol, so consumers hit
`EUNSUPPORTEDPROTOCOL: Unsupported URL Type "workspace:"` during
install. The bundled `dist/` already inlines core-utils at build
time, so the dependency belongs under `devDependencies`. Moved.
`0.47.1` is deprecated on npm; please install `0.47.2`.
## [0.47.1] — 2026-05-19
**Desktop shakeout.** Follow-ups to the 0.47.0 desktop launch:
inherit login-shell `PATH` so `nvm`/`asdf`/`fnm`-installed Node is
visible to `run_command` (#1331); stop claiming "Connected" on the QQ
settings page since the desktop is config-editor-only, not a live
bridge (#1326); re-enable devtools + right-click context menu in
release builds; route the in-app update check through the updater
plugin so CSP doesn't block it (#1298); prevent the browser-level
Select-All when the composer isn't focused (#1314); add unified
`button:disabled` style; ship selectable theme styles (#1291); a few
follow-up bug fixes from the release.
**Prompt budget — round one.** `codeSystemPrompt` compressed -51%
(~3.1k tokens/request, #1323) and tool spec descriptions -28% (~2.7k
tokens/request, #1321), with a byte-budget regression test locked in
(#1320). The cache-prefix shrinks accordingly — cheaper first turn,
same behavior.
**TUI / shell-exec.** Per-call shell-exec approval flow now surfaces
on the first run instead of failing silently (#1278); spinner +
stream tick rate dropped on legacy Windows conhost; light-theme
picker rows highlight on selection (#1330); `//` line-comment input
no longer parses as a slash command (#1288).
**Other:**
- `feat(core-utils)` new `@reasonix/core-utils` workspace package —
Phase 1 internal split, no public-API change (#1328)
- `feat(lifecycle)` opt-in engineering lifecycle (#1306)
- `feat(tools)` ordered interceptor chain (#1301)
- `feat(plan)` persist step evidence metadata (#1302)
- `feat(read_file)` lower outline threshold 512 KiB → 64 KiB (#1324)
- `fix(multi_edit)` roll back files that may have been modified on
write failure (#1325)
- `fix(permissions)` strip literal `*` from always-allow prefix in
Desktop/ACP (#1312)
- `fix(client)` skip `extra_body` for Azure endpoints (#1316)
- `fix(search)` honor `tavily` engine + read engine at call time
- `fix(cli)` resolve heap reexec entrypoint (#1303)
- `fix(docs)` point download mirrors at `desktop-v*` tag namespace
## [0.47.0] — 2026-05-18
**Desktop matures.** The Tauri app picks up the polish it was missing —
About modal with one-click update check, KaTeX math rendering in chat,
window/tab/session/scroll restore across relaunch, /compact /retry /btw
/feedback slash commands, per-message copy + file-export actions, QQ
settings entry, platform-aware keyboard shortcut hints. The auto-updater
now reads `latest.json` from the R2 mirror so an npm-only `v*` release
can no longer brick the in-app update banner; the banner also surfaces
download progress while the bundle pulls. Universal Node is bundled on
macOS so Intel Macs stop blank-screening at launch.
**TUI — composer round two.** Composer keys and visuals re-align with
Claude Code: rounded border, status row at the bottom, input-box
background fill, left stripe on user card. `ctrl+r` toggles verbose
(reasoning + raw tool I/O); `esc-esc` opens a rewind picker over the
last 5s; `u` undo is now gated to the same 5s window so stale taps
can't revert. SGR mouse wheel is on by default again, IME cursor stays
glued to `▌`, WelcomeBanner centers vertically on empty chats.
**Search hardening.** Regex now runs in a worker thread so a ReDoS
pattern can be terminated cleanly; worker deadline 5s → 60s and walk
deadline 15s → 120s for legitimately large repos. Tavily added as a
`web_search` backend — escape hatch when Mojeek 403s. `search_content`
gets a walk-level deadline and ESC preempts queued tool calls.
**Claude-ecosystem compat.** Reasonix now reads `.mcp.json` and
`.claude/skills/` from the repo so existing Claude Code setups work
without a second copy; common skill fields (`type`/`context`/`agent`)
are aliased.
**Other:**
- `feat(embedding)` batch OpenAI-compat embedding requests to respect
provider batch limits
- `feat(memory)` inject ancestor `AGENTS.md` into `list_directory`,
not only `read_file`
- `perf(session)` skip cross-workspace jsonls + byte-scan line count
— sidebar list ~10× faster
- `feat(config)` support pricing overrides and per-model rpm limits
- `feat(dashboard)` new / switch / delete sessions in-place, no CLI
bounce
- `fix(mcp)` runtime schema validation for MCP server responses; ESC
aborts hung handshakes during startup; surface the real bridge-
failure reason in the dashboard
- `fix(cli)` preserve flash-preset auto-escalate semantics
- `ci` split desktop + npm releases into separate tag namespaces:
`v*` → npm, `desktop-v*` → Tauri bundles
## [0.46.0] — 2026-05-17
**Breaking — Rust renderer removed.** Reasonix is back to a pure Ink/Node
TUI. The `reasonix-render` ratatui crate, the five
`@reasonix/render-{platform}-{arch}` optional sub-packages, the NAPI
loader (`src/cli/ui/scene/`), and the `--node` opt-out flag are all
gone. Cross-terminal compat issues (Termux #1149 / #1026, mac eager-spawn
chain, Windows alt-screen handoff, integrated-mode keyboard collisions)
disappear with them — at the cost of the streaming/animation perf the
rust renderer was supposed to buy us.
Notes for users:
- `REASONIX_RENDERER`, `REASONIX_RENDER_BIN`, `REASONIX_RENDER_CMD`,
`REASONIX_INPUT_CMD`, `REASONIX_RENDERER_INTEGRATED` env vars are no-ops
— drop them from your shell config.
- `--node` flag is no-op (and unrecognized; will error). Just drop it.
- `--no-alt-screen` / `--no-mouse` flags also gone — Ink defaults take
over end-to-end.
- `npm install [email protected]` no longer pulls a per-platform binary —
one dep tree on every OS, no optional resolution step.
**TUI overhaul** — same pass that removed the rust path also cleared
the Ink-side workarounds we'd accumulated on top of it:
- Card primitive drops the left `▎` stripe; cards are plain column
boxes with a top margin
- CardHeader drops the colored pill background behind titles
- Single consistent glyph vocabulary: `●` running, `✓` done, `✗`
failed, `⊘` aborted, `○` queued, `⚠` warn, `⎿` child row, `█`/`░`
bars, braille spinner
- Composer wrapped in a rounded border box; status row moved to the
bottom; on narrow terminals status pills wrap to a new line instead
of being truncated away (#1149)
- `/dashboard` URL surfaces as a startup info row (was easy to miss)
- `/copy` permanently in the startup hint list — vim-style copy mode
was undiscoverable before
## [0.44.2-rc.2] — 2026-05-17
**Fix:** macOS hang on `npx reasonix@next code` — keep-alive interval
from rc.1 prevented Node from exiting, but the rust child was never
actually spawned. Root cause: spawn was triggered by a React
`useEffect` (`useSceneTrace` → `emitSceneMessage` → `trace.ts`
`ensureInitialized`), and that effect simply never fired in some
macOS npx contexts. Node sat alive with the keep-alive holding the
event loop open, nothing on screen, no rust process.
Fix: spawn rust eagerly in `chat.tsx` via new
`ensureSceneTraceReady()` export, after `setIntegratedEventHandler` so
the integrated event callback is wired before spawn. Also:
- `renderer-process.ts` synthesizes an `exit` event when the rust child
dies on its own (panic / SIGKILL / terminal close) so the integrated
event handler tears Node down instead of hanging forever.
- `trace.ts` now logs a clear warning to stderr when `resolveRenderer`
returns no usable command, instead of bailing silently — anyone
hitting "TUI never appears" can find the cause in
`~/.reasonix/rust-render-stderr.log`.
## [0.44.2-rc.1] — 2026-05-17
**Fix:** macOS `npx reasonix code` (default rust + integrated TUI) exited
back to the shell prompt immediately without rendering. Root cause:
`makeNullStdin` / `makeNullStdout` are pure-JS Node streams with no
underlying libuv handles, so they don't keep the event loop alive. The
rust trace child is spawned by a React `useEffect` (via `useSceneTrace`
→ `emitSceneMessage`) — that effect is enqueued microseconds AFTER
`render()` returns, but on macOS the event loop sees no active handles
in that window and exits before the effect runs. Linux/Windows happen
to keep the loop alive via other handles in the boot path; macOS
doesn't.
Defensive `setInterval(()=>{}, 0x7fffffff)` keep-alive held for the
lifetime of `waitUntilExit()` and cleared in `finally`. Same renderer
binary as 0.44.0; only chat.tsx changed.
## [0.44.1] — 2026-05-17
**Fix:** Mac/Linux `npx reasonix@latest` failed with `EACCES` when spawning
Generated
-2187
View File
File diff suppressed because it is too large. Load diff
-9
View File
@@ -1,9 +0,0 @@
[workspace]
members = ["crates/reasonix-render"]
exclude = ["desktop"]
resolver = "2"
[workspace.package]
edition = "2021"
license = "MIT"
publish = false
+339
View File
@@ -0,0 +1,339 @@
<p align="center">
<img src="docs/logo.svg" alt="Reasonix" width="640"/>
</p>
> [!WARNING]
> **これはレガシーの TypeScript 系列(Reasonix 0.x)で、メンテナンスのみです。**
> 開発は **Go 版の書き直し** に移行しました —— 新しいデフォルトの [`main-v2`](https://github.com/esengine/DeepSeek-Reasonix/tree/main-v2) ブランチと[移行ガイド](https://github.com/esengine/DeepSeek-Reasonix/blob/main-v2/docs/MIGRATING.md)を参照してください。ここではバグ修正のみ反映されます。
<p align="center">
<a href="./README.md">English</a>
&nbsp;·&nbsp;
<a href="./README.zh-CN.md">简体中文</a>
&nbsp;·&nbsp;
<strong>日本語</strong>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/">公式サイト</a>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/configuration.html">ガイド</a>
&nbsp;·&nbsp;
<a href="./docs/ARCHITECTURE.md">アーキテクチャ</a>
&nbsp;·&nbsp;
<a href="./benchmarks/">ベンチマーク</a>
&nbsp;·&nbsp;
<strong><a href="https://discord.gg/XF78rEME2D">Discord</a></strong>
</p>
<p align="center">
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/v/reasonix.svg?style=flat-square&color=cb3837&labelColor=161b22&logo=npm&logoColor=white" alt="npm version"/></a>
<a href="https://github.com/esengine/reasonix/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/esengine/reasonix/ci.yml?style=flat-square&label=ci&labelColor=161b22&logo=githubactions&logoColor=white" alt="CI"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/reasonix.svg?style=flat-square&color=8b949e&labelColor=161b22" alt="license"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg?style=flat-square&color=3fb950&labelColor=161b22&label=downloads" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg?style=flat-square&color=5fa04e&labelColor=161b22&logo=nodedotjs&logoColor=white" alt="node"/></a>
<a href="https://github.com/esengine/reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/reasonix.svg?style=flat-square&color=dbab09&labelColor=161b22&logo=github&logoColor=white" alt="GitHub stars"/></a>
<a href="https://atomgit.com/esengine/DeepSeek-Reasonix"><img src="https://atomgit.com/esengine/DeepSeek-Reasonix/star/badge.svg" alt="AtomGit stars"/></a>
<a href="https://github.com/esengine/reasonix/graphs/contributors"><img src="https://img.shields.io/github/contributors/esengine/reasonix.svg?style=flat-square&color=bc8cff&labelColor=161b22&logo=github&logoColor=white" alt="contributors"/></a>
<a href="https://github.com/esengine/reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/reasonix.svg?style=flat-square&color=58a6ff&labelColor=161b22&logo=github&logoColor=white" alt="Discussions"/></a>
<a href="https://discord.gg/XF78rEME2D"><img src="https://img.shields.io/badge/discord-join-5865F2.svg?style=flat-square&labelColor=161b22&logo=discord&logoColor=white" alt="Discord"/></a>
</p>
<p align="center">
<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>
<p align="center">プレフィックスキャッシュの安定性を中心に設計されているため、長時間のセッションでもトークンコストを低く保ち、動かしっぱなしにできます。</p>
<br/>
<p align="center">
<img src="docs/assets/hero-terminal.svg" alt="Reasonix code mode — assistant proposes a SEARCH/REPLACE edit; nothing on disk until /apply" width="860"/>
</p>
<br/>
> [!TIP]
> **キャッシュの安定性はオンにする「機能」ではなく、ループそのものが前提として設計された不変条件です。** これこそが Reasonix が DeepSeek 専用である理由であり、すべてのレイヤーがバイト単位で安定したプレフィックスキャッシュの仕組みに合わせて調整されています。
> [!NOTE]
> **実ユーザーの1日(2026-05-01):** 入力トークン 4億3,500万、**キャッシュヒット率 99.82%**、同じワークロードを `v4-flash` でキャッシュなしに実行した場合の約 \$61 に対して、わずか約 \$12 で済んでいます — 詳しくは[ケーススタディ](./benchmarks/real-world-cache/README.md)を参照。キャッシュ可能なバイト列を提供するのは DeepSeek ですが、それを長時間のセッションにわたってキャッシュ可能に保つのが [Pillar 1](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) の4つの仕組みです。
> [!IMPORTANT]
> **Community · 加入社区** — セットアップのヘルプ(`#help` / `#求助`)、ワークフローのショーケース、機能アイデア、コントリビューター限定の PR 調整用チャンネルを備えたバイリンガル Discord。サーバー内で GitHub を認証すると、自動的に **Contributor** ロールが付与されます。→ **<https://discord.gg/XF78rEME2D>**
<br/>
## インストール
Node ≥ 22 が必要です。macOS · Linux · Windows(PowerShell · Git Bash · Windows Terminal)で動作します。
`reasonix` コマンドを `PATH` 上で使えるようにしたい場合は、Reasonix をグローバルにインストールします:
~~~bash
npm install -g reasonix
reasonix code my-project # 初回実行時に DeepSeek API キーを貼り付け。以降は保存される
~~~
または、グローバルインストールせずに一度だけ実行することもできます:
~~~bash
cd my-project
npx reasonix code # デフォルトでは常に最新のパッケージを使用
~~~
[DeepSeek API キーを取得 →](https://platform.deepseek.com/api_keys) · フラグは `reasonix code --help` を参照。
Reasonix を毎日使うなら、グローバルインストールが最もシンプルな方法です。とりあえず試してみたいだけなら `npx` を使ってください。
**キー入力を減らしたい?** より短い `dsnix` エイリアスが同じ CLI を指します:
~~~bash
npm install -g dsnix # PATH 上に `dsnix` を公開。reasonix に依存
npx dsnix@latest code # より短いコマンドで一度だけ実行
~~~
`npm install -g reasonix` でグローバルインストールすると `dsnix` のシムも PATH 上に配置されるため、2つは相互に置き換え可能です。
サブコマンドなしの `reasonix`(裸の `reasonix`)はカレントディレクトリで `code` を起動します — `reasonix` と入力するのは `reasonix code` と等価です。
| コマンド | 用途 |
|---|---|
| `reasonix` / `reasonix code [dir]` | コーディングエージェント。**ここから始めてください。** |
| `reasonix chat` | プレーンなチャット — ファイルシステムやシェルのツールなし。 |
| `reasonix run "task"` | 一度だけ実行し、stdout にストリーミング。パイプ向き。 |
| `reasonix doctor` | ヘルスチェック: Node、API キー、MCP の配線。 |
| `reasonix update` | Reasonix 自体をアップグレード。 |
その他のサブコマンド(`replay` · `diff` · `events` · `stats` · `index` · `mcp` · `prune-sessions`)は `reasonix --help` と [CLI リファレンス](https://esengine.github.io/DeepSeek-Reasonix/#cli)にあります。
### QQ チャンネル
QQ は既存の `chat`、`code`、またはデスクトップのセッションをリモートチャンネルとして拡張できます。これは独立したランタイムモードではなく、現在のセッションフローの一部です。
- CLI: セッションを開始し、`/qq connect` を実行
- デスクトップ: `Settings -> General -> QQ Channel` を開く
接続すると、QQ のメッセージを現在のセッションに取り込み、アシスタントの返信を QQ に転送し、その後のやり取りをリモートで継続できます。
詳しいセットアップ、デスクトップのクイックスタート、トラブルシューティングは [QQ チャンネルのセットアップ](./docs/qq-connect.md)を参照してください。
### デスクトップクライアント(プレリリース)
同じループの GUI が欲しいユーザー向けのネイティブ Tauri クライアント。マルチタブ対応で、右パネルにはこのセッションでエージェントが読み取り・編集したファイルが表示され、下部には同じコスト / キャッシュ / トークンのメーターがリアルタイムで表示されます。同じ DeepSeek API キー、同じ `~/.reasonix` 設定を使い、デスクトップ版は独自の Node ランタイムを同梱するため、別途 `npm install` する必要はありません。
各プラットフォームのインストーラーは [GitHub Releases](https://github.com/esengine/DeepSeek-Reasonix/releases) からダウンロードできます。デスクトップ版は **プレリリース** として提供されます: ループとプロトコルは CLI と同じですが、UI はまだ磨き込み中で、インストーラーはまだコード署名されていません。
- **macOS** — 初回起動時に Gatekeeper に引っかかります。一度きりの対処: `xattr -dr com.apple.quarantine /Applications/Reasonix.app`(または右クリック → 開く → 確認)。
- **Windows** — SmartScreen が「不明な発行元」と警告します。**詳細情報 → 実行** をクリックしてください。
- **Linux** — `.deb` と `.AppImage` はそのまま起動でき、追加の手順は不要です。
CLI が引き続き正規のインターフェースです。CLI に入った機能はすべてデスクトップのコンポーザーからも利用できます。
<details>
<summary><strong>別のフォルダで作業する · chat と code の違い · スキルを書く</strong></summary>
**別のフォルダで作業する。** Reasonix はファイルシステムツールを起動ディレクトリにスコープします。対象を変えるには `--dir` を渡してください。セッション途中での切り替えは設計上サポートされていません(メモリのパスが古いルートと絡まってしまうため)— 一度終了して再起動してください。
~~~bash
npx reasonix code --dir /path/to/project
~~~
**`chat` と `code` の選び方。** `code` がデフォルトであり、ファイルシステム / シェルツールと SEARCH/REPLACE レビューを備えた唯一のモードです。`chat` はより軽量でツールをオフにしたシェルです — MCP は接続しつつディスクアクセスのない思考のパートナーが欲しいときに使ってください。
| 得られるもの | `code` | `chat` |
|---|---|---|
| ファイルシステムツール + `edit_file` | ✓ | — |
| SEARCH/REPLACE → `/apply` レビュー | ✓ | — |
| シェルツール(ゲート付き) | ✓ | — |
| プランモード · `/todo` · `/skill new` · `/mcp add` | ✓ | — |
| メモリ(`remember` / `recall_memory`) | プロジェクト + グローバル | グローバルのみ |
| 設定からの MCP サーバー · ウェブ検索 · `ask_choice` | ✓ | ✓ |
| コーディング用システムプロンプト | ✓ | 汎用 |
| セッションのスコープ | ディレクトリごと | 共有デフォルト |
**最初のスキルを書く。** リモートレジストリはありません — 直接書きます。ファイル(`description:` フロントマター + 本文)を編集し、`/skill list` を実行します。本文をインライン展開する代わりに分離したサブエージェントループを生成するには `runAs: subagent` を追加します。
~~~bash
/skill new my-skill # <project>/.reasonix/skills/my-skill.md
/skill new my-skill --global # プロジェクト横断で使うなら ~/.reasonix/skills
~~~
**Claude 形式のスキルも読み込まれます。** `<project>/.claude/skills/<name>/SKILL.md` と `~/.claude/skills/` が Reasonix のネイティブパスと並んで読み込まれるため、Claude 形式のスキルを出力するツールはそのまま動きます。例 — 上流アダプターなしで OpenSpec ワークフローを投入する:
~~~bash
npx openspec init --tools claude # .claude/skills/openspec-*/SKILL.md を書き出す
/skill openspec-propose <task> # その後 Reasonix から呼び出す
~~~
</details>
<br/>
## 設定
`~/.reasonix/config.json` の1つの JSON ファイルと、`<project>/.reasonix/` 配下のプロジェクトごとのオーバーライドで設定します。すべてのキー、すべてのスラッシュコマンド、スキル / メモリ / フックのオンディスク構造を網羅した完全なバイリンガルリファレンスはこちら:
> 📘 **[設定ガイド](https://esengine.github.io/DeepSeek-Reasonix/configuration.html)** · [中文](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh)
| トピック | 概要 |
|---|---|
| [MCP サーバー](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#mcp) | stdio · SSE · Streamable HTTP。1つの仕様形式が `config.json` と `--mcp` の両方で動作。 |
| [スキル](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#skills) | モデルが呼び出せる Markdown のプレイブック。`inline` または `subagent` モード。 |
| [メモリ](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#memory) | プレフィックスにピン留めされるユーザー専用の知識。`user` / `feedback` / `project` / `reference` の型。 |
| [フック](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#hooks) | ライフサイクルイベント時のシェルコマンド。`PreToolUse`(ゲート) · `PostToolUse` · `UserPromptSubmit` · `Stop`。 |
| [権限](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#permissions) | ワークスペースごとのシェル許可リスト。完全な前方一致。 |
| [ウェブ検索](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#search) | デフォルトは Mojeek。`/search-engine` でセルフホストの SearXNG や Metaso に切り替え可能。 |
| [セマンティックインデックス](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#index) | `reasonix index` — ローカルの Ollama または任意の OpenAI 互換の埋め込みエンドポイント。 |
<br/>
## Reasonix の何が違うのか
ループは3つの柱を中心に構成されています。それぞれが、汎用的なエージェントフレームワークには見えてすらいない問題を解決します — それらは別のキャッシュの仕組み向けに設計されているからです。
<sub align="center">
完全なアーキテクチャ解説はこちらから → [Pillar 1 — キャッシュファーストのループ](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) · [Pillar 2 — ツール呼び出しの修復](./docs/ARCHITECTURE.md#pillar-2--tool-call-repair) · [Pillar 3 — コスト制御](./docs/ARCHITECTURE.md#pillar-3--cost-control-v06)
</sub>
<br/>
## 機能
<p align="center">
<img src="docs/assets/feature-grid.svg" alt="Reasonix capabilities — cell-diff renderer, MCP, plan mode, permissions, dashboard, persistent sessions, hooks/skills/memory, semantic search, auto-checkpoints, /effort knob, transcript replay, event log" width="880"/>
</p>
<br/>
## 比較
| | Reasonix | Claude Code | Cursor | Aider |
|-----------------------------------|------------------|-------------------|---------------------|--------------------|
| バックエンド | DeepSeek | Anthropic | OpenAI / Anthropic | 任意(OpenRouter) |
| ライセンス | **MIT** | クローズド | クローズド | Apache 2 |
| コストプロファイル | **タスクあたり低コスト** | プレミアム | サブスク + 従量 | まちまち |
| DeepSeek プレフィックスキャッシュ | **設計込み** | 該当なし | 該当なし | 偶発的 |
| 組み込みウェブダッシュボード | あり | — | 該当なし(IDE) | — |
| 設定可能なウェブ検索エンジン | `/search-engine` | — | — | — |
| ワークスペースごとの永続セッション | あり | 一部 | 該当なし | — |
| プランモード · MCP · フック · スキル | あり | あり | あり | 一部 |
| ウェブ検索(Mojeek + SearXNG + Metaso) | あり | あり | あり | あり |
| オープンなコミュニティ開発 | あり | — | — | あり |
リアルタイムのキャッシュヒット率、コスト、手法については [`benchmarks/`](./benchmarks/) を参照してください — 数値はモデルの料金とともに変動するため、README ではなくハーネスとともに置いています。
<br/>
## ドキュメント
- [**アーキテクチャ**](./docs/ARCHITECTURE.md) — 3つの柱: キャッシュファーストのループ、ツール呼び出しの修復、コスト制御
- [**CLI リファレンス**](./docs/CLI-REFERENCE.md) — すべてのシェルサブコマンド、すべてのスラッシュコマンド、すべてのキーバインド
- [**QQ チャンネルのセットアップ**](./docs/qq-connect.md) — CLI の初回接続フロー、デスクトップのエントリ、QQ Open Platform の認証情報
- [**ベンチマーク**](./benchmarks/) — τ-bench-lite ハーネス、トランスクリプト、コスト算出手法
- [**公式サイト**](https://esengine.github.io/DeepSeek-Reasonix/) — はじめに、ダッシュボードのモックアップ、TUI のモックアップ
- [**コントリビューション**](./CONTRIBUTING.md) — コメントポリシー、エラーハンドリングのルール、自作よりライブラリを優先
- [**行動規範**](./CODE_OF_CONDUCT.md) · [**セキュリティポリシー**](./SECURITY.md)
<br/>
## コミュニティ
> [!NOTE]
> Reasonix はオープンソースであり、コミュニティによって開発されています。このファイル末尾の謝辞ウォールにあるすべてのアバターは、実際にマージされた PR です。
スコープが切られた入門用チケット — それぞれ背景、コードの参照ポイント、受け入れ基準、ヒント付き — は [`good first issue`](https://github.com/esengine/reasonix/labels/good%20first%20issue) ラベルの下にあります。オープンなものなら何でも選んでください。
**オープンな Discussions — 意見募集中:**
- [#20 · CLI / TUI デザイン](https://github.com/esengine/reasonix/discussions/20) — 何が壊れていて、何が足りず、何を変えますか?
- [#21 · ダッシュボードデザイン](https://github.com/esengine/reasonix/discussions/21) — [提案中のモックアップ](https://esengine.github.io/DeepSeek-Reasonix/design/agent-dashboard.html)への反応をどうぞ
- [#22 · 今後の機能ウィッシュリスト](https://github.com/esengine/reasonix/discussions/22) — 次に Reasonix に組み込みたいものは?
**すでに Reasonix を使っていて、他の人に広める手伝いをしてもいい?** ブログ記事、記事、スクリーンショット、講演、動画を [**Show and tell**](https://github.com/esengine/reasonix/discussions/categories/show-and-tell) に公開してください。このプロジェクトにはマーケティング予算がありません — 新しいユーザーは口コミで見つけてくれます。継続的に応援してくれる人は、以下のバッジを獲得でき、付与されるとコントリビューターウォールの横に表示されます:
<p align="center">
<a href="https://github.com/esengine/reasonix/discussions/categories/show-and-tell">
<img src="https://img.shields.io/badge/REASONIX-📣%20ADVOCATE-c4b5fd?style=for-the-badge&labelColor=0d1117" alt="Reasonix Advocate badge — earned by sustained advocates"/>
</a>
</p>
**最初の PR の前に**: [`CONTRIBUTING.md`](./CONTRIBUTING.md) を読んでください — 短く厳格なルール(コメント、エラー、自作よりライブラリを優先)。`tests/comment-policy.test.ts` がコメントのルールを強制します。`npm run verify` がプッシュ前のゲートです。参加することで [行動規範](./CODE_OF_CONDUCT.md) に同意したものとみなされます。セキュリティの問題は → [SECURITY.md](./SECURITY.md)。
<br/>
## 非目標
> [!IMPORTANT]
> Reasonix には明確な方針があります。あえて *やらない* ことがいくつかあります — あなたの作業に合ったツールを選べるよう、ここに挙げておきます。
- **マルチプロバイダーの柔軟性。** あえて DeepSeek 専用にしています。1つのバックエンドに密結合していることは制限ではなく機能です。
- **IDE 統合。** ターミナルファースト。差分は `git diff` に、ファイルツリーは `ls` にあります。ダッシュボードはあくまで補助であり、Cursor の代替ではありません。
- **最難関リーダーボードの推論。** Claude Opus はいまだに一部のベンチマークで勝っています。DeepSeek はコーディングで競争力がありますが、もしあなたの作業が「この認証バグを直す」ではなく「この博士課程レベルの証明を解く」ものなら、Claude から始めてください。
- **エアギャップ / 完全無料。** Reasonix には有料の DeepSeek API キーが必要です。エアギャップ環境やゼロコストでの実行には Aider + Ollama または [Continue](https://continue.dev) を参照してください。
<br/>
## スター履歴
<a href="https://www.star-history.com/?repos=esengine%2FDeepSeek-Reasonix&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=esengine/DeepSeek-Reasonix&type=date&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=esengine/DeepSeek-Reasonix&type=date&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=esengine/DeepSeek-Reasonix&type=date&legend=top-left" />
</picture>
</a>
<br/>
## サポート
Reasonix が役に立って、お礼を言いたいと思ったらどうぞ。これはあくまでコーヒー一杯であって契約ではありません — 寄付で機能の優先順位が買えるわけでも、issue のトリアージのされ方が変わるわけでもありません。
- **International** — PayPal: [paypal.me/yuhuahui](https://paypal.me/yuhuahui)
- **国内** — 微信支付(扫码)
<p align="center">
<img src=".github/sponsor/wechat-pay.jpg" alt="WeChat Pay QR code" width="240"/>
</p>
<br/>
## 謝辞
Reasonix を最も形づくってくれた人々の小さなリストです — コミット数とコード量の両方で測っています。**重要度の順位付けはなく、アルファベット順に記載しています。** 完全なコントリビューターグラフは
[GitHub](https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors) にあります。
- [**ctharvey**](https://github.com/ctharvey)
- [**dimasd-angga**](https://github.com/dimasd-angga) (Dimas D. Angga)
- [**Evan-Pycraft**](https://github.com/Evan-Pycraft)
- [**ForeverYoungPp**](https://github.com/ForeverYoungPp)
- [**GTC2080**](https://github.com/GTC2080) (TaoMu)
- [**kabaka9527**](https://github.com/kabaka9527)
- [**lisniuse**](https://github.com/lisniuse) (Richie)
- [**wade19990814-hue**](https://github.com/wade19990814-hue)
- [**wviana**](https://github.com/wviana) (Wesley Viana)
また、プロジェクトのロゴをデザインしてくれた [**Bernardxu123**](https://github.com/Bernardxu123)([`docs/brand/`](./docs/brand/) を参照)と、小紅書(XiaoHongShu)でプロジェクトを宣伝してくれた [AIGC Link](https://xhslink.com/m/80ngts127cA) にも別途感謝します。
<p align="center">
<a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/DeepSeek-Reasonix&max=100&columns=12" alt="Contributors to esengine/DeepSeek-Reasonix" width="860"/>
</a>
</p>
<br/>
---
<p align="center">
<sub>MIT — <a href="./LICENSE">LICENSE</a> を参照</sub>
<br/>
<sub><a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors">esengine/DeepSeek-Reasonix</a> のコミュニティによって構築</sub>
</p>
+82 -42
View File
@@ -2,11 +2,18 @@
<img src="docs/logo.svg" alt="Reasonix" width="640"/>
</p>
> [!WARNING]
> **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.
<p align="center">
<strong>English</strong>
&nbsp;·&nbsp;
<a href="./README.zh-CN.md">简体中文</a>
&nbsp;·&nbsp;
<a href="./README.ja-JP.md">日本語</a>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/">Website</a>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/configuration.html">Guide</a>
@@ -14,6 +21,8 @@
<a href="./docs/ARCHITECTURE.md">Architecture</a>
&nbsp;·&nbsp;
<a href="./benchmarks/">Benchmarks</a>
&nbsp;·&nbsp;
<strong><a href="https://discord.gg/XF78rEME2D">Discord</a></strong>
</p>
<p align="center">
@@ -23,8 +32,10 @@
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg?style=flat-square&color=3fb950&labelColor=161b22&label=downloads" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg?style=flat-square&color=5fa04e&labelColor=161b22&logo=nodedotjs&logoColor=white" alt="node"/></a>
<a href="https://github.com/esengine/reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/reasonix.svg?style=flat-square&color=dbab09&labelColor=161b22&logo=github&logoColor=white" alt="GitHub stars"/></a>
<a href="https://atomgit.com/esengine/DeepSeek-Reasonix"><img src="https://atomgit.com/esengine/DeepSeek-Reasonix/star/badge.svg" alt="AtomGit stars"/></a>
<a href="https://github.com/esengine/reasonix/graphs/contributors"><img src="https://img.shields.io/github/contributors/esengine/reasonix.svg?style=flat-square&color=bc8cff&labelColor=161b22&logo=github&logoColor=white" alt="contributors"/></a>
<a href="https://github.com/esengine/reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/reasonix.svg?style=flat-square&color=58a6ff&labelColor=161b22&logo=github&logoColor=white" alt="Discussions"/></a>
<a href="https://discord.gg/XF78rEME2D"><img src="https://img.shields.io/badge/discord-join-5865F2.svg?style=flat-square&labelColor=161b22&logo=discord&logoColor=white" alt="Discord"/></a>
</p>
<p align="center">
@@ -52,6 +63,9 @@
> [!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.
> [!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
@@ -76,6 +90,15 @@ Grab a [DeepSeek API key →](https://platform.deepseek.com/api_keys) · `reason
If you use Reasonix daily, global install is the simplest path. If you just want to try it, use `npx`.
**Prefer fewer keystrokes?** The shorter `dsnix` alias resolves to the same CLI:
~~~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 |
@@ -86,43 +109,19 @@ Bare `reasonix` (no subcommand) launches `code` in the current directory — typ
| `reasonix doctor` | Health check: Node, API key, MCP wiring. |
| `reasonix update` | Upgrade Reasonix itself. |
### Terminal renderer (Rust by default)
Since 0.44.0, Reasonix ships a native ratatui renderer (`reasonix-render`) as the default TUI. `npm install` resolves one of five pre-built `@reasonix/render-{platform}-{arch}` sub-packages via `optionalDependencies` so install is zero-config on **win32-x64 · linux-x64 · linux-arm64 · darwin-x64 · darwin-arm64**. No cargo, no toolchain, nothing extra to fetch.
- Want the old Ink/Node TUI back? Pass `--node` to any subcommand (`reasonix --node`, `reasonix code --node`, `reasonix chat --node`) or set `REASONIX_RENDERER=node` in your shell.
- Running on a platform without a published sub-package (Linux musl, FreeBSD, ARM v7, etc.)? Reasonix prints a one-line warning and auto-falls-back to the Ink renderer — nothing breaks.
- Building rust from source? `cargo build --release --bin reasonix-render` inside the repo; the dev flow (`npm run dev`) does this automatically. The resolver also accepts `REASONIX_RENDER_BIN=/path/to/binary` to pin a specific build for testing.
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).
### QQ channel
Reasonix can attach QQ as a remote communication channel for existing `chat` and `code` sessions. It is not a separate runtime mode.
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.
Start a session first:
- CLI: start a session, then run `/qq connect`
- Desktop: open `Settings -> General -> QQ Channel`
~~~bash
reasonix code
# or
reasonix chat
~~~
Once connected, QQ messages can enter the current session, assistant replies route back to QQ, and follow-up interactions can continue remotely.
Then connect QQ from inside the session:
For full setup, desktop quick start, and troubleshooting, see [QQ channel setup](./docs/qq-connect.md).
~~~text
/qq connect
~~~
Available commands:
- `/qq connect`
- `/qq status`
- `/qq disconnect`
Once enabled, later `chat` / `code` sessions auto-start the QQ channel. Slash commands, confirmation prompts, and follow-up assistant replies can continue through QQ without terminal-side input.
See [QQ channel setup](./docs/qq-connect.md) for setup details and QQ Open Platform bot registration.
### 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.
@@ -164,6 +163,13 @@ npx reasonix code --dir /path/to/project
/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/>
@@ -181,7 +187,7 @@ One JSON file at `~/.reasonix/config.json` plus per-project overrides under `<pr
| [Memory](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#memory) | User-private knowledge pinned into the prefix. `user` / `feedback` / `project` / `reference` types. |
| [Hooks](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#hooks) | Shell commands on lifecycle events. `PreToolUse` (gating) · `PostToolUse` · `UserPromptSubmit` · `Stop`. |
| [Permissions](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#permissions) | Per-workspace shell allowlist. Exact-prefix match. |
| [Web search](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#search) | Mojeek by default; switch to self-hosted SearXNG or Metaso with `/search-engine`. |
| [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/>
@@ -218,7 +224,7 @@ Click through to the full architecture writeup → [Pillar 1 — Cache-first loo
| Configurable web search engine | `/search-engine` | — | — | — |
| Persistent per-workspace sessions | yes | partial | n/a | — |
| Plan mode · MCP · hooks · skills | yes | yes | yes | partial |
| Web search (Mojeek + SearXNG + Metaso) | yes | yes | yes | yes |
| 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.
@@ -229,7 +235,7 @@ For live cache-hit rates, costs, and methodology, see [`benchmarks/`](./benchmar
- [**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) — what it is, commands, setup flow, and QQ Open Platform credentials
- [**QQ channel setup**](./docs/qq-connect.md) — CLI first-connect flow, desktop entry, and QQ Open Platform credentials
- [**Benchmarks**](./benchmarks/) — τ-bench-lite harness, transcripts, cost methodology
- [**Website**](https://esengine.github.io/DeepSeek-Reasonix/) — getting started, dashboard mockup, TUI mockup
- [**Contributing**](./CONTRIBUTING.md) — comment policy, error-handling rules, library-over-hand-rolled
@@ -240,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.
@@ -260,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).
<p align="center">
<a href="https://github.com/esengine/reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/DeepSeek-Reasonix&max=100&columns=12" alt="Contributors to esengine/DeepSeek-Reasonix" width="860"/>
</a>
</p>
<br/>
## Non-goals
@@ -292,12 +292,52 @@ Scoped starter tickets — each with background, code pointers, acceptance crite
<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.
- **International** — PayPal: [paypal.me/yuhuahui](https://paypal.me/yuhuahui)
- **国内** — 微信支付(扫码)
<p align="center">
<img src=".github/sponsor/wechat-pay.jpg" alt="WeChat Pay QR code" width="240"/>
</p>
<br/>
## Acknowledgments
A small list of folks whose work has shaped Reasonix the most — measured
by both commit count and code volume. **Listed alphabetically, no ordering
of importance.** The full contributor graph is on
[GitHub](https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors).
- [**ctharvey**](https://github.com/ctharvey)
- [**dimasd-angga**](https://github.com/dimasd-angga) (Dimas D. Angga)
- [**Evan-Pycraft**](https://github.com/Evan-Pycraft)
- [**ForeverYoungPp**](https://github.com/ForeverYoungPp)
- [**GTC2080**](https://github.com/GTC2080) (TaoMu)
- [**kabaka9527**](https://github.com/kabaka9527)
- [**lisniuse**](https://github.com/lisniuse) (Richie)
- [**wade19990814-hue**](https://github.com/wade19990814-hue)
- [**wviana**](https://github.com/wviana) (Wesley Viana)
Also a separate thank-you to [**Bernardxu123**](https://github.com/Bernardxu123)
for designing the project logo (see [`docs/brand/`](./docs/brand/)), and to
[AIGC Link](https://xhslink.com/m/80ngts127cA) for promoting the project on XiaoHongShu.
<p align="center">
<a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/DeepSeek-Reasonix&max=100&columns=12" alt="Contributors to esengine/DeepSeek-Reasonix" width="860"/>
</a>
</p>
<br/>
---
<p align="center">
<sub>MIT — see <a href="./LICENSE">LICENSE</a></sub>
<br/>
<sub>Built by the community at <a href="https://github.com/esengine/reasonix/graphs/contributors">esengine/reasonix</a></sub>
<br/>
<sub>Special thanks to <a href="https://xhslink.com/m/80ngts127cA">AIGC Link</a> for the promotions on XiaoHongShu.</sub>
<sub>Built by the community at <a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors">esengine/DeepSeek-Reasonix</a></sub>
</p>
+63 -31
View File
@@ -2,11 +2,18 @@
<img src="docs/logo.svg" alt="Reasonix" width="640"/>
</p>
> [!WARNING]
> **这是 legacy TypeScript 线(Reasonix 0.x),仅维护。**
> 开发已转移到 **Go 重写版** —— 见 [`main-v2`](https://github.com/esengine/DeepSeek-Reasonix/tree/main-v2) 分支(新的默认分支)与[迁移指南](https://github.com/esengine/DeepSeek-Reasonix/blob/main-v2/docs/MIGRATING.md)。此处仅修复 bug。
<p align="center">
<a href="./README.md">English</a>
&nbsp;·&nbsp;
<strong>简体中文</strong>
&nbsp;·&nbsp;
<a href="./README.ja-JP.md">日本語</a>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/">官方网站</a>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh">配置指南</a>
@@ -14,6 +21,8 @@
<a href="./docs/ARCHITECTURE.md">架构文档</a>
&nbsp;·&nbsp;
<a href="./benchmarks/">基准测试</a>
&nbsp;·&nbsp;
<strong><a href="https://discord.gg/XF78rEME2D">Discord</a></strong>
</p>
<p align="center">
@@ -23,8 +32,10 @@
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg?style=flat-square&color=3fb950&labelColor=161b22&label=downloads" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg?style=flat-square&color=5fa04e&labelColor=161b22&logo=nodedotjs&logoColor=white" alt="node"/></a>
<a href="https://github.com/esengine/reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/reasonix.svg?style=flat-square&color=dbab09&labelColor=161b22&logo=github&logoColor=white" alt="GitHub stars"/></a>
<a href="https://atomgit.com/esengine/DeepSeek-Reasonix"><img src="https://atomgit.com/esengine/DeepSeek-Reasonix/star/badge.svg" alt="AtomGit stars"/></a>
<a href="https://github.com/esengine/reasonix/graphs/contributors"><img src="https://img.shields.io/github/contributors/esengine/reasonix.svg?style=flat-square&color=bc8cff&labelColor=161b22&logo=github&logoColor=white" alt="contributors"/></a>
<a href="https://github.com/esengine/reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/reasonix.svg?style=flat-square&color=58a6ff&labelColor=161b22&logo=github&logoColor=white" alt="Discussions"/></a>
<a href="https://discord.gg/XF78rEME2D"><img src="https://img.shields.io/badge/discord-join-5865F2.svg?style=flat-square&labelColor=161b22&logo=discord&logoColor=white" alt="Discord"/></a>
</p>
<p align="center">
@@ -49,6 +60,9 @@
> [!TIP]
> **缓存稳定不是开关,而是循环要围绕设计的不变量。** 这就是 Reasonix 只支持 DeepSeek 的根本原因 —— 每一层都为 DeepSeek 字节稳定的前缀缓存机制调过。
> [!IMPORTANT]
> **加入社区 · Community** — 中英双语 Discord,频道包括 `#求助` / `#help`、`#分享` / `#showcase`、`#想法反馈`、贡献者专属 PR 协调区。在群内绑定 GitHub 后自动识别贡献者身份。→ **<https://discord.gg/XF78rEME2D>**
<br/>
## 安装
@@ -74,31 +88,15 @@ npx reasonix code # 首次运行粘贴 DeepSeek API Key,之后会记住
### QQ 通道
Reasonix 可以把 QQ 挂到现有的 `chat` / `code` 会话上,作为远程通信通道使用。它不是一个独立的新模式。
Reasonix 可以把现有的 `chat`、`code` 或桌面端会话延伸到 QQ 上,作为远程通道使用;它扩展的是当前会话,不是独立的新运行模式。
先启动一个会话:
- CLI:先启动会话,再执行 `/qq connect`
- 桌面端:打开 `设置 -> 通用 -> QQ通道`
~~~bash
reasonix code
# 或
reasonix chat
~~~
连接成功后,QQ 消息可以进入当前会话,助手回复会回到 QQ,后续确认和跟进交互也可以继续在 QQ 上完成。
然后在会话里连接 QQ:
完整配置、桌面端快速上手与排障说明见:[QQ 连接指南](./docs/qq-connect.zh-CN.md)。
~~~text
/qq connect
~~~
可用命令:
- `/qq connect`
- `/qq status`
- `/qq disconnect`
启用后,后续的 `chat` / `code` 会话会自动启动 QQ 通道。斜杠命令、确认提示,以及后续助手回复都可以通过 QQ 继续完成,不需要回到终端交互。
详细说明见 [QQ 连接指南](./docs/qq-connect.zh-CN.md)。
<details>
<summary><strong>切换工作区 · chat vs. code · 写第一个 Skill</strong></summary>
@@ -145,7 +143,7 @@ npx reasonix code --dir /path/to/project
| [Memory](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh#memory) | 用户私有的知识,钉进前缀。`user` / `feedback` / `project` / `reference` 四类。 |
| [Hooks](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh#hooks) | 生命周期事件触发的 shell 命令。`PreToolUse`(拦截)· `PostToolUse` · `UserPromptSubmit` · `Stop`。 |
| [权限](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh#permissions) | 按工作区的 shell 白名单,精确前缀匹配。 |
| [Web 搜索](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh#search) | 默认 Mojeek;用 `/search-engine` 可切到自托管的 SearXNG 或 Metaso。 |
| [Web 搜索](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh#search) | 默认 Bing;可用 `/search-engine` 切到百度 AI Search、自托管 SearXNG、Metaso、Tavily、Perplexity、Exa、Brave 或 Ollama。 |
| [语义索引](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh#index) | `reasonix index` —— 本地 Ollama,或任何 OpenAI 兼容的 embedding 接口。 |
<br/>
@@ -191,7 +189,7 @@ npx reasonix code --dir /path/to/project
- [**架构**](./docs/ARCHITECTURE.md) —— 四大支柱、缓存优先循环、思维提取、脚手架
- [**CLI 参考**](./docs/CLI-REFERENCE.md) —— 每个 shell 子命令、每个 slash 命令、每个快捷键
- [**QQ 连接指南**](./docs/qq-connect.zh-CN.md) —— 通道定位、命令、配置流程和 QQ 开放平台凭据
- [**QQ 连接指南**](./docs/qq-connect.zh-CN.md) —— CLI 首次连接流程、桌面端入口和 QQ 开放平台凭据
- [**基准测试**](./benchmarks/) —— τ-bench-lite harness、transcript、成本方法论
- [**官方网站**](https://esengine.github.io/DeepSeek-Reasonix/) —— 入门、Dashboard 设计稿、TUI 设计稿
- [**贡献指南**](./CONTRIBUTING.md) —— 注释规则、错误处理、用现成库不手写
@@ -202,7 +200,7 @@ npx reasonix code --dir /path/to/project
## 社区
> [!NOTE]
> Reasonix 是开源、社区共建的项目。下面贡献者墙不是装饰 —— 每一个头像都对应一次真实合并的 PR。
> Reasonix 是开源、社区共建的项目。文末"致谢"那面贡献者墙上的每一个头像,都对应一次真实合并的 PR。
给新手准备的入门 issue —— 每个都带背景说明、代码定位、验收标准、提示 —— 全部挂在 [`good first issue`](https://github.com/esengine/reasonix/labels/good%20first%20issue) 标签下。挑任意一个还没人认领的就行。
@@ -222,12 +220,6 @@ npx reasonix code --dir /path/to/project
**第一次提 PR 之前**:先读 [`CONTRIBUTING.md`](./CONTRIBUTING.md) —— 短小、严格的项目规则(注释、错误处理、用现成库不手写)。`tests/comment-policy.test.ts` 静态强制执行注释那部分,`npm run verify` 是 push 前的闸。参与本项目即同意 [行为准则](./CODE_OF_CONDUCT.md)。安全相关问题请走 [SECURITY.md](./SECURITY.md)。
<p align="center">
<a href="https://github.com/esengine/reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/DeepSeek-Reasonix&max=100&columns=12" alt="esengine/DeepSeek-Reasonix 贡献者" width="860"/>
</a>
</p>
<br/>
## 不做的事
@@ -254,10 +246,50 @@ npx reasonix code --dir /path/to/project
<br/>
## 支持本项目
如果 Reasonix 帮你省了时间或 token,欢迎请杯咖啡。捐助不会换来 feature 优先级,也不会影响 issue 的处理顺序——就是「谢谢」。
- **国内** — 微信支付(扫下方二维码)
- **海外** — PayPal: [paypal.me/yuhuahui](https://paypal.me/yuhuahui)
<p align="center">
<img src=".github/sponsor/wechat-pay.jpg" alt="微信支付收款码" width="240"/>
</p>
<br/>
## 致谢
下面这些朋友的工作塑造了 Reasonix 今天的样子 —— 综合 commit 数和代码量两个维度。
**按字母顺序排列,排名不分先后。** 完整贡献者列表在
[GitHub](https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors)。
- [**ctharvey**](https://github.com/ctharvey)
- [**dimasd-angga**](https://github.com/dimasd-angga)(Dimas D. Angga)
- [**Evan-Pycraft**](https://github.com/Evan-Pycraft)
- [**ForeverYoungPp**](https://github.com/ForeverYoungPp)
- [**GTC2080**](https://github.com/GTC2080)(TaoMu)
- [**kabaka9527**](https://github.com/kabaka9527)
- [**lisniuse**](https://github.com/lisniuse)(Richie)
- [**wade19990814-hue**](https://github.com/wade19990814-hue)
- [**wviana**](https://github.com/wviana)(Wesley Viana)
另外特别感谢 [**Bernardxu123**](https://github.com/Bernardxu123) 设计的项目 logo
(见 [`docs/brand/`](./docs/brand/)),以及 [AIGC Link](https://xhslink.com/m/80ngts127cA) 在小红书上的推广。
<p align="center">
<a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/DeepSeek-Reasonix&max=100&columns=12" alt="esengine/DeepSeek-Reasonix 贡献者" width="860"/>
</a>
</p>
<br/>
---
<p align="center">
<sub>MIT —— 见 <a href="./LICENSE">LICENSE</a></sub>
<br/>
<sub>由 <a href="https://github.com/esengine/reasonix/graphs/contributors">esengine/reasonix</a> 社区共建</sub>
<sub>由 <a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors">esengine/DeepSeek-Reasonix</a> 社区共建</sub>
</p>
+39
View File
@@ -0,0 +1,39 @@
/** Evaluation harness — runs scenarios and collects results. */
import type { EvalReport, EvalResult, EvalScenario } from "./types.js";
export async function runScenarios(
scenarios: EvalScenario[],
opts: {
onResult?: (r: EvalResult) => void;
} = {},
): Promise<EvalReport> {
const results: EvalResult[] = [];
for (const sc of scenarios) {
const t0 = Date.now();
let result: EvalResult;
try {
result = await sc.run();
result.durationMs = Date.now() - t0;
} catch (err) {
result = {
scenarioId: sc.id,
pass: false,
durationMs: Date.now() - t0,
details: `UNEXPECTED ERROR: ${(err as Error).message}`,
};
}
results.push(result);
opts.onResult?.(result);
}
// Dynamic import avoids bundling VERSION into the harness module.
const { VERSION } = await import("../../src/version.js");
return {
meta: {
date: new Date().toISOString(),
reasonixVersion: VERSION,
},
results,
};
}
+81
View File
@@ -0,0 +1,81 @@
/** Render behavior-stability results.json → markdown report. */
import { readFileSync, writeFileSync } from "node:fs";
import { pathToFileURL } from "node:url";
import type { EvalReport } from "./types.js";
interface CliArgs {
input: string;
outPath: string;
}
function parseArgs(argv: string[]): CliArgs {
const out: CliArgs = { input: "", outPath: "benchmarks/behavior-stability/report.md" };
const positional: string[] = [];
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "--out") out.outPath = argv[++i] ?? out.outPath;
else if (a && !a.startsWith("--")) positional.push(a);
}
out.input = positional[0] ?? "";
if (!out.input) {
throw new Error(
"usage: npx tsx benchmarks/behavior-stability/report.ts <results.json> [--out report.md]",
);
}
return out;
}
function renderHeader(report: EvalReport): string {
return `# Reasonix Behavior-Stability Evaluation
**Date:** ${report.meta.date}
**Version:** ${report.meta.reasonixVersion}
`;
}
function renderSummary(report: EvalReport): string {
const passed = report.results.filter((r) => r.pass).length;
const total = report.results.length;
const pct = total > 0 ? ((passed / total) * 100).toFixed(0) : "0";
const rows = report.results.map((r) => {
const icon = r.pass ? "✅" : "❌";
return `| ${icon} | \`${r.scenarioId}\` | ${r.durationMs}ms | ${r.details} |`;
});
return `## Summary
**${passed}/${total} passed (${pct}%)**
| status | scenario | time | details |
|---|---:|---:|:---|
${rows.join("\n")}
`;
}
function render(report: EvalReport): string {
return [renderHeader(report), renderSummary(report)].join("\n\n");
}
function isMain(): boolean {
const entry = process.argv[1];
if (!entry) return false;
return import.meta.url === pathToFileURL(entry).href;
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
const raw = readFileSync(args.input, "utf8");
const report = JSON.parse(raw) as EvalReport;
const md = render(report);
writeFileSync(args.outPath, md, "utf8");
console.log(`Wrote ${args.outPath} (${report.results.length} results)`);
}
if (isMain()) {
main().catch((err) => {
console.error(err);
process.exit(1);
});
}
+87
View File
@@ -0,0 +1,87 @@
/** CLI runner for behavior-stability evaluation. */
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
import { loadDotenv } from "../../src/index.js";
import { ALL_SCENARIOS, API_SCENARIOS, LOCAL_SCENARIOS } from "./scenarios.js";
import { runScenarios } from "./harness.js";
import type { EvalScenario } from "./types.js";
loadDotenv();
interface CliArgs {
local: boolean;
api: boolean;
outPath: string | null;
}
function parseArgs(argv: string[]): CliArgs {
const out: CliArgs = { local: false, api: false, outPath: null };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "--local") out.local = true;
else if (a === "--api") out.api = true;
else if (a === "--out") out.outPath = argv[++i] ?? null;
}
// Default to local-only when neither flag is provided.
if (!out.local && !out.api) out.local = true;
return out;
}
function pickScenarios(args: CliArgs): EvalScenario[] {
const scenarios: EvalScenario[] = [];
if (args.local) scenarios.push(...LOCAL_SCENARIOS);
if (args.api) scenarios.push(...API_SCENARIOS);
return scenarios;
}
function isMain(): boolean {
const entry = process.argv[1];
if (!entry) return false;
return import.meta.url === pathToFileURL(entry).href;
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
const scenarios = pickScenarios(args);
if (scenarios.length === 0) {
console.log("No scenarios selected. Use --local, --api, or both.");
process.exit(0);
}
const categories = new Set(scenarios.map((s) => s.category));
console.log(`Running ${scenarios.length} scenario(s) [${[...categories].join(", ")}] …\n`);
const report = await runScenarios(scenarios, {
onResult: (r) => {
const icon = r.pass ? "✅" : "❌";
console.log(`${icon} ${r.scenarioId} (${r.durationMs}ms)`);
console.log(` ${r.details}\n`);
},
});
const passed = report.results.filter((r) => r.pass).length;
const total = report.results.length;
console.log(`────────────────────────────────────────`);
console.log(`Results: ${passed}/${total} passed`);
console.log(`Version: ${report.meta.reasonixVersion}`);
console.log(`Date: ${report.meta.date}`);
if (args.outPath) {
const dir = dirname(args.outPath);
if (dir !== ".") mkdirSync(dir, { recursive: true });
writeFileSync(args.outPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
console.log(`Wrote ${args.outPath}`);
}
if (passed < total) process.exit(1);
}
if (isMain()) {
main().catch((err) => {
console.error(err);
process.exit(1);
});
}
+147
View File
@@ -0,0 +1,147 @@
/** Behavior-stability scenario for PR #1462 — constraint persistence across context folds. */
import { AppendOnlyLog, SessionStats } from "../../src/index.js";
import { ContextManager } from "../../src/context-manager.js";
import { Usage } from "../../src/client.js";
import type { EvalResult, EvalScenario } from "./types.js";
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
function withTiming(fn: () => Promise<EvalResult>): Promise<EvalResult> {
const t0 = Date.now();
return fn().then((r) => ({ ...r, durationMs: Date.now() - t0 }));
}
function pass(id: string, details: string): EvalResult {
return { scenarioId: id, pass: true, durationMs: 0, details };
}
function fail(id: string, details: string): EvalResult {
return { scenarioId: id, pass: false, durationMs: 0, details };
}
/* ------------------------------------------------------------------ */
/* Mock client — returns a fixed summary for fold testing */
/* ------------------------------------------------------------------ */
class MockDeepSeekClient {
private _replyContent: string;
constructor(replyContent: string) {
this._replyContent = replyContent;
}
async chat(): Promise<{
content: string;
reasoningContent: string;
usage: Usage;
}> {
return {
content: this._replyContent,
reasoningContent: "",
usage: new Usage(100, 50, 150, 0, 100),
};
}
}
/* ------------------------------------------------------------------ */
/* #1462 — Constraint persistence across folds (local) */
/* ------------------------------------------------------------------ */
const constraintPersistence: EvalScenario = {
id: "constraint-persistence",
name: "Context fold preserves pinned constraints from system prompt",
category: "context",
requiresApi: false,
run: () =>
withTiming(async () => {
const systemPrompt = `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.`;
const log = new AppendOnlyLog();
// Fill log with synthetic long history to trigger a fold boundary > 0.
for (let i = 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.`,
});
}
const client = new MockDeepSeekClient("Summary of all prior turns.");
const stats = new SessionStats();
const ctx = new ContextManager({
client: client as any,
log,
stats,
sessionName: null,
getAbortSignal: () => new AbortController().signal,
getCurrentTurn: () => 1,
getSystemPrompt: () => systemPrompt,
});
// Use a tiny tail budget so almost everything becomes head and gets summarized.
const result = await ctx.fold("deepseek-v4-flash", { keepRecentTokens: 200 });
if (!result.folded) {
return fail(
"constraint-persistence",
`Fold did not happen (before=${result.beforeMessages}, after=${result.afterMessages}).`,
);
}
const foldedSystem = log.toMessages()[0];
if (foldedSystem?.role !== "assistant") {
return fail(
"constraint-persistence",
`Expected first folded message to be assistant summary, got ${foldedSystem?.role}.`,
);
}
const content = foldedSystem.content as string;
const checks = [
{ text: "DO NOT use npm install without asking", label: "HIGH PRIORITY constraint" },
{ text: "Never delete files without confirmation", label: "HIGH PRIORITY constraint 2" },
{ text: "TypeScript over JavaScript", label: "User memory" },
{ text: "pnpm instead of npm", label: "Project memory" },
];
const missing = checks.filter((c) => !content.includes(c.text));
if (missing.length > 0) {
return fail(
"constraint-persistence",
`Folded summary missing ${missing.length} constraint(s): ${missing.map((m) => m.label).join(", ")}.`,
);
}
return pass(
"constraint-persistence",
`Fold reduced ${result.beforeMessages} → ${result.afterMessages} messages and preserved all ${checks.length} pinned constraints.`,
);
}),
};
/* ------------------------------------------------------------------ */
/* Exports */
/* ------------------------------------------------------------------ */
export const LOCAL_SCENARIOS: EvalScenario[] = [constraintPersistence];
export const API_SCENARIOS: EvalScenario[] = [];
export const ALL_SCENARIOS: EvalScenario[] = [...LOCAL_SCENARIOS, ...API_SCENARIOS];
+26
View File
@@ -0,0 +1,26 @@
/** Behavior-stability evaluation types — lightweight, local-first regression suite. */
export interface EvalScenario {
id: string;
name: string;
category: "shell" | "context" | "integrity";
/** True when the scenario calls the live LLM API (costs money). */
requiresApi: boolean;
run: () => Promise<EvalResult>;
}
export interface EvalResult {
scenarioId: string;
pass: boolean;
durationMs: number;
details: string;
}
export interface EvalReport {
meta: {
date: string;
reasonixVersion: string;
model?: string;
};
results: EvalResult[];
}
+1
View File
@@ -0,0 +1 @@
runs/
+165
View File
@@ -0,0 +1,165 @@
import { readFileSync, writeFileSync } from "node:fs";
import { resolvePreset } from "../../src/cli/ui/presets.js";
import { DeepSeekClient } from "../../src/client.js";
import { codeSystemPrompt } from "../../src/code/prompt.js";
import { buildCodeToolset } from "../../src/code/setup.js";
import { loadApiKey, loadBaseUrl, loadPreset } from "../../src/config.js";
import { loadDotenv } from "../../src/env.js";
import { CacheFirstLoop } from "../../src/loop.js";
import { ImmutablePrefix } from "../../src/memory/runtime.js";
import { DEEPSEEK_CONTEXT_TOKENS } from "../../src/telemetry/stats.js";
interface DriverOptions {
taskFile: string;
transcriptOut: string;
budgetUsd: number;
rootDir: string;
/** Override DEEPSEEK_CONTEXT_TOKENS to force fold triggers on short tasks. */
fakeCtxMax: number | null;
}
function parseArgs(argv: string[]): DriverOptions {
let taskFile = "";
let transcriptOut = "";
let budgetUsd = 2.0;
let rootDir = process.cwd();
let fakeCtxMax: number | null = null;
for (let i = 0; i < argv.length; i++) {
const a = argv[i]!;
if (a === "--task-file") taskFile = argv[++i]!;
else if (a === "--transcript-out") transcriptOut = argv[++i]!;
else if (a === "--budget") budgetUsd = Number(argv[++i]);
else if (a === "--root") rootDir = argv[++i]!;
else if (a === "--fake-ctxmax") fakeCtxMax = Number(argv[++i]);
}
if (!taskFile || !transcriptOut) {
console.error(
"usage: driver.ts --task-file <p> --transcript-out <p> [--budget 2] [--root <dir>] [--fake-ctxmax N]",
);
process.exit(1);
}
return { taskFile, transcriptOut, budgetUsd, rootDir, fakeCtxMax };
}
interface TurnRecord {
turn: number;
role: string;
prompt_tokens?: number;
cache_hit_tokens?: number;
cache_miss_tokens?: number;
cost_usd?: number;
tool?: string;
content_preview?: string;
}
async function main(): Promise<void> {
loadDotenv();
const opts = parseArgs(process.argv.slice(2));
const key = loadApiKey();
if (!key) {
console.error("DEEPSEEK_API_KEY missing — run `reasonix setup` first");
process.exit(1);
}
process.env.DEEPSEEK_API_KEY = key;
const presetSettings = resolvePreset(loadPreset());
const model = presetSettings.model;
if (opts.fakeCtxMax !== null && opts.fakeCtxMax > 0) {
for (const k of Object.keys(DEEPSEEK_CONTEXT_TOKENS)) {
DEEPSEEK_CONTEXT_TOKENS[k] = opts.fakeCtxMax;
}
console.log(`ctxMax override (ALL deepseek models): -> ${opts.fakeCtxMax}`);
}
console.log(`model: ${model}`);
console.log(`root: ${opts.rootDir}`);
console.log(`budget: $${opts.budgetUsd}`);
const task = readFileSync(opts.taskFile, "utf8").trim();
console.log(`task: ${task.length} chars`);
const toolset = await buildCodeToolset({ rootDir: opts.rootDir });
console.log(`tools: ${toolset.tools.specs().length} registered`);
const client = new DeepSeekClient({ baseUrl: loadBaseUrl() });
const prefix = new ImmutablePrefix({
system: codeSystemPrompt(opts.rootDir),
toolSpecs: toolset.tools.specs(),
});
const loop = new CacheFirstLoop({
client,
prefix,
tools: toolset.tools,
model,
budgetUsd: opts.budgetUsd,
});
const records: TurnRecord[] = [];
const t0 = Date.now();
let lastTurn = 0;
try {
for await (const ev of loop.step(task)) {
if (ev.role === "assistant_final" && ev.stats?.usage) {
const u = ev.stats.usage;
const rec: TurnRecord = {
turn: ev.turn,
role: "assistant_final",
prompt_tokens: u.promptTokens,
cache_hit_tokens: u.promptCacheHitTokens,
cache_miss_tokens: u.promptCacheMissTokens,
cost_usd: ev.stats.cost,
content_preview: (ev.content ?? "").slice(0, 200),
};
records.push(rec);
lastTurn = ev.turn;
const ratio = u.promptCacheHitTokens / (u.promptTokens || 1);
process.stdout.write(
` turn ${ev.turn}: pt=${u.promptTokens} hit=${(ratio * 100).toFixed(1)}% cost=$${ev.stats.cost.toFixed(4)}\n`,
);
} else if (ev.role === "tool" && ev.toolName) {
records.push({
turn: ev.turn,
role: "tool",
tool: ev.toolName,
content_preview: (ev.content ?? "").slice(0, 200),
});
} else if (ev.role === "warning" || ev.role === "status") {
const lc = (ev.content ?? "").toLowerCase();
const isFold = lc.includes("fold") || lc.includes("compact") || lc.includes("summar");
records.push({
turn: ev.turn,
role: isFold ? "fold_event" : `${ev.role}_event`,
content_preview: ev.content,
});
if (isFold) {
process.stdout.write(
` ⟳ ${ev.role.toUpperCase()} at turn ${ev.turn}: ${ev.content.slice(0, 120)}\n`,
);
}
} else if (ev.role === "error") {
records.push({ turn: ev.turn, role: "error", content_preview: ev.error });
process.stdout.write(` ✗ error turn ${ev.turn}: ${ev.error}\n`);
} else if (ev.role === "done") {
process.stdout.write(` ✓ done (turn ${ev.turn})\n`);
}
}
} catch (err) {
process.stdout.write(` ✗ loop threw: ${(err as Error).message}\n`);
}
const elapsed = Math.round((Date.now() - t0) / 1000);
const s = loop.stats.summary();
console.log(
`\nDONE turns=${lastTurn} elapsed=${elapsed}s cache=${(s.cacheHitRatio * 100).toFixed(1)}% cost=$${s.totalCostUsd.toFixed(4)}`,
);
writeFileSync(
opts.transcriptOut,
`${JSON.stringify({ _meta: { model, task_length: task.length, elapsed_s: elapsed, summary: s } })}\n${records.map((r) => JSON.stringify(r)).join("\n")}\n`,
);
console.log(`transcript: ${opts.transcriptOut}`);
}
main().catch((err) => {
console.error("driver crashed:", err);
process.exit(1);
});
+325
View File
@@ -0,0 +1,325 @@
import { spawnSync } from "node:child_process";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
interface RunSpec {
name: string;
foldThreshold: number;
aggressiveThreshold: number;
}
interface RunSummary {
name: string;
repeat: number;
turns: number;
cacheHitRatio: number;
costUsd: number;
totalInputTokens: number;
cacheHitTokens: number;
cacheMissTokens: number;
foldCount: number;
exitCode: number;
}
const RUNS: RunSpec[] = [
{ name: "no-fold", foldThreshold: 0.99, aggressiveThreshold: 0.99 },
{ name: "current_50_70", foldThreshold: 0.5, aggressiveThreshold: 0.7 },
{ name: "very_late_75_90", foldThreshold: 0.75, aggressiveThreshold: 0.9 },
{ name: "aggressive_90_95", foldThreshold: 0.9, aggressiveThreshold: 0.95 },
];
function parseArgs(argv: string[]): {
taskFile: string;
budget: number;
outDir: string;
only: string | null;
fakeCtxMax: number | null;
repeats: number;
} {
let taskFile = "";
let budget = 2.0;
let outDir = "";
let only: string | null = null;
let fakeCtxMax: number | null = null;
let repeats = 1;
for (let i = 0; i < argv.length; i++) {
const a = argv[i]!;
if (a === "--task-file") taskFile = argv[++i]!;
else if (a === "--budget") budget = Number(argv[++i]);
else if (a === "--out-dir") outDir = argv[++i]!;
else if (a === "--only") only = argv[++i]!;
else if (a === "--fake-ctxmax") fakeCtxMax = Number(argv[++i]);
else if (a === "--repeats") repeats = Number(argv[++i]);
}
if (!taskFile) {
console.error(
"usage: tsx e2e.ts --task-file <p> [--budget N] [--out-dir <p>] [--only <n>] [--fake-ctxmax N] [--repeats N]",
);
process.exit(1);
}
if (!outDir) {
const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
outDir = `benchmarks/compression-eval/runs/${ts}`;
}
return { taskFile, budget, outDir, only, fakeCtxMax, repeats };
}
function loadTranscriptSummary(path: string): Partial<RunSummary> {
let turns = 0;
let inputTokens = 0;
let cacheHit = 0;
let cacheMiss = 0;
let costUsd = 0;
let foldCount = 0;
const promptSeq: number[] = [];
try {
const lines = readFileSync(path, "utf8").split("\n");
for (const ln of lines) {
const t = ln.trim();
if (!t) continue;
let rec: {
role?: string;
prompt_tokens?: number;
cache_hit_tokens?: number;
cache_miss_tokens?: number;
cost_usd?: number;
};
try {
rec = JSON.parse(t);
} catch {
continue;
}
if (rec.role === "assistant_final") {
turns++;
const pt = rec.prompt_tokens ?? 0;
inputTokens += pt;
cacheHit += rec.cache_hit_tokens ?? 0;
cacheMiss += rec.cache_miss_tokens ?? 0;
costUsd += rec.cost_usd ?? 0;
if (pt > 0) promptSeq.push(pt);
} else if (rec.role === "fold_event") {
foldCount++;
}
}
} catch {
/* file missing — caller will see exitCode and zeros */
}
if (foldCount === 0) {
for (let i = 1; i < promptSeq.length; i++) {
if (promptSeq[i]! < promptSeq[i - 1]! * 0.6) foldCount++;
}
}
return {
turns,
totalInputTokens: inputTokens,
cacheHitTokens: cacheHit,
cacheMissTokens: cacheMiss,
cacheHitRatio: inputTokens > 0 ? cacheHit / inputTokens : 0,
costUsd,
foldCount,
};
}
function runOne(
spec: RunSpec,
task: string,
budget: number,
outDir: string,
fakeCtxMax: number | null,
repeat: number,
): RunSummary {
const runName = repeat > 1 ? `${spec.name}_r${repeat}` : spec.name;
const runDir = join(outDir, runName);
mkdirSync(runDir, { recursive: true });
const transcript = join(runDir, "transcript.jsonl");
const logPath = join(runDir, "stdout.log");
console.log(
`\n>>> [${spec.name}] fold=${spec.foldThreshold} agg=${spec.aggressiveThreshold}`,
);
const tsxCli = join("node_modules", "tsx", "dist", "cli.mjs");
const taskFilePath = join(runDir, "task.txt");
writeFileSync(taskFilePath, task);
const t0 = Date.now();
const res = spawnSync(
process.execPath,
[
tsxCli,
"benchmarks/compression-eval/driver.ts",
"--task-file",
taskFilePath,
"--transcript-out",
transcript,
"--budget",
String(budget),
...(fakeCtxMax ? ["--fake-ctxmax", String(fakeCtxMax)] : []),
],
{
env: {
...process.env,
REASONIX_FOLD_THRESHOLD: String(spec.foldThreshold),
REASONIX_FOLD_AGGRESSIVE_THRESHOLD: String(spec.aggressiveThreshold),
},
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
shell: false,
maxBuffer: 1024 * 1024 * 128,
},
);
const exitCode = res.status ?? -1;
const stdout = res.stdout ?? "";
const stderr = res.stderr ?? "";
const elapsedS = Math.round((Date.now() - t0) / 1000);
writeFileSync(logPath, `${stdout}\n--- stderr ---\n${stderr}`);
console.log(` exit=${exitCode} elapsed=${elapsedS}s log=${logPath}`);
const parsed = loadTranscriptSummary(transcript);
return {
name: spec.name,
repeat,
turns: parsed.turns ?? 0,
cacheHitRatio: parsed.cacheHitRatio ?? 0,
costUsd: parsed.costUsd ?? 0,
totalInputTokens: parsed.totalInputTokens ?? 0,
cacheHitTokens: parsed.cacheHitTokens ?? 0,
cacheMissTokens: parsed.cacheMissTokens ?? 0,
foldCount: parsed.foldCount ?? 0,
exitCode,
};
}
function pct(n: number): string {
return `${(n * 100).toFixed(1)}%`;
}
function fmtTok(n: number): string {
if (n >= 1e6) return `${(n / 1e6).toFixed(2)}M`;
if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
return String(n);
}
interface AggregateRow {
name: string;
n: number;
meanCost: number;
stdCost: number;
meanMiss: number;
stdMiss: number;
meanHitPct: number;
stdHitPct: number;
meanTurns: number;
meanFolds: number;
}
function meanStd(xs: number[]): [number, number] {
if (xs.length === 0) return [0, 0];
const m = xs.reduce((a, b) => a + b, 0) / xs.length;
const v = xs.reduce((a, b) => a + (b - m) ** 2, 0) / xs.length;
return [m, Math.sqrt(v)];
}
function aggregateByConfig(rows: RunSummary[]): AggregateRow[] {
const groups = new Map<string, RunSummary[]>();
for (const r of rows) {
if (!groups.has(r.name)) groups.set(r.name, []);
groups.get(r.name)!.push(r);
}
const result: AggregateRow[] = [];
for (const [name, group] of groups) {
const [meanCost, stdCost] = meanStd(group.map((r) => r.costUsd));
const [meanMiss, stdMiss] = meanStd(group.map((r) => r.cacheMissTokens));
const [meanHitPct, stdHitPct] = meanStd(group.map((r) => r.cacheHitRatio * 100));
const [meanTurns] = meanStd(group.map((r) => r.turns));
const [meanFolds] = meanStd(group.map((r) => r.foldCount));
result.push({
name,
n: group.length,
meanCost,
stdCost,
meanMiss,
stdMiss,
meanHitPct,
stdHitPct,
meanTurns,
meanFolds,
});
}
return result;
}
function reportAggregate(rows: AggregateRow[]): string {
const cols: Array<[string, (r: AggregateRow) => string]> = [
["config", (r) => r.name],
["n", (r) => String(r.n)],
["turns", (r) => r.meanTurns.toFixed(1)],
["folds", (r) => r.meanFolds.toFixed(1)],
["hit%", (r) => `${r.meanHitPct.toFixed(1)}±${r.stdHitPct.toFixed(1)}`],
["miss", (r) => `${fmtTok(r.meanMiss)}±${fmtTok(r.stdMiss)}`],
["cost$", (r) => `${r.meanCost.toFixed(4)}±${r.stdCost.toFixed(4)}`],
];
const widths = cols.map(([h, f]) => Math.max(h.length, ...rows.map((r) => f(r).length)));
const head = cols.map(([h], i) => h.padEnd(widths[i]!)).join("│ ");
const sep = "─".repeat(widths.reduce((a, b) => a + b + 2, 0));
const body = rows
.map((r) => cols.map(([_, f], i) => f(r).padEnd(widths[i]!)).join("│ "))
.join("\n");
return `${head}\n${sep}\n${body}`;
}
function reportTable(rows: RunSummary[]): string {
const cols: Array<[string, (r: RunSummary) => string]> = [
["config", (r) => r.name],
["turns", (r) => String(r.turns)],
["input", (r) => fmtTok(r.totalInputTokens)],
["hit", (r) => fmtTok(r.cacheHitTokens)],
["hit%", (r) => pct(r.cacheHitRatio)],
["miss", (r) => fmtTok(r.cacheMissTokens)],
["folds", (r) => String(r.foldCount)],
["cost", (r) => `$${r.costUsd.toFixed(4)}`],
["exit", (r) => String(r.exitCode)],
];
const widths = cols.map(([h, f]) => Math.max(h.length, ...rows.map((r) => f(r).length)));
const head = cols.map(([h], i) => h.padEnd(widths[i]!)).join("│ ");
const sep = "─".repeat(widths.reduce((a, b) => a + b + 2, 0));
const body = rows
.map((r) => cols.map(([_, f], i) => f(r).padEnd(widths[i]!)).join("│ "))
.join("\n");
return `${head}\n${sep}\n${body}`;
}
function main(): void {
const { taskFile, budget, outDir, only, fakeCtxMax, repeats } = parseArgs(process.argv.slice(2));
const task = readFileSync(taskFile, "utf8").trim();
mkdirSync(outDir, { recursive: true });
const specs = only ? RUNS.filter((r) => r.name === only) : RUNS;
if (specs.length === 0) {
console.error(`no config matches --only=${only}; available: ${RUNS.map((r) => r.name).join(", ")}`);
process.exit(1);
}
console.log(`task: ${taskFile} (${task.length} chars)`);
console.log(`out: ${outDir}`);
console.log(`budget per run: $${budget}`);
console.log(`configs: ${specs.map((s) => s.name).join(", ")}`);
console.log(`repeats: ${repeats}`);
if (fakeCtxMax) console.log(`fake ctxMax: ${fakeCtxMax}`);
const summaries: RunSummary[] = [];
for (let r = 1; r <= repeats; r++) {
for (const spec of specs) {
summaries.push(runOne(spec, task, budget, outDir, fakeCtxMax, r));
}
}
const table = reportTable(summaries);
console.log(`\n=== Raw runs ===\n${table}`);
if (repeats > 1) {
const agg = aggregateByConfig(summaries);
const aggTable = reportAggregate(agg);
console.log(`\n=== Aggregate (mean ± std) ===\n${aggTable}`);
writeFileSync(join(outDir, "aggregate.txt"), aggTable);
}
writeFileSync(join(outDir, "summary.json"), JSON.stringify(summaries, null, 2));
writeFileSync(join(outDir, "summary.txt"), table);
console.log(`\nsaved: ${join(outDir, "summary.json")}`);
}
main();
+89
View File
@@ -0,0 +1,89 @@
import { basename } from "node:path";
import { loadSession, simulate, type RunResult, type ThresholdConfig } from "./simulator.js";
const BASELINE: ThresholdConfig = {
ctxMax: 1_000_000,
foldThreshold: 0.5,
tailFraction: 0.2,
aggressiveThreshold: 0.7,
aggressiveTailFraction: 0.1,
minSavingsFraction: 0.3,
summaryRatio: 0.05,
};
interface NamedConfig {
name: string;
config: ThresholdConfig;
}
function configs(ctxMax: number): NamedConfig[] {
const mk = (over: Partial<ThresholdConfig>): ThresholdConfig => ({ ...BASELINE, ...over, ctxMax });
return [
{ name: "no-fold", config: mk({ foldThreshold: 999, aggressiveThreshold: 999 }) },
{ name: "current (50/70)", config: mk({ foldThreshold: 0.5, aggressiveThreshold: 0.7 }) },
{ name: "late (60/80)", config: mk({ foldThreshold: 0.6, aggressiveThreshold: 0.8 }) },
{ name: "very-late (75/90)", config: mk({ foldThreshold: 0.75, aggressiveThreshold: 0.9 }) },
{ name: "early (35/55)", config: mk({ foldThreshold: 0.35, aggressiveThreshold: 0.55 }) },
];
}
function parseArgs(argv: string[]): { sessions: string[]; ctxMax: number } {
const sessions: string[] = [];
let ctxMax = 1_000_000;
for (let i = 0; i < argv.length; i++) {
const a = argv[i]!;
if (a === "--ctx-max") ctxMax = Number(argv[++i]);
else if (a === "--session") sessions.push(argv[++i]!);
else if (!a.startsWith("--")) sessions.push(a);
}
return { sessions, ctxMax };
}
function fmt(n: number): string {
if (n >= 1e9) return `${(n / 1e9).toFixed(2)}G`;
if (n >= 1e6) return `${(n / 1e6).toFixed(2)}M`;
if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
return String(n);
}
function pct(n: number): string {
return `${(n * 100).toFixed(1)}%`;
}
function report(label: string, rows: Array<{ name: string; result: RunResult }>): void {
console.log(`\n=== ${label} ===`);
const w = [22, 10, 10, 8, 10, 6, 10];
const headers = ["config", "input", "cache_hit", "hit%", "miss", "folds", "peak"];
console.log(headers.map((h, i) => h.padEnd(w[i]!)).join("│ "));
console.log("─".repeat(w.reduce((a, b) => a + b + 2, 0)));
for (const { name, result: r } of rows) {
const peak = r.perTurn.reduce((m, t) => Math.max(m, t.ratio), 0);
console.log(
[
name.padEnd(w[0]!),
fmt(r.totalInputTokens).padEnd(w[1]!),
fmt(r.totalCacheHitTokens).padEnd(w[2]!),
pct(r.cacheHitRatio).padEnd(w[3]!),
fmt(r.totalCacheMissTokens).padEnd(w[4]!),
String(r.foldCount).padEnd(w[5]!),
pct(peak).padEnd(w[6]!),
].join("│ "),
);
}
}
function main(): void {
const { sessions, ctxMax } = parseArgs(process.argv.slice(2));
if (sessions.length === 0) {
console.error("usage: tsx run.ts [--ctx-max N] <session.jsonl> [more...]");
process.exit(1);
}
for (const path of sessions) {
const msgs = loadSession(path);
const cfgs = configs(ctxMax);
const rows = cfgs.map(({ name, config }) => ({ name, result: simulate(msgs, config, path) }));
report(`${basename(path)} (${msgs.length} msgs, ctxMax=${fmt(ctxMax)})`, rows);
}
}
main();
+197
View File
@@ -0,0 +1,197 @@
import { readFileSync } from "node:fs";
import {
countTokensBounded,
estimateConversationTokens,
estimateRequestTokens,
} from "../../src/tokenizer.js";
import type { ChatMessage } from "../../src/types.js";
export interface ThresholdConfig {
ctxMax: number;
foldThreshold: number;
tailFraction: number;
aggressiveThreshold: number;
aggressiveTailFraction: number;
minSavingsFraction: number;
summaryRatio: number;
}
export interface FoldEvent {
turn: number;
ratioBeforeFold: number;
promptTokensBefore: number;
headMessages: number;
tailMessages: number;
headTokens: number;
summaryTokens: number;
aggressive: boolean;
}
export interface TurnRecord {
turn: number;
promptTokens: number;
cacheHitTokens: number;
cacheMissTokens: number;
ratio: number;
folded: boolean;
}
export interface RunResult {
config: ThresholdConfig;
sessionPath: string;
totalTurns: number;
totalInputTokens: number;
totalCacheHitTokens: number;
totalCacheMissTokens: number;
cacheHitRatio: number;
foldCount: number;
folds: FoldEvent[];
perTurn: TurnRecord[];
}
export function loadSession(path: string): ChatMessage[] {
const lines = readFileSync(path, "utf8").split("\n");
const out: ChatMessage[] = [];
for (const ln of lines) {
const t = ln.trim();
if (!t) continue;
try {
out.push(JSON.parse(t) as ChatMessage);
} catch {
continue;
}
}
return out;
}
function messageTokens(m: ChatMessage): number {
return estimateConversationTokens([m], true);
}
function messageKey(m: ChatMessage): string {
return JSON.stringify({
r: m.role,
c: m.content ?? "",
tc: m.tool_calls ?? null,
tcid: m.tool_call_id ?? null,
});
}
function commonPrefixTokens(curr: ChatMessage[], prev: ChatMessage[]): number {
const n = Math.min(curr.length, prev.length);
let tokens = 0;
for (let i = 0; i < n; i++) {
if (messageKey(curr[i]!) !== messageKey(prev[i]!)) break;
tokens += messageTokens(curr[i]!);
}
return tokens;
}
function findFoldBoundary(log: ChatMessage[], tailBudget: number): number {
let cum = 0;
let boundary = log.length;
for (let i = log.length - 1; i >= 0; i--) {
const t = messageTokens(log[i]!);
if (cum + t > tailBudget) break;
cum += t;
if (log[i]!.role === "user") boundary = i;
}
return boundary;
}
function synthesizeSummary(head: ChatMessage[], targetTokens: number): ChatMessage {
const userBits: string[] = [];
for (const m of head) {
if (m.role === "user" && typeof m.content === "string") userBits.push(m.content);
}
const seed = userBits.join("\n") || "earlier turns folded";
let text = `[CONVERSATION HISTORY SUMMARY — fold of ${head.length} messages]\n\n${seed}`;
const currentTokens = countTokensBounded(text);
if (currentTokens > targetTokens) {
const ratio = targetTokens / currentTokens;
text = text.slice(0, Math.max(80, Math.floor(text.length * ratio)));
}
return { role: "assistant", content: text, reasoning_content: "" };
}
function turnBoundaries(messages: ChatMessage[]): number[] {
const ends: number[] = [];
for (let i = 0; i < messages.length; i++) {
if (messages[i]!.role === "assistant") ends.push(i);
}
return ends;
}
export function simulate(messages: ChatMessage[], config: ThresholdConfig, sessionPath: string): RunResult {
const ends = turnBoundaries(messages);
const log: ChatMessage[] = [];
let prevSnapshot: ChatMessage[] = [];
const perTurn: TurnRecord[] = [];
const folds: FoldEvent[] = [];
let totalInput = 0;
let totalHit = 0;
let totalMiss = 0;
let cursor = 0;
for (let turn = 0; turn < ends.length; turn++) {
const end = ends[turn]!;
for (let i = cursor; i < end; i++) log.push(messages[i]!);
cursor = end;
const promptTokens = estimateRequestTokens(log, null, true);
const ratio = promptTokens / config.ctxMax;
const hit = commonPrefixTokens(log, prevSnapshot);
const miss = Math.max(0, promptTokens - hit);
let folded = false;
if (ratio > config.foldThreshold) {
const aggressive = ratio > config.aggressiveThreshold;
const tailFrac = aggressive ? config.aggressiveTailFraction : config.tailFraction;
const tailBudget = Math.floor(config.ctxMax * tailFrac);
const boundary = findFoldBoundary(log, tailBudget);
if (boundary > 0) {
const head = log.slice(0, boundary);
const tail = log.slice(boundary);
const headTokens = head.reduce((a, m) => a + messageTokens(m), 0);
const totalTokens = log.reduce((a, m) => a + messageTokens(m), 0);
if (headTokens >= totalTokens * config.minSavingsFraction) {
const summaryTokens = Math.max(64, Math.floor(headTokens * config.summaryRatio));
const summary = synthesizeSummary(head, summaryTokens);
const next = [summary, ...tail];
log.length = 0;
for (const m of next) log.push(m);
folds.push({
turn,
ratioBeforeFold: ratio,
promptTokensBefore: promptTokens,
headMessages: head.length,
tailMessages: tail.length,
headTokens,
summaryTokens,
aggressive,
});
folded = true;
}
}
}
totalInput += promptTokens;
totalHit += hit;
totalMiss += miss;
perTurn.push({ turn, promptTokens, cacheHitTokens: hit, cacheMissTokens: miss, ratio, folded });
prevSnapshot = log.slice();
}
return {
config,
sessionPath,
totalTurns: ends.length,
totalInputTokens: totalInput,
totalCacheHitTokens: totalHit,
totalCacheMissTokens: totalMiss,
cacheHitRatio: totalInput > 0 ? totalHit / totalInput : 0,
foldCount: folds.length,
folds,
perTurn,
};
}
+13
View File
@@ -0,0 +1,13 @@
为这个仓库的 src/ 目录写一份完整的架构总览文档。
要求:
1. 用 read_file / directory_tree / grep_search 等工具,**逐个**读取 src/ 下每个子目录(cli/, mcp/, memory/, telemetry/, transcript/, tools/, ui/, i18n/, loop/ 等)的代表性文件。每个子目录至少读 3-5 个核心 .ts 文件。
2. 不要只 grep 关键词就下结论 —— 必须打开文件读真实内容,从代码里抽出"这个模块的职责 / 它的核心数据结构 / 它对外暴露什么"。
3. 边读边在心里搭建依赖图。
4. 全部读完后,输出一份 markdown 报告,包含:
- 整体架构图(mermaid 或 ASCII,模块之间的依赖关系)
- 按模块列出:职责 / 关键文件 / 对外接口 / 内部依赖
- 至少 8 个具体的代码引用(路径:行号),证明你真读了
- 结尾给出"如果新人加入项目,应该按什么顺序读代码"的建议
这是一个真实的代码审计任务,请不要偷懒、不要瞎编、不要用通用模板。文件读得不够多就直接说"我读得不够"。
+11 -10
View File
@@ -20,22 +20,22 @@ Used with permission, anonymized.
## Cost — using the prices Reasonix bills against (`src/telemetry/stats.ts`)
USD per 1M tokens — `inputCacheHit / inputCacheMiss / output`:
- `deepseek-v4-flash` — `0.028 / 0.139 / 0.278`
- `deepseek-v4-pro` — `0.139 / 1.667 / 3.333`
- `deepseek-v4-flash` — `0.0028 / 0.14 / 0.28`
- `deepseek-v4-pro` — `0.003625 / 0.435 / 0.87`
Assuming **v4-flash** (the project default):
| | This user (99.82% hit) | Same workload, **0% cache** |
|---|---:|---:|
| Cache-hit input | $12.18 | — |
| Cache-miss input | $0.11 | $60.58 |
| Cache-hit input | $1.22 | — |
| Cache-miss input | $0.11 | $61.01 |
| Output | $0.05 | $0.05 |
| **Total / day** | **$12.34** | **$60.63** |
| **Total / day** | **$1.38** | **$61.06** |
→ Cache saved this user **$48.29**, or **~80%** off the un-cached baseline, on a single day.
→ Cache saved this user **$59.68**, or **~97.7%** off the un-cached baseline, on a single day.
On **v4-pro** (5× the prefix-cache discount) the same workload would cost
**~$62.35** vs **~$727.08** without cache — a **~91% saving**.
On **v4-pro** (6.25% of uncached input cost) the same workload would cost
**~$2.07** vs **~$189.73** without cache — a **~98.9%** saving.
## "Isn't that just DeepSeek's prefix cache?"
@@ -59,8 +59,9 @@ hit rates:
3. **`VolatileScratch`** — chain-of-thought / per-turn scratch lives outside
the cached prefix so it never poisons the next hit.
4. **Auto-compact** — when context approaches the cap, older turns fold into
a summary message *appended* to the prefix; the prefix itself isn't
rewritten, so the cache survives the fold.
a summary message. The summary request is shaped to reuse the main agent's
already-cached system/tool/history prefix; the following main-agent request
still pays a cold miss for the newly synthesized summary segment.
DeepSeek gave us cacheable bytes. The four mechanisms above are how we keep
the bytes cacheable.
+8 -1
View File
@@ -24,6 +24,13 @@
}
},
"files": {
"ignore": ["dist", "node_modules", "coverage", "*.d.ts", "dashboard/codemirror.js"]
"ignore": [
"dist",
"node_modules",
"coverage",
"*.d.ts",
"dashboard/codemirror.js",
"packages/ink/**"
]
}
}
-18
View File
@@ -1,18 +0,0 @@
[package]
name = "reasonix-render"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
anyhow = "1"
arboard = { version = "3", default-features = false }
chrono = { version = "0.4", features = ["clock"] }
crossterm = "0.29"
ctrlc = { version = "3", features = ["termination"] }
pulldown-cmark = { version = "0.13", default-features = false }
ratatui = "0.30"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
unicode-width = "0.2"
-18
View File
@@ -1,18 +0,0 @@
use std::io::{BufRead, Write};
use anyhow::{Context, Result};
pub fn run_decode_only<R: BufRead, W: Write>(input: R, mut output: W) -> Result<u64> {
let mut count = 0u64;
for (lineno, line) in input.lines().enumerate() {
let line = line.with_context(|| format!("read line {}", lineno + 1))?;
if line.trim().is_empty() {
continue;
}
let _value: serde_json::Value =
serde_json::from_str(&line).with_context(|| format!("decode line {}", lineno + 1))?;
count += 1;
writeln!(output, "frame {count}").ok();
}
Ok(count)
}
-110
View File
@@ -1,110 +0,0 @@
pub fn insert_char_at(buffer: &mut String, char_idx: usize, ch: char) {
let byte_idx = char_to_byte(buffer, char_idx);
buffer.insert(byte_idx, ch);
}
pub fn remove_char_at(buffer: &mut String, char_idx: usize) {
let Some((byte_idx, _)) = buffer.char_indices().nth(char_idx) else {
return;
};
buffer.remove(byte_idx);
}
pub fn char_to_byte(buffer: &str, char_idx: usize) -> usize {
buffer
.char_indices()
.nth(char_idx)
.map(|(b, _)| b)
.unwrap_or(buffer.len())
}
pub fn prev_word_boundary(buffer: &str, from: usize) -> usize {
let chars: Vec<char> = buffer.chars().collect();
let mut i = from.min(chars.len());
while i > 0 && chars[i - 1].is_whitespace() {
i -= 1;
}
while i > 0 && !chars[i - 1].is_whitespace() {
i -= 1;
}
i
}
pub fn next_word_boundary(buffer: &str, from: usize) -> usize {
let chars: Vec<char> = buffer.chars().collect();
let mut i = from.min(chars.len());
let n = chars.len();
while i < n && !chars[i].is_whitespace() {
i += 1;
}
while i < n && chars[i].is_whitespace() {
i += 1;
}
i
}
pub fn locate_cursor_in(buffer: &str, cursor: usize) -> (usize, usize) {
let mut line = 0usize;
let mut col = 0usize;
for (idx, ch) in buffer.chars().enumerate() {
if idx == cursor {
return (line, col);
}
if ch == '\n' {
line += 1;
col = 0;
} else {
col += 1;
}
}
(line, col)
}
pub fn line_col_to_cursor(buffer: &str, target_line: usize, target_col: usize) -> usize {
let mut line = 0usize;
let mut col = 0usize;
let mut idx = 0usize;
for ch in buffer.chars() {
if line == target_line && col == target_col {
return idx;
}
if ch == '\n' {
if line == target_line {
return idx;
}
line += 1;
col = 0;
} else {
col += 1;
}
idx += 1;
}
idx
}
pub fn move_cursor_line(buffer: &str, cursor: usize, delta: isize) -> usize {
let (line, col) = locate_cursor_in(buffer, cursor);
let new_line = if delta < 0 {
line.saturating_sub((-delta) as usize)
} else {
line + delta as usize
};
let max_line = buffer.chars().filter(|c| *c == '\n').count();
if new_line > max_line {
return buffer.chars().count();
}
if new_line == line {
return cursor;
}
line_col_to_cursor(buffer, new_line, col)
}
pub fn cursor_on_first_line(buffer: &str, cursor: usize) -> bool {
locate_cursor_in(buffer, cursor).0 == 0
}
pub fn cursor_on_last_line(buffer: &str, cursor: usize) -> bool {
let (line, _) = locate_cursor_in(buffer, cursor);
let last_line = buffer.chars().filter(|c| *c == '\n').count();
line >= last_line
}
-81
View File
@@ -1,81 +0,0 @@
/// Frame identity cache — skips deserialization and rendering when consecutive
/// frames are byte-identical. The trace scene emitted by useSceneTrace only
/// changes when cards, model, or activity label change, so most frames between
/// streaming deltas are duplicates.
///
/// Ratatui's Terminal::draw already diffs cells against the previous terminal
/// state before emitting ANSI. This cache operates one layer above: it avoids
/// the JSON parse + scene render + ratatui diff pipeline entirely for
/// unchanged frames, saving CPU on both the JS and Rust sides of the bridge.
#[derive(Default)]
pub struct FrameCache {
/// Raw JSON line from the previous frame.
prev_raw: String,
/// Number of consecutive skipped frames.
skipped: u64,
/// False until the first frame is seen — guarantees is_new returns true for frame 0.
has_prev: bool,
}
impl FrameCache {
/// Returns true if this raw JSON line differs from the previous one
/// (or if no previous frame exists). False means the frame is a
/// byte-for-byte duplicate and can be skipped entirely.
pub fn is_new(&mut self, raw: &str) -> bool {
if !self.has_prev {
self.prev_raw.clear();
self.prev_raw.push_str(raw);
self.has_prev = true;
return true;
}
if raw == self.prev_raw {
self.skipped = self.skipped.saturating_add(1);
return false;
}
self.prev_raw.clear();
self.prev_raw.push_str(raw);
self.skipped = 0;
true
}
/// Number of consecutive frames skipped since the last rendered frame.
pub fn skipped_count(&self) -> u64 {
self.skipped
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn first_frame_is_always_new() {
let mut cache = FrameCache::default();
assert!(cache.is_new(r#"{"v":1}"#));
}
#[test]
fn identical_frame_is_skipped() {
let mut cache = FrameCache::default();
assert!(cache.is_new(r#"{"v":1}"#));
assert!(!cache.is_new(r#"{"v":1}"#));
assert_eq!(cache.skipped_count(), 1);
}
#[test]
fn changed_frame_is_not_skipped() {
let mut cache = FrameCache::default();
assert!(cache.is_new(r#"{"v":1}"#));
assert!(cache.is_new(r#"{"v":2}"#));
assert_eq!(cache.skipped_count(), 0);
}
#[test]
fn empty_string_is_valid_frame() {
let mut cache = FrameCache::default();
// Empty lines are filtered before reaching the cache in main.rs,
// but if one arrives it should be treated normally.
assert!(cache.is_new(""));
assert!(!cache.is_new(""));
}
}
-113
View File
@@ -1,113 +0,0 @@
use crossterm::event::{
KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InputEvent {
pub event: &'static str,
pub code: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub char: Option<char>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub modifiers: Vec<&'static str>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PasteEvent {
pub event: &'static str,
pub text: String,
}
pub fn paste_event(text: String) -> PasteEvent {
PasteEvent {
event: "paste",
text,
}
}
pub fn translate_key(event: &KeyEvent) -> Option<InputEvent> {
if event.kind != KeyEventKind::Press {
return None;
}
let (code, ch) = match event.code {
KeyCode::Char(c) => ("Char".to_string(), Some(c)),
KeyCode::Enter => ("Enter".to_string(), None),
KeyCode::Esc => ("Esc".to_string(), None),
KeyCode::Up => ("Up".to_string(), None),
KeyCode::Down => ("Down".to_string(), None),
KeyCode::Left => ("Left".to_string(), None),
KeyCode::Right => ("Right".to_string(), None),
KeyCode::Backspace => ("Backspace".to_string(), None),
KeyCode::Tab => ("Tab".to_string(), None),
KeyCode::BackTab => ("BackTab".to_string(), None),
KeyCode::Home => ("Home".to_string(), None),
KeyCode::End => ("End".to_string(), None),
KeyCode::PageUp => ("PageUp".to_string(), None),
KeyCode::PageDown => ("PageDown".to_string(), None),
KeyCode::Delete => ("Delete".to_string(), None),
KeyCode::Insert => ("Insert".to_string(), None),
KeyCode::F(n) => (format!("F{n}"), None),
_ => return None,
};
Some(InputEvent {
event: "key",
code,
char: ch,
modifiers: collect_modifiers(event.modifiers),
})
}
fn collect_modifiers(m: KeyModifiers) -> Vec<&'static str> {
let mut out = Vec::new();
if m.contains(KeyModifiers::CONTROL) {
out.push("ctrl");
}
if m.contains(KeyModifiers::ALT) {
out.push("alt");
}
if m.contains(KeyModifiers::SHIFT) {
out.push("shift");
}
if m.contains(KeyModifiers::SUPER) {
out.push("super");
}
out
}
pub fn is_quit(event: &KeyEvent) -> bool {
event.kind == KeyEventKind::Press
&& event.code == KeyCode::Char('c')
&& event.modifiers.contains(KeyModifiers::CONTROL)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MouseInputEvent {
pub event: &'static str,
pub kind: &'static str,
/// 1-based row, matching the VT mouse-report convention the JS side expects.
pub row: u16,
/// 1-based column, same convention as row.
pub col: u16,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub modifiers: Vec<&'static str>,
}
pub fn translate_mouse(event: &MouseEvent) -> Option<MouseInputEvent> {
let kind = match event.kind {
MouseEventKind::Down(MouseButton::Left) => "click",
MouseEventKind::Drag(MouseButton::Left) => "drag",
MouseEventKind::Up(_) => "release",
MouseEventKind::ScrollUp => "scroll-up",
MouseEventKind::ScrollDown => "scroll-down",
_ => return None,
};
Some(MouseInputEvent {
event: "mouse",
kind,
// crossterm reports 0-based row/col; bump to 1-based on the wire.
row: event.row.saturating_add(1),
col: event.column.saturating_add(1),
modifiers: collect_modifiers(event.modifiers),
})
}
File diff suppressed because it is too large. Load diff
-9
View File
@@ -1,9 +0,0 @@
pub mod decode_only;
pub mod editor;
pub mod frame_cache;
pub mod input;
pub mod integrated;
pub mod state;
pub mod theme;
pub mod view;
pub mod whole_screen;
-768
View File
@@ -1,768 +0,0 @@
use std::io::{self, BufRead, BufWriter, Write};
use anyhow::{Context, Result};
use crossterm::event::{
self, DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
Event,
};
use crossterm::execute;
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use ratatui::backend::CrosstermBackend;
use reasonix_render::decode_only::run_decode_only;
use reasonix_render::editor::{
char_to_byte, insert_char_at, move_cursor_line, next_word_boundary, prev_word_boundary,
remove_char_at,
};
use reasonix_render::frame_cache::FrameCache;
use reasonix_render::input::{is_quit, paste_event, translate_key, translate_mouse};
use reasonix_render::state::{decode_message, Payload};
use reasonix_render::view::render_setup;
use reasonix_render::whole_screen::{
at_completion, at_match_count, cards_layout, demo_state, extract_text, slash_completion,
slash_is_exact, slash_match_count, Selection, WholeScreen,
};
type RenderTerminal = ratatui::Terminal<CrosstermBackend<BufWriter<io::Stdout>>>;
fn debug_log(msg: &str) {
let Ok(enabled) = std::env::var("REASONIX_RENDER_DEBUG") else {
return;
};
if enabled.is_empty() || enabled == "0" {
return;
}
let path = std::env::var("REASONIX_RENDER_DEBUG_LOG").unwrap_or_else(|_| {
let home = std::env::var("USERPROFILE")
.or_else(|_| std::env::var("HOME"))
.unwrap_or_default();
if home.is_empty() {
"reasonix-render-debug.log".to_string()
} else {
format!("{home}/.reasonix/rust-render-debug.log")
}
});
if let Some(parent) = std::path::Path::new(&path).parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
{
let _ = writeln!(f, "[reasonix-render] {msg}");
}
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.iter().any(|a| a == "--decode-only") {
let stdin = io::stdin();
let stdout = io::stdout();
run_decode_only(stdin.lock(), stdout.lock())?;
return Ok(());
}
if args.iter().any(|a| a == "--emit-input") {
install_signal_cleanup();
return run_emit_input();
}
install_panic_hook();
install_signal_cleanup();
let mut terminal = init_terminal().context("init terminal")?;
terminal.hide_cursor().ok();
terminal.clear().ok();
if let Ok(size) = terminal.size() {
debug_log(&format!(
"startup terminal.size = {}x{}",
size.width, size.height
));
}
let result = if args.iter().any(|a| a == "--demo") {
run_demo_loop(&mut terminal)
} else if args.iter().any(|a| a == "--integrated") {
reasonix_render::integrated::run_integrated_loop(&mut terminal)
} else {
run_stream_loop(&mut terminal)
};
restore_terminal(&mut terminal);
result
}
fn init_terminal() -> Result<RenderTerminal> {
enable_raw_mode().context("enable raw mode")?;
let mut stdout = BufWriter::new(io::stdout());
crossterm::execute!(stdout, crossterm::terminal::EnterAlternateScreen)
.context("enter alt screen")?;
let backend = CrosstermBackend::new(stdout);
let terminal = ratatui::Terminal::new(backend).context("create terminal")?;
Ok(terminal)
}
fn restore_terminal(terminal: &mut RenderTerminal) {
terminal.show_cursor().ok();
crossterm::execute!(
terminal.backend_mut(),
crossterm::terminal::LeaveAlternateScreen
)
.ok();
disable_raw_mode().ok();
}
/// Best-effort terminal restore on SIGTERM / SIGHUP / Windows console-close.
/// In raw mode ctrl+c is delivered as the byte 0x03 to crossterm and never
/// fires SIGINT, so the existing `is_quit` event-loop branch handles
/// interactive ctrl+c with a clean restore_terminal. This guard covers the
/// other paths — `taskkill`, parent process death, terminal disconnect — that
/// would otherwise leave the alt-screen + raw mode dirty and corrupt the
/// next launch's rendering.
fn install_signal_cleanup() {
let _ = ctrlc::set_handler(|| {
let _ = disable_raw_mode();
let _ = crossterm::execute!(
io::stdout(),
crossterm::terminal::LeaveAlternateScreen,
crossterm::cursor::Show,
);
std::process::exit(130);
});
}
fn install_panic_hook() {
let original = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let home = std::env::var("USERPROFILE")
.or_else(|_| std::env::var("HOME"))
.unwrap_or_default();
if !home.is_empty() {
let path = format!("{home}/.reasonix/rust-panic.log");
if let Some(parent) = std::path::Path::new(&path).parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
{
let now = chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
let _ = writeln!(f, "[{now}] {info}");
let bt = std::backtrace::Backtrace::force_capture();
let _ = writeln!(f, "{bt}\n");
}
}
let _ = disable_raw_mode();
let _ = crossterm::execute!(io::stdout(), crossterm::terminal::LeaveAlternateScreen);
original(info);
}));
}
fn run_demo_loop(terminal: &mut RenderTerminal) -> Result<()> {
use crossterm::event::{
DisableMouseCapture, EnableMouseCapture, KeyCode, KeyEventKind, KeyModifiers, MouseButton,
MouseEventKind,
};
use reasonix_render::state::SceneCard;
let mut stdout = io::stdout();
let mouse_enabled = crossterm::execute!(stdout, EnableMouseCapture).is_ok();
let mut state = demo_state();
let mut buffer = String::new();
let mut cursor: usize = 0;
let mut scroll_offset: u16 = 0;
let mut selection: Option<Selection> = None;
let mut dragging = false;
let mut slash_idx: usize = 0;
let mut at_idx: usize = 0;
let mut sidebar_visible = true;
let mut tick: u32 = 0;
let tick_period = std::time::Duration::from_millis(80);
let scroll_step: u16 = 3;
let page_step: u16 = 10;
let result: Result<()> = (|| loop {
let buf_chars = buffer.chars().count();
if cursor > buf_chars {
cursor = buf_chars;
}
state.composer_text = Some(buffer.clone());
state.composer_cursor = Some(cursor);
let slash_count = slash_match_count(&buffer, &state);
if slash_count == 0 {
slash_idx = 0;
} else if slash_idx >= slash_count {
slash_idx = slash_count - 1;
}
let at_count = if slash_count > 0 {
0
} else {
at_match_count(&buffer, &state)
};
if at_count == 0 {
at_idx = 0;
} else if at_idx >= at_count {
at_idx = at_count - 1;
}
let _ = crossterm::execute!(
terminal.backend_mut(),
crossterm::terminal::BeginSynchronizedUpdate
);
terminal
.draw(|f| {
let area = f.area();
f.render_widget(
WholeScreen::new(&state)
.with_scroll(scroll_offset)
.with_selection(selection)
.with_slash_index(slash_idx)
.with_at_index(at_idx)
.with_sidebar_visible(sidebar_visible)
.with_tick(tick),
area,
);
})
.context("terminal draw")?;
let _ = crossterm::execute!(
terminal.backend_mut(),
crossterm::terminal::EndSynchronizedUpdate
);
if !event::poll(tick_period)? {
tick = tick.wrapping_add(1);
continue;
}
match event::read()? {
Event::Key(key) if key.kind != KeyEventKind::Press => continue,
Event::Key(key) => {
if is_quit(&key) {
if let Some(sel) = selection {
if let Ok(size) = terminal.size() {
let rect = ratatui::layout::Rect::new(0, 0, size.width, size.height);
let text =
extract_text(&state, scroll_offset, rect, sel, sidebar_visible);
if !text.is_empty() {
if let Ok(mut cb) = arboard::Clipboard::new() {
let _ = cb.set_text(text);
}
}
}
selection = None;
continue;
}
return Ok(());
}
if key.code == KeyCode::Char('d') && key.modifiers.contains(KeyModifiers::CONTROL) {
return Ok(());
}
if key.code == KeyCode::Char('b') && key.modifiers.contains(KeyModifiers::CONTROL) {
sidebar_visible = !sidebar_visible;
continue;
}
let slash_active = slash_count > 0;
let at_active = !slash_active && at_count > 0;
let slash_complete_only = slash_active && !slash_is_exact(&buffer, &state);
match key.code {
KeyCode::Up if slash_active => {
slash_idx = slash_idx.saturating_sub(1);
}
KeyCode::Down if slash_active => {
slash_idx = (slash_idx + 1).min(slash_count - 1);
}
KeyCode::Tab if slash_active => {
if let Some(completion) = slash_completion(&buffer, slash_idx, &state) {
buffer = completion.trim_end().to_string();
cursor = buffer.chars().count();
}
}
KeyCode::BackTab if slash_active => {
slash_idx = if slash_idx == 0 {
slash_count - 1
} else {
slash_idx - 1
};
}
KeyCode::Enter if slash_complete_only => {
if let Some(completion) = slash_completion(&buffer, slash_idx, &state) {
cursor = completion.chars().count();
buffer = completion;
}
}
KeyCode::Up if at_active => {
at_idx = at_idx.saturating_sub(1);
}
KeyCode::Down if at_active => {
at_idx = (at_idx + 1).min(at_count - 1);
}
KeyCode::Tab if at_active => {
if let Some(completion) = at_completion(&buffer, at_idx, &state) {
cursor = completion.chars().count();
buffer = completion;
}
}
KeyCode::BackTab if at_active => {
at_idx = if at_idx == 0 {
at_count - 1
} else {
at_idx - 1
};
}
KeyCode::Enter if at_active => {
if let Some(completion) = at_completion(&buffer, at_idx, &state) {
cursor = completion.chars().count();
buffer = completion;
}
}
KeyCode::Up => {
cursor = move_cursor_line(&buffer, cursor, -1);
}
KeyCode::Down => {
cursor = move_cursor_line(&buffer, cursor, 1);
}
KeyCode::Esc => {
if selection.is_some() {
selection = None;
} else {
buffer.clear();
cursor = 0;
slash_idx = 0;
at_idx = 0;
}
}
KeyCode::PageUp => {
scroll_offset = scroll_offset.saturating_add(page_step);
}
KeyCode::PageDown => {
scroll_offset = scroll_offset.saturating_sub(page_step);
}
KeyCode::Left if key.modifiers.contains(KeyModifiers::CONTROL) => {
cursor = prev_word_boundary(&buffer, cursor);
}
KeyCode::Right if key.modifiers.contains(KeyModifiers::CONTROL) => {
cursor = next_word_boundary(&buffer, cursor);
}
KeyCode::Left => {
cursor = cursor.saturating_sub(1);
}
KeyCode::Right => {
cursor = (cursor + 1).min(buffer.chars().count());
}
KeyCode::Home => {
cursor = 0;
}
KeyCode::End => {
cursor = buffer.chars().count();
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
selection = None;
insert_char_at(&mut buffer, cursor, c);
cursor += 1;
slash_idx = 0;
at_idx = 0;
scroll_offset = 0;
}
KeyCode::Backspace if key.modifiers.contains(KeyModifiers::CONTROL) => {
selection = None;
let new_cursor = prev_word_boundary(&buffer, cursor);
let from_byte = char_to_byte(&buffer, new_cursor);
let to_byte = char_to_byte(&buffer, cursor);
buffer.drain(from_byte..to_byte);
cursor = new_cursor;
slash_idx = 0;
at_idx = 0;
}
KeyCode::Backspace => {
selection = None;
if cursor > 0 {
remove_char_at(&mut buffer, cursor - 1);
cursor -= 1;
}
slash_idx = 0;
at_idx = 0;
}
KeyCode::Delete => {
if cursor < buffer.chars().count() {
remove_char_at(&mut buffer, cursor);
}
slash_idx = 0;
at_idx = 0;
}
KeyCode::Enter if key.modifiers.contains(KeyModifiers::SHIFT) => {
selection = None;
insert_char_at(&mut buffer, cursor, '\n');
cursor += 1;
slash_idx = 0;
at_idx = 0;
}
KeyCode::Enter => {
selection = None;
let text = buffer.trim().to_string();
if !text.is_empty() {
state.cards.push(SceneCard {
kind: "user".to_string(),
body: Some(text),
ts: Some(chrono::Local::now().timestamp()),
..Default::default()
});
}
buffer.clear();
cursor = 0;
slash_idx = 0;
at_idx = 0;
scroll_offset = 0;
}
_ => {}
}
}
Event::Mouse(m) => {
let term_size = terminal.size().ok();
let term_rect =
term_size.map(|s| ratatui::layout::Rect::new(0, 0, s.width, s.height));
match m.kind {
MouseEventKind::Down(MouseButton::Left) => {
if let Some(rect) = term_rect {
let layout = cards_layout(rect, &state, scroll_offset, sidebar_visible);
if layout.contains_screen(m.column, m.row) {
let (col, virt_y) = layout.project_clamped(m.column, m.row);
selection = Some(Selection::new(col, virt_y));
dragging = true;
} else {
selection = None;
dragging = false;
}
}
}
MouseEventKind::Drag(MouseButton::Left) if dragging => {
if let Some(rect) = term_rect {
let layout = cards_layout(rect, &state, scroll_offset, sidebar_visible);
let (col, virt_y) = layout.project_clamped(m.column, m.row);
if let Some(s) = selection.as_mut() {
s.extend(col, virt_y);
}
let top = layout.screen_rect.y;
let bottom = layout.screen_rect.bottom();
if m.row < top {
scroll_offset = scroll_offset.saturating_add(1);
} else if bottom > 0 && m.row >= bottom.saturating_sub(1) {
scroll_offset = scroll_offset.saturating_sub(1);
}
}
}
MouseEventKind::Up(MouseButton::Left) => {
dragging = false;
if let Some(sel) = selection {
if !sel.is_empty() {
if let Ok(size) = terminal.size() {
let rect =
ratatui::layout::Rect::new(0, 0, size.width, size.height);
let text = extract_text(
&state,
scroll_offset,
rect,
sel,
sidebar_visible,
);
if !text.is_empty() {
if let Ok(mut cb) = arboard::Clipboard::new() {
let _ = cb.set_text(text);
}
}
}
}
}
}
MouseEventKind::ScrollUp => {
scroll_offset = scroll_offset.saturating_add(scroll_step);
}
MouseEventKind::ScrollDown => {
scroll_offset = scroll_offset.saturating_sub(scroll_step);
}
_ => {}
}
}
Event::Resize(_, _) => {}
_ => {}
}
tick = tick.wrapping_add(1);
})();
if mouse_enabled {
let _ = crossterm::execute!(io::stdout(), DisableMouseCapture);
}
result
}
fn run_stream_loop(terminal: &mut RenderTerminal) -> Result<()> {
use crossterm::event::{DisableMouseCapture, EnableMouseCapture, MouseButton, MouseEventKind};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
let mouse_enabled = crossterm::execute!(io::stdout(), EnableMouseCapture).is_ok();
let (tx, rx) = mpsc::channel::<String>();
let _reader = thread::spawn(move || {
let stdin = io::stdin();
for line in stdin.lock().lines() {
let Ok(l) = line else {
break;
};
if tx.send(l).is_err() {
break;
}
}
});
let mut logged_first_frame = false;
let mut last_size = terminal.size().ok();
let mut current_state: Option<Payload> = None;
let mut scroll_offset: u16 = 0;
let mut selection: Option<Selection> = None;
let mut dragging = false;
let mut tick: u32 = 0;
let tick_period = Duration::from_millis(80);
let scroll_step: u16 = 3;
let mut frame_cache = FrameCache::default();
let result: Result<()> = (|| loop {
let mut state_changed = false;
let mut stdin_closed = false;
loop {
match rx.try_recv() {
Ok(line) => {
if line.trim().is_empty() {
continue;
}
if !frame_cache.is_new(&line) {
continue;
}
if let Ok(p) = decode_message(&line) {
current_state = Some(p);
state_changed = true;
}
}
Err(mpsc::TryRecvError::Empty) => break,
Err(mpsc::TryRecvError::Disconnected) => {
stdin_closed = true;
break;
}
}
}
let current_size = terminal.size().ok();
if current_size != last_size {
terminal.clear().ok();
last_size = current_size;
state_changed = true;
}
if state_changed {
if let Some(payload) = &current_state {
draw_atomic_with_ui(
terminal,
payload,
&mut logged_first_frame,
scroll_offset,
selection,
tick,
)?;
}
}
if stdin_closed && current_state.is_none() {
return Ok(());
}
if crossterm::event::poll(tick_period)? {
let evt = crossterm::event::read()?;
let mut dirty = false;
if let Event::Mouse(m) = evt {
if let Some(Payload::Trace(state)) = current_state.as_ref() {
if let Ok(size) = terminal.size() {
let rect = ratatui::layout::Rect::new(0, 0, size.width, size.height);
let layout = cards_layout(rect, state, scroll_offset, true);
match m.kind {
MouseEventKind::Down(MouseButton::Left) => {
if layout.contains_screen(m.column, m.row) {
let (col, virt_y) = layout.project_clamped(m.column, m.row);
selection = Some(Selection::new(col, virt_y));
dragging = true;
} else {
selection = None;
dragging = false;
}
dirty = true;
}
MouseEventKind::Drag(MouseButton::Left) if dragging => {
let (col, virt_y) = layout.project_clamped(m.column, m.row);
if let Some(s) = selection.as_mut() {
s.extend(col, virt_y);
}
let top = layout.screen_rect.y;
let bottom = layout.screen_rect.bottom();
if m.row < top {
scroll_offset = scroll_offset.saturating_add(1);
} else if bottom > 0 && m.row >= bottom.saturating_sub(1) {
scroll_offset = scroll_offset.saturating_sub(1);
}
dirty = true;
}
MouseEventKind::Up(MouseButton::Left) => {
dragging = false;
if let Some(sel) = selection {
if !sel.is_empty() {
let text =
extract_text(state, scroll_offset, rect, sel, true);
if !text.is_empty() {
if let Ok(mut cb) = arboard::Clipboard::new() {
let _ = cb.set_text(text);
}
}
}
}
}
MouseEventKind::ScrollUp => {
scroll_offset = scroll_offset.saturating_add(scroll_step);
dirty = true;
}
MouseEventKind::ScrollDown => {
scroll_offset = scroll_offset.saturating_sub(scroll_step);
dirty = true;
}
_ => {}
}
}
}
}
if dirty {
if let Some(payload) = &current_state {
draw_atomic_with_ui(
terminal,
payload,
&mut logged_first_frame,
scroll_offset,
selection,
tick,
)?;
}
}
} else if let Some(payload) = &current_state {
tick = tick.wrapping_add(1);
draw_atomic_with_ui(
terminal,
payload,
&mut logged_first_frame,
scroll_offset,
selection,
tick,
)?;
}
})();
if mouse_enabled {
let _ = crossterm::execute!(io::stdout(), DisableMouseCapture);
}
result
}
fn draw_atomic_with_ui(
terminal: &mut RenderTerminal,
payload: &Payload,
logged_first_frame: &mut bool,
scroll_offset: u16,
selection: Option<Selection>,
tick: u32,
) -> Result<()> {
let _ = crossterm::execute!(
terminal.backend_mut(),
crossterm::terminal::BeginSynchronizedUpdate
);
let draw_err = terminal
.draw(|f| {
let area = f.area();
if !*logged_first_frame {
debug_log(&format!(
"first frame area = x={} y={} w={} h={}",
area.x, area.y, area.width, area.height
));
*logged_first_frame = true;
}
match payload {
Payload::Trace(state) => {
f.render_widget(
WholeScreen::new(state)
.with_scroll(scroll_offset)
.with_selection(selection)
.with_tick(tick),
area,
);
}
Payload::Setup(state) => render_setup(state, f),
}
})
.err();
let _ = crossterm::execute!(
terminal.backend_mut(),
crossterm::terminal::EndSynchronizedUpdate
);
if let Some(e) = draw_err {
return Err(e).context("terminal draw");
}
Ok(())
}
fn run_emit_input() -> Result<()> {
enable_raw_mode().context("enable raw mode")?;
let mut stdout_for_setup = io::stdout();
let paste_enabled = execute!(stdout_for_setup, EnableBracketedPaste).is_ok();
let mouse_enabled = execute!(stdout_for_setup, EnableMouseCapture).is_ok();
let result = emit_input_loop();
if mouse_enabled {
execute!(stdout_for_setup, DisableMouseCapture).ok();
}
if paste_enabled {
execute!(stdout_for_setup, DisableBracketedPaste).ok();
}
disable_raw_mode().ok();
result
}
fn emit_input_loop() -> Result<()> {
let stdout = io::stdout();
let mut out = stdout.lock();
loop {
match event::read()? {
Event::Key(key) => {
if is_quit(&key) {
return Ok(());
}
let Some(translated) = translate_key(&key) else {
continue;
};
let json = serde_json::to_string(&translated).context("serialize input event")?;
writeln!(out, "{json}").context("write input event")?;
out.flush().context("flush stdout")?;
}
Event::Paste(text) => {
let event = paste_event(text);
let json = serde_json::to_string(&event).context("serialize paste event")?;
writeln!(out, "{json}").context("write paste event")?;
out.flush().context("flush stdout")?;
}
Event::Mouse(m) => {
let Some(translated) = translate_mouse(&m) else {
continue;
};
let json = serde_json::to_string(&translated).context("serialize mouse event")?;
writeln!(out, "{json}").context("write mouse event")?;
out.flush().context("flush stdout")?;
}
_ => {}
}
}
}
-325
View File
@@ -1,325 +0,0 @@
use serde::Deserialize;
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SceneState {
#[serde(default)]
pub model: Option<String>,
#[serde(default)]
pub card_count: u32,
#[serde(default)]
pub cards: Vec<SceneCard>,
#[serde(default)]
pub busy: bool,
#[serde(default)]
pub activity: Option<String>,
#[serde(default)]
pub composer_text: Option<String>,
#[serde(default)]
pub composer_cursor: Option<usize>,
#[serde(default)]
pub slash_matches: Option<Vec<SlashMatch>>,
#[serde(default)]
pub slash_selected_index: Option<usize>,
#[serde(default)]
pub approval_kind: Option<String>,
#[serde(default)]
pub approval_prompt: Option<String>,
#[serde(default)]
pub sessions: Option<Vec<SessionItem>>,
#[serde(default)]
pub sessions_focused_index: Option<usize>,
#[serde(default)]
pub wallet_balance: Option<f64>,
#[serde(default)]
pub wallet_currency: Option<String>,
#[serde(default)]
pub mcp_server_count: Option<u32>,
#[serde(default)]
pub edit_mode: Option<EditMode>,
#[serde(default)]
pub preset: Option<String>,
#[serde(default)]
pub cwd: Option<String>,
#[serde(default, rename = "dashboardUrl")]
pub dashboard_url: Option<String>,
#[serde(default)]
pub ctx_tokens: Option<u32>,
#[serde(default)]
pub ctx_cap: Option<u32>,
#[serde(default)]
pub session_cost_usd: Option<f64>,
#[serde(default)]
pub last_turn_cost_usd: Option<f64>,
#[serde(default)]
pub cache_hit_ratio: Option<f64>,
#[serde(default)]
pub last_turn_ms: Option<u64>,
#[serde(default)]
pub session_input_tokens: Option<u32>,
#[serde(default)]
pub session_output_tokens: Option<u32>,
#[serde(default)]
pub slash_catalog: Option<Vec<SlashMatch>>,
#[serde(default)]
pub slash_arg_state: Option<SlashArgState>,
#[serde(default)]
pub prompt_history: Option<Vec<String>>,
#[serde(default)]
pub approval: Option<Approval>,
#[serde(default)]
pub at_state: Option<AtState>,
#[serde(default)]
pub prompt_input: Option<PromptInput>,
#[serde(default)]
pub list_picker: Option<ListPicker>,
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct ListPicker {
#[serde(default)]
pub id: String,
#[serde(default)]
pub title: String,
#[serde(default)]
pub hint: Option<String>,
#[serde(default)]
pub options: Vec<ListPickerOption>,
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct ListPickerOption {
#[serde(default)]
pub key: String,
#[serde(default)]
pub label: String,
#[serde(default)]
pub sublabel: Option<String>,
#[serde(default)]
pub meta: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct PromptInput {
#[serde(default)]
pub id: String,
#[serde(default)]
pub label: String,
#[serde(default, rename = "defaultValue")]
pub default_value: Option<String>,
#[serde(default)]
pub secret: bool,
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SlashArgState {
#[serde(default)]
pub cmd: String,
#[serde(default)]
pub partial: String,
#[serde(default)]
pub matches: Vec<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum Approval {
Plan {
#[serde(default)]
body: String,
#[serde(default)]
steps: Vec<PlanStepItem>,
},
Shell {
command: String,
#[serde(default)]
cwd: Option<String>,
#[serde(default, rename = "timeoutSec")]
timeout_sec: Option<u32>,
},
Path {
path: String,
#[serde(default)]
intent: String,
#[serde(default, rename = "toolName")]
tool_name: String,
},
Edit {
path: String,
#[serde(default)]
search: String,
#[serde(default)]
replace: String,
},
Choice {
question: String,
#[serde(default)]
options: Vec<ApprovalChoiceOption>,
#[serde(default, rename = "allowCustom")]
allow_custom: bool,
},
Checkpoint {
#[serde(default)]
title: Option<String>,
#[serde(default)]
completed: u32,
#[serde(default)]
total: u32,
},
}
#[derive(Debug, Clone, Deserialize)]
pub struct ApprovalChoiceOption {
pub id: String,
pub title: String,
#[serde(default)]
pub summary: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct PlanStepItem {
pub title: String,
#[serde(default)]
pub status: String,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SceneCard {
pub kind: String,
#[serde(default)]
pub summary: String,
#[serde(default)]
pub args: Option<String>,
#[serde(default)]
pub status: Option<ToolStatus>,
#[serde(default)]
pub elapsed: Option<String>,
#[serde(default)]
pub id: Option<String>,
#[serde(default)]
pub body: Option<String>,
#[serde(default)]
pub ts: Option<i64>,
#[serde(default)]
pub meta: Option<String>,
}
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ToolStatus {
Ok,
Err,
Running,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum EditMode {
Review,
Auto,
Yolo,
}
impl EditMode {
pub fn as_str(&self) -> &'static str {
match self {
EditMode::Review => "review",
EditMode::Auto => "auto",
EditMode::Yolo => "yolo",
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct SlashMatch {
pub cmd: String,
#[serde(default)]
pub summary: String,
#[serde(default)]
pub group: Option<String>,
#[serde(default, rename = "argsHint")]
pub args_hint: Option<String>,
#[serde(default)]
pub aliases: Vec<String>,
#[serde(default, rename = "argCompleter")]
pub arg_completer: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AtPickerEntry {
pub label: String,
pub insert_path: String,
#[serde(default)]
pub dir_suffix: String,
#[serde(default)]
pub is_dir: bool,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum AtState {
Browse {
#[serde(default, rename = "baseDir")]
base_dir: String,
#[serde(default)]
entries: Vec<AtPickerEntry>,
#[serde(default)]
loading: bool,
},
Search {
#[serde(default)]
filter: String,
#[serde(default)]
entries: Vec<AtPickerEntry>,
#[serde(default)]
scanned: u32,
#[serde(default)]
searching: bool,
},
}
#[derive(Debug, Clone, Deserialize)]
pub struct SessionItem {
pub title: String,
#[serde(default)]
pub meta: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetupState {
#[serde(default)]
pub buffer_length: usize,
#[serde(default)]
pub error: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
#[allow(clippy::large_enum_variant)]
pub enum Message {
Trace(SceneState),
Setup(SetupState),
}
#[allow(clippy::large_enum_variant)]
pub enum Payload {
Trace(SceneState),
Setup(SetupState),
}
pub fn decode_message(line: &str) -> Result<Payload, serde_json::Error> {
if let Ok(msg) = serde_json::from_str::<Message>(line) {
return Ok(match msg {
Message::Trace(state) => Payload::Trace(state),
Message::Setup(state) => Payload::Setup(state),
});
}
if let Ok(state) = serde_json::from_str::<SceneState>(line) {
return Ok(Payload::Trace(state));
}
let state: SetupState = serde_json::from_str(line)?;
Ok(Payload::Setup(state))
}
-68
View File
@@ -1,68 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Color {
Named(NamedColor),
Hex { hex: String },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NamedColor {
Default,
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
Gray,
}
pub fn hex(s: &'static str) -> Color {
Color::Hex { hex: s.to_string() }
}
pub mod palette {
use super::{hex, Color};
pub fn bg() -> Color {
hex("#0f1018")
}
pub fn bg2() -> Color {
hex("#161824")
}
pub fn fg() -> Color {
hex("#e8e9f3")
}
pub fn fg1() -> Color {
hex("#a8aabd")
}
pub fn fg2() -> Color {
hex("#6b6e85")
}
pub fn fg3() -> Color {
hex("#3d4055")
}
pub fn ds() -> Color {
hex("#6b85ff")
}
pub fn ds_bright() -> Color {
hex("#8b9fff")
}
pub fn ds_purple() -> Color {
hex("#a78bfa")
}
pub fn ok() -> Color {
hex("#5eead4")
}
pub fn warn() -> Color {
hex("#fbbf24")
}
pub fn err() -> Color {
hex("#fb7185")
}
}
-97
View File
@@ -1,97 +0,0 @@
use ratatui::style::{Color as RColor, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{Block, Paragraph, Wrap};
use ratatui::Frame;
use crate::state::SetupState;
use crate::theme::{palette, Color, NamedColor};
pub fn render_setup(state: &SetupState, frame: &mut Frame<'_>) {
let area = frame.area();
frame.render_widget(canvas_block(), area);
let mut lines: Vec<Line<'_>> = vec![Line::from(vec![
styled(" ● ", palette::ds(), Modifier::BOLD),
styled("REASONIX", palette::ds_bright(), Modifier::BOLD),
styled(" welcome", palette::fg2(), Modifier::empty()),
])];
lines.push(Line::raw(""));
lines.push(Line::from(styled(
" Enter your DeepSeek API key:",
palette::ds(),
Modifier::empty(),
)));
lines.push(Line::from(styled(
" get one at https://platform.deepseek.com",
palette::fg2(),
Modifier::empty(),
)));
let mut masked: Vec<Span<'_>> = vec![styled(" ❯ ", palette::ds(), Modifier::BOLD)];
if state.buffer_length == 0 {
masked.push(styled(
"(start typing your key)",
palette::fg2(),
Modifier::empty(),
));
} else {
let dots = "•".repeat(state.buffer_length);
masked.push(styled(dots, palette::fg(), Modifier::empty()));
masked.push(styled("▮", palette::ds(), Modifier::empty()));
}
lines.push(Line::from(masked));
if let Some(err) = state.error.as_deref() {
lines.push(Line::from(vec![
styled(" ✗ ", palette::err(), Modifier::BOLD),
styled(err.to_string(), palette::err(), Modifier::empty()),
]));
}
lines.push(Line::raw(""));
lines.push(Line::from(styled(
" Ctrl+C to exit · /exit to quit",
palette::fg2(),
Modifier::empty(),
)));
let paragraph = Paragraph::new(Text::from(lines))
.wrap(Wrap { trim: false })
.style(Style::default().bg(to_rcolor(palette::bg())));
frame.render_widget(paragraph, area);
}
fn canvas_block() -> Block<'static> {
Block::default().style(Style::default().bg(to_rcolor(palette::bg())))
}
fn styled<S: Into<String>>(text: S, color: Color, modifier: Modifier) -> Span<'static> {
Span::styled(
text.into(),
Style::default().fg(to_rcolor(color)).add_modifier(modifier),
)
}
fn to_rcolor(c: Color) -> RColor {
match c {
Color::Named(n) => match n {
NamedColor::Default => RColor::Reset,
NamedColor::Black => RColor::Black,
NamedColor::Red => RColor::Red,
NamedColor::Green => RColor::Green,
NamedColor::Yellow => RColor::Yellow,
NamedColor::Blue => RColor::Blue,
NamedColor::Magenta => RColor::Magenta,
NamedColor::Cyan => RColor::Cyan,
NamedColor::White => RColor::White,
NamedColor::Gray => RColor::Gray,
},
Color::Hex { hex } => parse_hex(&hex).unwrap_or(RColor::Reset),
}
}
fn parse_hex(hex: &str) -> Option<RColor> {
let s = hex.strip_prefix('#')?;
if s.len() != 6 {
return None;
}
let r = u8::from_str_radix(&s[0..2], 16).ok()?;
let g = u8::from_str_radix(&s[2..4], 16).ok()?;
let b = u8::from_str_radix(&s[4..6], 16).ok()?;
Some(RColor::Rgb(r, g, b))
}
@@ -1,384 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier};
use unicode_width::UnicodeWidthStr;
use crate::state::Approval;
use super::paint::{paint, paint_str};
use super::theme::{BG, DS_BRIGHT, DS_PURPLE, ERR, FG, FG1, FG2, FG3, OK, WARN};
const MAX_BODY_ROWS: u16 = 12;
pub fn render_approval(
buf: &mut Buffer,
screen: Rect,
approval: &Approval,
choice_idx: usize,
dock_h: u16,
) {
let popup_w = screen.width.saturating_sub(8).min(110);
if popup_w < 50 {
return;
}
let popup_x = screen.x + 2;
let accent = accent_for(approval);
let body = body_lines(
approval,
popup_w.saturating_sub(6) as usize,
choice_idx,
accent,
);
let actions = action_cells(approval);
let body_h = body.len().min(MAX_BODY_ROWS as usize) as u16;
let popup_h = 2 + body_h + 3;
let bottom_margin = dock_h.max(5) + 1;
if popup_h + bottom_margin > screen.height {
return;
}
let popup_y = screen.bottom().saturating_sub(popup_h + bottom_margin);
if popup_y < screen.y {
return;
}
let popup = Rect::new(popup_x, popup_y, popup_w, popup_h);
draw_box(buf, popup, accent);
draw_title(buf, popup, approval, accent);
let body_top = popup.y + 1;
for (i, line) in body.iter().take(MAX_BODY_ROWS as usize).enumerate() {
paint_str(
buf,
popup.x + 2,
body_top + 1 + i as u16,
line,
FG,
BG,
Modifier::empty(),
);
}
let footer_y = popup.y + popup.height - 2;
draw_actions(buf, popup, footer_y, &actions);
}
fn accent_for(approval: &Approval) -> Color {
match approval {
Approval::Plan { .. } | Approval::Edit { .. } => DS_PURPLE,
Approval::Shell { .. } => OK,
Approval::Path { .. } | Approval::Choice { .. } => DS_BRIGHT,
Approval::Checkpoint { .. } => OK,
}
}
fn draw_title(buf: &mut Buffer, area: Rect, approval: &Approval, accent: Color) {
let row = area.y;
let (glyph, kind, subtitle, dismiss) = title_parts(approval);
let mut col = area.x + 2;
col = paint_str(buf, col, row, glyph, accent, BG, Modifier::BOLD);
col = col.saturating_add(1);
col = paint_str(buf, col, row, kind, accent, BG, Modifier::BOLD);
if !subtitle.is_empty() {
col = col.saturating_add(2);
paint_str(buf, col, row, &subtitle, FG2, BG, Modifier::empty());
}
let hint = format!("esc {dismiss}");
let hint_col = area.x + area.width.saturating_sub(hint.width() as u16 + 2);
paint_str(buf, hint_col, row, &hint, FG3, BG, Modifier::empty());
}
fn title_parts(approval: &Approval) -> (&'static str, &'static str, String, &'static str) {
match approval {
Approval::Plan { body, steps } => {
let n = if steps.is_empty() {
body.lines().filter(|l| !l.trim().is_empty()).count()
} else {
steps.len()
};
(
"◇",
"REVIEW PLAN",
format!("{n} step{}", if n == 1 { "" } else { "s" }),
"skip",
)
}
Approval::Shell { command, .. } => {
let head = first_chunk(command, 40);
("⚡", "SHELL EXEC", head, "dismiss")
}
Approval::Path { path, intent, .. } => (
"▸",
"PATH ACCESS",
format!("{intent} {}", first_chunk(path, 50)),
"deny",
),
Approval::Edit { path, .. } => ("▣", "EDIT PREVIEW", first_chunk(path, 50), "dismiss"),
Approval::Choice { options, .. } => {
let n = options.len();
(
"◆",
"CHOOSE",
format!("{n} option{}", if n == 1 { "" } else { "s" }),
"skip",
)
}
Approval::Checkpoint {
completed, total, ..
} => (
"◉",
"STEP CHECKPOINT",
format!("{completed}/{total}"),
"stop",
),
}
}
fn wrap_inline(line: &str, max: usize) -> Vec<String> {
if line.is_empty() {
return vec![String::new()];
}
let w = max.max(10);
let mut out = Vec::new();
let mut current = String::new();
let mut current_w = 0usize;
for ch in line.chars() {
let cw = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
if current_w + cw > w && !current.is_empty() {
out.push(std::mem::take(&mut current));
current_w = 0;
}
current.push(ch);
current_w += cw;
}
if !current.is_empty() {
out.push(current);
}
if out.is_empty() {
out.push(String::new());
}
out
}
fn first_chunk(s: &str, max: usize) -> String {
let mut out = String::new();
let mut w = 0usize;
for ch in s.chars() {
let cw = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
if w + cw > max {
out.push('…');
break;
}
out.push(ch);
w += cw;
}
out
}
fn body_lines(approval: &Approval, max_w: usize, choice_idx: usize, accent: Color) -> Vec<String> {
let _ = accent;
match approval {
Approval::Plan { body, steps } => {
let mut out = Vec::new();
if !steps.is_empty() {
for (i, step) in steps.iter().enumerate().take(MAX_BODY_ROWS as usize) {
let marker = match step.status.as_str() {
"done" => "✓",
"running" => "◆",
"failed" => "✕",
"blocked" => "⊘",
"skipped" => "·",
_ => "○",
};
let label = first_chunk(&step.title, max_w.saturating_sub(8));
out.push(format!("{marker} [{}] {label}", i + 1));
}
} else {
for raw in body.lines() {
for line in wrap_inline(raw, max_w) {
out.push(line);
if out.len() >= MAX_BODY_ROWS as usize {
return out;
}
}
}
}
if out.is_empty() {
out.push("(plan body is empty)".to_string());
}
out
}
Approval::Shell {
command,
cwd,
timeout_sec,
} => {
let mut out = Vec::new();
out.push(format!(
"$ {}",
first_chunk(command, max_w.saturating_sub(2))
));
let mut meta = Vec::new();
if let Some(dir) = cwd.as_deref() {
meta.push(format!("cwd {dir}"));
}
if let Some(s) = timeout_sec {
meta.push(format!("timeout {s}s"));
}
if !meta.is_empty() {
out.push(String::new());
out.push(meta.join(" "));
}
out
}
Approval::Path {
path,
intent,
tool_name,
} => {
let mut out = Vec::new();
out.push(format!("intent {intent}"));
out.push(format!("tool {tool_name}"));
out.push(format!(
"path {}",
first_chunk(path, max_w.saturating_sub(8))
));
out
}
Approval::Edit {
path,
search,
replace,
} => {
let mut out = Vec::new();
let s_lines = search.lines().count();
let r_lines = replace.lines().count();
out.push(format!("{path} -{s_lines} +{r_lines}"));
out.push(String::new());
for line in search.lines().take(4) {
out.push(format!("- {}", first_chunk(line, max_w.saturating_sub(2))));
}
for line in replace.lines().take(4) {
out.push(format!("+ {}", first_chunk(line, max_w.saturating_sub(2))));
}
out
}
Approval::Checkpoint {
title,
completed,
total,
} => {
let mut out = Vec::new();
if let Some(t) = title.as_deref() {
out.push(format!(
"just finished: {}",
first_chunk(t, max_w.saturating_sub(15))
));
}
out.push(String::new());
out.push(format!("progress: {completed} of {total} step(s) done"));
out.push(String::new());
out.push("continue executing, type a refinement, or stop here?".to_string());
out
}
Approval::Choice {
question, options, ..
} => {
let mut out = Vec::new();
out.push(first_chunk(question, max_w));
out.push(String::new());
let sel = choice_idx.min(options.len().saturating_sub(1));
for (i, opt) in options.iter().enumerate().take(MAX_BODY_ROWS as usize - 2) {
let marker = if i == sel { "●" } else { "○" };
let letter = (b'a' + i as u8) as char;
out.push(format!(
"{letter}) {marker} {}",
first_chunk(&opt.title, max_w.saturating_sub(8))
));
if let Some(summary) = opt.summary.as_deref() {
if !summary.is_empty() {
out.push(format!(
" {}",
first_chunk(summary, max_w.saturating_sub(8))
));
}
}
}
out
}
}
}
fn action_cells(approval: &Approval) -> Vec<(&'static str, &'static str)> {
match approval {
Approval::Plan { .. } => vec![
("↵", "approve"),
("r", "refine"),
("v", "revise"),
("n", "cancel"),
],
Approval::Shell { .. } => vec![
("↵", "run"),
("a", "always allow this command"),
("n", "cancel"),
],
Approval::Path { .. } => vec![("↵", "allow once"), ("a", "always allow"), ("n", "deny")],
Approval::Edit { .. } => vec![
("↵", "apply"),
("r", "reject"),
("t", "rest of turn"),
("y", "flip to auto"),
],
Approval::Checkpoint { .. } => vec![("↵", "continue"), ("r", "revise"), ("s", "stop")],
Approval::Choice { allow_custom, .. } => {
let mut v = vec![("↑↓", "move"), ("↵", "pick"), ("1-9", "jump")];
if *allow_custom {
v.push(("c", "custom"));
}
v.push(("esc", "cancel"));
v
}
}
}
fn draw_actions(buf: &mut Buffer, area: Rect, row: u16, actions: &[(&str, &str)]) {
let sep_row = row.saturating_sub(1);
for x in (area.x + 1)..(area.x + area.width - 1) {
paint(buf, x, sep_row, '┄', FG3, BG, Modifier::empty());
}
let mut col = area.x + 2;
for (i, (key, label)) in actions.iter().enumerate() {
if i > 0 {
col = col.saturating_add(3);
}
col = paint_str(buf, col, row, key, FG1, BG, Modifier::BOLD);
col = col.saturating_add(1);
col = paint_str(buf, col, row, label, FG2, BG, Modifier::empty());
}
}
fn draw_box(buf: &mut Buffer, area: Rect, accent: Color) {
let w = area.width;
if w < 2 {
return;
}
let top = area.y;
let bot = area.y + area.height - 1;
let right = area.x + w - 1;
paint(buf, area.x, top, '╭', accent, BG, Modifier::empty());
paint(buf, right, top, '╮', accent, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, top, '─', accent, BG, Modifier::empty());
}
for y in (top + 1)..bot {
paint(buf, area.x, y, '│', accent, BG, Modifier::empty());
paint(buf, right, y, '│', accent, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, y, ' ', FG, BG, Modifier::empty());
}
}
paint(buf, area.x, bot, '╰', accent, BG, Modifier::empty());
paint(buf, right, bot, '╯', accent, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, bot, '─', accent, BG, Modifier::empty());
}
let _ = (ERR, WARN); // reserved for risk-tag highlights
}
@@ -1,188 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
use crate::state::SceneState;
use super::cards::render_cards;
use super::paint::{paint_link_wrapped, paint_str_to};
use super::theme::{DS, FG, FG2, FG3, LOGO};
pub fn render_scroll(
buf: &mut Buffer,
area: Rect,
state: &SceneState,
scroll_offset: u16,
tick: u32,
) {
if area.height == 0 {
return;
}
let mut row = area.y + 1;
row = render_logo(buf, area, row);
row = row.saturating_add(1);
row = render_boot_meta(buf, area, row, state);
row = row.saturating_add(1);
row = render_hint_line(buf, area, row);
row = row.saturating_add(1);
render_cards(buf, area, row, state, scroll_offset, tick);
}
fn render_logo(buf: &mut Buffer, area: Rect, start_row: u16) -> u16 {
use super::theme::BG;
let end_x = area.x.saturating_add(area.width);
let mut row = start_row;
for line in LOGO {
if row >= area.y + area.height {
break;
}
paint_str_to(buf, area.x + 2, row, line, end_x, DS, BG, Modifier::BOLD);
row += 1;
}
row
}
fn render_boot_meta(buf: &mut Buffer, area: Rect, start_row: u16, state: &SceneState) -> u16 {
use super::theme::{BG, DS_BRIGHT};
let bottom = area.y + area.height;
let end_x = area.x.saturating_add(area.width);
let key_col = area.x + 2;
let val_col = area.x + 14;
let mut row = start_row;
if row < bottom {
if let Some(model) = state.model.as_deref() {
paint_str_to(
buf,
key_col,
row,
"model",
end_x,
FG2,
BG,
Modifier::empty(),
);
let after = paint_str_to(
buf,
val_col,
row,
model,
end_x,
DS_BRIGHT,
BG,
Modifier::empty(),
);
if let Some(cap) = state.ctx_cap {
let ctx_col = after.saturating_add(4);
paint_str_to(
buf,
ctx_col,
row,
"context",
end_x,
FG2,
BG,
Modifier::empty(),
);
let ctx_text = match (state.ctx_tokens, cap) {
(Some(used), cap) if cap > 0 => {
let pct = (f64::from(used) / f64::from(cap) * 100.0) as i32;
format!("{} · {pct}% used", short_tokens(cap))
}
_ => short_tokens(cap),
};
paint_str_to(
buf,
ctx_col.saturating_add(10),
row,
&ctx_text,
end_x,
FG,
BG,
Modifier::empty(),
);
}
row += 1;
}
}
if row < bottom {
if let Some(cwd) = state.cwd.as_deref() {
paint_str_to(
buf,
key_col,
row,
"workdir",
end_x,
FG2,
BG,
Modifier::empty(),
);
paint_str_to(buf, val_col, row, cwd, end_x, FG, BG, Modifier::empty());
row += 1;
}
}
if row < bottom {
if let Some(url) = state.dashboard_url.as_deref() {
paint_str_to(
buf,
key_col,
row,
"dashboard",
end_x,
FG2,
BG,
Modifier::empty(),
);
let used =
paint_link_wrapped(buf, val_col, row, end_x, bottom, url, url, DS_BRIGHT, BG);
row += used.max(1);
}
}
row
}
fn short_tokens(n: u32) -> String {
if n >= 1_000_000 {
format!("{:.1}M", f64::from(n) / 1_000_000.0)
} else if n >= 1_000 {
format!("{}k", n / 1000)
} else {
format!("{n}")
}
}
fn render_hint_line(buf: &mut Buffer, area: Rect, row: u16) -> u16 {
use super::theme::BG;
if row >= area.y + area.height {
return row;
}
let end_x = area.x.saturating_add(area.width);
let mut col = area.x + 2;
let pairs: [(&str, &str); 6] = [
("type to chat", ""),
("/", "commands"),
("@", "file refs"),
("!", "shell"),
("Ctrl+C", "cancel"),
("Ctrl+D", "exit"),
];
for (i, (key, label)) in pairs.iter().enumerate() {
if col >= end_x {
break;
}
if i > 0 {
col = paint_str_to(buf, col, row, " · ", end_x, FG3, BG, Modifier::empty());
}
if label.is_empty() {
col = paint_str_to(buf, col, row, key, end_x, FG2, BG, Modifier::empty());
} else {
col = paint_str_to(buf, col, row, key, end_x, DS, BG, Modifier::BOLD);
col = paint_str_to(buf, col, row, " ", end_x, FG2, BG, Modifier::empty());
col = paint_str_to(buf, col, row, label, end_x, FG2, BG, Modifier::empty());
}
}
row + 1
}
@@ -1,180 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
use crate::state::SceneCard;
use super::super::paint::{paint, paint_str};
use super::super::theme::{BG, DS_BRIGHT, ERR, FG1, FG2, FG3, OK};
pub(super) fn render_diff_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
) -> u16 {
let mut row = render_diff_header(buf, area, start_row, card);
if let Some(body) = card.body.as_deref() {
row = render_diff_body(buf, area, row, body);
}
row.saturating_add(1)
}
fn render_diff_header(buf: &mut Buffer, area: Rect, row: u16, card: &SceneCard) -> u16 {
let bottom = area.y + area.height;
if row >= bottom {
return row;
}
let mut col = area.x;
col = paint_str(buf, col, row, "▎ ", DS_BRIGHT, BG, Modifier::empty());
col = paint_str(buf, col, row, "± ", DS_BRIGHT, BG, Modifier::BOLD);
col = paint_str(
buf,
col,
row,
&card.summary,
DS_BRIGHT,
BG,
Modifier::empty(),
);
if let Some(meta) = card.meta.as_deref() {
col = col.saturating_add(2);
paint_meta(buf, col, row, meta);
}
row + 1
}
fn paint_meta(buf: &mut Buffer, x: u16, row: u16, meta: &str) {
let mut col = x;
for tok in meta.split_whitespace() {
let (fg, modifier) = match tok.chars().next() {
Some('+') => (OK, Modifier::BOLD),
Some('-') | Some('−') => (ERR, Modifier::BOLD),
_ => (FG2, Modifier::empty()),
};
col = paint_str(buf, col, row, tok, fg, BG, modifier);
col = col.saturating_add(1);
}
}
fn render_diff_body(buf: &mut Buffer, area: Rect, start_row: u16, body: &str) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
let mut old_ln: u32 = 0;
let mut new_ln: u32 = 0;
for line in body.split('\n') {
if row >= bottom {
break;
}
if let Some((o, n)) = parse_hunk_header(line) {
old_ln = o;
new_ln = n;
render_hunk_line(buf, area, row, line);
row += 1;
continue;
}
let (kind, rest) = classify_line(line);
render_diff_line(buf, area, row, kind, &mut old_ln, &mut new_ln, rest);
row += 1;
}
row
}
fn render_hunk_line(buf: &mut Buffer, area: Rect, row: u16, line: &str) {
let mut col = area.x;
col = paint_str(buf, col, row, "▎", DS_BRIGHT, BG, Modifier::empty());
col = col.saturating_add(1);
paint_str(buf, col, row, line, FG2, BG, Modifier::ITALIC);
}
#[derive(Clone, Copy)]
enum DiffKind {
Ctx,
Add,
Del,
}
fn classify_line(line: &str) -> (DiffKind, &str) {
match line.chars().next() {
Some('+') => (DiffKind::Add, &line[1..]),
Some('-') => (DiffKind::Del, &line[1..]),
_ => (DiffKind::Ctx, line.strip_prefix(' ').unwrap_or(line)),
}
}
fn render_diff_line(
buf: &mut Buffer,
area: Rect,
row: u16,
kind: DiffKind,
old_ln: &mut u32,
new_ln: &mut u32,
code: &str,
) {
let mut col = area.x;
col = paint_str(buf, col, row, "▎", DS_BRIGHT, BG, Modifier::empty());
col = col.saturating_add(1);
let (ol_show, nl_show, sign_ch, code_fg, sign_fg) = match kind {
DiffKind::Ctx => (Some(*old_ln), Some(*new_ln), ' ', FG1, FG2),
DiffKind::Add => (None, Some(*new_ln), '+', OK, OK),
DiffKind::Del => (Some(*old_ln), None, '-', ERR, ERR),
};
col = paint_str(
buf,
col,
row,
&fmt_lineno(ol_show),
FG3,
BG,
Modifier::empty(),
);
col = col.saturating_add(1);
col = paint_str(
buf,
col,
row,
&fmt_lineno(nl_show),
FG3,
BG,
Modifier::empty(),
);
col = col.saturating_add(1);
paint(buf, col, row, sign_ch, sign_fg, BG, Modifier::empty());
col = col.saturating_add(2);
paint_str(buf, col, row, code, code_fg, BG, Modifier::empty());
match kind {
DiffKind::Ctx => {
*old_ln += 1;
*new_ln += 1;
}
DiffKind::Add => *new_ln += 1,
DiffKind::Del => *old_ln += 1,
}
}
fn fmt_lineno(n: Option<u32>) -> String {
match n {
Some(v) => format!("{v:>3}"),
None => " ".to_string(),
}
}
fn parse_hunk_header(line: &str) -> Option<(u32, u32)> {
let s = line.strip_prefix("@@ -")?;
let (old_part, rest) = s.split_once(' ')?;
let old_start = old_part.split_once(',').map(|(a, _)| a).unwrap_or(old_part);
let new_part = rest.strip_prefix('+')?;
let new_end = new_part
.find(|c: char| !c.is_ascii_digit() && c != ',')
.unwrap_or(new_part.len());
let new_section = &new_part[..new_end];
let new_start = new_section
.split_once(',')
.map(|(a, _)| a)
.unwrap_or(new_section);
Some((old_start.parse().ok()?, new_start.parse().ok()?))
}
@@ -1,135 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
use crate::state::SceneCard;
use super::super::md_render::render_markdown;
use super::super::paint::{format_ts, paint};
use super::super::theme::{BG, DS_BRIGHT, DS_PURPLE, FG, FG1, FG3};
use super::{
body_indent_col, body_width_for, paint_blank_after, paint_body_line, render_card_header,
wrap_visual,
};
pub(super) fn render_user_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
let ts = card.ts.map(format_ts);
render_card_header(
buf,
area,
row,
FG,
"❯",
FG,
"YOU",
FG,
ts.as_deref().map(|s| (s, FG3)),
);
row += 1;
let width = body_width_for(area);
if let Some(body) = card.body.as_deref() {
for raw in body.split('\n') {
for line in wrap_visual(raw, width) {
if row >= bottom {
return row;
}
paint_body_line(buf, area, row, FG, &line, FG, Modifier::empty());
row += 1;
}
}
}
paint_blank_after(buf, area, row, FG)
}
pub(super) fn render_reasoning_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
render_card_header(
buf,
area,
row,
DS_PURPLE,
"◇",
DS_PURPLE,
"THINKING",
DS_PURPLE,
card.meta.as_deref().map(|s| (s, FG3)),
);
row += 1;
let width = body_width_for(area);
if let Some(body) = card.body.as_deref() {
for raw in body.split('\n') {
for line in wrap_visual(raw, width) {
if row >= bottom {
return row;
}
paint_body_line(buf, area, row, DS_PURPLE, &line, FG1, Modifier::ITALIC);
row += 1;
}
}
}
paint_blank_after(buf, area, row, DS_PURPLE)
}
pub(super) fn render_assistant_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
streaming: bool,
tick: u32,
) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
let meta_text = if streaming {
Some("streaming…".to_string())
} else {
card.ts.map(format_ts)
};
render_card_header(
buf,
area,
row,
DS_BRIGHT,
"◆",
DS_BRIGHT,
"REASONIX",
DS_BRIGHT,
meta_text.as_deref().map(|s| (s, FG3)),
);
row += 1;
if let Some(body) = card.body.as_deref() {
let revealed: String = if streaming {
let total_chars = body.chars().count();
let n = ((tick as usize) / 2).min(total_chars);
body.chars().take(n).collect()
} else {
body.to_string()
};
let prev_row = row;
row = render_markdown(buf, area, row, bottom, DS_BRIGHT, FG, &revealed);
if streaming && (tick / 6).is_multiple_of(2) {
let caret_row = if row > prev_row { row - 1 } else { prev_row };
if caret_row < bottom {
let col = body_indent_col(area) + 4;
paint(buf, col, caret_row, '▊', DS_BRIGHT, BG, Modifier::empty());
}
}
if streaming && row == prev_row {
row = (prev_row + 1).min(bottom);
}
}
paint_blank_after(buf, area, row, DS_BRIGHT)
}
@@ -1,344 +0,0 @@
mod diff;
mod message;
mod notify;
mod output;
mod todo;
mod tool;
pub(super) use todo::{parse_todo_items, TodoState};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier};
use unicode_width::UnicodeWidthStr;
use crate::state::{SceneCard, SceneState};
use super::paint::{paint, paint_str};
use super::theme::{BG, DS, FG1, FG2, FG3, OK};
pub fn render_cards(
buf: &mut Buffer,
area: Rect,
start_row: u16,
state: &SceneState,
scroll_offset: u16,
tick: u32,
) {
let bottom = area.y + area.height;
if start_row >= bottom {
return;
}
if state.cards.is_empty() {
render_idle_banner(buf, area, start_row);
return;
}
let avail = bottom - start_row;
let scroll_w = if area.width > 0 { area.width - 1 } else { 0 };
if scroll_w == 0 {
return;
}
let body_w = body_width_for(Rect::new(0, 0, scroll_w, 1));
let total: u16 = state.cards.iter().map(|c| card_height(c, body_w)).sum();
if total == 0 {
return;
}
let virt_rect = Rect::new(0, 0, scroll_w, total);
let mut virt = Buffer::empty(virt_rect);
let mut row = 0u16;
let last_idx = state.cards.len().saturating_sub(1);
for (i, card) in state.cards.iter().enumerate() {
let streaming = state.busy && i == last_idx;
row = render_card(&mut virt, virt_rect, row, card, streaming, tick);
}
let max_offset = total.saturating_sub(avail);
let offset = scroll_offset.min(max_offset);
let view_h = avail.min(total);
let view_top = total.saturating_sub(view_h).saturating_sub(offset);
let dest_top = bottom.saturating_sub(view_h);
for dy in 0..view_h {
let src_y = view_top + dy;
if src_y >= total {
break;
}
for dx in 0..scroll_w {
buf[(area.x + dx, dest_top + dy)] = virt[(dx, src_y)].clone();
}
}
render_scrollbar(buf, area, start_row, total, view_h, offset);
}
fn render_scrollbar(
buf: &mut Buffer,
area: Rect,
start_row: u16,
total: u16,
view_h: u16,
offset: u16,
) {
if area.width == 0 || view_h == 0 || total <= view_h {
return;
}
let track_x = area.x + area.width - 1;
let track_top = area.y + area.height.saturating_sub(view_h);
let max_offset = total - view_h;
let thumb_size = ((view_h as f32 / total as f32) * view_h as f32).round() as u16;
let thumb_size = thumb_size.max(1).min(view_h);
let track_space = view_h - thumb_size;
let thumb_top = if max_offset == 0 {
track_space
} else {
let ratio = 1.0 - (offset as f32 / max_offset as f32);
(ratio * track_space as f32).round() as u16
};
for y in 0..view_h {
let abs_y = track_top + y;
if abs_y < start_row {
continue;
}
let in_thumb = y >= thumb_top && y < thumb_top + thumb_size;
let (ch, fg) = if in_thumb { ('█', FG2) } else { ('│', FG3) };
paint(buf, track_x, abs_y, ch, fg, BG, Modifier::empty());
}
}
fn render_idle_banner(buf: &mut Buffer, area: Rect, start_row: u16) {
let bottom = area.y + area.height;
if start_row >= bottom {
return;
}
paint_rail(buf, area, start_row, OK);
let mut col = area.x + 2;
col = paint_str(buf, col, start_row, "● ", OK, BG, Modifier::BOLD);
col = paint_str(buf, col, start_row, "idle", OK, BG, Modifier::BOLD);
let meta = "ready for next task";
let mcol = area.x + area.width.saturating_sub(meta.len() as u16 + 1);
paint_str(
buf,
mcol.max(col + 2),
start_row,
meta,
FG3,
BG,
Modifier::empty(),
);
let row = start_row + 1;
if row >= bottom {
return;
}
paint_rail(buf, area, row, OK);
let mut tcol = area.x + 4;
tcol = paint_str(buf, tcol, row, "type below", FG1, BG, Modifier::empty());
let pairs: [(&str, &str); 3] = [("/", "commands"), ("@", "file refs"), ("!", "shell")];
for (key, label) in pairs {
tcol = paint_str(buf, tcol, row, " · ", FG3, BG, Modifier::empty());
tcol = paint_str(buf, tcol, row, key, DS, BG, Modifier::BOLD);
tcol = paint_str(buf, tcol, row, " ", FG2, BG, Modifier::empty());
tcol = paint_str(buf, tcol, row, label, FG2, BG, Modifier::empty());
}
// Starter hints — surfaces the most-likely-useful slash commands
// upfront, matches the Node TUI WelcomeBanner; helps brand-new
// users discover the surface without /help.
let starters: [(&str, &str); 4] = [
("/help", "see all commands"),
("/cost", "session spend + tokens"),
("/init", "scan repo into REASONIX.md"),
("/sessions", "switch / resume past sessions"),
];
for (i, (cmd, desc)) in starters.iter().enumerate() {
let r = start_row + 3 + i as u16;
if r >= bottom {
break;
}
paint_rail(buf, area, r, OK);
let mut sc = area.x + 4;
sc = paint_str(buf, sc, r, cmd, DS, BG, Modifier::BOLD);
sc = paint_str(buf, sc, r, " ", FG3, BG, Modifier::empty());
paint_str(buf, sc, r, desc, FG2, BG, Modifier::empty());
}
}
pub(super) fn total_cards_height(state: &SceneState, body_width: u16) -> u16 {
state.cards.iter().map(|c| card_height(c, body_width)).sum()
}
pub(super) fn render_card_to(
buf: &mut Buffer,
area: Rect,
row: u16,
card: &SceneCard,
streaming: bool,
) -> u16 {
render_card(buf, area, row, card, streaming, u32::MAX)
}
pub(super) fn body_width_for(area: Rect) -> u16 {
area.width.saturating_sub(4)
}
pub(super) fn wrap_visual(line: &str, width: u16) -> Vec<String> {
let w = width as usize;
if w == 0 {
return vec![String::new()];
}
if line.is_empty() {
return vec![String::new()];
}
if UnicodeWidthStr::width(line) <= w {
return vec![line.to_string()];
}
let mut out = Vec::new();
let mut current = String::new();
let mut current_w = 0usize;
for ch in line.chars() {
let ch_w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
if current_w + ch_w > w && !current.is_empty() {
out.push(std::mem::take(&mut current));
current_w = 0;
}
current.push(ch);
current_w += ch_w;
}
if !current.is_empty() {
out.push(current);
}
if out.is_empty() {
out.push(String::new());
}
out
}
fn body_lines_height(body: &str, width: u16) -> u16 {
let mut total = 0u32;
for line in body.split('\n') {
let count = wrap_visual(line, width).len().max(1) as u32;
total += count;
}
total.min(u16::MAX as u32) as u16
}
fn card_height(card: &SceneCard, body_width: u16) -> u16 {
let is_md = matches!(card.kind.as_str(), "assistant" | "streaming");
let body_lines = card
.body
.as_deref()
.map(|b| {
if is_md {
super::md_render::count_visual_rows(b, body_width).min(u16::MAX as usize) as u16
} else {
body_lines_height(b, body_width)
}
})
.unwrap_or(0);
match card.kind.as_str() {
"user" | "reasoning" | "think" | "thinking" | "assistant" | "streaming" | "diff"
| "cmd" | "fileview" | "search" | "subagent" | "confirm" | "await" | "await_input"
| "error" | "info" | "warn" | "usage" | "doctor" | "memory" | "ctx" | "plan-card"
| "task" => 1 + body_lines + 1,
"todo" | "plan" => {
let items = card
.body
.as_deref()
.map(|b| parse_todo_items(b).len() as u16)
.unwrap_or(0);
1 + items + 1
}
"tool" => 1,
_ => 0,
}
}
fn render_card(
buf: &mut Buffer,
area: Rect,
row: u16,
card: &SceneCard,
streaming: bool,
tick: u32,
) -> u16 {
match card.kind.as_str() {
"user" => message::render_user_card(buf, area, row, card),
"reasoning" | "think" | "thinking" => message::render_reasoning_card(buf, area, row, card),
"tool" => tool::render_tool_card(buf, area, row, card, tick),
"assistant" | "streaming" => {
message::render_assistant_card(buf, area, row, card, streaming, tick)
}
"todo" | "plan" => todo::render_todo_card(buf, area, row, card),
"diff" => diff::render_diff_card(buf, area, row, card),
"cmd" => output::render_cmd_card(buf, area, row, card),
"fileview" => output::render_fileview_card(buf, area, row, card),
"search" => output::render_search_card(buf, area, row, card),
"subagent" => notify::render_subagent_card(buf, area, row, card),
"confirm" => notify::render_confirm_card(buf, area, row, card),
"await" | "await_input" => notify::render_await_card(buf, area, row, card),
"error" => notify::render_error_card(buf, area, row, card),
"info" => notify::render_info_card(buf, area, row, card, super::theme::INFO, "ⓘ"),
"warn" => notify::render_info_card(buf, area, row, card, super::theme::WARN, "▲"),
"usage" => notify::render_info_card(buf, area, row, card, super::theme::DS_BRIGHT, "$"),
"doctor" => notify::render_info_card(buf, area, row, card, super::theme::OK, "✚"),
"memory" => notify::render_info_card(buf, area, row, card, super::theme::DS_PURPLE, "◈"),
"ctx" => notify::render_info_card(buf, area, row, card, super::theme::INFO, "▦"),
"plan-card" => notify::render_info_card(buf, area, row, card, super::theme::DS_PURPLE, "◆"),
"task" => notify::render_info_card(buf, area, row, card, super::theme::DS_BRIGHT, "▸"),
_ => row,
}
}
pub(super) fn paint_rail(buf: &mut Buffer, area: Rect, row: u16, color: Color) {
paint(buf, area.x, row, '▎', color, BG, Modifier::empty());
}
#[allow(clippy::too_many_arguments)]
pub(super) fn render_card_header(
buf: &mut Buffer,
area: Rect,
row: u16,
rail_color: Color,
glyph: &str,
glyph_fg: Color,
label: &str,
label_fg: Color,
meta_right: Option<(&str, Color)>,
) {
paint_rail(buf, area, row, rail_color);
let mut col = area.x + 2;
col = paint_str(buf, col, row, glyph, glyph_fg, BG, Modifier::BOLD);
col = col.saturating_add(1);
paint_str(buf, col, row, label, label_fg, BG, Modifier::BOLD);
if let Some((text, fg)) = meta_right {
let w = text.width() as u16;
let mcol = area.x + area.width.saturating_sub(w + 1);
paint_str(buf, mcol, row, text, fg, BG, Modifier::empty());
}
}
pub(super) fn body_indent_col(area: Rect) -> u16 {
area.x + 4
}
pub(super) fn paint_body_line(
buf: &mut Buffer,
area: Rect,
row: u16,
rail_color: Color,
line: &str,
fg: Color,
modifier: Modifier,
) {
paint_rail(buf, area, row, rail_color);
paint_str(buf, body_indent_col(area), row, line, fg, BG, modifier);
}
pub(super) fn paint_blank_after(buf: &mut Buffer, area: Rect, row: u16, rail_color: Color) -> u16 {
if row >= area.y + area.height {
return row;
}
paint_rail(buf, area, row, rail_color);
row + 1
}
@@ -1,246 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
use unicode_width::UnicodeWidthStr;
use crate::state::SceneCard;
use super::super::paint::{paint, paint_str};
use super::super::theme::{BG, DS_BRIGHT, ERR, FG, FG1, FG2, FG3, INFO, WARN};
use super::{
body_indent_col, body_width_for, paint_blank_after, paint_body_line, paint_rail,
render_card_header, wrap_visual,
};
pub(super) fn render_subagent_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
render_card_header(
buf,
area,
row,
INFO,
"⧪",
INFO,
&card.summary,
INFO,
card.meta.as_deref().map(|s| (s, FG3)),
);
row += 1;
let width = body_width_for(area);
if let Some(body) = card.body.as_deref() {
for (i, raw) in body.split('\n').enumerate() {
let wrap_w = if i == 0 {
width
} else {
width.saturating_sub(2)
};
for (wi, line) in wrap_visual(raw, wrap_w).iter().enumerate() {
if row >= bottom {
return row;
}
if i == 0 || wi > 0 {
paint_body_line(buf, area, row, INFO, line, FG1, Modifier::empty());
} else {
paint_rail(buf, area, row, INFO);
let col = body_indent_col(area);
paint(buf, col, row, '→', INFO, BG, Modifier::BOLD);
paint_str(buf, col + 2, row, line, FG1, BG, Modifier::empty());
}
row += 1;
}
}
}
paint_blank_after(buf, area, row, INFO)
}
pub(super) fn render_confirm_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
let title = format!("permission required · {}", card.summary);
render_card_header(buf, area, row, WARN, "⚠", WARN, &title, WARN, None);
row += 1;
if let Some(body) = card.body.as_deref() {
let mut lines = body.split('\n');
if let Some(question) = lines.next() {
if row < bottom {
paint_body_line(buf, area, row, WARN, question, FG, Modifier::empty());
row += 1;
}
}
for opts in lines {
if row >= bottom {
return row;
}
paint_rail(buf, area, row, WARN);
let mut col = body_indent_col(area);
for tok in opts.split_whitespace() {
col = paint_option_token(buf, col, row, tok);
col = col.saturating_add(2);
}
row += 1;
}
}
paint_blank_after(buf, area, row, WARN)
}
fn paint_option_token(buf: &mut Buffer, x: u16, row: u16, tok: &str) -> u16 {
let (key, label) = match tok.find(']') {
Some(close) if tok.starts_with('[') => {
let key = &tok[1..close];
let label = &tok[close + 1..];
(key, label)
}
_ => ("", tok),
};
let mut col = x;
if !key.is_empty() {
let key_fg = match key {
"y" | "Y" => DS_BRIGHT,
"n" | "N" => FG2,
"a" | "A" => ERR,
_ => FG1,
};
col = paint_str(buf, col, row, "[", FG3, BG, Modifier::empty());
col = paint_str(buf, col, row, key, key_fg, BG, Modifier::BOLD);
col = paint_str(buf, col, row, "]", FG3, BG, Modifier::empty());
col = col.saturating_add(1);
}
paint_str(buf, col, row, label, FG1, BG, Modifier::empty())
}
pub(super) fn render_await_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
render_card_header(
buf,
area,
row,
DS_BRIGHT,
"?",
DS_BRIGHT,
if card.summary.is_empty() {
"awaiting input"
} else {
&card.summary
},
DS_BRIGHT,
None,
);
row += 1;
if let Some(body) = card.body.as_deref() {
let mut lines = body.split('\n');
if let Some(question) = lines.next() {
if row < bottom {
paint_body_line(buf, area, row, DS_BRIGHT, question, FG, Modifier::empty());
row += 1;
}
}
for line in lines {
if row >= bottom {
return row;
}
paint_rail(buf, area, row, DS_BRIGHT);
let col = body_indent_col(area);
paint_await_option(buf, col, row, line);
row += 1;
}
}
paint_blank_after(buf, area, row, DS_BRIGHT)
}
fn paint_await_option(buf: &mut Buffer, x: u16, row: u16, line: &str) {
if let Some(close) = line.find(')') {
let key = &line[..close];
let label = line[close + 1..].trim_start();
let key_w = key.width() as u16;
paint_str(buf, x, row, key, DS_BRIGHT, BG, Modifier::BOLD);
paint_str(buf, x + key_w, row, ")", FG2, BG, Modifier::empty());
paint_str(buf, x + key_w + 2, row, label, FG1, BG, Modifier::empty());
} else {
paint_str(buf, x, row, line, FG1, BG, Modifier::empty());
}
}
pub(super) fn render_info_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
accent: ratatui::style::Color,
glyph: &str,
) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
let meta = card.meta.as_deref().map(|m| (m, FG2));
render_card_header(
buf,
area,
row,
accent,
glyph,
accent,
&card.summary,
accent,
meta,
);
row += 1;
if let Some(body) = card.body.as_deref() {
let width = body_width_for(area);
for raw in body.split('\n') {
for line in wrap_visual(raw, width) {
if row >= bottom {
return row;
}
paint_body_line(buf, area, row, accent, &line, FG1, Modifier::empty());
row += 1;
}
}
}
paint_blank_after(buf, area, row, accent)
}
pub(super) fn render_error_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
render_card_header(buf, area, row, ERR, "✕", ERR, &card.summary, ERR, None);
row += 1;
if let Some(body) = card.body.as_deref() {
let width = body_width_for(area);
for raw in body.split('\n') {
let fg = if raw.trim_start().starts_with("at ") {
FG2
} else {
FG
};
for line in wrap_visual(raw, width) {
if row >= bottom {
return row;
}
paint_body_line(buf, area, row, ERR, &line, fg, Modifier::empty());
row += 1;
}
}
}
paint_blank_after(buf, area, row, ERR)
}
@@ -1,157 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
use unicode_width::UnicodeWidthStr;
use crate::state::SceneCard;
use super::super::paint::paint_str;
use super::super::theme::{BG, DS_BRIGHT, ERR, FG, FG1, FG2, FG3, INFO, OK};
use super::{
body_width_for, paint_blank_after, paint_body_line, paint_rail, render_card_header, wrap_visual,
};
pub(super) fn render_cmd_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
paint_rail(buf, area, row, OK);
let mut col = area.x + 2;
col = paint_str(buf, col, row, "$ ", OK, BG, Modifier::BOLD);
col = paint_str(buf, col, row, &card.summary, FG, BG, Modifier::empty());
if let Some(meta) = card.meta.as_deref() {
let w = meta.width() as u16;
let mcol = area.x + area.width.saturating_sub(w + 1);
let fg = if meta.contains("0") && meta.starts_with("exit 0") {
OK
} else if meta.starts_with("exit ") {
ERR
} else {
FG2
};
paint_str(buf, mcol.max(col + 2), row, meta, fg, BG, Modifier::empty());
}
row += 1;
if let Some(body) = card.body.as_deref() {
let width = body_width_for(area);
for raw in body.split('\n') {
let trimmed = raw.trim_end();
let fg = if trimmed.starts_with(" ✓") || trimmed.contains("passed") {
OK
} else if trimmed.starts_with(" ✕") || trimmed.contains("failed") {
ERR
} else if trimmed.starts_with("stdout")
|| trimmed.starts_with("stderr")
|| trimmed.starts_with(" RUN")
{
FG2
} else {
FG1
};
for line in wrap_visual(trimmed, width) {
if row >= bottom {
return row;
}
paint_body_line(buf, area, row, OK, &line, fg, Modifier::empty());
row += 1;
}
}
}
paint_blank_after(buf, area, row, OK)
}
pub(super) fn render_fileview_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
render_card_header(
buf,
area,
row,
DS_BRIGHT,
"📄",
DS_BRIGHT,
&card.summary,
DS_BRIGHT,
card.meta.as_deref().map(|s| (s, FG3)),
);
row += 1;
if let Some(body) = card.body.as_deref() {
for line in body.split('\n') {
if row >= bottom {
return row;
}
paint_rail(buf, area, row, DS_BRIGHT);
let (ln, code) = split_first_colon(line);
let mut col = area.x + 2;
col = paint_str(
buf,
col,
row,
&format!("{ln:>4}"),
FG3,
BG,
Modifier::empty(),
);
col = col.saturating_add(2);
paint_str(buf, col, row, code, FG1, BG, Modifier::empty());
row += 1;
}
}
paint_blank_after(buf, area, row, DS_BRIGHT)
}
pub(super) fn render_search_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
) -> u16 {
let bottom = area.y + area.height;
let mut row = start_row;
render_card_header(
buf,
area,
row,
INFO,
"⌕",
INFO,
&card.summary,
INFO,
card.meta.as_deref().map(|s| (s, FG3)),
);
row += 1;
if let Some(body) = card.body.as_deref() {
for line in body.split('\n') {
if row >= bottom {
return row;
}
paint_rail(buf, area, row, INFO);
let (file_part, rest) = split_first_colon(line);
let (ln_part, code_part) = split_first_colon(rest);
let mut col = area.x + 2;
col = paint_str(buf, col, row, file_part, DS_BRIGHT, BG, Modifier::empty());
col = paint_str(buf, col, row, ":", FG3, BG, Modifier::empty());
col = paint_str(buf, col, row, ln_part, FG2, BG, Modifier::empty());
col = col.saturating_add(2);
paint_str(buf, col, row, code_part, FG1, BG, Modifier::empty());
row += 1;
}
}
paint_blank_after(buf, area, row, INFO)
}
fn split_first_colon(s: &str) -> (&str, &str) {
match s.split_once(':') {
Some((a, b)) => (a, b),
None => (s, ""),
}
}
@@ -1,79 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
use crate::state::SceneCard;
use super::super::paint::paint_str;
use super::super::theme::{BG, DS_BRIGHT, DS_PURPLE, FG, FG1, FG2, FG3, OK};
use super::{paint_blank_after, paint_rail, render_card_header};
#[derive(Clone, Copy)]
pub(in crate::whole_screen) enum TodoState {
Done,
Active,
Pending,
}
pub(in crate::whole_screen) fn parse_todo_items(body: &str) -> Vec<(TodoState, &str)> {
body.lines()
.filter_map(|line| {
let t = line.trim_start();
if let Some(rest) = t.strip_prefix("[x]") {
Some((TodoState::Done, rest.trim_start()))
} else if let Some(rest) = t.strip_prefix("[~]") {
Some((TodoState::Active, rest.trim_start()))
} else if let Some(rest) = t.strip_prefix("[ ]") {
Some((TodoState::Pending, rest.trim_start()))
} else {
None
}
})
.collect()
}
pub(super) fn render_todo_card(
buf: &mut Buffer,
area: Rect,
start_row: u16,
card: &SceneCard,
) -> u16 {
let bottom = area.y + area.height;
let body = card.body.as_deref().unwrap_or("");
let items = parse_todo_items(body);
let done = items
.iter()
.filter(|(s, _)| matches!(s, TodoState::Done))
.count();
let meta = format!("{} of {} complete", done, items.len());
let mut row = start_row;
render_card_header(
buf,
area,
row,
DS_PURPLE,
"◆",
DS_PURPLE,
"PLAN",
DS_PURPLE,
Some((&meta, FG3)),
);
row += 1;
for (state, label) in items {
if row >= bottom {
return row;
}
paint_rail(buf, area, row, DS_PURPLE);
let (marker, marker_fg, label_fg, label_mod) = match state {
TodoState::Done => ("[x]", OK, FG2, Modifier::empty()),
TodoState::Active => ("[~]", DS_BRIGHT, FG, Modifier::BOLD),
TodoState::Pending => ("[ ]", FG3, FG1, Modifier::empty()),
};
let mut c = area.x + 2;
c = paint_str(buf, c, row, marker, marker_fg, BG, Modifier::BOLD);
c = c.saturating_add(1);
paint_str(buf, c, row, label, label_fg, BG, label_mod);
row += 1;
}
paint_blank_after(buf, area, row, DS_PURPLE)
}
@@ -1,78 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier};
use unicode_width::UnicodeWidthStr;
use crate::state::{SceneCard, ToolStatus};
use super::super::paint::paint_str;
use super::super::theme::{BG, DS_BRIGHT, DS_PURPLE, ERR, FG, FG1, FG2, FG3, INFO, OK, WARN};
use super::paint_rail;
const SPINNER: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
fn spinner_frame(tick: u32) -> char {
SPINNER[(tick as usize) % SPINNER.len()]
}
pub(super) fn render_tool_card(
buf: &mut Buffer,
area: Rect,
row: u16,
card: &SceneCard,
tick: u32,
) -> u16 {
let bottom = area.y + area.height;
if row >= bottom {
return row;
}
paint_rail(buf, area, row, FG2);
let mut col = area.x + 2;
col = paint_str(buf, col, row, "▸ ", FG2, BG, Modifier::empty());
let name = card.summary.as_str();
let name_fg = tool_name_color(name);
col = paint_str(buf, col, row, name, name_fg, BG, Modifier::BOLD);
if let Some(args) = card.args.as_deref() {
col = paint_str(buf, col, row, " (", FG2, BG, Modifier::empty());
col = paint_str(buf, col, row, args, FG1, BG, Modifier::empty());
col = paint_str(buf, col, row, ")", FG2, BG, Modifier::empty());
}
let elapsed = card.elapsed.as_deref().unwrap_or("");
let id = card.id.as_deref().unwrap_or("");
let mut spin_buf = [0u8; 4];
let (status_glyph, status_fg): (&str, _) = match card.status {
Some(ToolStatus::Ok) => ("✓", OK),
Some(ToolStatus::Err) => ("✕", ERR),
Some(ToolStatus::Running) => (spinner_frame(tick).encode_utf8(&mut spin_buf), WARN),
None => ("", FG3),
};
let right_w =
status_glyph.width() as u16 + 1 + elapsed.width() as u16 + 2 + id.width() as u16 + 1;
let mut rcol = area.x + area.width.saturating_sub(right_w);
if rcol < col + 2 {
rcol = col + 2;
}
if !status_glyph.is_empty() {
rcol = paint_str(buf, rcol, row, status_glyph, status_fg, BG, Modifier::BOLD);
rcol = rcol.saturating_add(1);
}
if !elapsed.is_empty() {
rcol = paint_str(buf, rcol, row, elapsed, FG2, BG, Modifier::empty());
rcol = rcol.saturating_add(2);
}
if !id.is_empty() {
paint_str(buf, rcol, row, id, FG3, BG, Modifier::empty());
}
row + 1
}
fn tool_name_color(name: &str) -> Color {
match name {
"Read" | "FileView" => DS_BRIGHT,
"Grep" | "Search" => INFO,
"Edit" | "Write" => DS_PURPLE,
"Bash" => OK,
"Fetch" | "WebFetch" => WARN,
_ => FG,
}
}
@@ -1,173 +0,0 @@
use chrono::Local;
use crate::state::{SceneCard, SceneState, SlashMatch, ToolStatus};
pub fn demo_state() -> SceneState {
let ts = Local::now().timestamp();
SceneState {
model: Some("deepseek-v3.2-coder".to_string()),
cwd: Some("~/work/reasonix-core".to_string()),
mcp_server_count: Some(0),
composer_text: Some(String::new()),
composer_cursor: Some(0),
busy: true,
activity: Some("streaming".to_string()),
ctx_tokens: Some(19_200),
ctx_cap: Some(128_000),
session_cost_usd: Some(0.043),
last_turn_cost_usd: Some(0.012),
cache_hit_ratio: Some(0.87),
last_turn_ms: Some(2_100),
session_input_tokens: Some(12_408),
session_output_tokens: Some(3_194),
edit_mode: Some(crate::state::EditMode::Auto),
preset: Some("pro".to_string()),
slash_catalog: Some(
[
("clear", "reset conversation context"),
("compact", "summarize history to free up tokens"),
("commit", "create a git commit from current changes"),
("diff", "show pending edits as a diff"),
("undo", "revert the last file edit"),
("help", "show help"),
]
.iter()
.map(|(cmd, summary)| SlashMatch {
cmd: (*cmd).to_string(),
summary: (*summary).to_string(),
group: Some("chat".to_string()),
args_hint: None,
aliases: Vec::new(),
arg_completer: None,
})
.collect(),
),
cards: vec![
SceneCard {
kind: "user".to_string(),
body: Some(
"帮我把 parser.ts 里的 token 流处理改成异步迭代器,顺便加点测试。".to_string(),
),
ts: Some(ts),
..Default::default()
},
SceneCard {
kind: "reasoning".to_string(),
body: Some(
"需要先看下当前 parser.ts 结构,再决定怎么改。\n\
流式场景下 AsyncIterator 比 callback 更自然。\n\
调用方有 7 处用到 parseStream,要确认接口形态变化是否会破坏外层。"
.to_string(),
),
meta: Some("8 steps · 2.1s".to_string()),
..Default::default()
},
SceneCard {
kind: "todo".to_string(),
body: Some(
"[x] 阅读 parser.ts 当前实现\n\
[x] 检查调用方依赖\n\
[~] 改写为 AsyncIterator 接口\n\
[ ] 迁移现有 callback 调用\n\
[ ] 编写 vitest 单元测试"
.to_string(),
),
..Default::default()
},
SceneCard {
kind: "tool".to_string(),
summary: "Read".to_string(),
args: Some("src/parser.ts".to_string()),
status: Some(ToolStatus::Ok),
elapsed: Some("0.12s".to_string()),
id: Some("#a4f1".to_string()),
..Default::default()
},
SceneCard {
kind: "tool".to_string(),
summary: "Grep".to_string(),
args: Some("\"parseStream\", in: src/".to_string()),
status: Some(ToolStatus::Ok),
elapsed: Some("0.08s".to_string()),
id: Some("#a4f2".to_string()),
..Default::default()
},
SceneCard {
kind: "subagent".to_string(),
summary: "subagent: code-reviewer".to_string(),
meta: Some("3 steps · 1.4s".to_string()),
body: Some(
"审查 parseStream 调用方是否依赖旧返回值形状\n\
scanned 7 call-sites in src/render/, src/parser.ts, tests/\n\
all callers expect AsyncIterable<Token>\n\
safe to rewrite, no caller migration needed"
.to_string(),
),
..Default::default()
},
SceneCard {
kind: "tool".to_string(),
summary: "Edit".to_string(),
args: Some("src/parser.ts, +34 -18".to_string()),
status: Some(ToolStatus::Running),
..Default::default()
},
SceneCard {
kind: "fileview".to_string(),
summary: "src/parser.ts".to_string(),
meta: Some("36 more lines".to_string()),
body: Some(
"14:import { escape } from \"./html\";\n\
15:\n\
16:// renders a single token to its display form\n\
17:export function formatToken(t: Token) {\n\
18: const { kind, value } = t;\n\
19: if (kind === \"text\") return value;\n\
20: return `<${kind}>${value}</${kind}>`;\n\
21:}"
.to_string(),
),
..Default::default()
},
SceneCard {
kind: "search".to_string(),
summary: "grep \"parseStream\" in src/".to_string(),
meta: Some("4 matches · 3 files".to_string()),
body: Some(
"src/render/output.ts:42:return chunks.map(parseStream).join(\"\");\n\
src/render/output.ts:88:const out = parseStream(token);\n\
src/parser.ts:134:stream.push(parseStream(t));\n\
tests/format.spec.ts:11:expect(parseStream({kind:\"text\"})).toBe(\"hi\");"
.to_string(),
),
..Default::default()
},
SceneCard {
kind: "cmd".to_string(),
summary: "pnpm test parser".to_string(),
meta: Some("exit 0 · 2.1s".to_string()),
body: Some(
" RUN v1.6.0 ~/work/reasonix-core\n\
\n\
stdout | parser.spec.ts > StreamParser\n\
✓ yields tokens from async iterable (3 ms)\n\
✓ handles split chunks across boundaries (5 ms)\n\
\n\
Test Files 1 passed (1)\n\
Tests 24 passed (24)"
.to_string(),
),
..Default::default()
},
SceneCard {
kind: "streaming".to_string(),
body: Some(
"已经把 parseStream 改成 async *parse() 异步生成器,并把 7 处调用迁移完成。"
.to_string(),
),
..Default::default()
},
],
..Default::default()
}
}
@@ -1,459 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier};
use unicode_width::UnicodeWidthStr;
use crate::state::SceneState;
use super::paint::{paint, paint_str};
use super::theme::{
BG, COMPOSER_PLACEHOLDER, DS_BRIGHT, DS_PURPLE, ERR, FG, FG1, FG2, FG3, INFO, OK, WARN,
};
pub fn render_dock(buf: &mut Buffer, area: Rect, state: &SceneState, tick: u32) {
if area.height < 3 {
return;
}
let inner_w = area.width;
let box_h = area.height.saturating_sub(2).max(3);
render_input_box(buf, area, box_h, state, tick);
let mut row = area.y + box_h;
if row < area.y + area.height {
render_input_meta(buf, area, row, inner_w);
row += 1;
}
if row < area.y + area.height {
render_status_bar(buf, area, row, inner_w, state);
}
}
fn render_input_box(buf: &mut Buffer, area: Rect, rows: u16, state: &SceneState, tick: u32) {
let w = area.width;
if w < 4 || rows < 3 {
return;
}
let top = area.y;
let bot = top + rows.saturating_sub(1);
let right = area.x + w - 1;
paint(buf, area.x, top, '╭', FG3, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, top, '─', FG3, BG, Modifier::empty());
}
paint(buf, right, top, '╮', FG3, BG, Modifier::empty());
for y in (top + 1)..bot {
paint(buf, area.x, y, '│', FG3, BG, Modifier::empty());
paint(buf, right, y, '│', FG3, BG, Modifier::empty());
}
paint(buf, area.x, bot, '╰', FG3, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, bot, '─', FG3, BG, Modifier::empty());
}
paint(buf, right, bot, '╯', FG3, BG, Modifier::empty());
let content_rows = rows.saturating_sub(2);
let prompt_input = state.prompt_input.as_ref();
let prompt_color = if prompt_input.is_some() {
WARN
} else {
match state
.composer_text
.as_deref()
.and_then(|s| s.chars().next())
{
Some('!') => OK,
Some('/') => DS_BRIGHT,
Some('@') => DS_PURPLE,
_ => DS_BRIGHT,
}
};
let raw_text = state.composer_text.as_deref().unwrap_or("");
let masked_storage: String;
let text: &str = if let Some(p) = prompt_input {
if p.secret {
masked_storage = "•".repeat(raw_text.chars().count());
&masked_storage
} else {
raw_text
}
} else {
raw_text
};
let placeholder: &str = if let Some(p) = prompt_input {
&p.label
} else {
COMPOSER_PLACEHOLDER
};
let prompt_glyph: &str = if prompt_input.is_some() { "? " } else { "❯ " };
let show_caret = (tick / 6).is_multiple_of(2);
let total_chars = text.chars().count();
let cursor = state
.composer_cursor
.unwrap_or(total_chars)
.min(total_chars);
let col_start = area.x + 2;
let text_start = col_start + 2;
let inner_w = if right > text_start + 1 {
(right - text_start - 1) as usize
} else {
0
};
let (visual_lines, cursor_visual_row, cursor_visual_col) =
build_composer_visual_lines(text, cursor, inner_w);
let visual_count = visual_lines.len();
let scroll_off = (cursor_visual_row + 1).saturating_sub(content_rows as usize);
let has_more_above = scroll_off > 0;
let has_more_below = scroll_off + (content_rows as usize) < visual_count;
for i in 0..content_rows {
let y = top + 1 + i;
if i == 0 {
paint_str(
buf,
col_start,
y,
prompt_glyph,
prompt_color,
BG,
Modifier::BOLD,
);
}
let vidx = scroll_off + i as usize;
if text.is_empty() && i == 0 {
paint_str(buf, text_start, y, placeholder, FG3, BG, Modifier::empty());
if show_caret {
paint(buf, text_start, y, '▮', DS_BRIGHT, BG, Modifier::empty());
}
continue;
}
let Some(line) = visual_lines.get(vidx) else {
continue;
};
if vidx == cursor_visual_row {
let before: String = line.chars().take(cursor_visual_col).collect();
let after: String = line.chars().skip(cursor_visual_col).collect();
let after_col = paint_str(buf, text_start, y, &before, FG, BG, Modifier::empty());
if show_caret {
paint(buf, after_col, y, '▮', DS_BRIGHT, BG, Modifier::empty());
paint_str(buf, after_col + 1, y, &after, FG, BG, Modifier::empty());
} else {
paint_str(buf, after_col, y, &after, FG, BG, Modifier::empty());
}
} else {
paint_str(buf, text_start, y, line, FG, BG, Modifier::empty());
}
}
if has_more_above && rows >= 3 {
paint(
buf,
right.saturating_sub(1),
top + 1,
'↑',
FG3,
BG,
Modifier::empty(),
);
}
if has_more_below && rows >= 3 {
paint(
buf,
right.saturating_sub(1),
bot.saturating_sub(1),
'↓',
FG3,
BG,
Modifier::empty(),
);
}
}
fn build_composer_visual_lines(
text: &str,
cursor: usize,
width: usize,
) -> (Vec<String>, usize, usize) {
let mut out: Vec<String> = Vec::new();
let mut cur_row = 0usize;
let mut cur_col = 0usize;
if text.is_empty() {
out.push(String::new());
return (out, 0, 0);
}
let w = width.max(1);
let mut chars_so_far = 0usize;
let logical: Vec<&str> = text.split('\n').collect();
for (li, line) in logical.iter().enumerate() {
let segs: Vec<String> = if line.is_empty() {
vec![String::new()]
} else {
wrap_visual_chars(line, w)
};
for seg in segs {
let seg_chars = seg.chars().count();
let seg_start = chars_so_far;
let seg_end = chars_so_far + seg_chars;
if cursor >= seg_start && cursor <= seg_end {
cur_row = out.len();
cur_col = cursor - seg_start;
}
chars_so_far = seg_end;
out.push(seg);
}
if li + 1 < logical.len() {
chars_so_far += 1;
}
}
(out, cur_row, cur_col)
}
fn wrap_visual_chars(line: &str, width: usize) -> Vec<String> {
if line.is_empty() {
return vec![String::new()];
}
let mut out = Vec::new();
let mut current = String::new();
let mut current_w = 0usize;
for ch in line.chars() {
let ch_w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
if current_w + ch_w > width && !current.is_empty() {
out.push(std::mem::take(&mut current));
current_w = 0;
}
current.push(ch);
current_w += ch_w;
}
if !current.is_empty() || out.is_empty() {
out.push(current);
}
out
}
fn render_input_meta(buf: &mut Buffer, area: Rect, row: u16, w: u16) {
let mut col = area.x + 1;
let left: [(&str, &str); 5] = [
("↵", "send"),
("⇧↵", "newline"),
("/", "cmd"),
("@", "file"),
("!", "shell"),
];
for (i, (key, label)) in left.iter().enumerate() {
if i > 0 {
col = col.saturating_add(2);
}
col = paint_str(buf, col, row, key, FG1, BG, Modifier::BOLD);
col = col.saturating_add(1);
col = paint_str(buf, col, row, label, FG2, BG, Modifier::empty());
}
let right: [(&str, &str); 2] = [("esc", "cancel"), ("↑", "history")];
let right_w = right_block_width(&right);
let mut rcol = area.x + w.saturating_sub(right_w + 1);
for (i, (key, label)) in right.iter().enumerate() {
if i > 0 {
rcol = rcol.saturating_add(2);
}
rcol = paint_str(buf, rcol, row, key, FG1, BG, Modifier::BOLD);
rcol = rcol.saturating_add(1);
rcol = paint_str(buf, rcol, row, label, FG2, BG, Modifier::empty());
}
}
fn right_block_width(pairs: &[(&str, &str)]) -> u16 {
let mut w = 0u16;
for (i, (key, label)) in pairs.iter().enumerate() {
if i > 0 {
w = w.saturating_add(2);
}
w = w.saturating_add(key.width() as u16 + 1 + label.width() as u16);
}
w
}
fn render_status_bar(buf: &mut Buffer, area: Rect, row: u16, w: u16, state: &SceneState) {
let mut col = area.x + 1;
// Brand dot pulses to a brighter color while busy so the user can
// tell the agent is actually doing something even when the cards
// pane is scrolled off-screen. Visual width stays at 1 cell so the
// rest of the status bar layout doesn't shift.
let dot_color = if state.busy { DS_BRIGHT } else { OK };
paint(buf, col, row, '●', dot_color, BG, Modifier::BOLD);
col = col.saturating_add(2);
let label = if state.busy {
activity_label(state.activity.as_deref())
} else {
"reasonix"
};
col = paint_str(buf, col, row, label, DS_BRIGHT, BG, Modifier::BOLD);
col = col.saturating_add(2);
if let Some(mode) = state.edit_mode.as_ref() {
let (label, color) = match mode {
crate::state::EditMode::Review => ("REVIEW", INFO),
crate::state::EditMode::Auto => ("AUTO", DS_PURPLE),
crate::state::EditMode::Yolo => ("YOLO", ERR),
};
col = paint_pill(buf, col, row, "MODE", label, color);
col = col.saturating_add(1);
}
if let Some(preset) = state.preset.as_deref() {
let (label, color) = match preset {
"auto" => ("AUTO", DS_BRIGHT),
"flash" => ("FLASH", OK),
"pro" => ("PRO", DS_BRIGHT),
_ => (preset, FG2),
};
let label_upper: String = label.chars().flat_map(char::to_uppercase).collect();
col = paint_pill(buf, col, row, "MODEL", &label_upper, color);
col = col.saturating_add(1);
}
col = paint_sep(buf, col, row);
let ctx_tokens = state.ctx_tokens.unwrap_or(0);
let ctx_cap = state.ctx_cap.unwrap_or(0);
let ctx_pct = if ctx_cap > 0 {
(f64::from(ctx_tokens) / f64::from(ctx_cap) * 100.0) as f32
} else {
0.0
};
col = paint_str(buf, col, row, "ctx ", FG2, BG, Modifier::empty());
col = paint_ctx_bar(buf, col, row, ctx_pct);
let ctx_text = if ctx_cap > 0 {
format!(" {}/{}", format_tokens(ctx_tokens), format_tokens(ctx_cap))
} else {
" —".to_string()
};
col = paint_str(buf, col, row, &ctx_text, FG, BG, Modifier::empty());
col = paint_sep(buf, col, row);
if state.session_input_tokens.is_some() || state.session_output_tokens.is_some() {
col = paint_str(buf, col, row, "tok ", FG2, BG, Modifier::empty());
let up = format!(
"↑{} ",
format_tokens(state.session_input_tokens.unwrap_or(0))
);
col = paint_str(buf, col, row, &up, OK, BG, Modifier::empty());
let dn = format!(
"↓{}",
format_tokens(state.session_output_tokens.unwrap_or(0))
);
col = paint_str(buf, col, row, &dn, FG1, BG, Modifier::empty());
col = paint_sep(buf, col, row);
}
col = paint_str(buf, col, row, "cache ", FG2, BG, Modifier::empty());
let cache_text = state
.cache_hit_ratio
.map(|r| format!("{}%", (r * 100.0).round() as i32))
.unwrap_or_else(|| "—".to_string());
col = paint_str(buf, col, row, &cache_text, OK, BG, Modifier::empty());
col = paint_sep(buf, col, row);
col = paint_str(buf, col, row, "cost ", FG2, BG, Modifier::empty());
let cost_text = format_cost(state.session_cost_usd, state.wallet_currency.as_deref());
col = paint_str(buf, col, row, &cost_text, FG, BG, Modifier::empty());
if let (Some(balance), Some(curr)) = (state.wallet_balance, state.wallet_currency.as_deref()) {
let bal_text = format!("{} {}", format_balance(balance), curr);
let bal_w = bal_text.width() as u16 + 2;
if col + bal_w < area.x + w {
let rcol = area.x + w.saturating_sub(bal_w);
paint_str(buf, rcol, row, &bal_text, FG2, BG, Modifier::empty());
}
}
}
fn activity_label(activity: Option<&str>) -> &'static str {
match activity.unwrap_or("") {
"reasoning" | "thinking" => "reasoning…",
"streaming" => "streaming…",
"tool" | "tools" => "running tool…",
"planning" | "plan" => "planning…",
"compacting" | "compact" => "compacting context…",
"" => "working…",
_ => "working…",
}
}
fn format_tokens(n: u32) -> String {
if n >= 1_000_000 {
format!("{:.1}M", f64::from(n) / 1_000_000.0)
} else if n >= 100_000 {
format!("{}k", n / 1000)
} else if n >= 1_000 {
format!("{:.1}k", f64::from(n) / 1000.0)
} else {
format!("{n}")
}
}
fn format_cost(usd: Option<f64>, currency: Option<&str>) -> String {
let Some(v) = usd else {
return "—".to_string();
};
match currency {
Some("CNY") | Some("RMB") => format!("¥{:.3}", v * 7.2),
_ => format!("${v:.3}"),
}
}
fn format_balance(n: f64) -> String {
if n >= 1000.0 {
format!("{:.1}", n)
} else if n >= 100.0 {
format!("{:.2}", n)
} else {
format!("{:.3}", n)
}
}
fn paint_sep(buf: &mut Buffer, col: u16, row: u16) -> u16 {
paint_str(buf, col, row, " │ ", FG3, BG, Modifier::empty())
}
fn paint_pill(
buf: &mut Buffer,
col: u16,
row: u16,
label: &str,
value: &str,
accent: ratatui::style::Color,
) -> u16 {
let mut c = col;
c = paint_str(buf, c, row, "◇ ", accent, BG, Modifier::BOLD);
c = paint_str(buf, c, row, label, FG3, BG, Modifier::empty());
c = paint_str(buf, c, row, " ", BG, BG, Modifier::empty());
c = paint_str(buf, c, row, value, accent, BG, Modifier::BOLD);
c
}
fn paint_ctx_bar(buf: &mut Buffer, x: u16, row: u16, pct: f32) -> u16 {
let cells = 12u16;
let filled = ((pct.clamp(0.0, 100.0) / 100.0) * f32::from(cells)).round() as u16;
let bar_fg = ctx_color(pct);
for i in 0..cells {
let ch = if i < filled { '▰' } else { '▱' };
let fg = if i < filled { bar_fg } else { FG3 };
paint(buf, x + i, row, ch, fg, BG, Modifier::empty());
}
x + cells
}
fn ctx_color(pct: f32) -> Color {
if pct > 80.0 {
ERR
} else if pct > 60.0 {
WARN
} else {
DS_BRIGHT
}
}
@@ -1,143 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
use unicode_width::UnicodeWidthStr;
use crate::state::ListPicker;
use super::paint::{paint, paint_str};
use super::theme::{BG, DS, DS_BRIGHT, FG, FG2, FG3};
pub fn render_list_picker(buf: &mut Buffer, area: Rect, picker: &ListPicker, selected: usize) {
if picker.options.is_empty() {
return;
}
let max_label_w = picker
.options
.iter()
.map(|o| o.label.width() + o.sublabel.as_deref().map(|s| s.width() + 4).unwrap_or(0))
.max()
.unwrap_or(20);
let max_meta_w = picker
.options
.iter()
.map(|o| o.meta.as_deref().map(UnicodeWidthStr::width).unwrap_or(0))
.max()
.unwrap_or(0);
let title_w = picker.title.width();
let inner_w = title_w
.max(max_label_w + if max_meta_w > 0 { max_meta_w + 4 } else { 0 })
.max(40);
let popup_w = (inner_w as u16 + 6).min(area.width.saturating_sub(4));
if popup_w < 30 {
return;
}
let visible_cap = (area.height as usize).saturating_sub(6).clamp(3, 16);
let visible = picker.options.len().min(visible_cap) as u16;
let popup_h = 4 + visible + if picker.hint.is_some() { 1 } else { 0 };
if popup_h > area.height {
return;
}
let popup_x = area.x + (area.width.saturating_sub(popup_w)) / 2;
let popup_y = area.y + (area.height.saturating_sub(popup_h)) / 2;
let popup = Rect::new(popup_x, popup_y, popup_w, popup_h);
draw_box(buf, popup);
paint_str(
buf,
popup.x + 2,
popup.y + 1,
&picker.title,
DS_BRIGHT,
BG,
Modifier::BOLD,
);
let count_text = format!(
"{} option{}",
picker.options.len(),
if picker.options.len() == 1 { "" } else { "s" }
);
let ccol = popup.x + popup.width.saturating_sub(count_text.width() as u16 + 2);
paint_str(
buf,
ccol,
popup.y + 1,
&count_text,
FG3,
BG,
Modifier::empty(),
);
let chosen = selected.min(picker.options.len().saturating_sub(1));
let visible_usz = visible as usize;
let start = if chosen >= visible_usz {
chosen + 1 - visible_usz
} else {
0
};
let row_top = popup.y + 3;
for (i, opt) in picker
.options
.iter()
.enumerate()
.skip(start)
.take(visible_usz)
{
let row = row_top + (i - start) as u16;
let is_sel = i == chosen;
let label_fg = if is_sel { FG } else { DS_BRIGHT };
let modifier = if is_sel {
Modifier::BOLD
} else {
Modifier::empty()
};
if is_sel {
paint_str(buf, popup.x + 2, row, "▸", DS_BRIGHT, BG, Modifier::BOLD);
}
let mut col = popup.x + 4;
col = paint_str(buf, col, row, &opt.label, label_fg, BG, modifier);
if let Some(sub) = opt.sublabel.as_deref() {
col = col.saturating_add(2);
paint_str(buf, col, row, sub, FG2, BG, Modifier::empty());
}
if let Some(meta) = opt.meta.as_deref() {
let mw = meta.width() as u16;
let mcol = popup.x + popup.width.saturating_sub(mw + 2);
paint_str(buf, mcol, row, meta, FG3, BG, Modifier::ITALIC);
}
}
let hint_row = popup.y + popup.height.saturating_sub(2);
let hint = picker
.hint
.as_deref()
.unwrap_or("↑↓ move ↵ select esc cancel");
paint_str(buf, popup.x + 2, hint_row, hint, FG2, BG, Modifier::empty());
}
fn draw_box(buf: &mut Buffer, area: Rect) {
let w = area.width;
if w < 2 {
return;
}
let top = area.y;
let bot = area.y + area.height - 1;
let right = area.x + w - 1;
paint(buf, area.x, top, '╭', DS, BG, Modifier::empty());
paint(buf, right, top, '╮', DS, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, top, '─', DS, BG, Modifier::empty());
}
for y in (top + 1)..bot {
paint(buf, area.x, y, '│', DS, BG, Modifier::empty());
paint(buf, right, y, '│', DS, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, y, ' ', FG, BG, Modifier::empty());
}
}
paint(buf, area.x, bot, '╰', DS, BG, Modifier::empty());
paint(buf, right, bot, '╯', DS, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, bot, '─', DS, BG, Modifier::empty());
}
}
@@ -1,363 +0,0 @@
use pulldown_cmark::{Alignment, CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
#[derive(Clone, Debug, Default)]
pub struct InlineStyle {
pub bold: bool,
pub italic: bool,
pub code: bool,
pub strike: bool,
pub link: bool,
}
#[derive(Clone, Debug)]
pub struct InlineSpan {
pub text: String,
pub style: InlineStyle,
}
#[derive(Clone, Copy, Debug)]
pub enum CellAlign {
Left,
Center,
Right,
}
#[derive(Clone, Debug)]
pub enum MdBlock {
Paragraph(Vec<InlineSpan>),
Heading {
level: u8,
spans: Vec<InlineSpan>,
},
Code {
#[allow(dead_code)]
lang: String,
text: String,
},
ListItem {
ordered: bool,
index: u32,
depth: u8,
spans: Vec<InlineSpan>,
},
BlockQuote(Vec<InlineSpan>),
Hr,
Table {
aligns: Vec<CellAlign>,
head: Vec<Vec<InlineSpan>>,
rows: Vec<Vec<Vec<InlineSpan>>>,
},
}
pub fn parse(text: &str) -> Vec<MdBlock> {
let mut opts = Options::empty();
opts.insert(Options::ENABLE_STRIKETHROUGH);
opts.insert(Options::ENABLE_TASKLISTS);
opts.insert(Options::ENABLE_TABLES);
let parser = Parser::new_ext(text, opts);
let mut out: Vec<MdBlock> = Vec::new();
let mut style = InlineStyle::default();
let mut current_spans: Vec<InlineSpan> = Vec::new();
let mut current_kind: Option<TagKind> = None;
let mut list_stack: Vec<ListFrame> = Vec::new();
let mut code_lang = String::new();
let mut code_buf = String::new();
let mut in_code = false;
let mut table_aligns: Vec<CellAlign> = Vec::new();
let mut table_head: Vec<Vec<InlineSpan>> = Vec::new();
let mut table_rows: Vec<Vec<Vec<InlineSpan>>> = Vec::new();
let mut current_row: Vec<Vec<InlineSpan>> = Vec::new();
for ev in parser {
match ev {
Event::Start(Tag::Paragraph) => {
start_block(
&mut out,
&mut current_spans,
&mut current_kind,
TagKind::Paragraph,
);
}
Event::End(TagEnd::Paragraph) => {
end_block(
&mut out,
&mut current_spans,
&mut current_kind,
list_stack.last(),
);
}
Event::Start(Tag::Heading { level, .. }) => {
start_block(
&mut out,
&mut current_spans,
&mut current_kind,
TagKind::Heading(heading_level(level)),
);
}
Event::End(TagEnd::Heading(_)) => {
end_block(
&mut out,
&mut current_spans,
&mut current_kind,
list_stack.last(),
);
}
Event::Start(Tag::CodeBlock(kind)) => {
in_code = true;
code_lang = match kind {
CodeBlockKind::Fenced(s) => {
s.split_whitespace().next().unwrap_or("").to_string()
}
CodeBlockKind::Indented => String::new(),
};
code_buf.clear();
}
Event::End(TagEnd::CodeBlock) => {
let text = code_buf.trim_end_matches('\n').to_string();
out.push(MdBlock::Code {
lang: std::mem::take(&mut code_lang),
text,
});
in_code = false;
code_buf.clear();
}
Event::Start(Tag::BlockQuote(_)) => {
start_block(
&mut out,
&mut current_spans,
&mut current_kind,
TagKind::BlockQuote,
);
}
Event::End(TagEnd::BlockQuote(_)) => {
end_block(
&mut out,
&mut current_spans,
&mut current_kind,
list_stack.last(),
);
}
Event::Start(Tag::List(start)) => {
list_stack.push(ListFrame {
ordered: start.is_some(),
next_index: start.unwrap_or(1) as u32,
depth: list_stack.len() as u8,
});
}
Event::End(TagEnd::List(_)) => {
list_stack.pop();
}
Event::Start(Tag::Item) => {
let frame = list_stack.last().copied();
start_block(
&mut out,
&mut current_spans,
&mut current_kind,
TagKind::ListItem,
);
if let Some(f) = frame {
current_kind = Some(TagKind::ListItemFor(f));
}
}
Event::End(TagEnd::Item) => {
end_block(
&mut out,
&mut current_spans,
&mut current_kind,
list_stack.last(),
);
if let Some(frame) = list_stack.last_mut() {
if frame.ordered {
frame.next_index += 1;
}
}
}
Event::Rule => {
out.push(MdBlock::Hr);
}
Event::Start(Tag::Table(aligns)) => {
table_aligns = aligns.into_iter().map(map_align).collect();
table_head.clear();
table_rows.clear();
}
Event::End(TagEnd::Table) => {
out.push(MdBlock::Table {
aligns: std::mem::take(&mut table_aligns),
head: std::mem::take(&mut table_head),
rows: std::mem::take(&mut table_rows),
});
}
Event::Start(Tag::TableHead) => {
current_row = Vec::new();
}
Event::End(TagEnd::TableHead) => {
table_head = std::mem::take(&mut current_row);
}
Event::Start(Tag::TableRow) => {
current_row = Vec::new();
}
Event::End(TagEnd::TableRow) => {
table_rows.push(std::mem::take(&mut current_row));
}
Event::Start(Tag::TableCell) => {
current_spans.clear();
}
Event::End(TagEnd::TableCell) => {
current_row.push(std::mem::take(&mut current_spans));
}
Event::Start(Tag::Strong) => {
style.bold = true;
}
Event::End(TagEnd::Strong) => {
style.bold = false;
}
Event::Start(Tag::Emphasis) => {
style.italic = true;
}
Event::End(TagEnd::Emphasis) => {
style.italic = false;
}
Event::Start(Tag::Strikethrough) => {
style.strike = true;
}
Event::End(TagEnd::Strikethrough) => {
style.strike = false;
}
Event::Start(Tag::Link { .. }) => {
style.link = true;
}
Event::End(TagEnd::Link) => {
style.link = false;
}
Event::Code(s) => {
let mut code_style = style.clone();
code_style.code = true;
current_spans.push(InlineSpan {
text: s.into_string(),
style: code_style,
});
}
Event::Text(s) => {
if in_code {
code_buf.push_str(&s);
} else {
current_spans.push(InlineSpan {
text: s.into_string(),
style: style.clone(),
});
}
}
Event::SoftBreak | Event::HardBreak if !in_code => {
current_spans.push(InlineSpan {
text: " ".to_string(),
style: style.clone(),
});
}
_ => {}
}
}
end_block(
&mut out,
&mut current_spans,
&mut current_kind,
list_stack.last(),
);
out
}
fn map_align(a: Alignment) -> CellAlign {
match a {
Alignment::Left | Alignment::None => CellAlign::Left,
Alignment::Center => CellAlign::Center,
Alignment::Right => CellAlign::Right,
}
}
fn heading_level(level: HeadingLevel) -> u8 {
match level {
HeadingLevel::H1 => 1,
HeadingLevel::H2 => 2,
HeadingLevel::H3 => 3,
HeadingLevel::H4 => 4,
HeadingLevel::H5 => 5,
HeadingLevel::H6 => 6,
}
}
#[derive(Clone, Copy, Debug)]
struct ListFrame {
ordered: bool,
next_index: u32,
depth: u8,
}
#[derive(Clone, Copy, Debug)]
enum TagKind {
Paragraph,
Heading(u8),
BlockQuote,
ListItem,
ListItemFor(ListFrame),
}
fn start_block(
out: &mut Vec<MdBlock>,
spans: &mut Vec<InlineSpan>,
kind: &mut Option<TagKind>,
new_kind: TagKind,
) {
if !spans.is_empty() {
flush(out, std::mem::take(spans), *kind, None);
}
*kind = Some(new_kind);
}
fn end_block(
out: &mut Vec<MdBlock>,
spans: &mut Vec<InlineSpan>,
kind: &mut Option<TagKind>,
active_frame: Option<&ListFrame>,
) {
let taken = std::mem::take(spans);
let k = kind.take();
if !taken.is_empty() || matches!(k, Some(TagKind::ListItem) | Some(TagKind::ListItemFor(_))) {
flush(out, taken, k, active_frame);
}
}
fn flush(
out: &mut Vec<MdBlock>,
spans: Vec<InlineSpan>,
kind: Option<TagKind>,
active_frame: Option<&ListFrame>,
) {
match kind {
Some(TagKind::Heading(level)) => out.push(MdBlock::Heading { level, spans }),
Some(TagKind::BlockQuote) => out.push(MdBlock::BlockQuote(spans)),
Some(TagKind::ListItem) => {
let frame = active_frame.copied().unwrap_or(ListFrame {
ordered: false,
next_index: 1,
depth: 0,
});
out.push(MdBlock::ListItem {
ordered: frame.ordered,
index: frame.next_index,
depth: frame.depth,
spans,
});
}
Some(TagKind::ListItemFor(frame)) => out.push(MdBlock::ListItem {
ordered: frame.ordered,
index: frame.next_index,
depth: frame.depth,
spans,
}),
Some(TagKind::Paragraph) | None => {
if !spans.is_empty() {
out.push(MdBlock::Paragraph(spans));
}
}
}
}
@@ -1,492 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier};
use unicode_width::UnicodeWidthChar;
use super::cards::{body_indent_col, paint_rail};
use super::markdown::{parse, CellAlign, InlineSpan, InlineStyle, MdBlock};
use super::paint::paint_str;
use super::theme::{BG, DS_BRIGHT, FG2, FG3, INFO, OK, WARN};
pub fn count_visual_rows(text: &str, width: u16) -> usize {
let blocks = parse(text);
let mut total = 0usize;
for block in &blocks {
total += block_rows(block, width);
}
total
}
pub fn render_markdown(
buf: &mut Buffer,
area: Rect,
start_row: u16,
bottom: u16,
rail_color: Color,
default_fg: Color,
text: &str,
) -> u16 {
let blocks = parse(text);
let mut row = start_row;
let width = area.width.saturating_sub(4);
for block in blocks {
if row >= bottom {
return row;
}
row = render_block(
buf, area, row, bottom, rail_color, default_fg, &block, width,
);
}
row
}
#[allow(clippy::too_many_arguments)]
fn render_block(
buf: &mut Buffer,
area: Rect,
mut row: u16,
bottom: u16,
rail_color: Color,
default_fg: Color,
block: &MdBlock,
width: u16,
) -> u16 {
match block {
MdBlock::Paragraph(spans) => {
let lines = wrap_spans(spans, width);
for line in lines {
if row >= bottom {
return row;
}
paint_rail(buf, area, row, rail_color);
paint_styled(buf, body_indent_col(area), row, &line, default_fg);
row += 1;
}
}
MdBlock::Heading { level, spans } => {
if row >= bottom {
return row;
}
paint_rail(buf, area, row, rail_color);
let prefix = match level {
1 => "▎ ",
2 => "▍ ",
_ => "▏ ",
};
let mut col = body_indent_col(area);
col = paint_str(buf, col, row, prefix, DS_BRIGHT, BG, Modifier::BOLD);
let bold_spans: Vec<InlineSpan> = spans
.iter()
.map(|s| {
let mut style = s.style.clone();
style.bold = true;
InlineSpan {
text: s.text.clone(),
style,
}
})
.collect();
paint_styled(buf, col, row, &bold_spans, DS_BRIGHT);
row += 1;
}
MdBlock::Code { lang: _, text } => {
for line in text.lines() {
if row >= bottom {
return row;
}
paint_rail(buf, area, row, rail_color);
let col = body_indent_col(area);
paint_str(buf, col, row, "┃ ", FG3, BG, Modifier::empty());
paint_str(buf, col + 2, row, line, OK, BG, Modifier::empty());
row += 1;
}
}
MdBlock::ListItem {
ordered,
index,
depth,
spans,
} => {
let indent = " ".repeat(*depth as usize * 2);
let marker = if *ordered {
format!("{indent}{index}. ")
} else {
format!("{indent}• ")
};
let marker_w = marker
.chars()
.map(|c| UnicodeWidthChar::width(c).unwrap_or(0))
.sum::<usize>() as u16;
let body_w = width.saturating_sub(marker_w);
let lines = wrap_spans(spans, body_w);
for (i, line) in lines.iter().enumerate() {
if row >= bottom {
return row;
}
paint_rail(buf, area, row, rail_color);
let mut col = body_indent_col(area);
if i == 0 {
col = paint_str(buf, col, row, &marker, FG2, BG, Modifier::BOLD);
} else {
col = paint_str(
buf,
col,
row,
&" ".repeat(marker_w as usize),
default_fg,
BG,
Modifier::empty(),
);
}
paint_styled(buf, col, row, line, default_fg);
row += 1;
}
}
MdBlock::BlockQuote(spans) => {
let lines = wrap_spans(spans, width.saturating_sub(2));
for line in lines {
if row >= bottom {
return row;
}
paint_rail(buf, area, row, rail_color);
let col = body_indent_col(area);
paint_str(buf, col, row, "▌ ", FG3, BG, Modifier::empty());
paint_styled(buf, col + 2, row, &line, FG2);
row += 1;
}
}
MdBlock::Hr => {
if row >= bottom {
return row;
}
paint_rail(buf, area, row, rail_color);
let col = body_indent_col(area);
let dash: String = "─".repeat(width as usize);
paint_str(buf, col, row, &dash, FG3, BG, Modifier::empty());
row += 1;
}
MdBlock::Table { aligns, head, rows } => {
row = render_table(
buf, area, row, bottom, rail_color, default_fg, width, aligns, head, rows,
);
}
}
row
}
#[allow(clippy::too_many_arguments)]
fn render_table(
buf: &mut Buffer,
area: Rect,
mut row: u16,
bottom: u16,
rail_color: Color,
default_fg: Color,
width: u16,
aligns: &[CellAlign],
head: &[Vec<InlineSpan>],
rows: &[Vec<Vec<InlineSpan>>],
) -> u16 {
let n_cols = head
.len()
.max(rows.iter().map(|r| r.len()).max().unwrap_or(0));
if n_cols == 0 {
return row;
}
let mut col_widths = vec![0usize; n_cols];
for (i, cell) in head.iter().enumerate() {
if i < n_cols {
col_widths[i] = col_widths[i].max(span_text_width(cell));
}
}
for r in rows {
for (i, cell) in r.iter().enumerate() {
if i < n_cols {
col_widths[i] = col_widths[i].max(span_text_width(cell));
}
}
}
let frame_cols = n_cols * 3 + 1;
let total_min: usize = col_widths.iter().sum::<usize>() + frame_cols;
let avail = width as usize;
if total_min > avail {
let overflow = total_min - avail;
let mut remaining = overflow;
while remaining > 0 {
let max_idx = col_widths
.iter()
.enumerate()
.max_by_key(|(_, w)| **w)
.map(|(i, _)| i)
.unwrap_or(0);
if col_widths[max_idx] <= 3 {
break;
}
col_widths[max_idx] -= 1;
remaining -= 1;
}
}
let base = body_indent_col(area);
let draw_border = |buf: &mut Buffer, y: u16, l: char, m: char, r: char, h: char| {
paint_rail(buf, area, y, rail_color);
let mut c = base;
let lc = l.to_string();
c = paint_str(buf, c, y, &lc, FG3, BG, Modifier::empty());
for (i, cw) in col_widths.iter().enumerate() {
let bar: String = (0..*cw + 2).map(|_| h).collect();
c = paint_str(buf, c, y, &bar, FG3, BG, Modifier::empty());
let sep = if i + 1 == col_widths.len() {
r.to_string()
} else {
m.to_string()
};
c = paint_str(buf, c, y, &sep, FG3, BG, Modifier::empty());
}
let _ = c;
};
if row < bottom {
draw_border(buf, row, '╭', '┬', '╮', '─');
row += 1;
}
if !head.is_empty() && row < bottom {
paint_rail(buf, area, row, rail_color);
let mut c = base;
c = paint_str(buf, c, row, "│", FG3, BG, Modifier::empty());
for (i, cell) in head.iter().enumerate() {
if i >= n_cols {
break;
}
c = paint_str(buf, c, row, " ", default_fg, BG, Modifier::empty());
let align = aligns.get(i).copied().unwrap_or(CellAlign::Left);
c = paint_cell(buf, c, row, cell, col_widths[i], align, default_fg, true);
c = paint_str(buf, c, row, " │", FG3, BG, Modifier::empty());
}
let _ = c;
row += 1;
if row < bottom {
draw_border(buf, row, '├', '┼', '┤', '─');
row += 1;
}
}
for r in rows {
if row >= bottom {
break;
}
paint_rail(buf, area, row, rail_color);
let mut c = base;
c = paint_str(buf, c, row, "│", FG3, BG, Modifier::empty());
for (i, &col_w) in col_widths.iter().enumerate().take(n_cols) {
c = paint_str(buf, c, row, " ", default_fg, BG, Modifier::empty());
let empty: Vec<InlineSpan> = Vec::new();
let cell = r.get(i).unwrap_or(&empty);
let align = aligns.get(i).copied().unwrap_or(CellAlign::Left);
c = paint_cell(buf, c, row, cell, col_w, align, default_fg, false);
c = paint_str(buf, c, row, " │", FG3, BG, Modifier::empty());
}
let _ = c;
row += 1;
}
if row < bottom {
draw_border(buf, row, '╰', '┴', '╯', '─');
row += 1;
}
row
}
fn span_text_width(spans: &[InlineSpan]) -> usize {
spans
.iter()
.flat_map(|s| s.text.chars())
.map(|c| UnicodeWidthChar::width(c).unwrap_or(0))
.sum()
}
#[allow(clippy::too_many_arguments)]
fn paint_cell(
buf: &mut Buffer,
x: u16,
row: u16,
cell: &[InlineSpan],
width: usize,
align: CellAlign,
default_fg: Color,
bold: bool,
) -> u16 {
let cell_w = span_text_width(cell);
let trimmed = clip_spans(cell, width);
let used = span_text_width(&trimmed).min(width);
let pad_total = width.saturating_sub(used);
let (left_pad, right_pad) = match align {
CellAlign::Left => (0, pad_total),
CellAlign::Right => (pad_total, 0),
CellAlign::Center => (pad_total / 2, pad_total - pad_total / 2),
};
let mut col = x;
if left_pad > 0 {
col = paint_str(
buf,
col,
row,
&" ".repeat(left_pad),
default_fg,
BG,
Modifier::empty(),
);
}
for span in &trimmed {
let (fg, mut mods) = style_to_paint(&span.style, default_fg);
if bold {
mods |= Modifier::BOLD;
}
col = paint_str(buf, col, row, &span.text, fg, BG, mods);
}
if right_pad > 0 {
col = paint_str(
buf,
col,
row,
&" ".repeat(right_pad),
default_fg,
BG,
Modifier::empty(),
);
}
let _ = cell_w;
col
}
fn clip_spans(spans: &[InlineSpan], width: usize) -> Vec<InlineSpan> {
let mut out: Vec<InlineSpan> = Vec::new();
let mut used = 0usize;
for span in spans {
let mut buf = String::new();
for ch in span.text.chars() {
let cw = UnicodeWidthChar::width(ch).unwrap_or(0);
if used + cw > width {
if width > 0 && used < width {
buf.push('…');
}
if !buf.is_empty() {
out.push(InlineSpan {
text: buf,
style: span.style.clone(),
});
}
return out;
}
buf.push(ch);
used += cw;
}
if !buf.is_empty() {
out.push(InlineSpan {
text: buf,
style: span.style.clone(),
});
}
}
out
}
fn block_rows(block: &MdBlock, width: u16) -> usize {
let body_w = width;
match block {
MdBlock::Paragraph(spans) => wrap_spans(spans, body_w).len().max(1),
MdBlock::Heading { .. } => 1,
MdBlock::Code { text, .. } => text.lines().count().max(1),
MdBlock::ListItem {
ordered,
index,
depth,
spans,
} => {
let indent = (*depth as usize * 2) as u16;
let marker_w = indent
+ if *ordered {
let digits = ((*index as f64).log10().floor() as u16) + 1;
digits + 2
} else {
2
};
wrap_spans(spans, body_w.saturating_sub(marker_w))
.len()
.max(1)
}
MdBlock::BlockQuote(spans) => wrap_spans(spans, body_w.saturating_sub(2)).len().max(1),
MdBlock::Hr => 1,
MdBlock::Table { head, rows, .. } => {
let head_rows = if head.is_empty() { 0 } else { 2 };
2 + head_rows + rows.len()
}
}
}
fn wrap_spans(spans: &[InlineSpan], width: u16) -> Vec<Vec<InlineSpan>> {
let w = width.max(1) as usize;
let mut out: Vec<Vec<InlineSpan>> = Vec::new();
let mut current: Vec<InlineSpan> = Vec::new();
let mut current_w = 0usize;
let mut buf = String::new();
for span in spans {
buf.clear();
for ch in span.text.chars() {
let cw = UnicodeWidthChar::width(ch).unwrap_or(0);
if current_w + cw > w && (current_w > 0 || !buf.is_empty()) {
if !buf.is_empty() {
current.push(InlineSpan {
text: std::mem::take(&mut buf),
style: span.style.clone(),
});
}
out.push(std::mem::take(&mut current));
current_w = 0;
}
buf.push(ch);
current_w += cw;
}
if !buf.is_empty() {
current.push(InlineSpan {
text: std::mem::take(&mut buf),
style: span.style.clone(),
});
}
}
if !current.is_empty() {
out.push(current);
}
if out.is_empty() {
out.push(Vec::new());
}
out
}
fn paint_styled(buf: &mut Buffer, x: u16, row: u16, spans: &[InlineSpan], default_fg: Color) {
let mut col = x;
for span in spans {
let (fg, modifier) = style_to_paint(&span.style, default_fg);
col = paint_str(buf, col, row, &span.text, fg, BG, modifier);
}
}
fn style_to_paint(style: &InlineStyle, default_fg: Color) -> (Color, Modifier) {
let mut mods = Modifier::empty();
let mut fg = default_fg;
if style.bold {
mods |= Modifier::BOLD;
}
if style.italic {
mods |= Modifier::ITALIC;
}
if style.strike {
mods |= Modifier::CROSSED_OUT;
}
if style.code {
fg = WARN;
}
if style.link {
mods |= Modifier::UNDERLINED;
fg = INFO;
}
(fg, mods)
}
@@ -1,212 +0,0 @@
mod approval;
mod boot;
mod cards;
mod demo;
mod dock;
mod list_picker;
mod markdown;
mod md_render;
mod mode_picker;
mod overlay;
mod overlay_at;
mod paint;
mod selection;
mod sidebar;
mod theme;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
use crate::state::SceneState;
pub use demo::demo_state;
pub use overlay::{
slash_arg_completion, slash_arg_match_count, slash_completion, slash_is_exact,
slash_match_count,
};
pub use overlay_at::{at_completion, at_match_count};
pub use paint::{paint, paint_str};
pub use selection::{cards_layout, extract_text, CardsLayout, ScrollbarGeom, Selection};
use approval::render_approval;
use boot::render_scroll;
use dock::render_dock;
use list_picker::render_list_picker;
use mode_picker::{mode_picker_options, preset_picker_options, render_picker};
use overlay::{render_slash_arg_overlay, render_slash_overlay};
use overlay_at::render_at_overlay;
use paint::fill_bg;
use selection::apply_highlight;
use sidebar::render_sidebar;
use theme::{BG, DOCK_HEIGHT, MAX_COMPOSER_ROWS, SIDEBAR_WIDTH};
use theme::{DS_BRIGHT, DS_PURPLE};
pub struct WholeScreen<'a> {
state: &'a SceneState,
scroll_offset: u16,
selection: Option<Selection>,
slash_idx: usize,
slash_arg_idx: usize,
at_idx: usize,
approval_idx: usize,
mode_picker_idx: Option<usize>,
preset_picker_idx: Option<usize>,
list_picker_idx: usize,
sidebar_visible: bool,
tick: u32,
}
impl<'a> WholeScreen<'a> {
pub fn new(state: &'a SceneState) -> Self {
Self {
state,
scroll_offset: 0,
selection: None,
slash_idx: 0,
slash_arg_idx: 0,
at_idx: 0,
approval_idx: 0,
mode_picker_idx: None,
preset_picker_idx: None,
list_picker_idx: 0,
sidebar_visible: true,
tick: 0,
}
}
pub fn with_sidebar_visible(mut self, visible: bool) -> Self {
self.sidebar_visible = visible;
self
}
pub fn with_tick(mut self, tick: u32) -> Self {
self.tick = tick;
self
}
pub fn with_scroll(mut self, offset: u16) -> Self {
self.scroll_offset = offset;
self
}
pub fn with_selection(mut self, sel: Option<Selection>) -> Self {
self.selection = sel;
self
}
pub fn with_slash_index(mut self, idx: usize) -> Self {
self.slash_idx = idx;
self
}
pub fn with_at_index(mut self, idx: usize) -> Self {
self.at_idx = idx;
self
}
pub fn with_slash_arg_index(mut self, idx: usize) -> Self {
self.slash_arg_idx = idx;
self
}
pub fn with_approval_index(mut self, idx: usize) -> Self {
self.approval_idx = idx;
self
}
pub fn with_mode_picker(mut self, idx: Option<usize>) -> Self {
self.mode_picker_idx = idx;
self
}
pub fn with_preset_picker(mut self, idx: Option<usize>) -> Self {
self.preset_picker_idx = idx;
self
}
pub fn with_list_picker_index(mut self, idx: usize) -> Self {
self.list_picker_idx = idx;
self
}
}
impl Widget for WholeScreen<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
fill_bg(buf, area, BG);
let (main, side) = split_main_sidebar(area, self.sidebar_visible);
render_main(buf, main, self.state, self.scroll_offset, self.tick);
if side.width > 0 {
render_sidebar(buf, side, self.state);
}
if let Some(sel) = self.selection {
let layout = cards_layout(area, self.state, self.scroll_offset, self.sidebar_visible);
apply_highlight(buf, &layout, sel);
}
let dock_h = dock_height_for(self.state).min(area.height);
let full_dock = Rect::new(area.x, area.y + area.height - dock_h, area.width, dock_h);
render_slash_overlay(buf, full_dock, self.state, self.slash_idx);
render_slash_arg_overlay(buf, full_dock, self.state, self.slash_arg_idx);
render_at_overlay(buf, full_dock, self.state, self.at_idx);
if let Some(approval) = self.state.approval.as_ref() {
render_approval(buf, area, approval, self.approval_idx, dock_h);
}
if let Some(idx) = self.mode_picker_idx {
let opts = mode_picker_options();
render_picker(
buf,
full_dock,
"AUTONOMY MODE",
"controls when the agent asks before acting",
DS_PURPLE,
&opts,
idx,
);
} else if let Some(idx) = self.preset_picker_idx {
let opts = preset_picker_options();
render_picker(
buf,
full_dock,
"MODEL PRESET",
"picks the default DeepSeek model bundle",
DS_BRIGHT,
&opts,
idx,
);
}
if let Some(picker) = self.state.list_picker.as_ref() {
render_list_picker(buf, area, picker, self.list_picker_idx);
}
}
}
fn split_main_sidebar(area: Rect, sidebar_visible: bool) -> (Rect, Rect) {
if !sidebar_visible || area.width <= SIDEBAR_WIDTH + 30 {
return (area, Rect::new(area.x, area.y, 0, area.height));
}
let main_w = area.width - SIDEBAR_WIDTH;
let main = Rect::new(area.x, area.y, main_w, area.height);
let side = Rect::new(area.x + main_w, area.y, SIDEBAR_WIDTH, area.height);
(main, side)
}
fn render_main(buf: &mut Buffer, area: Rect, state: &SceneState, scroll_offset: u16, tick: u32) {
let dock_h = dock_height_for(state).min(area.height);
let scroll_h = area.height.saturating_sub(dock_h);
let scroll = Rect::new(area.x, area.y, area.width, scroll_h);
let dock = Rect::new(area.x, area.y + scroll_h, area.width, dock_h);
render_scroll(buf, scroll, state, scroll_offset, tick);
render_dock(buf, dock, state, tick);
}
pub(super) fn dock_height_for(state: &SceneState) -> u16 {
let text = state.composer_text.as_deref().unwrap_or("");
let lines = if text.is_empty() {
1u16
} else {
text.split('\n')
.count()
.clamp(1, MAX_COMPOSER_ROWS as usize) as u16
};
DOCK_HEIGHT + lines.saturating_sub(1)
}
@@ -1,188 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier};
use unicode_width::UnicodeWidthStr;
use super::paint::{paint, paint_str};
use super::theme::{BG, DS_BRIGHT, DS_PURPLE, ERR, FG, FG1, FG2, FG3, INFO, OK, WARN};
pub struct PickerOption {
pub marker: &'static str,
pub marker_color: Color,
pub title: &'static str,
pub summary: &'static str,
pub hot: &'static str,
}
pub fn mode_picker_options() -> [PickerOption; 3] {
[
PickerOption {
marker: "○",
marker_color: INFO,
title: "review",
summary: "每个工具调用都要确认 · 最安全",
hot: "shift+tab",
},
PickerOption {
marker: "◆",
marker_color: DS_PURPLE,
title: "auto",
summary: "只在编辑 / 删除 / shell 时确认 · 默认",
hot: "shift+tab",
},
PickerOption {
marker: "⚡",
marker_color: ERR,
title: "yolo",
summary: "完全自主 · 任何操作都不问 · 危险",
hot: "shift+tab",
},
]
}
pub fn preset_picker_options() -> [PickerOption; 3] {
[
PickerOption {
marker: "◇",
marker_color: DS_BRIGHT,
title: "auto",
summary: "flash → pro on hard turns · default",
hot: "click",
},
PickerOption {
marker: "◇",
marker_color: OK,
title: "flash",
summary: "v4-flash always · cheapest, predictable",
hot: "click",
},
PickerOption {
marker: "◇",
marker_color: DS_BRIGHT,
title: "pro",
summary: "v4-pro always · ~3× flash, hard multi-turn work",
hot: "click",
},
]
}
pub fn render_picker(
buf: &mut Buffer,
dock_area: Rect,
title: &str,
subtitle: &str,
accent: Color,
options: &[PickerOption],
selected_idx: usize,
) {
let row_h: u16 = 2;
let inner_rows = (options.len() as u16) * row_h;
let popup_h = 3 + inner_rows;
let popup_w = dock_area.width.saturating_sub(4).min(110);
if popup_w < 40 || popup_h > dock_area.y {
return;
}
let popup_x = dock_area.x + 2;
let popup_y = dock_area.y.saturating_sub(popup_h);
let popup = Rect::new(popup_x, popup_y, popup_w, popup_h);
draw_box(buf, popup, accent);
draw_title(buf, popup, title, subtitle, accent);
let body_top = popup.y + 2;
for (i, opt) in options.iter().enumerate() {
let row = body_top + (i as u16) * row_h;
let selected = i == selected_idx;
let title_color = if selected { opt.marker_color } else { FG };
let title_mod = if selected {
Modifier::BOLD
} else {
Modifier::empty()
};
if selected {
paint_str(
buf,
popup.x + 2,
row,
"▸",
opt.marker_color,
BG,
Modifier::BOLD,
);
}
paint_str(
buf,
popup.x + 4,
row,
opt.marker,
opt.marker_color,
BG,
Modifier::BOLD,
);
let mut col = popup.x + 6;
col = paint_str(buf, col, row, opt.title, title_color, BG, title_mod);
let _ = col;
let hot_label = opt.hot;
let right_w = hot_label.width() as u16;
let hot_col = popup.x + popup.width.saturating_sub(right_w + 2);
paint_str(buf, hot_col, row, hot_label, FG3, BG, Modifier::empty());
if row + 1 < popup.y + popup.height - 1 {
paint_str(
buf,
popup.x + 6,
row + 1,
opt.summary,
FG2,
BG,
Modifier::empty(),
);
}
}
let _ = (FG1, WARN);
}
fn draw_title(buf: &mut Buffer, area: Rect, title: &str, subtitle: &str, accent: Color) {
let row = area.y;
let mut col = area.x + 2;
col = paint_str(buf, col, row, "▢", accent, BG, Modifier::BOLD);
col = col.saturating_add(1);
col = paint_str(buf, col, row, title, accent, BG, Modifier::BOLD);
if !subtitle.is_empty() {
col = col.saturating_add(2);
paint_str(buf, col, row, subtitle, FG2, BG, Modifier::empty());
}
let hint = "esc close";
let hint_col = area.x + area.width.saturating_sub(hint.width() as u16 + 2);
paint_str(buf, hint_col, row, hint, FG3, BG, Modifier::empty());
}
fn draw_box(buf: &mut Buffer, area: Rect, accent: Color) {
let w = area.width;
if w < 2 {
return;
}
let top = area.y;
let bot = area.y + area.height - 1;
let right = area.x + w - 1;
paint(buf, area.x, top, '╭', accent, BG, Modifier::empty());
paint(buf, right, top, '╮', accent, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, top, '─', accent, BG, Modifier::empty());
}
for y in (top + 1)..bot {
paint(buf, area.x, y, '│', accent, BG, Modifier::empty());
paint(buf, right, y, '│', accent, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, y, ' ', FG, BG, Modifier::empty());
}
}
paint(buf, area.x, bot, '╰', accent, BG, Modifier::empty());
paint(buf, right, bot, '╯', accent, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, bot, '─', accent, BG, Modifier::empty());
}
}
@@ -1,758 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
use unicode_width::UnicodeWidthStr;
use crate::state::{SceneState, SlashMatch};
use super::paint::{paint, paint_str};
use super::theme::{BG, DS, DS_BRIGHT, FG, FG2, FG3};
const FALLBACK_COMMANDS: &[(&str, &str)] = &[
("/clear", "reset conversation context"),
("/compact", "summarize history to free up tokens"),
("/help", "show help"),
];
const ABS_MAX_ROWS: usize = 24;
pub fn slash_match_count(query: &str, state: &SceneState) -> usize {
if !query.starts_with('/') {
return 0;
}
match_iter(query, state).count()
}
/// True when `query` is `/<cmd>` for a `<cmd>` that exists in the catalog
/// (case-insensitive). The composer uses this to decide whether Enter
/// should auto-complete the highlighted match or submit the typed command
/// directly. Without this, typing the full name (e.g. `/cost`) re-completes
/// to `/cost ` and the user has to press Enter twice.
pub fn slash_is_exact(query: &str, state: &SceneState) -> bool {
let Some(needle) = query.strip_prefix('/') else {
return false;
};
if needle.is_empty() || needle.contains(' ') {
return false;
}
let needle_lower = needle.to_lowercase();
if let Some(catalog) = state.slash_catalog.as_ref() {
return catalog
.iter()
.any(|m| m.cmd.eq_ignore_ascii_case(&needle_lower));
}
FALLBACK_COMMANDS.iter().any(|(name, _)| {
name.trim_start_matches('/')
.eq_ignore_ascii_case(&needle_lower)
})
}
pub fn slash_completion(query: &str, idx: usize, state: &SceneState) -> Option<String> {
if !query.starts_with('/') {
return None;
}
match_iter(query, state)
.nth(idx)
.map(|name| format!("/{name} "))
}
/// Number of arg-completer matches for `/<cmd> <partial>`. Returns 0 when
/// the command has no static argCompleter, partial already exact-matches a
/// value, or partial has progressed past the first argument (contains a
/// space). Dynamic completers (`"models"`, `"path"`, `"mcp-resources"`,
/// `"mcp-prompts"`, `"skills"`) are not surfaced here yet — those live on
/// the Node side.
pub fn slash_arg_match_count(query: &str, state: &SceneState) -> usize {
slash_arg_matches(query, state)
.map(|v| v.len())
.unwrap_or(0)
}
/// Build the full composer text after picking arg `idx` — replaces the
/// trailing partial with the chosen value. Returns None when there are
/// no matches.
pub fn slash_arg_completion(query: &str, idx: usize, state: &SceneState) -> Option<String> {
let matches = slash_arg_matches(query, state)?;
let chosen = matches.get(idx)?;
let (cmd, _partial) = split_slash_arg(query)?;
Some(format!("/{cmd} {chosen}"))
}
fn slash_arg_matches(query: &str, state: &SceneState) -> Option<Vec<String>> {
let (cmd, partial) = split_slash_arg(query)?;
if partial.contains(' ') {
return None;
}
// Prefer the Node-resolved scene field: it's the only way to surface
// dynamic completers (models / path / mcp-resources / mcp-prompts /
// skills) because rust can't read MCP catalogs or the filesystem from
// here. Match by cmd + partial so a stale push doesn't leak in.
if let Some(s) = state.slash_arg_state.as_ref() {
if s.cmd.eq_ignore_ascii_case(cmd) && s.partial == partial && !s.matches.is_empty() {
return Some(s.matches.clone());
}
}
let catalog = state.slash_catalog.as_ref()?;
let m = catalog.iter().find(|m| m.cmd.eq_ignore_ascii_case(cmd))?;
let completer = m.arg_completer.as_ref()?;
let needle = partial.to_lowercase();
if !partial.is_empty() && completer.iter().any(|v| v.to_lowercase() == needle) {
return None;
}
if partial.is_empty() {
return Some(completer.clone());
}
Some(
completer
.iter()
.filter(|v| v.to_lowercase().starts_with(&needle))
.cloned()
.collect(),
)
}
fn split_slash_arg(query: &str) -> Option<(&str, &str)> {
let stripped = query.strip_prefix('/')?;
let space_pos = stripped.find(' ')?;
let cmd = &stripped[..space_pos];
let partial = &stripped[space_pos + 1..];
Some((cmd, partial))
}
fn match_iter<'a>(query: &'a str, state: &'a SceneState) -> Box<dyn Iterator<Item = &'a str> + 'a> {
// strip_prefix removes ONE leading '/', not all of them — so "//" has
// needle "/" which matches nothing (intended: user typed two slashes
// as literal punctuation). trim_start_matches('/') would collapse
// them and surface the whole catalog instead.
let needle = query.strip_prefix('/').unwrap_or("").to_lowercase();
if let Some(catalog) = state.slash_catalog.as_ref() {
return Box::new(
catalog
.iter()
.filter(move |m| matches_query(&m.cmd, &needle))
.map(|m| m.cmd.as_str()),
);
}
Box::new(
FALLBACK_COMMANDS
.iter()
.filter(move |(name, _)| matches_query(name.trim_start_matches('/'), &needle))
.map(|(name, _)| name.trim_start_matches('/')),
)
}
fn matches_query(cmd: &str, needle_lower: &str) -> bool {
if needle_lower.is_empty() {
return true;
}
cmd.to_lowercase().starts_with(needle_lower)
}
pub fn render_slash_arg_overlay(
buf: &mut Buffer,
dock_area: Rect,
state: &SceneState,
selected_idx: usize,
) {
let Some(text) = state.composer_text.as_deref() else {
return;
};
let Some(matches) = slash_arg_matches(text, state) else {
return;
};
if matches.is_empty() {
return;
}
let Some((cmd, partial)) = split_slash_arg(text) else {
return;
};
let max_value_w = matches.iter().map(|s| s.width()).max().unwrap_or(8);
let header = format!("/{cmd} <arg>");
let header_w = header.width();
let popup_w = (header_w.max(max_value_w + 4) as u16 + 4).min(dock_area.width.saturating_sub(4));
if popup_w < 12 {
return;
}
let cap = (dock_area.y as usize).saturating_sub(3).clamp(1, 10);
let visible = matches.len().min(cap) as u16;
let popup_h = 3 + visible;
if popup_h > dock_area.y {
return;
}
let popup_x = dock_area.x + 2;
let popup_y = dock_area.y - popup_h;
let popup = Rect::new(popup_x, popup_y, popup_w, popup_h);
draw_box(buf, popup);
paint_str(
buf,
popup.x + 2,
popup.y + 1,
&header,
DS_BRIGHT,
BG,
Modifier::BOLD,
);
let count_text = if matches.len() == 1 {
"1 option".to_string()
} else {
format!("{} options", matches.len())
};
let ccol = popup.x + popup.width.saturating_sub(count_text.width() as u16 + 2);
paint_str(
buf,
ccol,
popup.y + 1,
&count_text,
FG3,
BG,
Modifier::empty(),
);
let selected = selected_idx.min(matches.len().saturating_sub(1));
let start = if selected >= visible as usize {
selected + 1 - visible as usize
} else {
0
};
let needle = partial.to_lowercase();
for (i, value) in matches
.iter()
.enumerate()
.skip(start)
.take(visible as usize)
{
let row = popup.y + 2 + (i - start) as u16;
let is_sel = i == selected;
if is_sel {
paint_str(buf, popup.x + 2, row, "▸", DS_BRIGHT, BG, Modifier::BOLD);
}
let fg = if is_sel { FG } else { DS_BRIGHT };
let modifier = if is_sel {
Modifier::BOLD
} else {
Modifier::empty()
};
paint_str(buf, popup.x + 4, row, value, fg, BG, modifier);
if !partial.is_empty() && value.to_lowercase().starts_with(&needle) {
let suffix: String = value.chars().skip(partial.chars().count()).collect();
let typed_w = partial.width() as u16;
paint_str(
buf,
popup.x + 4 + typed_w,
row,
&suffix,
FG2,
BG,
Modifier::empty(),
);
}
}
}
pub fn render_slash_overlay(
buf: &mut Buffer,
dock_area: Rect,
state: &SceneState,
selected_idx: usize,
) {
let Some(text) = state.composer_text.as_deref() else {
return;
};
if !text.starts_with('/') {
return;
}
let all_rows: Vec<SlashRow> = collect_rows(text, state);
if all_rows.is_empty() {
render_no_match(buf, dock_area, text);
return;
}
let total = all_rows.len();
let selected = selected_idx.min(total.saturating_sub(1));
let popup_w = dock_area.width.saturating_sub(4).min(140);
if popup_w < 40 {
return;
}
let layout = compute_columns(&all_rows, popup_w);
let heights: Vec<usize> = all_rows
.iter()
.enumerate()
.map(|(i, r)| row_visual_height(r, &layout, i == selected))
.collect();
let available_rows = (dock_area.y as usize).saturating_sub(3);
let max_visual_rows = available_rows.clamp(1, ABS_MAX_ROWS);
let mut window_start = selected;
let mut window_end = selected + 1;
let mut used = heights[selected];
while used < max_visual_rows {
let grew = grow_window(
&heights,
&mut window_start,
&mut window_end,
&mut used,
max_visual_rows,
total,
);
if !grew {
break;
}
}
let visible_rows: u16 = heights[window_start..window_end]
.iter()
.sum::<usize>()
.min(max_visual_rows) as u16;
let popup_h = 3 + visible_rows;
if popup_h > dock_area.y {
return;
}
let popup_x = dock_area.x + 2;
let popup_y = dock_area.y.saturating_sub(popup_h);
let popup = Rect::new(popup_x, popup_y, popup_w, popup_h);
draw_box(buf, popup);
draw_header(buf, popup, total, window_start, window_end - window_start);
draw_rows_wrapped(
buf,
popup,
&all_rows[window_start..window_end],
text,
selected - window_start,
&layout,
);
}
fn grow_window(
heights: &[usize],
start: &mut usize,
end: &mut usize,
used: &mut usize,
cap: usize,
total: usize,
) -> bool {
let next_below = if *end < total {
Some(heights[*end])
} else {
None
};
let next_above = if *start > 0 {
Some(heights[*start - 1])
} else {
None
};
if let Some(h) = next_below {
if *used + h <= cap {
*used += h;
*end += 1;
return true;
}
}
if let Some(h) = next_above {
if *used + h <= cap {
*used += h;
*start -= 1;
return true;
}
}
false
}
#[derive(Clone, Copy)]
struct ColumnLayout {
name_col_off: u16,
args_col_off: u16,
desc_col_off: u16,
desc_w: u16,
}
fn compute_columns(rows: &[SlashRow], popup_w: u16) -> ColumnLayout {
const MAX_ARGS_HINT_W: u16 = 28;
const MAX_NAME_W: u16 = 22;
let raw_name_w =
(rows.iter().map(|r| r.name.width()).max().unwrap_or(8) as u16).min(MAX_NAME_W);
let raw_args_w = (rows
.iter()
.map(|r| r.args_hint.as_deref().map(|s| s.width()).unwrap_or(0))
.max()
.unwrap_or(0) as u16)
.min(MAX_ARGS_HINT_W);
let right_edge_off = popup_w.saturating_sub(2);
let name_col_off = 4;
let min_desc_w = 25u16;
let want_args_col_off = name_col_off + raw_name_w + 2;
let want_desc_col_off = if raw_args_w > 0 {
want_args_col_off + raw_args_w + 2
} else {
want_args_col_off
};
if right_edge_off >= want_desc_col_off + min_desc_w {
return ColumnLayout {
name_col_off,
args_col_off: want_args_col_off,
desc_col_off: want_desc_col_off,
desc_w: right_edge_off - want_desc_col_off,
};
}
let gap_after_name = 2u16;
let gap_after_args = if raw_args_w > 0 { 2 } else { 0 };
let used_gaps = gap_after_name + gap_after_args;
let cols_budget = right_edge_off
.saturating_sub(name_col_off)
.saturating_sub(min_desc_w)
.saturating_sub(used_gaps);
let total_natural = raw_name_w + raw_args_w;
let max_name_w = if total_natural > 0 {
((u32::from(cols_budget) * u32::from(raw_name_w)) / u32::from(total_natural)) as u16
} else {
cols_budget
};
let max_args_w = cols_budget.saturating_sub(max_name_w);
let args_col_off = name_col_off + max_name_w + gap_after_name;
let desc_col_off = if max_args_w > 0 {
args_col_off + max_args_w + gap_after_args
} else {
args_col_off
};
let desc_w = right_edge_off.saturating_sub(desc_col_off).max(10);
ColumnLayout {
name_col_off,
args_col_off,
desc_col_off,
desc_w,
}
}
fn description_with_aliases(row: &SlashRow) -> String {
if row.aliases.is_empty() {
row.desc.clone()
} else {
format!(
"{} · {}",
row.desc,
row.aliases
.iter()
.map(|a| format!("/{a}"))
.collect::<Vec<_>>()
.join(" ")
)
}
}
fn row_visual_height(row: &SlashRow, layout: &ColumnLayout, selected: bool) -> usize {
let header = if row.header_above { 1 } else { 0 };
if !selected {
return header + 1;
}
let desc = description_with_aliases(row);
header + wrap_desc(&desc, layout.desc_w as usize).len().max(1)
}
fn wrap_desc(text: &str, width: usize) -> Vec<String> {
let w = width.max(1);
if text.is_empty() {
return vec![String::new()];
}
let mut out: Vec<String> = Vec::new();
let mut current = String::new();
let mut current_w = 0usize;
for word in text.split_inclusive(' ') {
let word_w: usize = word
.chars()
.map(|c| unicode_width::UnicodeWidthChar::width(c).unwrap_or(0))
.sum();
if current_w + word_w > w && !current.is_empty() {
out.push(std::mem::take(&mut current));
current_w = 0;
}
if word_w > w {
for ch in word.chars() {
let cw = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
if current_w + cw > w && !current.is_empty() {
out.push(std::mem::take(&mut current));
current_w = 0;
}
current.push(ch);
current_w += cw;
}
} else {
current.push_str(word);
current_w += word_w;
}
}
if !current.is_empty() {
out.push(current);
}
if out.is_empty() {
out.push(String::new());
}
out
}
#[derive(Clone)]
struct SlashRow {
name: String,
desc: String,
args_hint: Option<String>,
aliases: Vec<String>,
group: Option<String>,
/// Render a group header row just above this command. Set true for
/// the first row of each group when the user is browsing the bare
/// `/` menu (group mode); always false in search mode.
header_above: bool,
}
fn collect_rows(query: &str, state: &SceneState) -> Vec<SlashRow> {
// See match_iter for why strip_prefix instead of trim_start_matches.
let needle = query.strip_prefix('/').unwrap_or("").to_lowercase();
let group_mode = needle.is_empty();
let raw: Vec<SlashRow> = if let Some(catalog) = state.slash_catalog.as_ref() {
catalog
.iter()
.filter(|m| matches_query(&m.cmd, &needle))
.map(|m: &SlashMatch| SlashRow {
name: format!("/{}", m.cmd),
desc: m.summary.clone(),
args_hint: m.args_hint.clone(),
aliases: m.aliases.clone(),
group: m.group.clone(),
header_above: false,
})
.collect()
} else {
FALLBACK_COMMANDS
.iter()
.filter(|(name, _)| matches_query(name.trim_start_matches('/'), &needle))
.map(|(name, desc)| SlashRow {
name: (*name).to_string(),
desc: (*desc).to_string(),
args_hint: None,
aliases: Vec::new(),
group: None,
header_above: false,
})
.collect()
};
if !group_mode {
return raw;
}
let mut out = raw;
let mut prev_group: Option<&str> = None;
for row in out.iter_mut() {
let g = row.group.as_deref();
if g != prev_group {
row.header_above = true;
prev_group = g;
}
}
out
}
fn render_no_match(buf: &mut Buffer, dock_area: Rect, query: &str) {
let popup_w = dock_area.width.saturating_sub(4).min(80);
if popup_w < 30 {
return;
}
let popup_h: u16 = 3;
if popup_h > dock_area.y {
return;
}
let popup_x = dock_area.x + 2;
let popup_y = dock_area.y - popup_h;
let popup = Rect::new(popup_x, popup_y, popup_w, popup_h);
draw_box(buf, popup);
let msg = format!("no command matches '{query}'");
paint_str(buf, popup.x + 2, popup.y + 1, "▲", FG2, BG, Modifier::BOLD);
paint_str(
buf,
popup.x + 4,
popup.y + 1,
&msg,
FG2,
BG,
Modifier::empty(),
);
}
fn group_label(group: &str) -> &'static str {
match group {
"setup" => "SETUP",
"info" => "INFO",
"chat" => "CHAT",
"extend" => "EXTEND",
"session" => "SESSION",
"code" => "CODE",
"jobs" => "JOBS",
"advanced" => "ADVANCED",
_ => "OTHER",
}
}
fn draw_box(buf: &mut Buffer, area: Rect) {
let w = area.width;
if w < 2 {
return;
}
let top = area.y;
let bot = area.y + area.height - 1;
let right = area.x + w - 1;
paint(buf, area.x, top, '╭', DS, BG, Modifier::empty());
paint(buf, right, top, '╮', DS, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, top, '─', DS, BG, Modifier::empty());
}
for y in (top + 1)..bot {
paint(buf, area.x, y, '│', DS, BG, Modifier::empty());
paint(buf, right, y, '│', DS, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, y, ' ', FG, BG, Modifier::empty());
}
}
paint(buf, area.x, bot, '╰', DS, BG, Modifier::empty());
paint(buf, right, bot, '╯', DS, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, bot, '─', DS, BG, Modifier::empty());
}
}
fn draw_header(buf: &mut Buffer, area: Rect, total: usize, window_start: usize, visible: usize) {
let row = area.y + 1;
let mut col = paint_str(
buf,
area.x + 2,
row,
"/ SLASH COMMANDS",
DS_BRIGHT,
BG,
Modifier::BOLD,
);
let position = if total <= visible {
format!(" {total} commands")
} else {
let end = (window_start + visible).min(total);
format!(" {}-{}/{}", window_start + 1, end, total)
};
col = paint_str(buf, col, row, &position, FG2, BG, Modifier::empty());
let _ = col;
let hint = "↑↓ move ↵ select esc dismiss";
let hcol = area.x + area.width.saturating_sub(hint.width() as u16 + 2);
paint_str(buf, hcol, row, hint, FG2, BG, Modifier::empty());
}
fn draw_rows_wrapped(
buf: &mut Buffer,
area: Rect,
rows_data: &[SlashRow],
query: &str,
selected_idx: usize,
layout: &ColumnLayout,
) {
let body_top = area.y + 2;
let name_col = area.x + layout.name_col_off;
let args_col = area.x + layout.args_col_off;
let desc_col = area.x + layout.desc_col_off;
let bottom = area.y + area.height - 1;
let name_budget = layout.args_col_off.saturating_sub(layout.name_col_off + 1) as usize;
let args_budget = layout.desc_col_off.saturating_sub(layout.args_col_off + 1) as usize;
let mut row = body_top;
for (i, row_data) in rows_data.iter().enumerate() {
if row >= bottom {
break;
}
if row_data.header_above {
let label = row_data
.group
.as_deref()
.map(group_label)
.unwrap_or("OTHER");
paint_str(buf, area.x + 2, row, label, FG3, BG, Modifier::BOLD);
row += 1;
if row >= bottom {
break;
}
}
let selected = i == selected_idx;
let name_clipped = clip_with_ellipsis(&row_data.name, name_budget);
if selected {
paint_str(buf, area.x + 2, row, "▸", DS_BRIGHT, BG, Modifier::BOLD);
paint_str(buf, name_col, row, &name_clipped, FG, BG, Modifier::BOLD);
} else {
paint_str(
buf,
name_col,
row,
&name_clipped,
DS_BRIGHT,
BG,
Modifier::BOLD,
);
}
if name_clipped.starts_with(query) && !name_clipped.ends_with('…') {
let typed_w = query.width() as u16;
let suffix: String = name_clipped.chars().skip(query.chars().count()).collect();
paint_str(
buf,
name_col + typed_w,
row,
&suffix,
FG2,
BG,
Modifier::empty(),
);
}
if let Some(hint) = row_data.args_hint.as_deref() {
let args_clipped = clip_with_ellipsis(hint, args_budget);
paint_str(buf, args_col, row, &args_clipped, FG2, BG, Modifier::ITALIC);
}
let desc_fg = if selected { FG } else { FG2 };
let desc = description_with_aliases(row_data);
if selected {
let lines = wrap_desc(&desc, layout.desc_w as usize);
for (li, line) in lines.iter().enumerate() {
let target = row + li as u16;
if target >= bottom {
break;
}
paint_str(buf, desc_col, target, line, desc_fg, BG, Modifier::empty());
}
row += lines.len().max(1) as u16;
} else {
let clipped = clip_with_ellipsis(&desc, layout.desc_w as usize);
paint_str(buf, desc_col, row, &clipped, desc_fg, BG, Modifier::empty());
row += 1;
}
}
}
fn clip_with_ellipsis(text: &str, width: usize) -> String {
let w = width.max(1);
let total: usize = text
.chars()
.map(|c| unicode_width::UnicodeWidthChar::width(c).unwrap_or(0))
.sum();
if total <= w {
return text.to_string();
}
let budget = w.saturating_sub(1);
let mut out = String::new();
let mut used = 0usize;
for ch in text.chars() {
let cw = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
if used + cw > budget {
break;
}
out.push(ch);
used += cw;
}
out.push('…');
out
}
@@ -1,339 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
use unicode_width::UnicodeWidthStr;
use crate::state::{AtPickerEntry, AtState, SceneState};
use super::paint::{paint, paint_str};
use super::theme::{BG, DS_PURPLE, FG, FG2, FG3, WARN};
const ABS_MAX_ROWS: usize = 24;
fn at_token(buffer: &str) -> Option<(usize, &str)> {
let at_pos = buffer.rfind('@')?;
let prefix = &buffer[..at_pos];
let suffix = &buffer[at_pos + 1..];
let valid_prefix = prefix.is_empty() || prefix.chars().last().is_some_and(char::is_whitespace);
if !valid_prefix {
return None;
}
if suffix.chars().any(char::is_whitespace) {
return None;
}
Some((at_pos, suffix))
}
fn entries_for(state: &SceneState) -> Option<&[AtPickerEntry]> {
match state.at_state.as_ref()? {
AtState::Browse { entries, .. } | AtState::Search { entries, .. } => {
Some(entries.as_slice())
}
}
}
pub fn at_match_count(buffer: &str, state: &SceneState) -> usize {
if at_token(buffer).is_none() {
return 0;
}
entries_for(state).map(|e| e.len()).unwrap_or(0)
}
pub fn at_completion(buffer: &str, idx: usize, state: &SceneState) -> Option<String> {
let (at_pos, _) = at_token(buffer)?;
let entries = entries_for(state)?;
let entry = entries.get(idx)?;
let prefix = &buffer[..at_pos];
let suffix = if entry.is_dir {
format!("{}/", entry.insert_path.trim_end_matches('/'))
} else {
format!("{} ", entry.insert_path)
};
Some(format!("{prefix}@{suffix}"))
}
pub fn render_at_overlay(
buf: &mut Buffer,
dock_area: Rect,
state: &SceneState,
selected_idx: usize,
) {
let Some(text) = state.composer_text.as_deref() else {
return;
};
if at_token(text).is_none() {
return;
}
let Some(at_state) = state.at_state.as_ref() else {
return;
};
let entries = match at_state {
AtState::Browse { entries, .. } | AtState::Search { entries, .. } => entries.as_slice(),
};
let total = entries.len();
let available_rows = (dock_area.y as usize).saturating_sub(3);
let cap = available_rows.clamp(1, ABS_MAX_ROWS);
let popup_w = dock_area.width.saturating_sub(4).min(120);
if popup_w < 30 {
return;
}
let popup_x = dock_area.x + 2;
if total == 0 {
let popup_h = 3u16;
if popup_h > dock_area.y {
return;
}
let popup_y = dock_area.y.saturating_sub(popup_h);
let popup = Rect::new(popup_x, popup_y, popup_w, popup_h);
draw_box(buf, popup);
draw_header(buf, popup, at_state, 0, 0, 0);
let label = match at_state {
AtState::Browse { loading: true, .. } => "loading…",
AtState::Browse { .. } => "(empty directory)",
AtState::Search {
searching: true, ..
} => "scanning…",
AtState::Search { .. } => "(no matches)",
};
paint_str(
buf,
popup.x + 4,
popup.y + 2,
label,
FG3,
BG,
Modifier::ITALIC,
);
return;
}
let selected = selected_idx.min(total - 1);
let visible_n = total.min(cap).max(1);
let mut window_start = selected.saturating_sub(visible_n.saturating_sub(1));
if selected < window_start {
window_start = selected;
}
if window_start + visible_n > total {
window_start = total.saturating_sub(visible_n);
}
let visible = visible_n as u16;
let popup_h = 3 + visible;
if popup_h > dock_area.y {
return;
}
let popup_y = dock_area.y.saturating_sub(popup_h);
let popup = Rect::new(popup_x, popup_y, popup_w, popup_h);
let window = &entries[window_start..window_start + visible_n];
draw_box(buf, popup);
draw_header(buf, popup, at_state, total, window_start, visible_n);
draw_rows(buf, popup, window, at_state, selected - window_start);
}
fn draw_box(buf: &mut Buffer, area: Rect) {
let w = area.width;
if w < 2 {
return;
}
let top = area.y;
let bot = area.y + area.height - 1;
let right = area.x + w - 1;
paint(buf, area.x, top, '╭', DS_PURPLE, BG, Modifier::empty());
paint(buf, right, top, '╮', DS_PURPLE, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, top, '─', DS_PURPLE, BG, Modifier::empty());
}
for y in (top + 1)..bot {
paint(buf, area.x, y, '│', DS_PURPLE, BG, Modifier::empty());
paint(buf, right, y, '│', DS_PURPLE, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, y, ' ', FG, BG, Modifier::empty());
}
}
paint(buf, area.x, bot, '╰', DS_PURPLE, BG, Modifier::empty());
paint(buf, right, bot, '╯', DS_PURPLE, BG, Modifier::empty());
for x in 1..w - 1 {
paint(buf, area.x + x, bot, '─', DS_PURPLE, BG, Modifier::empty());
}
}
fn draw_header(
buf: &mut Buffer,
area: Rect,
at_state: &AtState,
total: usize,
window_start: usize,
visible: usize,
) {
let row = area.y + 1;
let mut col = area.x + 2;
col = paint_str(buf, col, row, "@ ", DS_PURPLE, BG, Modifier::BOLD);
let lead = match at_state {
AtState::Browse { base_dir, .. } => {
if base_dir.is_empty() {
"/".to_string()
} else {
format!("{base_dir}/")
}
}
AtState::Search { filter, .. } => format!("search: {filter}"),
};
col = paint_str(buf, col, row, &lead, DS_PURPLE, BG, Modifier::BOLD);
let position = if total <= visible {
format!(" {total} entries")
} else {
let end = (window_start + visible).min(total);
format!(" {}-{}/{}", window_start + 1, end, total)
};
col = paint_str(buf, col, row, &position, FG2, BG, Modifier::empty());
let status = match at_state {
AtState::Browse { loading: true, .. } => " · loading…",
AtState::Search {
searching: true, ..
} => " · scanning…",
_ => "",
};
if !status.is_empty() {
col = paint_str(buf, col, row, status, FG3, BG, Modifier::empty());
}
let _ = col;
let hint = "↑↓ move ↵ select ⇥ drill esc dismiss";
let hcol = area.x + area.width.saturating_sub(hint.width() as u16 + 2);
paint_str(buf, hcol, row, hint, FG3, BG, Modifier::empty());
}
fn draw_rows(
buf: &mut Buffer,
area: Rect,
entries: &[AtPickerEntry],
at_state: &AtState,
selected_idx: usize,
) {
let body_top = area.y + 2;
let max_w = area.width.saturating_sub(6);
let filter = match at_state {
AtState::Search { filter, .. } => filter.as_str(),
AtState::Browse { .. } => "",
};
for (i, entry) in entries.iter().enumerate().take(ABS_MAX_ROWS) {
let row = body_top + i as u16;
let selected = i == selected_idx;
if selected {
paint_str(buf, area.x + 2, row, "▸", DS_PURPLE, BG, Modifier::BOLD);
}
let name_col = area.x + 4;
let label = if entry.is_dir {
format!("{}/", entry.label.trim_end_matches('/'))
} else {
entry.label.clone()
};
let suffix_label = entry.dir_suffix.as_str();
paint_entry(
buf,
name_col,
row,
&label,
suffix_label,
filter,
max_w,
selected,
entry.is_dir,
);
}
}
#[allow(clippy::too_many_arguments)]
fn paint_entry(
buf: &mut Buffer,
x: u16,
row: u16,
label: &str,
suffix: &str,
filter: &str,
max_w: u16,
selected: bool,
is_dir: bool,
) {
let base_fg = if selected { FG } else { FG2 };
let base_mod = if selected || is_dir {
Modifier::BOLD
} else {
Modifier::empty()
};
let mut budget = max_w;
let mut col = x;
if let Some((before, mid, after)) = case_insensitive_split(label, filter) {
col = paint_clipped(buf, col, row, before, base_fg, base_mod, &mut budget);
col = paint_clipped(buf, col, row, mid, WARN, Modifier::BOLD, &mut budget);
col = paint_clipped(buf, col, row, after, base_fg, base_mod, &mut budget);
} else {
col = paint_clipped(buf, col, row, label, base_fg, base_mod, &mut budget);
}
if !suffix.is_empty() && budget > 1 {
col = paint_clipped(buf, col, row, " ", FG3, Modifier::empty(), &mut budget);
let _ = paint_clipped(buf, col, row, suffix, FG3, Modifier::empty(), &mut budget);
}
}
/// Char-boundary-safe case-insensitive substring split. Returns (before, mid, after) byte slices of `label` where `mid` is the matched range. Avoids byte indexing into `label.to_lowercase()` whose char-boundary mapping is not preserved across casefolding.
fn case_insensitive_split<'a>(label: &'a str, filter: &str) -> Option<(&'a str, &'a str, &'a str)> {
if filter.is_empty() {
return None;
}
let needle: Vec<char> = filter.chars().flat_map(char::to_lowercase).collect();
if needle.is_empty() {
return None;
}
let chars: Vec<(usize, char)> = label.char_indices().collect();
let n = chars.len();
'outer: for start in 0..n {
let mut j = 0usize;
let mut i = start;
while j < needle.len() {
if i >= n {
continue 'outer;
}
let lc: Vec<char> = chars[i].1.to_lowercase().collect();
if lc.len() != 1 || lc[0] != needle[j] {
continue 'outer;
}
i += 1;
j += 1;
}
let start_byte = chars[start].0;
let end_byte = if i >= n { label.len() } else { chars[i].0 };
return Some((
&label[..start_byte],
&label[start_byte..end_byte],
&label[end_byte..],
));
}
None
}
fn paint_clipped(
buf: &mut Buffer,
x: u16,
row: u16,
s: &str,
fg: ratatui::style::Color,
modifier: Modifier,
budget: &mut u16,
) -> u16 {
if *budget == 0 {
return x;
}
let mut w = 0u16;
let mut clipped = String::new();
for ch in s.chars() {
let cw = crate::whole_screen::paint::char_width(ch);
if w + cw > *budget {
break;
}
w += cw;
clipped.push(ch);
}
paint_str(buf, x, row, &clipped, fg, BG, modifier);
*budget = budget.saturating_sub(w);
x + w
}
@@ -1,203 +0,0 @@
use chrono::{Local, TimeZone};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use unicode_width::UnicodeWidthChar;
/// Display width of a character. Returns 0 for control characters
/// (where unicode-width returns None) and combining marks, so the
/// layout engine skips them instead of giving them a spurious width-1
/// cell that overwrites the next character.
pub fn char_width(ch: char) -> u16 {
UnicodeWidthChar::width(ch).unwrap_or(0) as u16
}
pub fn paint(buf: &mut Buffer, x: u16, y: u16, ch: char, fg: Color, bg: Color, modifier: Modifier) {
if x >= buf.area.right() || y >= buf.area.bottom() {
return;
}
let w = char_width(ch);
if w == 0 {
return;
}
let mut tmp = [0u8; 4];
let s = ch.encode_utf8(&mut tmp);
let style = Style::default().fg(fg).bg(bg).add_modifier(modifier);
buf[(x, y)].set_symbol(s).set_style(style).set_skip(false);
for off in 1..w {
let cx = x + off;
if cx >= buf.area.right() {
break;
}
buf[(cx, y)]
.set_symbol("")
.set_style(Style::default().bg(bg))
.set_skip(true);
}
}
pub fn paint_str(
buf: &mut Buffer,
x: u16,
y: u16,
s: &str,
fg: Color,
bg: Color,
modifier: Modifier,
) -> u16 {
paint_str_to(buf, x, y, s, buf.area.right(), fg, bg, modifier)
}
#[allow(clippy::too_many_arguments)]
pub fn paint_str_to(
buf: &mut Buffer,
x: u16,
y: u16,
s: &str,
end_x: u16,
fg: Color,
bg: Color,
modifier: Modifier,
) -> u16 {
let limit = end_x.min(buf.area.right());
let mut col = x;
for ch in s.chars() {
// Tab → 2 spaces (terminal convention, matches common tab-stop width).
if ch == '\t' {
for _ in 0..2 {
if col >= limit {
break;
}
paint(buf, col, y, ' ', fg, bg, modifier);
col += 1;
}
continue;
}
let w = char_width(ch);
// Zero-width characters (control chars, combining marks, ZWJ/ZWNJ,
// variation selectors) are skipped — they'd otherwise land at the
// same column as the next character and cause overwrite artifacts.
if w == 0 {
continue;
}
if col.saturating_add(w) > limit {
break;
}
paint(buf, col, y, ch, fg, bg, modifier);
col = col.saturating_add(w);
}
col
}
/// OSC 8 hyperlink — the entire escape sequence (open + visible text +
/// close) lives in one cell's symbol; subsequent cells covered by the
/// visible width are flagged `skip` so the diff layer doesn't repaint
/// them. Terminals that understand OSC 8 (Windows Terminal, iTerm2,
/// WezTerm, gnome-terminal ≥3.26, kitty, etc.) render this as a
/// clickable link; older terminals print the escapes as no-ops and
/// fall back to plain underlined text.
pub fn paint_link(
buf: &mut Buffer,
x: u16,
y: u16,
url: &str,
visible: &str,
fg: Color,
bg: Color,
) -> u16 {
use ratatui::style::Style;
use unicode_width::UnicodeWidthStr;
if x >= buf.area.right() || y >= buf.area.bottom() {
return x;
}
let width = UnicodeWidthStr::width(visible) as u16;
if width == 0 {
return x;
}
let symbol = format!("\x1b]8;;{url}\x1b\\{visible}\x1b]8;;\x1b\\");
let style = Style::default()
.fg(fg)
.bg(bg)
.add_modifier(Modifier::UNDERLINED);
buf[(x, y)]
.set_symbol(&symbol)
.set_style(style)
.set_skip(false);
for off in 1..width {
let cx = x + off;
if cx >= buf.area.right() {
break;
}
buf[(cx, y)]
.set_symbol("")
.set_style(Style::default().bg(bg))
.set_skip(true);
}
x + width
}
/// Multi-row variant of `paint_link`. Splits `visible` into chunks that fit
/// `[x, end_x)` and stacks them on consecutive rows, each chunk a clickable
/// link to the full `url`. Returns rows consumed (0 if nothing fit).
#[allow(clippy::too_many_arguments)]
pub fn paint_link_wrapped(
buf: &mut Buffer,
x: u16,
y: u16,
end_x: u16,
bottom: u16,
url: &str,
visible: &str,
fg: Color,
bg: Color,
) -> u16 {
use unicode_width::UnicodeWidthChar;
let limit = end_x.min(buf.area.right());
let bottom = bottom.min(buf.area.bottom());
if x >= limit || y >= bottom {
return 0;
}
let max_w = (limit - x) as usize;
if max_w == 0 {
return 0;
}
let mut row = y;
let mut chunk = String::new();
let mut chunk_w = 0usize;
for ch in visible.chars() {
let cw = UnicodeWidthChar::width(ch).unwrap_or(1);
if chunk_w + cw > max_w && !chunk.is_empty() {
paint_link(buf, x, row, url, &chunk, fg, bg);
row += 1;
if row >= bottom {
return row - y;
}
chunk.clear();
chunk_w = 0;
}
chunk.push(ch);
chunk_w += cw;
}
if !chunk.is_empty() {
paint_link(buf, x, row, url, &chunk, fg, bg);
row += 1;
}
row - y
}
pub fn fill_bg(buf: &mut Buffer, area: Rect, bg: Color) {
let style = Style::default().bg(bg);
for y in area.y..area.y.saturating_add(area.height) {
for x in area.x..area.x.saturating_add(area.width) {
buf[(x, y)].set_style(style);
}
}
}
pub fn format_ts(ts: i64) -> String {
Local
.timestamp_opt(ts, 0)
.single()
.map(|dt| dt.format("%H:%M:%S").to_string())
.unwrap_or_default()
}
@@ -1,260 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
use unicode_width::UnicodeWidthStr;
use crate::state::SceneState;
use super::cards::{body_width_for, render_card_to, total_cards_height};
use super::dock_height_for;
use super::theme::SIDEBAR_WIDTH;
const BOOT_HEIGHT: u16 = 15;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Selection {
pub anchor: (u16, u16),
pub head: (u16, u16),
}
impl Selection {
pub fn new(col: u16, virt_y: u16) -> Self {
Self {
anchor: (col, virt_y),
head: (col, virt_y),
}
}
pub fn extend(&mut self, col: u16, virt_y: u16) {
self.head = (col, virt_y);
}
pub fn is_empty(&self) -> bool {
self.anchor == self.head
}
pub fn normalized(&self) -> ((u16, u16), (u16, u16)) {
let (ac, ay) = self.anchor;
let (hc, hy) = self.head;
if (ay, ac) <= (hy, hc) {
(self.anchor, self.head)
} else {
(self.head, self.anchor)
}
}
pub fn contains_virt(&self, col: u16, virt_y: u16) -> bool {
let ((sc, sy), (ec, ey)) = self.normalized();
if virt_y < sy || virt_y > ey {
return false;
}
if sy == ey {
col >= sc && col <= ec
} else if virt_y == sy {
col >= sc
} else if virt_y == ey {
col <= ec
} else {
true
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct CardsLayout {
pub screen_rect: Rect,
pub view_top: u16,
pub view_h: u16,
pub total: u16,
}
#[derive(Clone, Copy, Debug)]
pub struct ScrollbarGeom {
pub track_x: u16,
pub track_top: u16,
pub track_space: u16,
pub thumb_top: u16,
pub thumb_size: u16,
pub max_offset: u16,
}
impl CardsLayout {
pub fn contains_screen(&self, x: u16, y: u16) -> bool {
x >= self.screen_rect.x
&& x < self.screen_rect.right()
&& y >= self.screen_rect.y
&& y < self.screen_rect.bottom()
}
pub fn project_clamped(&self, x: u16, y: u16) -> (u16, u16) {
let min_x = self.screen_rect.x;
let max_x = self.screen_rect.right().saturating_sub(2).max(min_x);
let min_y = self.screen_rect.y;
let max_y = self.screen_rect.bottom().saturating_sub(1).max(min_y);
let col = x.clamp(min_x, max_x);
let row = y.clamp(min_y, max_y);
let virt_y = self.view_top.saturating_add(row - min_y);
(col, virt_y)
}
pub fn scrollbar(&self, scroll_offset: u16) -> Option<ScrollbarGeom> {
if self.screen_rect.width == 0 || self.view_h == 0 || self.total <= self.view_h {
return None;
}
let track_x = self.screen_rect.right().saturating_sub(1);
let track_top = self.screen_rect.bottom().saturating_sub(self.view_h);
let max_offset = self.total - self.view_h;
let thumb_size_raw =
((f32::from(self.view_h) / f32::from(self.total)) * f32::from(self.view_h)).round();
let thumb_size = (thumb_size_raw as u16).clamp(1, self.view_h);
let track_space = self.view_h - thumb_size;
let offset = scroll_offset.min(max_offset);
let thumb_top_rel = if max_offset == 0 {
track_space
} else {
let ratio = 1.0 - (f32::from(offset) / f32::from(max_offset));
(ratio * f32::from(track_space)).round() as u16
};
let thumb_top = track_top + thumb_top_rel.min(track_space);
Some(ScrollbarGeom {
track_x,
track_top,
track_space,
thumb_top,
thumb_size,
max_offset,
})
}
}
impl ScrollbarGeom {
pub fn contains(&self, x: u16, y: u16) -> bool {
x == self.track_x
&& y >= self.track_top
&& y < self.track_top + (self.track_space + self.thumb_size)
}
pub fn thumb_contains(&self, y: u16) -> bool {
y >= self.thumb_top && y < self.thumb_top + self.thumb_size
}
pub fn offset_for_thumb_top_rel(&self, thumb_top_rel: u16) -> u16 {
if self.track_space == 0 {
return self.max_offset;
}
let clamped = thumb_top_rel.min(self.track_space);
let ratio = 1.0 - (f32::from(clamped) / f32::from(self.track_space));
(ratio * f32::from(self.max_offset)).round() as u16
}
}
pub fn cards_layout(
terminal: Rect,
state: &SceneState,
scroll_offset: u16,
sidebar_visible: bool,
) -> CardsLayout {
let main_w = if sidebar_visible && terminal.width > SIDEBAR_WIDTH + 30 {
terminal.width - SIDEBAR_WIDTH
} else {
terminal.width
};
let dock_h = dock_height_for(state).min(terminal.height);
let scroll_h = terminal.height.saturating_sub(dock_h);
let boot = BOOT_HEIGHT.min(scroll_h);
let cards_y = terminal.y + boot;
let cards_h = scroll_h.saturating_sub(boot);
let screen_rect = Rect::new(terminal.x, cards_y, main_w, cards_h);
let body_w = body_width_for(Rect::new(0, 0, main_w.saturating_sub(1), 1));
let total = total_cards_height(state, body_w);
let avail = cards_h;
let max_offset = total.saturating_sub(avail);
let offset = scroll_offset.min(max_offset);
let view_h = avail.min(total);
let view_top = total.saturating_sub(view_h).saturating_sub(offset);
CardsLayout {
screen_rect,
view_top,
view_h,
total,
}
}
pub fn apply_highlight(buf: &mut Buffer, layout: &CardsLayout, sel: Selection) {
if sel.is_empty() || layout.view_h == 0 {
return;
}
let top = layout.screen_rect.y;
let bottom = layout.screen_rect.bottom();
let left = layout.screen_rect.x;
let right = layout.screen_rect.right().saturating_sub(1);
for y in top..bottom {
let virt_y = layout.view_top + (y - top);
for x in left..right {
if sel.contains_virt(x, virt_y) {
let style = buf[(x, y)].style().add_modifier(Modifier::REVERSED);
buf[(x, y)].set_style(style);
}
}
}
}
pub fn extract_text(
state: &SceneState,
scroll_offset: u16,
terminal: Rect,
sel: Selection,
sidebar_visible: bool,
) -> String {
if sel.is_empty() {
return String::new();
}
let layout = cards_layout(terminal, state, scroll_offset, sidebar_visible);
if layout.total == 0 {
return String::new();
}
let scroll_w = layout.screen_rect.width.saturating_sub(1);
if scroll_w == 0 {
return String::new();
}
let virt_rect = Rect::new(0, 0, scroll_w, layout.total);
let mut virt = Buffer::empty(virt_rect);
let mut row = 0u16;
let last_idx = state.cards.len().saturating_sub(1);
for (i, card) in state.cards.iter().enumerate() {
let streaming = state.busy && i == last_idx;
row = render_card_to(&mut virt, virt_rect, row, card, streaming);
}
let ((sc, sy), (ec, ey)) = sel.normalized();
let offset_x = layout.screen_rect.x;
let start_x = sc.saturating_sub(offset_x);
let end_x = ec.saturating_sub(offset_x);
let mut out = String::new();
for y in sy..=ey {
if y >= layout.total {
break;
}
let row_start = if y == sy { start_x } else { 0 };
let row_end = if y == ey {
end_x
} else {
scroll_w.saturating_sub(1)
};
let mut x = row_start;
let mut line = String::new();
while x <= row_end && x < scroll_w {
let sym = virt[(x, y)].symbol();
line.push_str(sym);
let cw = UnicodeWidthStr::width(sym).max(1) as u16;
x = x.saturating_add(cw);
}
out.push_str(line.trim_end());
if y < ey {
out.push('\n');
}
}
out
}
@@ -1,298 +0,0 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier};
use unicode_width::UnicodeWidthStr;
use crate::state::{SceneCard, SceneState, ToolStatus};
use super::cards::{parse_todo_items, wrap_visual, TodoState};
use super::paint::{paint, paint_str};
use super::theme::{BG, DS_BRIGHT, DS_PURPLE, ERR, FG, FG1, FG2, FG3, OK, WARN};
pub fn render_sidebar(buf: &mut Buffer, area: Rect, state: &SceneState) {
for y in area.y..area.y + area.height {
paint(buf, area.x, y, '│', FG3, BG, Modifier::empty());
}
let inner_x = area.x + 2;
let mut row = area.y + 1;
let bottom = area.y + area.height;
if row < bottom {
paint_str(buf, inner_x, row, "⚙ ", FG, BG, Modifier::empty());
paint_str(
buf,
inner_x + 2,
row,
"MISSION CONTROL",
DS_BRIGHT,
BG,
Modifier::BOLD,
);
let toggle = "^B hide";
let toggle_col = area.x + area.width.saturating_sub(toggle.width() as u16 + 1);
paint_str(buf, toggle_col, row, toggle, FG3, BG, Modifier::empty());
row += 1;
}
row += 1;
let plan_body = state
.cards
.iter()
.rev()
.find(|c| c.kind == "todo" || c.kind == "plan")
.and_then(|c| c.body.as_deref())
.unwrap_or("");
let plan_items = parse_todo_items(plan_body);
if plan_items.is_empty() {
row = sidebar_section(
buf,
area,
row,
"◇",
"PLAN",
DS_PURPLE,
"waiting for a task — type below",
);
} else {
row = sidebar_plan(buf, area, row, &plan_items);
}
let recent_tools: Vec<&SceneCard> = state
.cards
.iter()
.rev()
.filter(|c| c.kind == "tool")
.take(4)
.collect();
if recent_tools.is_empty() {
row = sidebar_section(buf, area, row, "⚡", "JOBS", WARN, "no jobs run yet");
} else {
row = sidebar_jobs(buf, area, row, &recent_tools);
}
row = sidebar_section(buf, area, row, "▣", "CHANGES", DS_BRIGHT, "no edits yet");
if row < bottom {
paint_str(buf, inner_x, row, "▥ ", OK, BG, Modifier::BOLD);
paint_str(buf, inner_x + 2, row, "SESSION", OK, BG, Modifier::BOLD);
row += 1;
let model_label = state.model.as_deref().unwrap_or("—");
row = sidebar_kv(buf, area, row, "model", model_label, DS_BRIGHT);
row = sidebar_kv(buf, area, row, "context", &format_ctx(state), FG);
if let Some(n) = state.session_input_tokens {
row = sidebar_kv(buf, area, row, "↑ input", &short_num(n), FG);
}
if let Some(n) = state.session_output_tokens {
row = sidebar_kv(buf, area, row, "↓ output", &short_num(n), FG);
}
row = sidebar_kv(buf, area, row, "cache", &format_cache(state), FG);
let currency = state.wallet_currency.as_deref();
row = sidebar_kv(
buf,
area,
row,
"cost",
&format_session_cost(state, currency),
FG,
);
if let (Some(balance), Some(cur)) = (state.wallet_balance, currency) {
row = sidebar_kv(
buf,
area,
row,
"balance",
&format!("{:.2} {}", balance, cur),
FG,
);
}
let _ = sidebar_kv(
buf,
area,
row,
"last turn",
&format_last_turn(state, currency),
FG,
);
}
}
fn format_ctx(state: &SceneState) -> String {
match (state.ctx_tokens, state.ctx_cap) {
(Some(t), Some(c)) if c > 0 => format!("{} / {}", short_num(t), short_num(c)),
_ => "—".to_string(),
}
}
fn format_cache(state: &SceneState) -> String {
state
.cache_hit_ratio
.map(|r| format!("{}%", (r * 100.0).round() as i32))
.unwrap_or_else(|| "—".to_string())
}
fn format_session_cost(state: &SceneState, currency: Option<&str>) -> String {
let Some(v) = state.session_cost_usd else {
return "—".to_string();
};
match currency {
Some("CNY") | Some("RMB") => format!("¥{:.3}", v * 7.2),
_ => format!("${v:.3}"),
}
}
fn format_last_turn(state: &SceneState, currency: Option<&str>) -> String {
let elapsed = state.last_turn_ms.map(|ms| {
if ms >= 60_000 {
format!("{:.1}m", ms as f64 / 60_000.0)
} else if ms >= 1000 {
format!("{:.1}s", ms as f64 / 1000.0)
} else {
format!("{ms}ms")
}
});
let cost = state.last_turn_cost_usd.map(|v| match currency {
Some("CNY") | Some("RMB") => format!("¥{:.3}", v * 7.2),
_ => format!("${v:.3}"),
});
match (elapsed, cost) {
(Some(t), Some(c)) => format!("{t} · {c}"),
(Some(t), None) => t,
(None, Some(c)) => c,
(None, None) => "—".to_string(),
}
}
fn short_num(n: u32) -> String {
if n >= 1_000_000 {
format!("{:.1}M", f64::from(n) / 1_000_000.0)
} else if n >= 100_000 {
format!("{}k", n / 1000)
} else if n >= 1_000 {
format!("{:.1}k", f64::from(n) / 1000.0)
} else {
format!("{n}")
}
}
fn sidebar_section(
buf: &mut Buffer,
area: Rect,
start_row: u16,
glyph: &str,
title: &str,
color: Color,
empty_hint: &str,
) -> u16 {
let bottom = area.y + area.height;
let inner_x = area.x + 2;
let mut row = start_row;
if row >= bottom {
return row;
}
paint_str(buf, inner_x, row, glyph, color, BG, Modifier::BOLD);
paint_str(buf, inner_x + 2, row, title, color, BG, Modifier::BOLD);
row += 1;
if row < bottom {
paint_str(buf, inner_x + 2, row, empty_hint, FG3, BG, Modifier::ITALIC);
row += 1;
}
row + 1
}
fn sidebar_plan(buf: &mut Buffer, area: Rect, start_row: u16, items: &[(TodoState, &str)]) -> u16 {
let bottom = area.y + area.height;
let inner_x = area.x + 2;
let mut row = start_row;
if row >= bottom {
return row;
}
let done = items
.iter()
.filter(|(s, _)| matches!(s, TodoState::Done))
.count();
paint_str(buf, inner_x, row, "◇", DS_PURPLE, BG, Modifier::BOLD);
paint_str(buf, inner_x + 2, row, "PLAN", DS_PURPLE, BG, Modifier::BOLD);
let count = format!("{}/{}", done, items.len());
let ccol = area.x + area.width.saturating_sub(count.width() as u16 + 1);
paint_str(buf, ccol, row, &count, FG3, BG, Modifier::empty());
row += 1;
let inner_w = area.width.saturating_sub(5);
for (state, label) in items {
if row >= bottom {
return row;
}
let (marker, marker_fg, label_fg, label_mod) = match state {
TodoState::Done => ("✓", OK, FG2, Modifier::empty()),
TodoState::Active => ("◆", DS_BRIGHT, FG, Modifier::BOLD),
TodoState::Pending => ("○", FG3, FG1, Modifier::empty()),
};
paint_str(buf, inner_x, row, marker, marker_fg, BG, Modifier::BOLD);
for (i, seg) in wrap_visual(label, inner_w).iter().enumerate() {
if row >= bottom {
return row;
}
if i > 0 {
paint(buf, area.x, row, '│', FG3, BG, Modifier::empty());
}
paint_str(buf, inner_x + 2, row, seg, label_fg, BG, label_mod);
row += 1;
}
}
row + 1
}
fn sidebar_jobs(buf: &mut Buffer, area: Rect, start_row: u16, tools: &[&SceneCard]) -> u16 {
let bottom = area.y + area.height;
let inner_x = area.x + 2;
let mut row = start_row;
if row >= bottom {
return row;
}
paint_str(buf, inner_x, row, "⚡", WARN, BG, Modifier::BOLD);
paint_str(buf, inner_x + 2, row, "JOBS", WARN, BG, Modifier::BOLD);
let count = format!("{} recent", tools.len());
let ccol = area.x + area.width.saturating_sub(count.width() as u16 + 1);
paint_str(buf, ccol, row, &count, FG3, BG, Modifier::empty());
row += 1;
let inner_w = area.width.saturating_sub(5);
for tool in tools {
if row >= bottom {
return row;
}
let (glyph, gfg) = match tool.status {
Some(ToolStatus::Ok) => ("✓", OK),
Some(ToolStatus::Err) => ("✕", ERR),
Some(ToolStatus::Running) => ("…", WARN),
None => ("·", FG3),
};
paint_str(buf, inner_x, row, glyph, gfg, BG, Modifier::BOLD);
let mut label = tool.summary.clone();
if let Some(args) = tool.args.as_deref() {
label.push(' ');
label.push_str(args);
}
for (i, seg) in wrap_visual(&label, inner_w).iter().enumerate() {
if row >= bottom {
return row;
}
if i > 0 {
paint(buf, area.x, row, '│', FG3, BG, Modifier::empty());
}
paint_str(buf, inner_x + 2, row, seg, FG, BG, Modifier::empty());
row += 1;
}
}
row + 1
}
fn sidebar_kv(buf: &mut Buffer, area: Rect, row: u16, key: &str, val: &str, val_fg: Color) -> u16 {
let bottom = area.y + area.height;
if row >= bottom {
return row;
}
let inner_x = area.x + 4;
paint_str(buf, inner_x, row, key, FG2, BG, Modifier::empty());
let val_col = area.x + area.width.saturating_sub(val.width() as u16 + 1);
paint_str(buf, val_col, row, val, val_fg, BG, Modifier::empty());
row + 1
}
@@ -1,28 +0,0 @@
use ratatui::style::Color;
pub const BG: Color = Color::Rgb(0x0f, 0x10, 0x18);
pub const FG: Color = Color::Rgb(0xe8, 0xe9, 0xf3);
pub const FG1: Color = Color::Rgb(0xa8, 0xaa, 0xbd);
pub const FG2: Color = Color::Rgb(0x6b, 0x6e, 0x85);
pub const FG3: Color = Color::Rgb(0x3d, 0x40, 0x55);
pub const DS: Color = Color::Rgb(0x6b, 0x85, 0xff);
pub const DS_BRIGHT: Color = Color::Rgb(0x8b, 0x9f, 0xff);
pub const DS_PURPLE: Color = Color::Rgb(0xa7, 0x8b, 0xfa);
pub const OK: Color = Color::Rgb(0x5e, 0xea, 0xd4);
pub const WARN: Color = Color::Rgb(0xfb, 0xbf, 0x24);
pub const ERR: Color = Color::Rgb(0xfb, 0x71, 0x85);
pub const INFO: Color = Color::Rgb(0x60, 0xa5, 0xfa);
pub const LOGO: [&str; 6] = [
"██████╗ ███████╗ █████╗ ███████╗ ██████╗ ███╗ ██╗██╗██╗ ██╗",
"██╔══██╗██╔════╝██╔══██╗██╔════╝██╔═══██╗████╗ ██║██║╚██╗██╔╝",
"██████╔╝█████╗ ███████║███████╗██║ ██║██╔██╗ ██║██║ ╚███╔╝ ",
"██╔══██╗██╔══╝ ██╔══██║╚════██║██║ ██║██║╚██╗██║██║ ██╔██╗ ",
"██║ ██║███████╗██║ ██║███████║╚██████╔╝██║ ╚████║██║██╔╝ ██╗",
"╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝╚═╝ ╚═╝",
];
pub const SIDEBAR_WIDTH: u16 = 34;
pub const DOCK_HEIGHT: u16 = 5;
pub const MAX_COMPOSER_ROWS: u16 = 5;
pub const COMPOSER_PLACEHOLDER: &str = "type to chat / for commands @ for files";
@@ -1,45 +0,0 @@
use reasonix_render::decode_only::run_decode_only;
#[test]
fn counts_and_emits_one_line_per_frame() {
let input = concat!(
r#"{"schemaVersion":1,"cols":80,"rows":24,"root":{"kind":"text","runs":[{"text":"a"}]}}"#,
"\n",
r#"{"schemaVersion":1,"cols":80,"rows":24,"root":{"kind":"text","runs":[{"text":"b"}]}}"#,
"\n",
);
let mut out = Vec::<u8>::new();
let count = run_decode_only(input.as_bytes(), &mut out).expect("decode");
assert_eq!(count, 2);
let s = String::from_utf8(out).expect("utf8");
assert!(s.contains("frame 1"), "{s}");
assert!(s.contains("frame 2"), "{s}");
}
#[test]
fn skips_blank_lines_and_keeps_counting() {
let input = concat!(
"\n",
r#"{"schemaVersion":1,"cols":80,"rows":24,"root":{"kind":"text","runs":[{"text":"a"}]}}"#,
"\n",
" \n",
r#"{"schemaVersion":1,"cols":80,"rows":24,"root":{"kind":"text","runs":[{"text":"b"}]}}"#,
"\n",
);
let mut out = Vec::<u8>::new();
let count = run_decode_only(input.as_bytes(), &mut out).expect("decode");
assert_eq!(count, 2);
}
#[test]
fn surfaces_decode_errors_with_line_context() {
let input = concat!(
r#"{"schemaVersion":1,"cols":80,"rows":24,"root":{"kind":"text","runs":[{"text":"a"}]}}"#,
"\n",
r#"{not valid json"#,
"\n",
);
let mut out = Vec::<u8>::new();
let err = run_decode_only(input.as_bytes(), &mut out).unwrap_err();
assert!(err.to_string().contains("line 2"), "{err}");
}
-96
View File
@@ -1,96 +0,0 @@
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
use reasonix_render::input::{is_quit, translate_key};
fn press(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {
KeyEvent {
code,
modifiers,
kind: KeyEventKind::Press,
state: KeyEventState::NONE,
}
}
#[test]
fn translates_a_plain_char() {
let e = press(KeyCode::Char('a'), KeyModifiers::NONE);
let t = translate_key(&e).expect("translate");
assert_eq!(t.code, "Char");
assert_eq!(t.char, Some('a'));
assert!(t.modifiers.is_empty());
}
#[test]
fn translates_enter_with_no_char() {
let e = press(KeyCode::Enter, KeyModifiers::NONE);
let t = translate_key(&e).expect("translate");
assert_eq!(t.code, "Enter");
assert_eq!(t.char, None);
}
#[test]
fn translates_ctrl_a_with_a_ctrl_modifier() {
let e = press(KeyCode::Char('a'), KeyModifiers::CONTROL);
let t = translate_key(&e).expect("translate");
assert_eq!(t.char, Some('a'));
assert_eq!(t.modifiers, vec!["ctrl"]);
}
#[test]
fn collects_multiple_modifiers_in_canonical_order() {
let e = press(
KeyCode::Char('x'),
KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT,
);
let t = translate_key(&e).expect("translate");
assert_eq!(t.modifiers, vec!["ctrl", "alt", "shift"]);
}
#[test]
fn renders_function_keys_as_f1_through_f12() {
let t = translate_key(&press(KeyCode::F(5), KeyModifiers::NONE)).expect("translate");
assert_eq!(t.code, "F5");
}
#[test]
fn skips_release_events_so_only_presses_emit() {
let e = KeyEvent {
code: KeyCode::Char('a'),
modifiers: KeyModifiers::NONE,
kind: KeyEventKind::Release,
state: KeyEventState::NONE,
};
assert!(translate_key(&e).is_none());
}
#[test]
fn serializes_a_plain_key_to_one_compact_json_line() {
let t = translate_key(&press(KeyCode::Enter, KeyModifiers::NONE)).expect("translate");
let json = serde_json::to_string(&t).expect("serialize");
assert_eq!(json, r#"{"event":"key","code":"Enter"}"#);
}
#[test]
fn serializes_a_char_event_with_a_char_field() {
let t = translate_key(&press(KeyCode::Char('z'), KeyModifiers::NONE)).expect("translate");
let json = serde_json::to_string(&t).expect("serialize");
assert_eq!(json, r#"{"event":"key","code":"Char","char":"z"}"#);
}
#[test]
fn serializes_modifiers_as_a_string_array() {
let t = translate_key(&press(KeyCode::Char('c'), KeyModifiers::CONTROL)).expect("translate");
let json = serde_json::to_string(&t).expect("serialize");
assert_eq!(
json,
r#"{"event":"key","code":"Char","char":"c","modifiers":["ctrl"]}"#
);
}
#[test]
fn is_quit_matches_only_ctrl_c() {
assert!(is_quit(&press(KeyCode::Char('c'), KeyModifiers::CONTROL)));
assert!(!is_quit(&press(KeyCode::Char('c'), KeyModifiers::NONE)));
assert!(!is_quit(&press(KeyCode::Char('d'), KeyModifiers::CONTROL)));
assert!(!is_quit(&press(KeyCode::Esc, KeyModifiers::NONE)));
}
-45
View File
@@ -1,45 +0,0 @@
use ratatui::backend::TestBackend;
use ratatui::Terminal;
use reasonix_render::state::SetupState;
use reasonix_render::view::render_setup;
fn draw_setup(state: &SetupState, cols: u16, rows: u16) -> String {
let backend = TestBackend::new(cols, rows);
let mut terminal = Terminal::new(backend).unwrap();
terminal.draw(|f| render_setup(state, f)).unwrap();
let buffer = terminal.backend().buffer().clone();
let mut out = String::new();
for y in 0..buffer.area.height {
for x in 0..buffer.area.width {
out.push_str(buffer[(x, y)].symbol());
}
out.push('\n');
}
out
}
#[test]
fn setup_renders_welcome_and_masked_dots() {
let state = SetupState {
buffer_length: 4,
error: None,
};
let rendered = draw_setup(&state, 80, 24);
assert!(rendered.contains("REASONIX"));
assert!(rendered.contains("welcome"));
assert!(rendered.contains("API key"));
assert!(rendered.contains("••••"));
assert!(rendered.contains("▮"));
assert!(rendered.contains("Ctrl+C"));
}
#[test]
fn setup_with_error_renders_error_row() {
let state = SetupState {
buffer_length: 0,
error: Some("key malformed".to_string()),
};
let rendered = draw_setup(&state, 80, 24);
assert!(rendered.contains("✗"));
assert!(rendered.contains("key malformed"));
}
File diff suppressed because it is too large. Load diff
+4 -3
View File
@@ -2,13 +2,14 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-capable" content="yes" />
<title>Reasonix</title>
<meta name="reasonix-token" content="__REASONIX_TOKEN__" />
<meta name="reasonix-mode" content="__REASONIX_MODE__" />
<!-- Production: served by CLI server; Vite dev: transformed by vite.config.ts -->
<link rel="stylesheet" href="/assets/app.css?token=__REASONIX_TOKEN__" />
<link rel="stylesheet" href="/assets/vendor-uplot.css?token=__REASONIX_TOKEN__" />
<link rel="stylesheet" href="/assets/vendor-hljs.css?token=__REASONIX_TOKEN__" />
</head>
<body>
<div id="root">
+3601
View File
File diff suppressed because it is too large. Load diff
+34
View File
@@ -0,0 +1,34 @@
{
"name": "reasonix-dashboard-v2",
"private": true,
"version": "0.47.2",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"@fontsource/geist": "^5.2.8",
"@fontsource/geist-mono": "^5.2.7",
"@fontsource/inter": "^5.2.8",
"katex": "^0.16.21",
"lucide-react": "^0.469.0",
"prism-react-renderer": "^2.4.1",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-markdown": "^9.0.1",
"react-virtuoso": "^4.12.5",
"rehype-katex": "^7.0.1",
"remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.0",
"remark-math": "^6.0.0"
},
"devDependencies": {
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.6.3",
"vite": "^5.4.10"
}
}
File diff suppressed because it is too large. Load diff
+163
View File
@@ -0,0 +1,163 @@
import { Highlight, type PrismTheme } from "prism-react-renderer";
import { useEffect, useRef, useState } from "react";
const DARK_THEME: PrismTheme = {
plain: { color: "#dde1ea", backgroundColor: "transparent" },
styles: [
{ types: ["comment", "prolog", "doctype", "cdata"], style: { color: "#6d6e80", fontStyle: "italic" } },
{ types: ["punctuation"], style: { color: "#a8a9b8" } },
{ types: ["property", "tag", "boolean", "number", "constant", "symbol", "deleted"], style: { color: "#fbbf24" } },
{ types: ["selector", "attr-name", "string", "char", "builtin", "inserted"], style: { color: "#86dcb1" } },
{ types: ["operator", "entity", "url"], style: { color: "#84b9e8" } },
{ types: ["atrule", "attr-value", "keyword"], style: { color: "#b4a8f0" } },
{ types: ["function", "class-name", "maybe-class-name"], style: { color: "#84b9e8", fontWeight: "500" } },
{ types: ["regex", "important", "variable"], style: { color: "#f0c062" } },
{ types: ["important", "bold"], style: { fontWeight: "bold" } },
{ types: ["italic"], style: { fontStyle: "italic" } },
],
};
const LIGHT_THEME: PrismTheme = {
plain: { color: "#24292e", backgroundColor: "transparent" },
styles: [
{ types: ["comment", "prolog", "doctype", "cdata"], style: { color: "#6a737d", fontStyle: "italic" } },
{ types: ["punctuation"], style: { color: "#24292e" } },
{ types: ["property", "tag", "boolean", "number", "constant", "symbol", "deleted"], style: { color: "#d73a49" } },
{ types: ["selector", "attr-name", "string", "char", "builtin", "inserted"], style: { color: "#032f62" } },
{ types: ["operator", "entity", "url"], style: { color: "#d73a49" } },
{ types: ["atrule", "attr-value", "keyword"], style: { color: "#d73a49" } },
{ types: ["function", "class-name", "maybe-class-name"], style: { color: "#6f42c1", fontWeight: "500" } },
{ types: ["regex", "important", "variable"], style: { color: "#e36209" } },
{ types: ["important", "bold"], style: { fontWeight: "bold" } },
{ types: ["italic"], style: { fontStyle: "italic" } },
],
};
function usePrismTheme(): PrismTheme {
const [theme, setTheme] = useState<"dark" | "light">(() =>
document.documentElement.dataset.theme === "light" ? "light" : "dark",
);
const prevRef = useRef(theme);
useEffect(() => {
const el = document.documentElement;
const cb = () => {
const t = el.dataset.theme === "light" ? "light" : "dark";
if (t !== prevRef.current) {
prevRef.current = t;
setTheme(t);
}
};
const mo = new MutationObserver(cb);
mo.observe(el, { attributes: true, attributeFilter: ["data-theme"] });
return () => mo.disconnect();
}, []);
return theme === "dark" ? DARK_THEME : LIGHT_THEME;
}
export const PRISM_THEME = DARK_THEME;
const EXTS: Record<string, string> = {
ts: "typescript", tsx: "tsx", mts: "typescript", cts: "typescript",
js: "javascript", jsx: "jsx", mjs: "javascript", cjs: "javascript",
py: "python", pyi: "python",
rs: "rust",
go: "go",
json: "json", jsonc: "json",
md: "markdown", mdx: "markdown",
css: "css", scss: "scss", less: "less",
html: "markup", htm: "markup", xml: "markup", svg: "markup",
yaml: "yaml", yml: "yaml",
toml: "toml",
sh: "bash", bash: "bash", zsh: "bash", fish: "bash",
sql: "sql",
rb: "ruby",
java: "java", kt: "kotlin",
swift: "swift",
c: "c", h: "c",
cpp: "cpp", cc: "cpp", cxx: "cpp", hpp: "cpp", hxx: "cpp",
cs: "csharp",
php: "php",
lua: "lua",
dart: "dart",
ex: "elixir", exs: "elixir",
erl: "erlang",
hs: "haskell",
clj: "clojure", cljs: "clojure",
zig: "zig",
vue: "markup",
svelte: "markup",
graphql: "graphql", gql: "graphql",
proto: "protobuf",
dockerfile: "docker",
};
export function langFromPath(path: string | null | undefined): string | null {
if (!path) return null;
const base = path.split(/[\\/]/).pop() ?? "";
if (base.toLowerCase() === "dockerfile") return "docker";
if (base.toLowerCase() === "makefile") return "makefile";
const m = /\.([a-z0-9]+)$/i.exec(base);
if (!m) return null;
return EXTS[m[1].toLowerCase()] ?? null;
}
export function CodeView({
text,
lang,
startLine = 1,
showLineNumbers = true,
}: {
text: string;
lang: string;
startLine?: number;
showLineNumbers?: boolean;
}) {
const theme = usePrismTheme();
return (
<Highlight theme={theme} code={text} language={lang}>
{({ className, tokens, getLineProps, getTokenProps }) => (
<pre className={`codeview ${className}`}>
{tokens.map((line, i) => (
<div key={i} {...getLineProps({ line })} className="codeview-line">
{showLineNumbers && (
<span className="codeview-line-num">{i + startLine}</span>
)}
<span className="codeview-line-content">
{line.map((token, k) => (
<span key={k} {...getTokenProps({ token })} />
))}
</span>
</div>
))}
</pre>
)}
</Highlight>
);
}
export function CollapsibleCode({
text,
lang,
startLine = 1,
maxLines = 20,
}: {
text: string;
lang: string;
startLine?: number;
maxLines?: number;
}) {
const [open, setOpen] = useState(false);
const lines = text.split("\n");
const tooLong = lines.length > maxLines;
const shown = open || !tooLong ? text : lines.slice(0, maxLines).join("\n");
return (
<>
<CodeView text={shown} lang={lang} startLine={startLine} />
{tooLong && (
<button type="button" className="tool-more" onClick={() => setOpen((v) => !v)}>
{open ? "less" : `+ ${lines.length - maxLines} more lines`}
</button>
)}
</>
);
}
+345
View File
@@ -0,0 +1,345 @@
import {
ClipboardCopy,
Download,
FilePlus,
FocusIcon,
FolderOpen,
Info,
Plus,
Search,
Settings,
SquareX,
StopCircle,
Trash2,
} from "lucide-react";
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { t, useLang } from "./i18n";
import { Shortcut, type ShortcutKey } from "./ui/shortcut";
export type CommandGroup = "nav" | "action" | "workspace" | "settings";
export type Command = {
id: string;
label: string;
hint?: string;
icon: ReactNode;
shortcut?: ShortcutKey[];
group: CommandGroup;
run: () => void;
};
export function useCommandPalette(active: boolean = true) {
const [open, setOpen] = useState(false);
useEffect(() => {
// Skip in background tabs — each TabRuntime calls this hook, so without the gate Cmd+K toggles every tab's palette at once.
if (!active) return;
const onKey = (e: KeyboardEvent) => {
const mod = e.ctrlKey || e.metaKey;
if (mod && (e.key === "k" || e.key === "K")) {
e.preventDefault();
setOpen((v) => !v);
} else if (e.key === "Escape") {
setOpen(false);
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [active]);
return { open, setOpen };
}
export type CommandHandlers = {
newChat: () => void;
clearChat: () => void;
focusComposer: () => void;
openSettings: () => void;
about: () => void;
abort: () => void;
copyLast: () => void;
conversationCopy: () => void;
exportMarkdown: () => void;
pickWorkspace: () => void;
newTab: () => void;
closeTab: () => void;
busy: boolean;
canCloseTab: boolean;
hasMessages: boolean;
};
export function buildCommands(handlers: CommandHandlers): Command[] {
const list: Command[] = [
{
id: "new-chat",
group: "nav",
label: t("palette.newChat"),
hint: t("palette.newChatHint"),
icon: <FilePlus size={13} />,
shortcut: ["mod", "N"],
run: handlers.newChat,
},
{
id: "new-tab",
group: "nav",
label: t("palette.newTab"),
hint: t("palette.newTabHint"),
icon: <Plus size={13} />,
shortcut: ["mod", "T"],
run: handlers.newTab,
},
];
if (handlers.canCloseTab) {
list.push({
id: "close-tab",
group: "nav",
label: t("palette.closeTab"),
hint: t("palette.closeTabHint"),
icon: <SquareX size={13} />,
shortcut: ["mod", "W"],
run: handlers.closeTab,
});
}
list.push({
id: "focus-composer",
group: "nav",
label: t("palette.focusComposer"),
icon: <FocusIcon size={13} />,
shortcut: ["mod", "L"],
run: handlers.focusComposer,
});
if (handlers.busy) {
list.push({
id: "abort",
group: "action",
label: t("palette.abort"),
hint: t("palette.abortHint"),
icon: <StopCircle size={13} />,
shortcut: ["esc"],
run: handlers.abort,
});
}
if (handlers.hasMessages) {
list.push({
id: "copy-last",
group: "action",
label: t("palette.copyLast"),
hint: t("palette.copyLastHint"),
icon: <ClipboardCopy size={13} />,
run: handlers.copyLast,
});
list.push({
id: "copy-conv",
group: "action",
label: t("palette.copyConv"),
hint: t("palette.copyConvHint"),
icon: <ClipboardCopy size={13} />,
run: handlers.conversationCopy,
});
list.push({
id: "export-md",
group: "action",
label: t("palette.exportMd"),
hint: t("palette.exportMdHint"),
icon: <Download size={13} />,
run: handlers.exportMarkdown,
});
list.push({
id: "clear-chat",
group: "action",
label: t("palette.clearChat"),
hint: t("palette.clearChatHint"),
icon: <Trash2 size={13} />,
run: handlers.clearChat,
});
}
list.push({
id: "pick-workspace",
group: "workspace",
label: t("palette.pickWorkspace"),
hint: t("palette.pickWorkspaceHint"),
icon: <FolderOpen size={13} />,
run: handlers.pickWorkspace,
});
list.push({
id: "settings",
group: "settings",
label: t("palette.settings"),
hint: t("palette.settingsHint"),
icon: <Settings size={13} />,
run: handlers.openSettings,
});
list.push({
id: "about",
group: "settings",
label: t("palette.about"),
icon: <Info size={13} />,
run: handlers.about,
});
return list;
}
const GROUP_ORDER: CommandGroup[] = ["nav", "action", "workspace", "settings"];
function groupLabel(g: CommandGroup): string {
switch (g) {
case "nav": return t("palette.groupNav");
case "action": return t("palette.groupAction");
case "workspace": return t("palette.groupWorkspace");
case "settings": return t("palette.groupSettings");
}
}
export function CommandPalette({
open,
onClose,
commands,
}: {
open: boolean;
onClose: () => void;
commands: Command[];
}) {
useLang();
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return commands;
return commands.filter((c) =>
[c.label, c.hint].filter(Boolean).join(" ").toLowerCase().includes(q),
);
}, [query, commands]);
useEffect(() => {
if (open) {
setQuery("");
setActive(0);
requestAnimationFrame(() => inputRef.current?.focus());
}
}, [open]);
useEffect(() => {
setActive((a) => Math.min(a, Math.max(0, filtered.length - 1)));
}, [filtered.length]);
useEffect(() => {
const el = listRef.current?.querySelector<HTMLElement>(`[data-idx="${active}"]`);
el?.scrollIntoView({ block: "nearest" });
}, [active]);
const grouped = useMemo(() => {
const byGroup = new Map<CommandGroup, Command[]>();
for (const c of filtered) {
const arr = byGroup.get(c.group) ?? [];
arr.push(c);
byGroup.set(c.group, arr);
}
return GROUP_ORDER
.map((g) => ({ group: g, items: byGroup.get(g) ?? [] }))
.filter((s) => s.items.length > 0);
}, [filtered]);
if (!open) return null;
const run = (cmd: Command) => {
cmd.run();
onClose();
};
return (
<div className="cmdk-mask" onMouseDown={onClose}>
<div className="cmdk" onMouseDown={(e) => e.stopPropagation()}>
<div className="cmdk-head">
<Search size={14} />
<input
ref={inputRef}
placeholder={t("palette.searchPlaceholder")}
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setActive((a) => Math.min(a + 1, filtered.length - 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((a) => Math.max(a - 1, 0));
} else if (e.key === "Enter") {
e.preventDefault();
const cmd = filtered[active];
if (cmd) run(cmd);
}
}}
/>
<span className="hint">
<Shortcut keys={["esc"]} />
</span>
</div>
<div className="cmdk-body" ref={listRef}>
{filtered.length === 0 ? (
<div className="cmdk-empty">{t("palette.empty")}</div>
) : null}
{grouped.map((section) => (
<div className="cmdk-group" key={section.group}>
<div className="cmdk-gh">{groupLabel(section.group)}</div>
{section.items.map((c) => {
const i = filtered.indexOf(c);
return (
<div
key={c.id}
data-idx={i}
className="cmdk-row"
data-active={i === active}
onMouseEnter={() => setActive(i)}
onClick={() => run(c)}
>
<span className="ic">{c.icon}</span>
<span className="l">{c.label}</span>
<span className="g">{groupLabel(c.group)}</span>
{c.shortcut ? (
<span className="kb">
<Shortcut keys={c.shortcut} />
</span>
) : (
<span className="kb-empty" />
)}
</div>
);
})}
</div>
))}
</div>
<div className="cmdk-foot">
<span>
<Shortcut keys={["updown"]} />
{t("palette.footMove")}
</span>
<span>
<Shortcut keys={["enter"]} />
{t("palette.footRun")}
</span>
<span>
<Shortcut keys={["esc"]} />
{t("palette.footClose")}
</span>
<span style={{ marginLeft: "auto", color: "var(--muted)" }}>
{filtered.length} {t("palette.countSuffix")}
</span>
</div>
</div>
</div>
);
}
export function Toast({ message }: { message: { msg: string; yolo?: boolean } | null }) {
if (!message) return null;
if (message.yolo) {
return (
<div className="toast toast-yolo">
<span className="toast-yolo-badge">YOLO</span>
{message.msg}
</div>
);
}
return <div className="toast">{message.msg}</div>;
}
+271
View File
@@ -0,0 +1,271 @@
import { invoke } from "@tauri-apps/api/core";
import { openPath, openUrl } from "@tauri-apps/plugin-opener";
import { Check, Copy, ExternalLink, FileText } from "lucide-react";
import {
Children,
cloneElement,
createContext,
isValidElement,
memo,
type ReactNode,
useContext,
useState,
} from "react";
import ReactMarkdown from "react-markdown";
import rehypeKatex from "rehype-katex";
import remarkBreaks from "remark-breaks";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import { CodeView } from "./CodeView";
import { t, useLang } from "./i18n";
async function openWithEditor(
editor: string | undefined,
abs: string,
line?: number,
): Promise<void> {
if (editor && editor.trim()) {
await invoke("open_in_editor", { command: editor, path: abs, line: line ?? null });
return;
}
await openPath(abs);
}
type WorkspaceCtx = { dir?: string; editor?: string };
const WorkspaceContext = createContext<WorkspaceCtx>({});
export const WorkspaceProvider = WorkspaceContext.Provider;
function resolveAgainstWorkspace(rel: string, ws: string | undefined): string {
if (!ws) return rel;
if (/^[a-zA-Z]:[\\/]/.test(rel) || rel.startsWith("/")) return rel;
const sep = ws.includes("\\") ? "\\" : "/";
const trimmed = ws.replace(/[\\/]$/, "");
return `${trimmed}${sep}${rel.replace(/^\.[\\/]/, "")}`;
}
const KNOWN_EXTS =
"ts|tsx|mts|cts|js|jsx|mjs|cjs|py|pyi|rs|go|json|jsonc|md|mdx|css|scss|less|html|htm|xml|svg|yaml|yml|toml|sh|bash|zsh|fish|sql|rb|java|kt|swift|c|cpp|cc|cxx|h|hpp|hxx|cs|php|lua|dart|ex|exs|erl|hs|clj|cljs|zig|vue|svelte|graphql|gql|proto";
// No lookbehind here — Tauri's WKWebView on macOS Monterey (Safari < 16.4)
// can't parse `(?<=...)` and the whole bundle fails to load with an
// "invalid group specifier name" error. Capture the leading char as
// group 1 instead and let splitFilePaths skip past it. Issue #1209.
const FILE_PATH_RE = new RegExp(
`(^|[\\s\`'"(\\[])((?:[\\w.-]+\\/)+[\\w.-]+\\.(?:${KNOWN_EXTS}))(?::(\\d+(?:-\\d+)?))?(?=[\\s.,;!?\\]\\)'"\`]|$)`,
"g",
);
function FilePill({ path, line }: { path: string; line?: string }) {
useLang();
const ctx = useContext(WorkspaceContext);
const [done, setDone] = useState<"open" | "copy" | null>(null);
const display = line ? `${path}:${line}` : path;
const openInEditor = async () => {
try {
const abs = resolveAgainstWorkspace(path, ctx.dir);
const lineNum = line ? Number.parseInt(line.split("-")[0] ?? line, 10) : undefined;
await openWithEditor(ctx.editor, abs, Number.isFinite(lineNum) ? lineNum : undefined);
setDone("open");
setTimeout(() => setDone(null), 1200);
} catch {
try {
await navigator.clipboard.writeText(display);
setDone("copy");
setTimeout(() => setDone(null), 1200);
} catch {
/* ignore */
}
}
};
const copyOnly = async (e: React.MouseEvent) => {
e.stopPropagation();
try {
await navigator.clipboard.writeText(display);
setDone("copy");
setTimeout(() => setDone(null), 1200);
} catch {
/* ignore */
}
};
return (
<span
className={`file-pill ${done ? "done" : ""}`}
role="button"
tabIndex={0}
onClick={openInEditor}
onContextMenu={(e) => {
e.preventDefault();
void copyOnly(e);
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
void openInEditor();
}
}}
title={t("markdown.filePillTitle")}
>
<FileText size={10} className="file-pill-icon" />
<span className="file-pill-path">{path}</span>
{line && <span className="file-pill-line">:{line}</span>}
{done && <Check size={10} className="file-pill-check" />}
</span>
);
}
function splitFilePaths(text: string): ReactNode[] | string {
FILE_PATH_RE.lastIndex = 0;
const out: ReactNode[] = [];
let last = 0;
let m: RegExpExecArray | null = FILE_PATH_RE.exec(text);
while (m !== null) {
const prefix = m[1] ?? "";
const path = m[2]!;
const line = m[3];
const pillStart = m.index + prefix.length;
if (pillStart > last) out.push(text.slice(last, pillStart));
out.push(<FilePill key={`fp-${pillStart}`} path={path} line={line} />);
last = pillStart + path.length + (line ? line.length + 1 : 0);
m = FILE_PATH_RE.exec(text);
}
if (out.length === 0) return text;
if (last < text.length) out.push(text.slice(last));
return out;
}
type AnyProps = { children?: ReactNode } & Record<string, unknown>;
function withFilePills(children: ReactNode): ReactNode {
return Children.map(children, (child) => {
if (typeof child === "string") return splitFilePaths(child);
if (isValidElement(child)) {
const props = child.props as AnyProps;
if (props.children !== undefined) {
return cloneElement(child, undefined, withFilePills(props.children));
}
}
return child;
});
}
export const Markdown = memo(function Markdown({ source }: { source: string }) {
return (
<div className="markdown">
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkBreaks, remarkMath]}
rehypePlugins={[[rehypeKatex, { throwOnError: false }]]}
components={{
pre: ({ children }) => {
// react-markdown v9 nests children unpredictably — flatten all text.
const rawText = flattenChildText(children).trimEnd();
return <CodeBlock lang={extractFencedLang(children)} text={rawText} />;
},
code: ({ className, children }) => <code className={className}>{children}</code>,
a: ({ href, children }) => <SafeLink href={href}>{children}</SafeLink>,
p: ({ children }) => <p>{withFilePills(children)}</p>,
li: ({ children }) => <li>{withFilePills(children)}</li>,
td: ({ children }) => <td>{withFilePills(children)}</td>,
}}
>
{source}
</ReactMarkdown>
</div>
);
});
function SafeLink({ href, children }: { href?: string; children: ReactNode }) {
useLang();
const ctx = useContext(WorkspaceContext);
const [done, setDone] = useState(false);
const isExternal = !!href && /^https?:\/\//i.test(href);
const onClick = async (e: React.MouseEvent) => {
e.preventDefault();
if (!href) return;
if (isExternal) {
try {
await openUrl(href);
} catch {
window.open(href, "_blank", "noopener,noreferrer");
}
return;
}
try {
const stripped = href.replace(/^file:\/\//, "");
const abs = resolveAgainstWorkspace(stripped, ctx.dir);
await openWithEditor(ctx.editor, abs);
} catch {
try {
await navigator.clipboard.writeText(href);
setDone(true);
setTimeout(() => setDone(false), 1200);
} catch {
/* ignore */
}
}
};
return (
<a
href={href ?? "#"}
onClick={onClick}
className={`md-link ${isExternal ? "external" : "local"} ${done ? "done" : ""}`}
title={
isExternal
? t("markdown.externalLinkTitle", { href: href ?? "" })
: t("markdown.localLinkTitle", { href: href ?? "" })
}
>
{children}
{isExternal ? (
<ExternalLink size={10} className="md-link-icon" />
) : done ? (
<Check size={10} className="md-link-icon" />
) : null}
</a>
);
}
export function extractFencedLang(children: ReactNode): string {
for (const kid of Children.toArray(children)) {
if (isValidElement(kid)) {
const cls = (kid.props as Record<string, unknown>).className;
if (typeof cls === "string") {
const m = cls.match(/language-([\w-]+)/);
if (m) return m[1]!;
}
}
}
return "text";
}
function flattenChildText(node: ReactNode): string {
if (typeof node === "string" || typeof node === "number") return String(node);
if (Array.isArray(node)) return node.map(flattenChildText).join("");
if (isValidElement(node))
return flattenChildText((node.props as { children?: ReactNode }).children);
return "";
}
function CodeBlock({ lang, text }: { lang: string; text: string }): ReactNode {
useLang();
const [copied, setCopied] = useState(false);
const onCopy = async () => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 1400);
} catch {
/* ignore */
}
};
return (
<div className="codeblock">
<div className="codeblock-head">
<span className="codeblock-lang">{lang}</span>
<button type="button" className={`copy-btn ${copied ? "done" : ""}`} onClick={onCopy}>
{copied ? <Check size={11} /> : <Copy size={11} />}
{copied ? t("markdown.copied") : t("markdown.copy")}
</button>
</div>
<CodeView text={text} lang={lang} />
</div>
);
}
-912
View File
@@ -1,912 +0,0 @@
import { marked } from "marked";
import { memo } from "preact/compat";
import { useState } from "preact/hooks";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
import {
escapeHtml,
hlLine,
langFromPath,
renderHighlightedBlock,
renderMarkdownToString,
renderSearchReplace,
} from "../lib/markdown.js";
export type ChatRole = "user" | "assistant" | "tool" | "info" | "warning" | "error";
export interface ChatMsg {
id: string;
role: ChatRole;
text?: string;
reasoning?: string;
toolName?: string;
toolArgs?: string;
}
const ROLE_GLYPH: Record<ChatRole, string> = {
user: "◇",
assistant: "◆",
tool: "▣",
info: "·",
warning: "▲",
error: "✦",
};
export type OnResolve = (kind: string, ...args: unknown[]) => void;
interface ToolCardProps {
msg: ChatMsg;
}
interface ChatMessageProps {
msg: ChatMsg;
streaming?: boolean;
}
interface ModalCardProps {
accent: string;
icon: string;
title: string;
subtitle?: string;
children?: unknown;
}
interface ShellModalSpec {
command: string;
allowPrefix?: string;
shellKind?: string;
}
interface ChoiceOption {
id: string;
title: string;
summary?: string;
}
interface ChoiceModalSpec {
question: string;
options: ChoiceOption[];
allowCustom?: boolean;
}
interface PlanModalSpec {
body?: string;
}
interface EditReviewSpec {
search?: string;
replace?: string;
path?: string;
remaining: number;
total: number;
}
interface WorkspaceSpec {
path: string;
}
interface CheckpointSpec {
stepId: string;
title?: string;
completed?: number;
total?: number;
}
interface RevisionStep {
id: string;
title: string;
action: string;
risk?: "low" | "med" | "high";
}
interface RevisionSpec {
summary?: string;
reason: string;
remainingSteps: RevisionStep[];
}
export type PickerActionName =
| "pick"
| "delete"
| "rename"
| "new"
| "install"
| "uninstall"
| "load-more"
| "refine"
| "cancel";
export interface PickerItemSpec {
id: string;
title: string;
subtitle?: string;
badge?: string;
meta?: string;
}
export interface PickerModalSpec {
pickerKind: string;
title: string;
query?: string;
items: PickerItemSpec[];
actions: PickerActionName[];
hasMore?: boolean;
hint?: string;
}
export interface ViewerStep {
id: string;
title: string;
status: "done" | "queued";
}
export interface ViewerModalSpec {
viewerKind: string;
title: string;
body?: string;
steps?: ViewerStep[];
meta?: string;
}
interface DiffEntry {
kind: "context" | "ins" | "del";
text: string;
}
interface DiffPair {
left: string | null;
right: string | null;
kind: "context" | "change" | "ins" | "del";
}
export function renderMessageBody(text: string | null | undefined) {
if (!text) return null;
return html`<div class="md" dangerouslySetInnerHTML=${{ __html: renderMarkdownToString(text) }}></div>`;
}
export function parseToolArgs(raw: string | null | undefined): Record<string, unknown> | null {
if (!raw) return null;
try {
return JSON.parse(raw);
} catch {
return null;
}
}
export function ToolCard({ msg }: ToolCardProps) {
useLang();
const args = parseToolArgs(msg.toolArgs);
const name = msg.toolName ?? "tool";
// Reasonix's filesystem tools emit the path in args.path; MCP-bridged
// ones may differ but most expose a `path` field too. Normalize.
const path = (args?.path ?? args?.file_path ?? args?.filename) as string | undefined;
// edit_file (Reasonix) — search/replace pair → diff view.
if (
(name === "edit_file" || name.endsWith("_edit_file")) &&
args &&
typeof args.search === "string" &&
typeof args.replace === "string"
) {
const diffHtml = renderSearchReplace(
args.search as string,
args.replace as string,
path ?? "",
);
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">✎</span>
<span class="tool-card-name">edit_file</span>
${path ? html`<code class="tool-card-path">${path}</code>` : null}
</div>
<div dangerouslySetInnerHTML=${{ __html: diffHtml }}></div>
${msg.text ? html`<div class="tool-card-result">${msg.text}</div>` : null}
</div>
`;
}
// write_file — show new content as a code block with path-derived lang.
if (
(name === "write_file" || name.endsWith("_write_file")) &&
args &&
typeof args.content === "string"
) {
const lang = langFromPath(path);
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">+</span>
<span class="tool-card-name">write_file</span>
${path ? html`<code class="tool-card-path">${path}</code>` : null}
${lang ? html`<span class="pill">${lang}</span>` : null}
</div>
<div dangerouslySetInnerHTML=${{ __html: renderHighlightedBlock(args.content as string, lang) }}></div>
${msg.text ? html`<div class="tool-card-result">${msg.text}</div>` : null}
</div>
`;
}
// read_file / list_files — content lands in msg.text.
if (name === "read_file" || name.endsWith("_read_file") || name === "filesystem_read_file") {
const lang = langFromPath(path);
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">▤</span>
<span class="tool-card-name">read_file</span>
${path ? html`<code class="tool-card-path">${path}</code>` : null}
${lang ? html`<span class="pill">${lang}</span>` : null}
</div>
<div dangerouslySetInnerHTML=${{ __html: renderHighlightedBlock(msg.text ?? "", lang) }}></div>
</div>
`;
}
// run_command / run_background — terminal-style.
if (name === "run_command" || name === "run_background") {
const cmd = args?.command;
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">⚡</span>
<span class="tool-card-name">${name === "run_background" ? "run_background" : "run_command"}</span>
</div>
${
cmd
? html`<pre class="tool-card-cmd"><span class="tool-card-prompt">$</span> <code>${cmd}</code></pre>`
: null
}
${msg.text ? html`<pre class="tool-card-output">${msg.text}</pre>` : null}
</div>
`;
}
// list_files / file_exists / delete_file — show args + result inline.
if (
name === "list_files" ||
name === "file_exists" ||
name === "delete_file" ||
name === "create_directory" ||
name === "delete_directory" ||
name.endsWith("_list_files")
) {
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">▣</span>
<span class="tool-card-name">${name}</span>
${path ? html`<code class="tool-card-path">${path}</code>` : null}
</div>
<pre class="tool-card-output">${msg.text}</pre>
</div>
`;
}
// Default — keep the legacy compact box but add an args preview when
// present so MCP-bridged tools still surface something readable.
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">▣</span>
<span class="tool-card-name">${name}</span>
</div>
${
args
? html`<details class="tool-card-args"><summary>${t("modal.arguments")}</summary><pre>${escapeHtml(JSON.stringify(args, null, 2))}</pre></details>`
: null
}
<pre class="tool-card-output">${msg.text}</pre>
</div>
`;
}
// memo() short-circuits re-renders when shallow props are unchanged.
// Historical messages keep stable msg references across deltas, so the
// O(N) marked.parse + hljs work that used to fire per assistant_delta
// now only runs on truly new messages and the live streaming bubble.
export const ChatMessage = memo(function ChatMessage({ msg, streaming }: ChatMessageProps) {
const role = msg.role;
const glyph = ROLE_GLYPH[role as ChatRole] ?? "·";
if (role === "tool") {
return html`
<div class="chat-msg tool">
<div class="glyph">${glyph}</div>
<${ToolCard} msg=${msg} />
</div>
`;
}
return html`
<div class="chat-msg ${role}">
<div class="glyph">${glyph}</div>
<div class="body">
${msg.reasoning ? html`<div class="reasoning">${msg.reasoning}</div>` : null}
${renderMessageBody(msg.text)}
${streaming ? html`<span class="chat-streaming-cursor"></span>` : null}
</div>
</div>
`;
});
//
// Each component renders a card matching the TUI's ModalCard accent
// palette: red for shell (run-now), magenta for choice (branching),
// cyan for plan (decision), green for edits. onResolve pushes to the
// server; the SSE channel will echo back a modal-down that clears the
// local state — both surfaces stay in lockstep without polling.
export function ModalCard({ accent, icon, title, subtitle, children }: ModalCardProps) {
return html`
<div class="modal-card" style=${`border-left-color: ${accent};`}>
<div class="modal-card-head">
<span class="modal-card-icon" style=${`color: ${accent};`}>${icon}</span>
<div>
<div class="modal-card-title">${title}</div>
${subtitle ? html`<div class="modal-card-subtitle">${subtitle}</div>` : null}
</div>
</div>
${children}
</div>
`;
}
export function ShellModal({ modal, onResolve }: { modal: ShellModalSpec; onResolve: OnResolve }) {
useLang();
const isBg = modal.shellKind === "run_background";
return html`
<${ModalCard}
accent="#f87171"
icon=${isBg ? "⏱" : "⚡"}
title=${isBg ? t("modal.shellBgTitle") : t("modal.shellTitle")}
subtitle=${
isBg ? t("modal.shellBgSubtitle") : t("modal.shellSubtitle")
}
>
<div class="modal-cmd"><span class="modal-cmd-prompt">$</span> <code>${modal.command}</code></div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("shell", "run_once")}>${t("modal.runOnce")}</button>
<button onClick=${() => onResolve("shell", "always_allow")}>${t("modal.alwaysAllow", { prefix: modal.allowPrefix ?? "" })}</button>
<button class="danger" onClick=${() => onResolve("shell", "deny")}>${t("modal.deny")}</button>
</div>
<//>
`;
}
export function ChoiceModal({ modal, onResolve }: { modal: ChoiceModalSpec; onResolve: OnResolve }) {
useLang();
const [custom, setCustom] = useState("");
const [showCustom, setShowCustom] = useState(false);
return html`
<${ModalCard} accent="#f0abfc" icon="🔀" title=${t("modal.choiceTitle")} subtitle=${modal.question}>
${modal.options.map(
(opt: ChoiceOption) => html`
<button
key=${opt.id}
class="modal-choice-row"
onClick=${() => onResolve("choice", { kind: "pick", optionId: opt.id })}
>
<span class="modal-choice-id">${opt.id}</span>
<span class="modal-choice-title">${opt.title}</span>
${opt.summary ? html`<span class="modal-choice-summary">${opt.summary}</span>` : null}
</button>
`,
)}
${
modal.allowCustom
? showCustom
? html`
<div class="modal-custom">
<textarea
placeholder=${t("modal.typePlaceholder")}
rows="2"
value=${custom}
onInput=${(e: Event) => setCustom((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("choice", { kind: "custom", text: custom })} disabled=${!custom.trim()}>${t("modal.send")}</button>
<button onClick=${() => {
setShowCustom(false);
setCustom("");
}}>${t("common.back")}</button>
</div>
</div>
`
: html`
<button class="modal-choice-row" onClick=${() => setShowCustom(true)}>
<span class="modal-choice-id">·</span>
<span class="modal-choice-title">${t("modal.typeOwn")}</span>
<span class="modal-choice-summary">${t("modal.typeOwnSummary")}</span>
</button>
`
: null
}
<button class="modal-choice-row modal-choice-cancel" onClick=${() => onResolve("choice", { kind: "cancel" })}>
<span class="modal-choice-id">×</span>
<span class="modal-choice-title">${t("modal.cancel")}</span>
<span class="modal-choice-summary">${t("modal.cancelSummary")}</span>
</button>
<//>
`;
}
export function PlanModal({ modal, onResolve }: { modal: PlanModalSpec; onResolve: OnResolve }) {
useLang();
const [feedback, setFeedback] = useState("");
const [stage, setStage] = useState<"approve" | "refine" | null>(null);
const send = () => onResolve("plan", stage, feedback);
return html`
<${ModalCard} accent="#67e8f9" icon="◆" title=${t("modal.planTitle")} subtitle=${t("modal.planSubtitle")}>
<div class="md modal-plan-body" dangerouslySetInnerHTML=${{ __html: marked.parse(modal.body || "") }}></div>
${
stage
? html`
<textarea
placeholder=${
stage === "approve"
? t("modal.approveInstructions")
: t("modal.refinePlaceholder")
}
rows="3"
value=${feedback}
onInput=${(e: Event) => setFeedback((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${send}>${stage === "approve" ? t("modal.approve") : t("modal.sendRefinement")}</button>
<button onClick=${() => {
setStage(null);
setFeedback("");
}}>${t("common.back")}</button>
</div>
`
: html`
<div class="modal-actions">
<button class="primary" onClick=${() => setStage("approve")}>${t("modal.approve")}</button>
<button onClick=${() => setStage("refine")}>${t("modal.refine")}</button>
<button class="danger" onClick=${() => onResolve("plan", "cancel")}>${t("modal.cancel")}</button>
</div>
`
}
<//>
`;
}
// Line-level LCS diff. Returns an ordered list of rows; "context" rows
// appear on both sides, "del" only on the left (red), "ins" only on the
// right (green). Adjacent del/ins are paired into one row downstream so
// the change reads "old → new" left-to-right like a git side-by-side.
function lineDiff(aLines: string[], bLines: string[]): DiffEntry[] {
const m = aLines.length;
const n = bLines.length;
const dp: number[][] = Array.from({ length: m + 1 }, () => new Array<number>(n + 1).fill(0));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (aLines[i - 1] === bLines[j - 1]) dp[i]![j] = dp[i - 1]![j - 1]! + 1;
else dp[i]![j] = Math.max(dp[i - 1]![j]!, dp[i]![j - 1]!);
}
}
const out: DiffEntry[] = [];
let i = m;
let j = n;
while (i > 0 || j > 0) {
if (i > 0 && j > 0 && aLines[i - 1] === bLines[j - 1]) {
out.push({ kind: "context", text: aLines[i - 1]! });
i--;
j--;
} else if (j > 0 && (i === 0 || dp[i]![j - 1]! >= dp[i - 1]![j]!)) {
out.push({ kind: "ins", text: bLines[j - 1]! });
j--;
} else {
out.push({ kind: "del", text: aLines[i - 1]! });
i--;
}
}
return out.reverse();
}
// Pair del/ins runs into side-by-side rows. A run of consecutive dels
// followed by a run of inss collapses into rows of (del[k], ins[k]) so
// the modified line lines up across the gutter; surplus on either side
// produces rows with the opposite cell empty.
function pairDiffRows(diff: DiffEntry[]): DiffPair[] {
const rows: DiffPair[] = [];
let k = 0;
while (k < diff.length) {
const entry = diff[k]!;
if (entry.kind === "context") {
rows.push({ left: entry.text, right: entry.text, kind: "context" });
k++;
continue;
}
const dels: string[] = [];
const inss: string[] = [];
while (k < diff.length && diff[k]!.kind === "del") {
dels.push(diff[k]!.text);
k++;
}
while (k < diff.length && diff[k]!.kind === "ins") {
inss.push(diff[k]!.text);
k++;
}
const pairs = Math.max(dels.length, inss.length);
for (let p = 0; p < pairs; p++) {
const dp = dels[p];
const ip = inss[p];
rows.push({
left: dp ?? null,
right: ip ?? null,
kind: dp != null && ip != null ? "change" : dp != null ? "del" : "ins",
});
}
}
return rows;
}
export function EditReviewModal({ modal, onResolve }: { modal: EditReviewSpec; onResolve: OnResolve }) {
useLang();
const search = modal.search ?? "";
const replace = modal.replace ?? "";
const lang = langFromPath(modal.path);
const aLines = search.split("\n");
const bLines = replace.split("\n");
const rows = pairDiffRows(lineDiff(aLines, bLines));
return html`
<${ModalCard}
accent="#86efac"
icon="◆"
title=${t("modal.editTitle")}
subtitle=${t("modal.editSubtitle", { path: modal.path ?? "", remaining: modal.remaining, total: modal.total })}
>
<div class="edit-diff-wrap">
<div class="edit-diff-head">
<div class="edit-diff-side edit-diff-side-old">
<span class="edit-diff-marker">−</span> ${t("modal.before")}
</div>
<div class="edit-diff-side edit-diff-side-new">
<span class="edit-diff-marker">+</span> ${t("modal.after")}
</div>
</div>
<div class="edit-diff-body">
${rows.map(
(row, i) => html`
<div key=${i} class=${`edit-diff-row edit-diff-row-${row.kind}`}>
<div class="edit-diff-cell edit-diff-cell-old">
${
row.left != null
? html`<span
class="edit-diff-line"
dangerouslySetInnerHTML=${{ __html: hlLine(row.left, lang) || "&nbsp;" }}
></span>`
: html`<span class="edit-diff-empty">&nbsp;</span>`
}
</div>
<div class="edit-diff-cell edit-diff-cell-new">
${
row.right != null
? html`<span
class="edit-diff-line"
dangerouslySetInnerHTML=${{ __html: hlLine(row.right, lang) || "&nbsp;" }}
></span>`
: html`<span class="edit-diff-empty">&nbsp;</span>`
}
</div>
</div>
`,
)}
</div>
</div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("edit-review", "apply")}>${t("chat.confirmBtn")}</button>
<button onClick=${() => onResolve("edit-review", "reject")}>${t("chat.rejectBtn")}</button>
<button onClick=${() => onResolve("edit-review", "apply-rest-of-turn")}>${t("chat.applyRestBtn")}</button>
<button onClick=${() => onResolve("edit-review", "flip-to-auto")}>${t("chat.flipAutoBtn")}</button>
</div>
<//>
`;
}
export function WorkspaceModal({ modal, onResolve }: { modal: WorkspaceSpec; onResolve: OnResolve }) {
useLang();
return html`
<${ModalCard}
accent="#fbbf24"
icon="◇"
title=${t("modal.workspaceTitle")}
subtitle=${t("modal.workspaceSubtitle")}
>
<div class="modal-cmd"><span class="modal-cmd-prompt">→</span> <code>${modal.path}</code></div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("workspace", "switch")}>${t("modal.switchBtn")}</button>
<button class="danger" onClick=${() => onResolve("workspace", "deny")}>${t("modal.denyBtn")}</button>
</div>
<//>
`;
}
export function CheckpointModal({ modal, onResolve }: { modal: CheckpointSpec; onResolve: OnResolve }) {
useLang();
const [reviseText, setReviseText] = useState("");
const [staged, setStaged] = useState(false);
const label = modal.title ? `${modal.stepId} · ${modal.title}` : modal.stepId;
const counter = (modal.total ?? 0) > 0 ? ` (${modal.completed}/${modal.total})` : "";
return html`
<${ModalCard}
accent="#a5f3fc"
icon="✓"
title=${t("modal.stepComplete", { counter })}
subtitle=${label}
>
${
staged
? html`
<textarea
placeholder=${t("modal.revisePlaceholder")}
rows="3"
value=${reviseText}
onInput=${(e: Event) => setReviseText((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("checkpoint", "revise", reviseText)}>${t("modal.sendRevision")}</button>
<button onClick=${() => {
setStaged(false);
setReviseText("");
}}>${t("common.back")}</button>
</div>
`
: html`
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("checkpoint", "continue")}>${t("modal.continueBtn")}</button>
<button onClick=${() => setStaged(true)}>${t("modal.reviseBtn")}</button>
<button class="danger" onClick=${() => onResolve("checkpoint", "stop")}>${t("modal.stopBtn")}</button>
</div>
`
}
<//>
`;
}
export function PickerModal({
modal,
onResolve,
}: {
modal: PickerModalSpec;
onResolve: OnResolve;
}) {
useLang();
const [selectedId, setSelectedId] = useState<string | null>(modal.items[0]?.id ?? null);
const [query, setQuery] = useState(modal.query ?? "");
const [renameTarget, setRenameTarget] = useState<string | null>(null);
const [renameText, setRenameText] = useState("");
const [showNew, setShowNew] = useState(false);
const [newText, setNewText] = useState("");
const has = (a: PickerActionName) => modal.actions.includes(a);
const selected = modal.items.find((i) => i.id === selectedId) ?? null;
const submitRefine = (next: string) => {
setQuery(next);
if (has("refine")) onResolve("picker", { action: "refine", query: next });
};
const startRename = (id: string) => {
const item = modal.items.find((i) => i.id === id);
if (!item) return;
setRenameTarget(id);
setRenameText(item.title);
};
const sendRename = () => {
if (!renameTarget || !renameText.trim()) return;
onResolve("picker", { action: "rename", id: renameTarget, text: renameText });
setRenameTarget(null);
setRenameText("");
};
const sendNew = () => {
onResolve("picker", newText.trim() ? { action: "new", text: newText } : { action: "new" });
setShowNew(false);
setNewText("");
};
return html`
<${ModalCard}
accent="#fcd34d"
icon="≡"
title=${modal.title}
subtitle=${modal.hint}
>
${
has("refine")
? html`<input
class="modal-picker-search"
type="search"
placeholder=${t("modal.pickerFilter")}
value=${query}
onInput=${(e: Event) => submitRefine((e.target as HTMLInputElement).value)}
/>`
: null
}
<div class="modal-picker-list">
${
modal.items.length === 0
? html`<div class="modal-picker-empty">${t("modal.pickerEmpty")}</div>`
: modal.items.map(
(it) => html`
<button
key=${it.id}
class=${`modal-picker-row${it.id === selectedId ? " selected" : ""}`}
onClick=${() => setSelectedId(it.id)}
onDblClick=${() => has("pick") && onResolve("picker", { action: "pick", id: it.id })}
>
<span class="modal-picker-title">${it.title}</span>
${it.badge ? html`<span class="modal-picker-badge">${it.badge}</span>` : null}
${it.subtitle ? html`<span class="modal-picker-subtitle">${it.subtitle}</span>` : null}
${it.meta ? html`<span class="modal-picker-meta">${it.meta}</span>` : null}
</button>
`,
)
}
</div>
${
modal.hasMore && has("load-more")
? html`<button
class="modal-picker-more"
onClick=${() => onResolve("picker", { action: "load-more" })}
>${t("modal.pickerLoadMore")}</button>`
: null
}
${
renameTarget
? html`
<div class="modal-picker-form">
<input
type="text"
value=${renameText}
onInput=${(e: Event) => setRenameText((e.target as HTMLInputElement).value)}
/>
<div class="modal-actions">
<button class="primary" onClick=${sendRename} disabled=${!renameText.trim()}>${t("common.save")}</button>
<button onClick=${() => setRenameTarget(null)}>${t("common.back")}</button>
</div>
</div>
`
: showNew
? html`
<div class="modal-picker-form">
<input
type="text"
placeholder=${t("modal.pickerNewPlaceholder")}
value=${newText}
onInput=${(e: Event) => setNewText((e.target as HTMLInputElement).value)}
/>
<div class="modal-actions">
<button class="primary" onClick=${sendNew}>${t("common.add")}</button>
<button onClick=${() => setShowNew(false)}>${t("common.back")}</button>
</div>
</div>
`
: html`
<div class="modal-actions">
${
has("pick") && selected
? html`<button
class="primary"
onClick=${() => onResolve("picker", { action: "pick", id: selected.id })}
>${t("modal.pickerPick")}</button>`
: null
}
${
has("install") && selected
? html`<button
class="primary"
onClick=${() => onResolve("picker", { action: "install", id: selected.id })}
>${t("modal.pickerInstall")}</button>`
: null
}
${
has("uninstall") && selected
? html`<button
onClick=${() => onResolve("picker", { action: "uninstall", id: selected.id })}
>${t("modal.pickerUninstall")}</button>`
: null
}
${
has("rename") && selected
? html`<button onClick=${() => startRename(selected.id)}>${t("modal.pickerRename")}</button>`
: null
}
${
has("delete") && selected
? html`<button
class="danger"
onClick=${() => onResolve("picker", { action: "delete", id: selected.id })}
>${t("common.delete")}</button>`
: null
}
${
has("new")
? html`<button onClick=${() => setShowNew(true)}>${t("modal.pickerNew")}</button>`
: null
}
<button onClick=${() => onResolve("picker", { action: "cancel" })}>${t("modal.cancel")}</button>
</div>
`
}
<//>
`;
}
export function ViewerModal({
modal,
onResolve,
}: {
modal: ViewerModalSpec;
onResolve: OnResolve;
}) {
useLang();
return html`
<${ModalCard}
accent="#67e8f9"
icon="◇"
title=${modal.title}
subtitle=${modal.meta}
>
${
modal.steps && modal.steps.length > 0
? html`
<ol class="modal-viewer-steps">
${modal.steps.map(
(s: ViewerStep) => html`
<li key=${s.id} class=${`modal-viewer-step modal-viewer-step-${s.status}`}>
<span class="modal-viewer-step-mark">${s.status === "done" ? "✓" : "·"}</span>
<span class="modal-viewer-step-title">${s.title}</span>
</li>
`,
)}
</ol>
`
: null
}
${
modal.body
? html`<div class="md modal-viewer-body" dangerouslySetInnerHTML=${{ __html: marked.parse(modal.body) }}></div>`
: null
}
<div class="modal-actions">
<button onClick=${() => onResolve("viewer", { action: "close" })}>${t("modal.viewerClose")}</button>
</div>
<//>
`;
}
export function RevisionModal({ modal, onResolve }: { modal: RevisionSpec; onResolve: OnResolve }) {
useLang();
const riskColor = (r: string | undefined) =>
r === "high" ? "#f87171" : r === "med" ? "#fbbf24" : r === "low" ? "#86efac" : "#9ca3af";
return html`
<${ModalCard}
accent="#c4b5fd"
icon="✎"
title=${t("modal.revisionTitle")}
subtitle=${modal.summary || modal.reason}
>
<div class="modal-revise-reason">${modal.reason}</div>
<ol class="modal-revise-steps">
${modal.remainingSteps.map(
(s: RevisionStep) => html`
<li key=${s.id}>
<span class="modal-revise-dot" style=${`background:${riskColor(s.risk)}`}></span>
<span class="modal-revise-id">${s.id}</span>
<span class="modal-revise-title">${s.title}</span>
<span class="modal-revise-action">${s.action}</span>
</li>
`,
)}
</ol>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("revision", "accept")}>${t("modal.accept")}</button>
<button class="danger" onClick=${() => onResolve("revision", "reject")}>${t("modal.reject")}</button>
</div>
<//>
`;
}
File diff suppressed because it is too large. Load diff
+617 -20
View File
@@ -23,6 +23,111 @@ export const en = {
themeToggle: "Toggle theme",
themeLight: "Light",
themeDark: "Dark",
skill: {
scope: {
builtin: "Built-in",
global: "Global",
project: "Project",
},
runAs: {
subagent: "Subagent",
inline: "Inline",
},
generic: "Skill",
},
exportReasoningSummary: "Reasoning Summary",
exportToolLabel: "Tool Calls",
exportUserLabel: "User Messages",
empty: {
currentWorkspace: "Current workspace",
selectWorkspace: "Select a workspace to get started",
suggestion0: "Start a new conversation",
suggestion1: "Open settings",
suggestion2: "View overview",
suggestion3: "Browse sessions",
welcome: "Welcome to Reasonix",
},
errorLabel: "Error",
connecting: "Connecting…",
session: {
format: "Session",
new: "New Session",
},
setup: {
choose: "Choose a workspace",
description: "Select a workspace to start working",
notSelected: "No workspace selected",
saveAndStart: "Save & Start",
welcome: "Welcome",
workspace: "Workspace",
},
tab: {
newTab: "+ New Tab",
newTabTitle: "Open a new tab",
},
titlebar: {
clearChat: "Clear Chat",
close: "Close",
commandPalette: "Command Palette",
contextPanel: "Context Panel",
copyMd: "Copy as Markdown",
exportMd: "Export as Markdown",
maximize: "Maximize",
minimize: "Minimize",
more: "More",
restore: "Restore",
settings: "Settings",
sidebar: "Sidebar",
windowControls: "Window Controls",
},
toast: {
cleared: "Chat cleared",
copied: "Copied to clipboard",
copiedMd: "Copied as Markdown",
emptySession: "No messages to export",
exportDialogTitle: "Export Chat",
exportedMd: "Exported as Markdown",
exportFailed: "Export failed",
langSwitched: "Language switched",
modelSwitched: "Model → {model}",
effortSwitched: "Effort → {effort}",
modeSwitched: "Mode switched",
newSession: "New session created",
},
yolo: {
toast: "YOLO mode enabled",
},
cmd: {
abort: "Abort",
btw: "BTW",
clearChat: "Clear Chat",
compact: "Compact",
copyLast: "Copy Last",
exportMd: "Export as Markdown",
feedback: "Feedback",
help: "Help",
newSession: "New Session",
retry: "Retry",
switchModel: "Switch Model",
toggleCurrency: "Toggle Currency",
toggleLang: "Toggle Language",
toggleTheme: "Toggle Theme",
},
header: {
abort: "Abort",
clickToSelect: "Click to select",
copy: "Copy",
copyMd: "Copy as Markdown",
export: "Export",
exportMd: "Export as Markdown",
newChat: "New Chat",
noWorkspace: "No workspace",
running: "Running…",
},
jumpToBottom: "Jump to bottom",
langEN: "English",
langZH: "中文",
splashSubtitle: "AI-powered coding assistant",
},
changes: {
chatPlaceholder: "Ask about your code...",
@@ -101,29 +206,51 @@ export const en = {
saved: "saved: {fields}",
sectionApi: "DeepSeek API",
apiKey: "API key",
apiKeyNotSet: "Not set",
apiKeySave: "Save key",
apiKeySet: "Set",
apiSection: "API Configuration",
notSet: "(not set)",
replace: "replace",
pasteKey: "paste a fresh sk-… token",
saveKey: "Save key",
baseUrl: "base url",
baseUrlPlaceholder: "https://api.deepseek.com (default)",
baseUrlHint: "Base URL for API requests",
sectionDefaults: "Defaults",
preset: "preset",
presetAuto: "auto — flash → pro on hard turns",
presetFlash: "flash — always flash, no auto-escalate",
presetPro: "pro — always pro",
effortSection: "Reasoning effort",
modelCustom: "Custom model id",
modelCustomHint: "Any OpenAI-compatible id your endpoint serves (vLLM, Ollama, Together, …).",
modelCustomActive: "Currently running on a custom id: {model}",
appliesNextTurn: "applies next turn",
effort: "effort",
effortMax: "max (default — best)",
effortHigh: "high (cheaper / faster)",
effortMax: "max (DeepSeek extension — rejected by stock OpenAI / vLLM)",
effortHigh: "high (safe default — vLLM / Azure compatible)",
effortMedium: "medium",
effortLow: "low (fastest)",
webSearch: "web search",
webSearchNote: "web_fetch + web_search tools",
sectionCompute: "Compute",
proNext: "/pro one-shot",
proArm: "Arm for next turn",
proArmed: "Armed — disarms after next turn",
proNextNote: "next turn runs on deepseek-v4-pro, then auto-disarms",
webSearchEngine: "search engine",
webSearchEngineBing: "bing — default, works from CN without proxy",
webSearchEngineBingIntl: "bing-intl — international index via www.bing.com",
webSearchEngineSearxng: "searxng — self-hosted (set endpoint via /se searxng <url>)",
webSearchEngineMetaso: "metaso — 100/day free (CN-friendly, free key at metaso.cn)",
webSearchEngineBaidu: "baidu — Baidu AI Search (set BAIDU_API_KEY or QIANFAN_API_KEY)",
webSearchEngineTavily: "tavily — 1000/mo free (set TAVILY_API_KEY)",
webSearchEnginePerplexity: "perplexity — AI-native (set PERPLEXITY_API_KEY)",
webSearchEngineExa: "exa — AI-native 1000/mo free (set EXA_API_KEY)",
webSearchEngineBrave: "brave — independent index, 2000/mo free (set BRAVE_SEARCH_API_KEY)",
webSearchEngineOllama: "ollama — Ollama cloud web search (set OLLAMA_API_KEY)",
webSearchEngineNote: "applies to the next web_search call",
webSearchApiKeySignup: "(get key)",
webSearchApiKeyClear: "Clear",
webSearchApiKey: {
baidu: "Baidu API key",
},
sectionBudget: "Budget",
budget: "Budget",
budgetHint: "Set spending limits",
budgetPlaceholder: "Enter budget amount",
budgetOf: "of",
budgetSetCap: "set a cap",
budgetCustom: "custom",
@@ -149,21 +276,153 @@ export const en = {
skillPaths: "skill paths",
skillPathsPlaceholder: "/path/to/skills-a, /path/to/skills-b",
skillPathsNote: "comma-separated · next /new or new session",
skillsEmpty: "No skills loaded",
skillsLoaded: "Skills loaded",
subagentModelFlash: "flash",
subagentModelPro: "pro",
subagentModelHint: "Model used when this skill spawns its isolated subagent",
sectionRuntime: "Runtime",
activeModel: "active model",
model: "Model",
modelFlashDesc: "Flash — always flash",
modelProDesc: "Pro — always pro",
modelPricingLine: "${hit} hit · ${miss} miss · ${out} out per 1M tok",
editMode: "edit mode",
editModeNote: "switch from the Chat tab header",
editModeHint: "Configure edit mode",
showSystemEvents: "system events",
showSystemEventsHint: "Show quiet inline notices for context compaction, abort, rate-limit.",
shown: "shown",
hidden: "hidden",
sectionLanguage: "Language",
language: "language",
languageHint: "Switch language",
langEn: "English",
langZhCn: "简体中文",
appMode: "App mode",
appearanceSection: "Appearance",
behaviorSection: "Behavior",
ruleAutoApprovalHint: "Configure auto-approval rules",
ruleAutoApprovalSection: "Auto-approval Rules",
theme: "Theme",
themeDark: "Dark",
themeHint: "Switch between light and dark themes",
themeLight: "Light",
themeStyle: "Theme style",
themeStyleHint: "Choose theme style",
themeStyleGraphite: "Graphite",
themeStyleGraphiteDesc: "Cool dark neutrals — best for long sessions.",
themeStyleEmber: "Ember",
themeStyleEmberDesc: "Warm dark with a stronger Reasonix orange accent.",
themeStyleAurora: "Aurora",
themeStyleAuroraDesc: "Teal-green dark for a softer low-light workspace.",
themeStyleSandstone: "Sandstone",
themeStyleSandstoneDesc: "Warm light tones — easy on bright rooms.",
themeStylePorcelain: "Porcelain",
themeStylePorcelainDesc: "Clean light with extra contrast.",
themeStyleLinen: "Linen",
themeStyleLinenDesc: "Editorial warm light with paper-like surfaces.",
themeStyleGlacier: "Glacier",
themeStyleGlacierDesc: "Cool light with crisp blue accents.",
themeStyleMidnight: "Midnight",
themeStyleMidnightDesc: "Deep dark with cooler highlights.",
pageGeneralLabel: "General",
pageGeneralDesc: "Theme, fonts, language and workspace.",
pageModelsLabel: "Models",
pageModelsDesc: "Default model and reasoning effort.",
pageMcpLabel: "MCP servers",
pageMcpDesc: "Connect external tool servers.",
pageSkillsLabel: "Skills",
pageSkillsDesc: "User-defined skills you can run with /skill.",
pageMemoryLabel: "Memory",
pageMemoryDesc: "Long-lived notes carried across sessions.",
pageRulesLabel: "Rules",
pageRulesDesc: "Auto-approval rules for shell + path access.",
pageBillingLabel: "Billing",
pageBillingDesc: "API key, balance and per-session budget.",
pageShortcutsLabel: "Shortcuts",
pageShortcutsDesc: "Keyboard shortcuts reference.",
fontFamily: "Font family",
fontFamilyHint: "Choose font family",
fontFamilySans: "Sans-serif",
fontFamilySerif: "Serif",
fontFamilySystem: "System",
fontScale: "Font scale",
fontScaleHint: "Adjust font size",
fontScaleLarge: "Large",
fontScaleMedium: "Medium",
fontScaleSmall: "Small",
currentWorkspace: "Current workspace",
defaultModelCurrent: "Current model",
editor: "Editor",
editorHint: "Configure editor preferences",
maxOutput: "Max output",
reasoningEffort: "Reasoning effort",
reasoningEffortHint: "Adjust reasoning depth",
sessionCost: "Session cost",
balanceAvailable: "Available",
balanceLabel: "Balance",
balanceLow: "Low balance",
cacheHitRate: "Cache hit rate",
ctxWindow: "Context window",
notSelected: "Not selected",
parseError: "Parse error",
workspaceChange: "Change",
workspaceSection: "Workspace",
mcpAdd: "Add",
mcpAddSection: "Add MCP Server",
mcpBridged: "Bridged",
mcpConfigured: "Configured",
mcpEmpty: "No MCP servers",
mcpNotBridged: "Not bridged",
mcpRemove: "Remove",
mcpSpecFormat: "JSON format",
mcpSpecLabel: "Server spec",
memoryDesc: "Configure memory settings",
memorySection: "Memory",
shortcutAbort: "Abort",
shortcutCloseTab: "Close Tab",
shortcutCommandPalette: "Command Palette",
shortcutFocusComposer: "Focus Composer",
shortcutNewChat: "New Chat",
shortcutNewTab: "New Tab",
shortcutSettings: "Settings",
shortcutSwitchTab: "Switch Tab",
qqAccessAllowlist: "Allowlist",
qqAccessOpen: "Open",
qqAccessOwner: "Owner",
qqAccessOwnerWithAllowlist: "Owner + Allowlist",
qqAccessRuntime: "Runtime",
qqAppId: "App ID",
qqApplyAction: "Apply",
qqApplyLabel: "Apply",
qqAppSecret: "App Secret",
qqBack: "Back",
qqConfigure: "Configure",
qqConfigureHint: "Set up QQ integration",
qqConfigureTitle: "QQ Configuration",
qqConnected: "Connected",
qqConnecting: "Connecting…",
qqDisconnected: "Disconnected",
qqEnvironment: "Environment",
qqFailed: "Failed",
qqProduction: "Production",
qqSandbox: "Sandbox",
qqSave: "Save",
qqSaveAndConnect: "Save & Connect",
qqSection: "QQ Integration",
qqSummaryAppId: "App ID",
qqSummaryDetail: "Details",
qqSummaryMissing: "Not configured",
qqTitle: "QQ Bot",
},
chat: {
modeMirror: "TUI mirror",
modeView: "session view",
placeholder: "Type a prompt — Enter sends, Shift+Enter for a newline · / @ for pickers",
placeholderBusy: "wait for the current turn to finish…",
placeholderSteerBusy: "type to steer — commands and pickers are disabled while busy",
steerHint: "message steers the current turn (added as instruction)",
send: "Send",
new: "New",
clear: "Clear",
@@ -185,15 +444,10 @@ export const en = {
slashCommands: "slash commands",
projectFiles: "project files",
effortTitle: "reasoning_effort — applies next turn",
effortMaxTitle: "max (default — best quality)",
effortHighTitle: "high (cheaper / faster)",
presetTitle: "preset — model commitment",
presetAutoTitle:
"auto — flash baseline; auto-escalates to pro on hard turns (NEEDS_PRO / failure threshold)",
presetFlashTitle:
"flash — always flash; no auto-escalate. /pro still works for one-shot manual",
presetProTitle:
"pro — always pro; ~3× flash cost (5/31 discount). Locks in on hard architecture work.",
effortMaxTitle: "max (DeepSeek extension)",
effortHighTitle: "high (safe default — vLLM / Azure compatible)",
effortMediumTitle: "medium",
effortLowTitle: "low (fastest)",
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",
@@ -304,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…",
@@ -431,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}",
@@ -614,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:
@@ -679,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",
@@ -743,4 +1018,326 @@ export const en = {
hoursAgo: "{n}h ago",
daysAgo: "{n}d ago",
},
cards: {
applied: "Applied",
cacheHit: "Cache hit",
checkpointRewind: "Checkpoint Rewind",
cost: "Cost",
diffApply: "Apply",
diffApplyChanges: "Apply Changes",
diffAwaiting: "Awaiting review",
diffDiscard: "Discard",
done: "Done",
elapsed: "Elapsed",
error: "Error",
errorName: "Error",
failed: "Failed",
hits: "Hits",
memoryCountSuffix: "memories",
memoryName: "Memory",
output: "Output",
planDefaultTitle: "Plan",
prompt: "Prompt",
compactionMeta: "{chars} chars",
compactionName: "Compacted history",
reasoningComplete: "Reasoning complete",
reasoningName: "Reasoning",
result: "Result",
running: "Running",
searchName: "Search",
shellAlwaysAllow: "Always Allow",
shellAwaiting: "Awaiting approval",
shellExecuteHint: "Execute this command?",
shellReject: "Reject",
shellRun: "Run",
shellRunning: "Running",
streaming: "Streaming",
subagentDone: "Subagent done",
subagentDoneProgress: "Subagent done ({pct}%)",
subagentFailed: "Subagent failed",
subagentRunning: "Subagent running",
},
planBadge: {
blocked: "Blocked",
done: "Done",
failed: "Failed",
pending: "Pending",
running: "Running",
},
composer: {
atHeader: "Mention files",
close: "Close",
commandPalette: "Command Palette",
commands: "Commands",
commandsLabel: "Commands",
confirm: "Confirm",
imageFilterName: "Images",
insertFile: "Insert File",
insertImage: "Insert Image",
interrupt: "Interrupt",
mentionFiles: "Mention Files",
mentionLabel: "Mention",
newline: "New Line",
noMatches: "No matches",
placeholder: "Type a prompt…",
queue: "Queue",
queueCount: "{count} queued",
select: "Select",
send: "Send",
slashHeader: "Slash Commands",
switchModel: "Switch Model",
switchEffort: "Switch Reasoning Effort",
workspaceRoot: "Workspace Root",
},
contextPanel: {
allow: "Allow",
ask: "Ask",
autoApproveTitle: "Auto-approve",
cacheKey: "Cache",
contextTokens: "Context tokens",
fileInContext: "In context",
fileModified: "Modified",
filesCount: "{count} files",
filesTab: "Files",
filesTitle: "Files",
freeKey: "Free",
itemCount: "{count} items",
mcpConfigured: "Configured",
mcpConnecting: "Connecting…",
mcpDisabled: "Disabled",
mcpEmpty: "No MCP servers",
mcpFailed: "Failed",
mcpReady: "Ready",
mcpReadyAll: "All ready",
mcpReadySome: "Some ready",
mcpTitle: "MCP",
mcpTools: "Tools",
memoryTab: "Memory",
memoryTitle: "Memory",
noFilesMsg: "No files in context",
noMemoriesMsg: "No memories",
reservedKey: "Reserved",
ruleReadOnly: "Read-only",
ruleReview: "Review",
ruleShellAllowlist: "Shell allowlist",
rulesTab: "Rules",
ruleWritesAsk: "Writes ask",
ruleYolo: "YOLO",
scopeGlobal: "Global",
scopeProject: "Project",
toolsTab: "Tools",
usedKey: "Used",
},
dragDrop: {
overlay: "Drop files here",
},
extraCards: {
approve: "Approve",
balance: "Balance",
cache: "Cache",
cacheHit: "Cache hit",
contextWindow: "Context window",
doctorTitle: "Diagnostics",
output: "Output",
prompt: "Prompt",
reasoning: "Reasoning",
reject: "Reject",
sessionCost: "Session cost",
sessionUsage: "Session usage",
topToolsUsage: "Top tools",
unknownKind: "Unknown",
memoryUser: "User",
memoryFeedback: "Feedback",
memoryProject: "Project",
memoryReference: "Reference",
},
jobs: {
empty: "No background jobs",
exited: "Exited",
kbClose: "Close",
kbToggle: "Toggle",
running: "Running",
stop: "Stop",
stopAll: "Stop All",
stopAllTip: "Stop all jobs",
stopOne: "Stop",
title: "Background Jobs",
},
live: {
deliveredWaiting: "Waiting for next message",
reasoning: "Reasoning",
running: "Running",
secondsAgo: "{n}s ago",
you: "You",
},
markdown: {
copied: "Copied!",
copy: "Copy",
externalLinkTitle: "Open in new tab",
filePillTitle: "Open file",
localLinkTitle: "Open link",
},
palette: {
abort: "Abort",
abortHint: "Abort current request",
about: "About",
clearChat: "Clear Chat",
clearChatHint: "Clear conversation",
closeTab: "Close Tab",
closeTabHint: "Close current tab",
copyConv: "Copy Conversation",
copyConvHint: "Copy conversation as Markdown",
copyLast: "Copy Last Response",
copyLastHint: "Copy last assistant message",
countSuffix: "items",
empty: "No matching commands",
exportMd: "Export as Markdown",
exportMdHint: "Export chat as Markdown file",
focusComposer: "Focus Composer",
footClose: "Close",
footMove: "Move",
footRun: "Run",
groupAction: "Actions",
groupNav: "Navigation",
groupSettings: "Settings",
groupWorkspace: "Workspace",
newChat: "New Chat",
newChatHint: "Start a new conversation",
newTab: "New Tab",
newTabHint: "Open a new tab",
pickWorkspace: "Switch Workspace",
pickWorkspaceHint: "Change workspace",
searchPlaceholder: "Search commands…",
settings: "Settings",
settingsHint: "Open settings",
},
panel: {
renderError: "Panel crashed",
},
sidebarPanel: {
approvalRules: "Approval Rules",
cancel: "Cancel",
commandPalette: "Command Palette",
daysAgo: "{n}d ago",
delete: "Delete",
deleteSession: "Delete Session",
hoursAgo: "{n}h ago",
justNow: "Just now",
loading: "Loading…",
messageCount: "{count} messages",
minutesAgo: "{n}m ago",
newChat: "New Chat",
noMatches: "No matches",
noSessions: "No sessions",
recent: "Recent",
searchSessions: "Search sessions…",
sessionTitle: "Sessions",
settings: "Settings",
weeksAgo: "{n}w ago",
},
statusbar: {
balance: "Balance",
busy: "Busy",
cache: "Cache",
cacheHit: "Cache hit",
jobs: "Jobs",
jobsTip: "Background jobs",
offline: "Offline",
online: "Online",
switchCurrency: "Switch currency",
switchTheme: "Switch theme",
switchWorkspace: "Switch workspace",
themeDark: "Dark",
themeLight: "Light",
themeStyleGraphite: "Graphite",
themeStyleEmber: "Ember",
themeStyleAurora: "Aurora",
themeStyleSandstone: "Sandstone",
themeStylePorcelain: "Porcelain",
themeStyleLinen: "Linen",
themeStyleGlacier: "Glacier",
themeStyleMidnight: "Midnight",
thisTurn: "This turn",
tokens: "Tokens",
},
thread: {
activePlan: "Active plan",
allowRead: "Allow read",
allowWrite: "Allow write",
alwaysAllow: "Always allow",
alwaysAllowPrefix: "Always allow {prefix}",
approve: "Approve",
approveRewrite: "Approve rewrite",
cancel: "Cancel",
checkpointKind: "Checkpoint",
checkpointSub: "Save current state",
checkpointTitle: "Create checkpoint",
collapse: "Collapse",
continue: "Continue",
copyMessage: "Copy message",
copyResponse: "Copy response",
execute: "Execute",
keepOriginal: "Keep original",
keepSteps: "Keep steps",
optionCount: "{count} options",
pathAccessKind: "Path access",
planConfirmationKind: "Plan approval",
planRevisionKind: "Plan revision",
planRunning: "Plan in progress",
planStepCount: "Step {done}/{total}",
readPathOutsideSandbox: "Read path outside sandbox",
refine: "Refine",
reject: "Reject",
revise: "Revise",
revisionMeta: "Revision",
rewritePlan: "Rewrite plan",
risk: "Risk assessment",
riskMedium: "Medium risk",
runBackgroundCommand: "Run in background",
runCommand: "Run command",
shellConfirmationKind: "Shell confirmation",
startPlan: "Start plan",
stop: "Stop",
subagent: "Subagent",
userChoiceKind: "User choice",
writePathOutsideSandbox: "Write path outside sandbox",
you: "You",
},
workdir: {
browse: "Browse…",
cancel: "Cancel",
empty: "No workspaces",
emptyDir: "No subdirectories.",
go: "Go",
goTip: "Navigate to this path",
loading: "Loading…",
openHere: "Open this folder",
pathPlaceholder: "Absolute path…",
promptWeb: "Enter the absolute path of the workspace to open:",
searchPlaceholder: "Search workspaces…",
title: "Workspace",
},
about: {
close: "Close",
repo: "Repository",
sidebarLabel: "About",
tagline: "AI-powered coding assistant",
version: "Version",
},
effort: {
lowDesc: "fastest — minimal reasoning",
mediumDesc: "balanced",
highDesc: "default — safe for vLLM / Azure",
maxDesc: "DeepSeek extension; rejected by stock OpenAI / vLLM",
},
editMode: {
plan: "Plan",
planHint: "read-only · all write tools refuse to dispatch",
review: "Review",
reviewHint: "both edits and non-allowlisted shell ask first",
auto: "Auto",
autoHint: "edits auto-apply, shell still asks",
yolo: "YOLO",
yoloHint: "edits AND shell auto-run, allowlist bypassed",
},
};
+115 -6
View File
@@ -1,8 +1,117 @@
import { createT } from "../lib/i18n.js";
import { en } from "./en.js";
import { zhCN } from "./zh-CN.js";
import { useEffect, useState } from "react";
import { de } from "./de";
import { en } from "./en";
import { ja } from "./ja";
import { ru } from "./ru";
import { zhCN } from "./zh-CN";
export { getLang, initLangFromServer, setLang, useLang, onLangChange } from "../lib/i18n.js";
export type { DashboardLang } from "../lib/i18n.js";
export type Lang = "en" | "zh-CN" | "de" | "ja" | "ru";
export const t = createT({ en, "zh-CN": zhCN });
const SUPPORTED_LANGS: readonly Lang[] = ["en", "zh-CN", "de", "ja", "ru"];
const SUPPORTED: ReadonlySet<Lang> = new Set<Lang>(SUPPORTED_LANGS);
const LANG_LABELS: Record<Lang, string> = {
en: "English",
"zh-CN": "简体中文",
de: "Deutsch",
ja: "日本語",
ru: "Русский",
};
const STORAGE_KEY = "reasonix.lang";
type Listener = () => void;
const listeners: Listener[] = [];
function detectDefault(): Lang {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored && SUPPORTED.has(stored as Lang)) return stored as Lang;
} catch {
/* private mode */
}
const nav = typeof navigator !== "undefined" ? navigator.language : "";
const lower = nav.toLowerCase();
if (lower.startsWith("zh")) return "zh-CN";
if (lower.startsWith("de")) return "de";
if (lower.startsWith("ja")) return "ja";
if (lower.startsWith("ru")) return "ru";
return "en";
}
let currentLang: Lang = detectDefault();
function syncHtmlLang(lang: Lang): void {
if (typeof document === "undefined") return;
try {
document.documentElement.lang = lang;
} catch {
/* document not ready */
}
}
syncHtmlLang(currentLang);
export function getLang(): Lang {
return currentLang;
}
export function getSupportedLangs(): readonly Lang[] {
return SUPPORTED_LANGS;
}
export function getLangLabel(lang: Lang): string {
return LANG_LABELS[lang];
}
export function setLang(lang: Lang): void {
if (!SUPPORTED.has(lang) || lang === currentLang) return;
currentLang = lang;
try {
localStorage.setItem(STORAGE_KEY, lang);
} catch {
/* ignore */
}
syncHtmlLang(lang);
for (const cb of listeners) cb();
}
export function useLang(): Lang {
const [, setTick] = useState(0);
useEffect(() => {
const cb = () => setTick((n) => n + 1);
listeners.push(cb);
return () => {
const idx = listeners.indexOf(cb);
if (idx >= 0) listeners.splice(idx, 1);
};
}, []);
return currentLang;
}
const dicts = { en, "zh-CN": zhCN, de, ja, ru } as const;
type Dict = typeof en;
type Path<T, K extends keyof T = keyof T> = K extends string
? T[K] extends Record<string, unknown>
? `${K}.${Path<T[K]>}`
: K
: never;
export type TKey = Path<Dict>;
function resolve(dict: Dict, key: string): string {
const parts = key.split(".");
let cursor: unknown = dict;
for (const p of parts) {
if (cursor && typeof cursor === "object" && p in (cursor as Record<string, unknown>)) {
cursor = (cursor as Record<string, unknown>)[p];
} else {
return key;
}
}
return typeof cursor === "string" ? cursor : key;
}
export function t(key: TKey, params?: Record<string, string | number>): string {
const raw = resolve(dicts[currentLang], key);
if (!params) return raw;
return raw.replace(/\{(\w+)\}/g, (_, k) => (k in params ? String(params[k]) : `{${k}}`));
}
+507
View File
@@ -0,0 +1,507 @@
import { en } from "./en";
export const ja: typeof en = {
...en,
app: {
...en.app,
sectionWorkspace: "ワークスペース",
sectionObserve: "監視",
sectionConfigure: "設定",
tabChat: "チャット",
tabPlans: "プラン",
tabSessions: "セッション",
tabOverview: "概要",
tabUsage: "使用量",
tabSystem: "システム",
tabSemantic: "セマンティック",
tabTools: "ツール",
tabPermissions: "権限",
tabMcp: "MCP",
tabSkills: "スキル",
tabMemory: "メモリ",
tabHooks: "フック",
tabSettings: "設定",
sectionChanges: "変更",
tabChanges: "変更",
footer: "127.0.0.1 のみ · トークン認証",
themeToggle: "テーマ切替",
themeLight: "ライト",
themeDark: "ダーク",
skill: {
...en.app.skill,
scope: {
...en.app.skill.scope,
builtin: "ビルトイン",
global: "グローバル",
project: "プロジェクト",
},
runAs: {
...en.app.skill.runAs,
subagent: "サブエージェント",
inline: "インライン",
},
generic: "スキル",
},
exportReasoningSummary: "推論サマリー",
exportToolLabel: "ツール呼び出し",
exportUserLabel: "ユーザーメッセージ",
empty: {
...en.app.empty,
currentWorkspace: "現在のワークスペース",
selectWorkspace: "ワークスペースを選択して開始",
suggestion0: "新しい会話を始める",
suggestion1: "設定を開く",
suggestion2: "概要を表示",
suggestion3: "セッションを閲覧",
welcome: "Reasonix へようこそ",
},
errorLabel: "エラー",
connecting: "接続中…",
session: {
...en.app.session,
format: "セッション",
new: "新しいセッション",
},
setup: {
...en.app.setup,
choose: "ワークスペースを選択",
description: "作業を開始するワークスペースを選択",
notSelected: "ワークスペース未選択",
saveAndStart: "保存して開始",
welcome: "ようこそ",
workspace: "ワークスペース",
},
tab: {
...en.app.tab,
newTab: "+ 新しいタブ",
newTabTitle: "新しいタブを開く",
},
titlebar: {
...en.app.titlebar,
clearChat: "チャットクリア",
close: "閉じる",
commandPalette: "コマンドパレット",
contextPanel: "コンテキストパネル",
copyMd: "Markdownでコピー",
exportMd: "Markdownでエクスポート",
maximize: "最大化",
minimize: "最小化",
more: "その他",
restore: "元に戻す",
settings: "設定",
sidebar: "サイドバー",
windowControls: "ウィンドウ操作",
},
toast: {
...en.app.toast,
cleared: "チャットをクリアしました",
copied: "クリップボードにコピーしました",
copiedMd: "Markdownでコピーしました",
emptySession: "エクスポートするメッセージがありません",
exportDialogTitle: "チャットをエクスポート",
exportedMd: "Markdownでエクスポートしました",
exportFailed: "エクスポートに失敗しました",
langSwitched: "言語を切り替えました",
modelSwitched: "モデル → {model}",
effortSwitched: "努力 → {effort}",
modeSwitched: "モードを切り替えました",
newSession: "新しいセッションを作成しました",
},
yolo: {
...en.app.yolo,
toast: "YOLOモードが有効です",
},
cmd: {
...en.app.cmd,
abort: "中断",
btw: "BTW",
clearChat: "チャットクリア",
compact: "圧縮",
copyLast: "最後をコピー",
exportMd: "Markdownでエクスポート",
feedback: "フィードバック",
help: "ヘルプ",
newSession: "新しいセッション",
retry: "再試行",
switchModel: "モデル切替",
toggleCurrency: "通貨切替",
toggleLang: "言語切替",
toggleTheme: "テーマ切替",
},
header: {
...en.app.header,
abort: "中断",
clickToSelect: "クリックで選択",
copy: "コピー",
copyMd: "Markdownでコピー",
export: "エクスポート",
exportMd: "Markdownでエクスポート",
newChat: "新しいチャット",
noWorkspace: "ワークスペースなし",
running: "実行中…",
},
jumpToBottom: "最下部にジャンプ",
langEN: "English",
langZH: "中文",
splashSubtitle: "AI搭載コーディングアシスタント",
},
changes: {
...en.changes,
chatPlaceholder: "コードについて質問…",
chatWelcome: "変更 — プロジェクトファイルについて質問してください。",
chatSend: "送信",
viewerPlaceholder: "表示するファイルを選択",
treeEmpty: "(空)",
tabClose: "タブを閉じる",
newConversation: "新規",
clearConversation: "クリア",
newTitle: "/new — 会話コンテキストを消去",
clearTitle: "/clear — 表示スクロールバックを消去",
newConfirmBusy: "ターンが実行中です。中断して新しい会話を始めますか?",
newConfirm: "現在の会話をクリアして新しく始めますか?",
newToast: "新しい会話",
clearToast: "スクロールバックをクリアしました",
newFailed: "/new 失敗: {error}",
clearFailed: "/clear 失敗: {error}",
chatSendBtn: "送信",
fileTreeTitle: "ファイル",
codeViewerTitle: "コードビューア",
chatPanelTitle: "チャット",
loadingFiles: "プロジェクトファイルを読み込み中…",
review: "レビュー",
allFiles: "すべてのファイル",
changes: "変更",
commentLabel: "行にコメント",
commentPlaceholder: "コメントを追加…",
commentCancel: "キャンセル",
commentSubmit: "コメント",
commentLine: "行",
commentEdit: "編集",
commentDelete: "削除",
diffSourceGit: "Gitの変更",
diffSourceSession: "前回のセッション",
diffSourceCheckpoint: "チェックポイント",
checkpointEmpty: "このワークスペースにチェックポイントはまだありません。",
restoreBtn: "復元",
restoreConfirm: '"{name}" を復元しますか?現在のファイルが上書きされます。',
deleteBtn: "削除",
deleteConfirm:
'チェックポイント "{name}" を削除しますか?スナップショットは削除され、ファイルはそのままです。',
createBtn: "スナップショット",
createPlaceholder: "スナップショット名…",
backToList: "リストに戻る",
reviewEmpty: "保留中のレビューはありません。",
diffStyleUnified: "統合",
diffStyleSplit: "分割",
expandAll: "すべて展開",
collapseAll: "すべて折りたたみ",
createFailed: "作成に失敗しました",
restoreFailed: "復元に失敗しました",
deleteFailed: "削除に失敗しました",
},
common: {
...en.common,
loading: "読み込み中…",
loadingFailed: "{name} 失敗: {error}",
back: "← 戻る",
save: "保存",
remove: "削除",
cancel: "キャンセル",
delete: "削除",
add: "追加",
confirm: "確認",
noData: "まだ {name} がありません。",
all: "すべて",
yes: "はい",
no: "いいえ",
on: "オン",
off: "オフ",
enabled: "有効",
disabled: "無効",
},
settings: {
...en.settings,
title: "設定",
loading: "設定を読み込み中…",
saved: "保存: {fields}",
sectionApi: "DeepSeek API",
apiKey: "APIキー",
apiKeyNotSet: "未設定",
apiKeySave: "キーを保存",
apiKeySet: "設定済み",
apiSection: "API設定",
notSet: "(未設定)",
replace: "置換",
pasteKey: "新しい sk-… トークンを貼り付け",
saveKey: "キーを保存",
baseUrl: "ベースURL",
baseUrlPlaceholder: "https://api.deepseek.com (デフォルト)",
baseUrlHint: "APIリクエストのベースURL",
sectionDefaults: "デフォルト",
effortSection: "推論努力",
modelCustom: "カスタムモデルID",
modelCustomHint: "エンドポイントが提供するOpenAI互換ID (vLLM, Ollama, Together, …)。",
modelCustomActive: "現在カスタムIDで実行中: {model}",
appliesNextTurn: "次のターンから適用",
effort: "努力",
effortMax: "max (DeepSeek拡張 — 標準OpenAI / vLLMでは拒否)",
effortHigh: "high (安全なデフォルト — vLLM / Azure互換)",
effortMedium: "medium",
effortLow: "low (最速)",
webSearch: "Web検索",
webSearchNote: "web_fetch + web_search ツール",
webSearchEngine: "検索エンジン",
webSearchEngineBing: "bing — デフォルト、プロキシなしで中国から利用可",
webSearchEngineBingIntl: "bing-intl — www.bing.com 経由の国際版インデックス",
webSearchEngineSearxng: "searxng — セルフホスト (/se searxng <url> でエンドポイント設定)",
webSearchEngineMetaso: "metaso — 100回/日無料 (中国対応、metaso.cnで無料キー取得)",
webSearchEngineBaidu: "baidu — Baidu AI Search (BAIDU_API_KEY または QIANFAN_API_KEY を設定)",
webSearchEngineTavily: "tavily — 1000回/月無料 (TAVILY_API_KEY を設定)",
webSearchEnginePerplexity: "perplexity — AIネイティブ (PERPLEXITY_API_KEY を設定)",
webSearchEngineExa: "exa — AIネイティブ 1000回/月無料 (EXA_API_KEY を設定)",
webSearchEngineBrave: "brave — 独立インデックス、2000回/月無料 (BRAVE_SEARCH_API_KEY を設定)",
webSearchEngineOllama: "ollama — Ollama クラウド Web 検索 (OLLAMA_API_KEY を設定)",
webSearchEngineNote: "次の web_search 呼び出しに適用",
webSearchApiKeySignup: "(キーを取得)",
webSearchApiKeyClear: "クリア",
webSearchApiKey: {
...en.settings.webSearchApiKey,
baidu: "Baidu APIキー",
},
sectionBudget: "予算",
budget: "予算",
budgetHint: "支出制限を設定",
budgetPlaceholder: "予算額を入力",
budgetOf: "/",
budgetSetCap: "上限を設定",
budgetCustom: "カスタム",
budgetBumpHint: "上限を引き上げて続行",
budgetClear: "上限をクリア",
budgetIdleLine: "80%で警告 · 100%超過で拒否",
budgetWarnLine: "上限接近 — ループは100%超過で拒否",
budgetRefusing: "上限到達 — 引き上げまたはクリアまで次のターンは拒否",
sectionLoop: "ループ",
loopIdleHint: "固定間隔でプロンプトを自動再送信。",
loopCostHint: "各イテレーションのコスト ~{cost} (前回ターン)。",
loopInterval: "間隔",
loopCustom: "カスタム",
loopRangeError: "間隔は5秒〜6時間の範囲である必要があります",
loopPrompt: "プロンプト",
loopPromptPlaceholder: "例: デプロイ状態を確認してエラーを報告",
loopStart: "ループ開始",
loopStop: "停止",
loopRunning: "実行中",
loopIter: "反復 {iter}",
loopFiresIn: "{remaining} 後に実行",
sectionSkills: "スキル",
skillPaths: "スキルパス",
skillPathsPlaceholder: "/path/to/skills-a, /path/to/skills-b",
skillPathsNote: "カンマ区切り · 次の /new または新規セッション",
skillsEmpty: "スキルが読み込まれていません",
skillsLoaded: "スキル読み込み済み",
subagentModelFlash: "flash",
subagentModelPro: "pro",
subagentModelHint: "このスキルが分離サブエージェントを生成するときに使用するモデル",
sectionRuntime: "ランタイム",
activeModel: "アクティブモデル",
model: "モデル",
modelFlashDesc: "Flash — 常にflash",
modelProDesc: "Pro — 常にpro",
modelPricingLine: "${hit} ヒット · ${miss} ミス · ${out} 出力 / 1M tok",
editMode: "編集モード",
editModeNote: "チャットタブヘッダーから切り替え",
editModeHint: "編集モードを設定",
showSystemEvents: "システムイベント",
showSystemEventsHint: "コンテキスト圧縮、中断、レート制限の通知を表示。",
shown: "表示",
hidden: "非表示",
sectionLanguage: "言語",
language: "言語",
languageHint: "言語を切り替え",
langEn: "English",
langZhCn: "简体中文",
appMode: "アプリモード",
appearanceSection: "外観",
behaviorSection: "動作",
ruleAutoApprovalHint: "自動承認ルールを設定",
ruleAutoApprovalSection: "自動承認ルール",
theme: "テーマ",
themeDark: "ダーク",
themeHint: "ライト/ダークテーマを切り替え",
themeLight: "ライト",
themeStyle: "テーマスタイル",
themeStyleHint: "テーマスタイルを選択",
themeStyleGraphite: "グラファイト",
themeStyleGraphiteDesc: "クールなダークニュートラル — 長時間のセッションに最適。",
themeStyleEmber: "エンバー",
themeStyleEmberDesc: "Reasonixのオレンジを強めた暖かいダーク。",
themeStyleAurora: "オーロラ",
themeStyleAuroraDesc: "低照度でも柔らかいティールグリーンのダーク。",
themeStyleSandstone: "サンドストーン",
themeStyleSandstoneDesc: "温かみのあるライトトーン — 明るい部屋に最適。",
themeStylePorcelain: "ポーセリン",
themeStylePorcelainDesc: "クリーンなライト、高コントラスト。",
themeStyleLinen: "リネン",
themeStyleLinenDesc: "紙のような表面を持つ編集調の暖かいライト。",
themeStyleGlacier: "グレイシャー",
themeStyleGlacierDesc: "くっきりしたブルーアクセントのクールなライト。",
themeStyleMidnight: "ミッドナイト",
themeStyleMidnightDesc: "深いダーク、クールなハイライト。",
pageGeneralLabel: "一般",
pageGeneralDesc: "テーマ、フォント、言語、ワークスペース。",
pageModelsLabel: "モデル",
pageModelsDesc: "デフォルトモデルと推論努力。",
pageMcpLabel: "MCPサーバー",
pageMcpDesc: "外部ツールサーバーに接続。",
pageSkillsLabel: "スキル",
pageSkillsDesc: "/skill で実行できるユーザー定義スキル。",
pageMemoryLabel: "メモリ",
pageMemoryDesc: "セッションをまたいで保持される長期メモ。",
pageRulesLabel: "ルール",
pageRulesDesc: "シェル+パスアクセスの自動承認ルール。",
pageBillingLabel: "請求",
pageBillingDesc: "APIキー、残高、セッションごとの予算。",
pageShortcutsLabel: "ショートカット",
pageShortcutsDesc: "キーボードショートカットリファレンス。",
fontFamily: "フォントファミリー",
fontFamilyHint: "フォントファミリーを選択",
fontFamilySans: "サンセリフ",
fontFamilySerif: "セリフ",
fontFamilySystem: "システム",
fontScale: "フォントスケール",
fontScaleHint: "フォントサイズを調整",
fontScaleLarge: "大",
fontScaleMedium: "中",
fontScaleSmall: "小",
currentWorkspace: "現在のワークスペース",
defaultModelCurrent: "現在のモデル",
editor: "エディタ",
editorHint: "エディタ設定を構成",
maxOutput: "最大出力",
reasoningEffort: "推論努力",
reasoningEffortHint: "推論の深さを調整",
sessionCost: "セッションコスト",
balanceAvailable: "利用可能",
balanceLabel: "残高",
balanceLow: "残高不足",
cacheHitRate: "キャッシュヒット率",
ctxWindow: "コンテキストウィンドウ",
notSelected: "未選択",
parseError: "パースエラー",
workspaceChange: "変更",
workspaceSection: "ワークスペース",
mcpAdd: "追加",
mcpAddSection: "MCPサーバーを追加",
mcpBridged: "ブリッジ済み",
mcpConfigured: "設定済み",
mcpEmpty: "MCPサーバーなし",
mcpNotBridged: "ブリッジ未接続",
mcpRemove: "削除",
mcpSpecFormat: "JSON形式",
mcpSpecLabel: "サーバー仕様",
memoryDesc: "メモリ設定を構成",
memorySection: "メモリ",
shortcutAbort: "中断",
shortcutCloseTab: "タブを閉じる",
shortcutCommandPalette: "コマンドパレット",
shortcutFocusComposer: "入力欄にフォーカス",
shortcutNewChat: "新しいチャット",
shortcutNewTab: "新しいタブ",
shortcutSettings: "設定",
shortcutSwitchTab: "タブ切替",
qqAccessAllowlist: "許可リスト",
qqAccessOpen: "オープン",
qqAccessOwner: "所有者",
qqAccessOwnerWithAllowlist: "所有者 + 許可リスト",
qqAccessRuntime: "ランタイム",
qqAppId: "App ID",
qqApplyAction: "申請",
qqApplyLabel: "申請",
qqAppSecret: "App Secret",
qqBack: "戻る",
qqConfigure: "設定",
qqConfigureHint: "QQ統合を設定",
qqConfigureTitle: "QQ設定",
qqConnected: "接続済み",
qqConnecting: "接続中…",
qqDisconnected: "切断済み",
qqEnvironment: "環境",
qqFailed: "失敗",
qqProduction: "本番",
qqSandbox: "サンドボックス",
qqSave: "保存",
qqSaveAndConnect: "保存して接続",
qqSection: "QQ統合",
qqSummaryAppId: "App ID",
qqSummaryDetail: "詳細",
qqSummaryMissing: "未設定",
qqTitle: "QQボット",
},
chat: {
...en.chat,
modeMirror: "TUIミラー",
modeView: "セッションビュー",
placeholder: "プロンプトを入力 — Enterで送信、Shift+Enterで改行 · / @ でピッカー",
placeholderBusy: "現在のターンの完了を待っています…",
placeholderSteerBusy: "入力で操作 — ビジー中はコマンドとピッカーが無効です",
steerHint: "メッセージが現在のターンを操作します(指示として追加)",
send: "送信",
new: "新規",
clear: "クリア",
newTitle: "/new — 会話コンテキストを消去(ループログ + スクロールバック)",
clearTitle: "/clear — 表示スクロールバックのみ消去(コンテキストは保持)",
noConversation: "まだ会話がありません。下のプロンプトを送信して開始してください。",
newConfirmBusy: "ターンが実行中です。中断して新しい会話を始めますか?",
newConfirm: "現在の会話をクリアして新しく始めますか?",
newToast: "新しい会話",
clearToast: "スクロールバックをクリアしました",
newFailed: "/new 失敗: {error}",
clearFailed: "/clear 失敗: {error}",
eventStreamError: "イベントストリームが中断されました — 再接続中…",
semanticBanner: "このプロジェクトではセマンティック検索が有効になっていません。",
semanticBannerDesc:
"インデックスを一度構築すると、モデルは正確な文字列のgrepではなく意味でコードを見つけられるようになります(「認証失敗をどのように処理しているか?」など)。",
semanticBannerBtn: "構築する →",
semanticBannerDismiss: "閉じる(再表示しない)",
slashCommands: "スラッシュコマンド",
projectFiles: "プロジェクトファイル",
effortTitle: "reasoning_effort — 次のターンから適用",
effortMaxTitle: "max (DeepSeek拡張)",
effortHighTitle: "high (安全なデフォルト — vLLM / Azure互換)",
effortMediumTitle: "medium",
effortLowTitle: "low (最速)",
editGateTitle: "編集ゲート — TUIではShift+Tabで切替",
editReviewTitle: "review — 編集と未許可シェルの両方が最初に確認",
editAutoTitle: "auto — 編集は自動適用、シェルは確認あり",
editYoloTitle: "yolo — 編集とシェルの両方が自動実行、許可リストバイパス",
railSession: "セッション",
railTurns: "ターン",
railPromptTok: "プロンプトtok",
railCost: "コスト",
railCacheHit: "キャッシュヒット",
railToolBudget: "ツール予算",
railSpend: "消費",
railActivePlan: "アクティブプラン",
railProgress: "進捗",
statusModel: "モデル",
statusCtx: "ctx",
statusCache: "キャッシュ",
statusTurn: "ターン",
statusSession: "セッション",
statusBalance: "残高",
statusTurns: "{count} ターン",
waitingStats: "· · · ライブ統計待ち",
inflightPhase: "{phase}",
inflightRunning: "実行中",
inflightThinking: "思考中",
inflightStreaming: "ストリーミング中",
inflightWaiting: "待機中",
inflightReasoning: "推論 {count} ch",
inflightOut: "出力 {count} ch",
abortBtn: "中断 (Esc)",
confirmBtn: "適用 (y)",
rejectBtn: "拒否 (n)",
applyRestBtn: "残りを適用 (a)",
flipAutoBtn: "AUTOに切替 (A)",
},
};
+5
View File
@@ -0,0 +1,5 @@
import { en } from "./en";
export const ru: typeof en = {
...en,
};
+621 -21
View File
@@ -23,6 +23,111 @@ export const zhCN = {
themeToggle: "切换主题",
themeLight: "浅色",
themeDark: "深色",
skill: {
scope: {
builtin: "内置",
global: "全局",
project: "项目",
},
runAs: {
subagent: "子代理",
inline: "内联",
},
generic: "技能",
},
exportReasoningSummary: "推理摘要",
exportToolLabel: "工具调用",
exportUserLabel: "用户消息",
empty: {
currentWorkspace: "当前工作区",
selectWorkspace: "选择一个工作区开始",
suggestion0: "开始新对话",
suggestion1: "打开设置",
suggestion2: "查看概览",
suggestion3: "浏览会话",
welcome: "欢迎使用 Reasonix",
},
errorLabel: "错误",
connecting: "连接中…",
session: {
format: "会话",
new: "新建会话",
},
setup: {
choose: "选择工作区",
description: "选择一个工作区开始工作",
notSelected: "未选择工作区",
saveAndStart: "保存并开始",
welcome: "欢迎",
workspace: "工作区",
},
tab: {
newTab: "+ 新建标签",
newTabTitle: "打开新标签",
},
titlebar: {
clearChat: "清除对话",
close: "关闭",
commandPalette: "命令面板",
contextPanel: "上下文面板",
copyMd: "复制为 Markdown",
exportMd: "导出为 Markdown",
maximize: "最大化",
minimize: "最小化",
more: "更多",
restore: "还原",
settings: "设置",
sidebar: "侧边栏",
windowControls: "窗口控制",
},
toast: {
cleared: "对话已清除",
copied: "已复制到剪贴板",
copiedMd: "已复制为 Markdown",
emptySession: "无消息可导出",
exportDialogTitle: "导出对话",
exportedMd: "已导出为 Markdown",
exportFailed: "导出失败",
langSwitched: "语言已切换",
modelSwitched: "模型 → {model}",
effortSwitched: "强度 → {effort}",
modeSwitched: "模式已切换",
newSession: "新会话已创建",
},
yolo: {
toast: "YOLO 模式已启用",
},
cmd: {
abort: "中止",
btw: "顺便说一下",
clearChat: "清除对话",
compact: "紧凑",
copyLast: "复制上条",
exportMd: "导出为 Markdown",
feedback: "反馈",
help: "帮助",
newSession: "新建会话",
retry: "重试",
switchModel: "切换模型",
toggleCurrency: "切换货币",
toggleLang: "切换语言",
toggleTheme: "切换主题",
},
header: {
abort: "中止",
clickToSelect: "点击选择",
copy: "复制",
copyMd: "复制为 Markdown",
export: "导出",
exportMd: "导出为 Markdown",
newChat: "新建对话",
noWorkspace: "无工作区",
running: "运行中…",
},
jumpToBottom: "跳到底部",
langEN: "English",
langZH: "中文",
splashSubtitle: "AI 驱动的编程助手",
},
changes: {
chatPlaceholder: "询问代码问题…",
@@ -56,6 +161,8 @@ export const zhCN = {
commentLine: "第",
commentEdit: "编辑",
commentDelete: "删除",
diffSourceGit: "Git 变更",
diffSourceSession: "上一轮变更",
diffSourceCheckpoint: "检查点",
checkpointEmpty: "暂无检查点",
restoreBtn: "恢复",
@@ -66,8 +173,6 @@ export const zhCN = {
createPlaceholder: "检查点名称…",
backToList: "返回列表",
reviewEmpty: "暂无可审查的更改",
diffSourceGit: "Git 变更",
diffSourceSession: "上一轮变更",
diffStyleUnified: "统一视图",
diffStyleSplit: "分栏视图",
expandAll: "全部展开",
@@ -101,29 +206,51 @@ export const zhCN = {
saved: "已保存:{fields}",
sectionApi: "DeepSeek API",
apiKey: "API 密钥",
apiKeyNotSet: "未设置",
apiKeySave: "保存密钥",
apiKeySet: "已设置",
apiSection: "API 配置",
notSet: "(未设置)",
replace: "替换",
pasteKey: "粘贴新的 sk-… 令牌",
saveKey: "保存密钥",
baseUrl: "基础 URL",
baseUrlPlaceholder: "https://api.deepseek.com(默认)",
baseUrlHint: "API 请求的基础 URL",
sectionDefaults: "默认设置",
preset: "预设",
presetAuto: "auto — flash 基线,困难时自动升级为 pro",
presetFlash: "flash — 始终使用 flash,不自动升级",
presetPro: "pro — 始终使用 pro",
effortSection: "推理强度",
modelCustom: "自定义模型 ID",
modelCustomHint: "任何 OpenAI 兼容的 ID(vLLM、Ollama、Together …)。",
modelCustomActive: "当前运行自定义 ID:{model}",
appliesNextTurn: "下一轮生效",
effort: "推理强度",
effortMax: "max(默认 — 最佳质量)",
effortHigh: "high(更便宜 / 更快)",
effortMax: "max(DeepSeek 扩展 — 标准 OpenAI / vLLM 会拒绝)",
effortHigh: "high(安全默认 — vLLM / Azure 兼容)",
effortMedium: "medium",
effortLow: "low(最快)",
webSearch: "网页搜索",
webSearchNote: "web_fetch + web_search 工具",
sectionCompute: "计算",
proNext: "/pro 单轮",
proArm: "为下一轮装备",
proArmed: "已装备 — 下一轮后自动解除",
proNextNote: "下一轮使用 deepseek-v4-pro,之后自动解除",
webSearchEngine: "搜索引擎",
webSearchEngineBing: "bing — 默认,国内裸 IP 直连,无需代理",
webSearchEngineBingIntl: "bing-intl — 国际版索引,走 www.bing.com",
webSearchEngineSearxng: "searxng — 自托管(端点用 /se searxng <url> 配置)",
webSearchEngineMetaso: "metaso — 每日 100 次免费(国内友好,metaso.cn 可领免费 key)",
webSearchEngineBaidu: "baidu — 百度 AI Search(设置 BAIDU_API_KEY 或 QIANFAN_API_KEY)",
webSearchEngineTavily: "tavily — 每月 1000 次免费(设置 TAVILY_API_KEY)",
webSearchEnginePerplexity: "perplexity — AI 直接回答(设置 PERPLEXITY_API_KEY)",
webSearchEngineExa: "exa — AI 直接回答,每月 1000 次免费(设置 EXA_API_KEY)",
webSearchEngineBrave: "brave — 独立索引,每月 2000 次免费(设置 BRAVE_SEARCH_API_KEY)",
webSearchEngineOllama: "ollama — Ollama 云端网页搜索(设置 OLLAMA_API_KEY)",
webSearchEngineNote: "下一次 web_search 调用生效",
webSearchApiKeySignup: "(获取 key)",
webSearchApiKeyClear: "清除",
webSearchApiKey: {
baidu: "百度 API key",
},
sectionBudget: "预算",
budget: "预算",
budgetHint: "设置支出限额",
budgetPlaceholder: "输入预算金额",
budgetOf: "/",
budgetSetCap: "设置上限",
budgetCustom: "自定义",
@@ -149,21 +276,153 @@ export const zhCN = {
skillPaths: "技能路径",
skillPathsPlaceholder: "/path/to/skills-a, /path/to/skills-b",
skillPathsNote: "英文逗号分隔 · 下次 /new 或新会话生效",
skillsEmpty: "无已加载技能",
skillsLoaded: "技能已加载",
subagentModelFlash: "flash",
subagentModelPro: "pro",
subagentModelHint: "技能派生独立 subagent 时使用的模型",
sectionRuntime: "运行时",
activeModel: "当前模型",
model: "模型",
modelFlashDesc: "Flash — 始终 flash",
modelProDesc: "Pro — 始终 pro",
modelPricingLine: "${hit} 命中 · ${miss} 未命中 · ${out} 输出 / 100 万 tok",
editMode: "编辑模式",
editModeNote: "在对话标签页头部切换",
editModeHint: "配置编辑模式",
showSystemEvents: "系统事件",
showSystemEventsHint: "在对话流中以细线显示压缩 / 中断 / 限速等系统事件",
shown: "显示",
hidden: "隐藏",
appMode: "应用模式",
sectionLanguage: "语言",
language: "语言",
languageHint: "切换语言",
langEn: "English",
langZhCn: "简体中文",
appearanceSection: "外观",
behaviorSection: "行为",
ruleAutoApprovalHint: "配置自动审批规则",
ruleAutoApprovalSection: "自动审批规则",
theme: "主题",
themeDark: "深色",
themeHint: "在浅色和深色主题之间切换",
themeLight: "浅色",
themeStyle: "主题风格",
themeStyleHint: "选择主题风格",
themeStyleGraphite: "石墨",
themeStyleGraphiteDesc: "冷色深色调,适合长时间使用。",
themeStyleEmber: "余烬",
themeStyleEmberDesc: "暖黑深色调,强化 Reasonix 橙色品牌感。",
themeStyleAurora: "极光",
themeStyleAuroraDesc: "青绿色深色调,低光环境更柔和。",
themeStyleSandstone: "砂岩",
themeStyleSandstoneDesc: "暖色浅色调,明亮环境更舒适。",
themeStylePorcelain: "瓷白",
themeStylePorcelainDesc: "高对比度浅色,简洁清爽。",
themeStyleLinen: "亚麻",
themeStyleLinenDesc: "偏纸张质感的温暖浅色调。",
themeStyleGlacier: "冰川",
themeStyleGlacierDesc: "冷白浅色调,蓝色强调更清爽。",
themeStyleMidnight: "午夜",
themeStyleMidnightDesc: "深色配冷色高光,更深邃。",
pageGeneralLabel: "通用",
pageGeneralDesc: "主题、字体、语言与工作目录。",
pageModelsLabel: "模型",
pageModelsDesc: "默认模型与推理强度。",
pageMcpLabel: "MCP 服务器",
pageMcpDesc: "接入外部工具服务器。",
pageSkillsLabel: "技能",
pageSkillsDesc: "可通过 /skill 调用的自定义技能。",
pageMemoryLabel: "记忆",
pageMemoryDesc: "跨会话保留的长期笔记。",
pageRulesLabel: "规则",
pageRulesDesc: "Shell 与路径访问的自动审批规则。",
pageBillingLabel: "账单",
pageBillingDesc: "API key、余额与会话预算。",
pageShortcutsLabel: "快捷键",
pageShortcutsDesc: "键盘快捷键参考。",
fontFamily: "字体",
fontFamilyHint: "选择字体",
fontFamilySans: "无衬线",
fontFamilySerif: "衬线",
fontFamilySystem: "系统",
fontScale: "字体大小",
fontScaleHint: "调整字体大小",
fontScaleLarge: "大",
fontScaleMedium: "中",
fontScaleSmall: "小",
currentWorkspace: "当前工作区",
defaultModelCurrent: "当前模型",
editor: "编辑器",
editorHint: "配置编辑器偏好",
maxOutput: "最大输出",
reasoningEffort: "推理强度",
reasoningEffortHint: "调整推理深度",
sessionCost: "会话成本",
balanceAvailable: "可用",
balanceLabel: "余额",
balanceLow: "余额不足",
cacheHitRate: "缓存命中率",
ctxWindow: "上下文窗口",
notSelected: "未选择",
parseError: "解析错误",
workspaceChange: "更改",
workspaceSection: "工作区",
mcpAdd: "添加",
mcpAddSection: "添加 MCP 服务器",
mcpBridged: "已桥接",
mcpConfigured: "已配置",
mcpEmpty: "无 MCP 服务器",
mcpNotBridged: "未桥接",
mcpRemove: "移除",
mcpSpecFormat: "JSON 格式",
mcpSpecLabel: "服务器规格",
memoryDesc: "配置记忆设置",
memorySection: "记忆",
shortcutAbort: "中止",
shortcutCloseTab: "关闭标签",
shortcutCommandPalette: "命令面板",
shortcutFocusComposer: "聚焦编辑器",
shortcutNewChat: "新建对话",
shortcutNewTab: "新建标签",
shortcutSettings: "设置",
shortcutSwitchTab: "切换标签",
qqAccessAllowlist: "允许列表",
qqAccessOpen: "开放",
qqAccessOwner: "所有者",
qqAccessOwnerWithAllowlist: "所有者 + 允许列表",
qqAccessRuntime: "运行时",
qqAppId: "App ID",
qqApplyAction: "应用",
qqApplyLabel: "应用",
qqAppSecret: "App Secret",
qqBack: "返回",
qqConfigure: "配置",
qqConfigureHint: "设置 QQ 集成",
qqConfigureTitle: "QQ 配置",
qqConnected: "已连接",
qqConnecting: "连接中…",
qqDisconnected: "已断开",
qqEnvironment: "环境",
qqFailed: "失败",
qqProduction: "生产环境",
qqSandbox: "沙箱环境",
qqSave: "保存",
qqSaveAndConnect: "保存并连接",
qqSection: "QQ 集成",
qqSummaryAppId: "App ID",
qqSummaryDetail: "详情",
qqSummaryMissing: "未配置",
qqTitle: "QQ 机器人",
},
chat: {
modeMirror: "TUI 镜像",
modeView: "会话视图",
placeholder: "输入提示词 — Enter 发送,Shift+Enter 换行 · / @ 打开选择器",
placeholderBusy: "请等待当前轮次完成…",
placeholderSteerBusy: "输入消息以引导当前任务 — 忙碌时不支持命令和选择器",
steerHint: "消息将作为附加指示引导当前轮次",
send: "发送",
new: "新建",
clear: "清除",
@@ -179,18 +438,16 @@ export const zhCN = {
eventStreamError: "事件流中断 — 正在重连…",
semanticBanner: "此项目未启用语义搜索。",
semanticBannerDesc:
"构建一次索引,模型即可按含义查找代码(“哪里处理认证失败?”),而不仅依赖精确字符串的 grep。",
"构建一次索引,模型即可按含义查找代码(\u201C哪里处理认证失败?\u201D),而不仅依赖精确字符串的 grep。",
semanticBannerBtn: "构建 →",
semanticBannerDismiss: "关闭(不再显示)",
slashCommands: "斜杠命令",
projectFiles: "项目文件",
effortTitle: "reasoning_effort — 下一轮生效",
effortMaxTitle: "max(默认 — 最佳质量)",
effortHighTitle: "high(更便宜 / 更快)",
presetTitle: "预设 — 模型承诺",
presetAutoTitle: "auto — flash 基线;困难轮次自动升级为 pro(NEEDS_PRO / 失败阈值)",
presetFlashTitle: "flash — 始终 flash;不自动升级。/pro 仍可用于一次性手动提升",
presetProTitle: "pro — 始终 pro;约 3 倍 flash 成本(5/31 折扣)。锁定困难的架构工作。",
effortMaxTitle: "max(DeepSeek 扩展)",
effortHighTitle: "high(安全默认 — vLLM / Azure 兼容)",
effortMediumTitle: "medium",
effortLowTitle: "low(最快)",
editGateTitle: "编辑门控 — Shift+Tab 在 TUI 中循环",
editReviewTitle: "review — 编辑和非允许列表的 shell 命令都会先询问",
editAutoTitle: "auto — 编辑自动应用,shell 仍会询问",
@@ -300,6 +557,16 @@ export const zhCN = {
loadingTranscript: "加载转录稿…",
emptyTranscript: "空的转录稿。",
messages: "{count} 条消息",
newBtn: "新建会话",
newHint: "归档当前会话并开启新会话",
switchBtn: "切换到此会话",
deleteBtn: "删除",
deleteConfirm: "确定删除会话「{name}」?转录文件将被移除,无法撤销。",
cantDeleteActive: "请先切换到其他会话,再删除当前会话。",
attachRequired:
"实时会话操作需要已连接的 CLI 会话。请通过 reasonix chat 启动,或在 TUI 会话中打开仪表盘。",
activeChip: "当前",
activePill: "当前",
},
tools: {
loading: "加载工具…",
@@ -407,6 +674,10 @@ export const zhCN = {
whyUnbridgedDesc:
"此规格存在于您的 config.json 中,但未桥接到实时会话。MCP 服务器在 reasonix code 启动时连接;仪表盘本身无法生成子进程。",
whyUnbridgedHint: "激活方法:重启 reasonix code,然后刷新此仪表盘。",
bridgeFailed: "桥接失败",
bridgeFailedTitle: "桥接失败 · 在配置中",
bridgeFailedHint:
"已尝试桥接但失败。常见原因:URL 错误、需要鉴权、上游 404 / 5xx、本地命令缺失。修复后重启 reasonix code 重试。",
pickHint: "选择左侧的 MCP 服务器以检查工具 / 资源 / 提示。",
toolsTitle: "工具 · {count}",
resourcesTitle: "资源 · {count}",
@@ -570,7 +841,7 @@ export const zhCN = {
builtWith: "构建来源",
currentTarget: "当前目标",
incompatibleHint:
"磁盘上的这个索引是为不同的 provider 或 model 构建的。运行“完全重建”即可替换。",
"磁盘上的这个索引是为不同的 provider 或 model 构建的。运行\u201C完全重建\u201D即可替换。",
runIndexHint: "运行索引以启用 semantic_search。",
reIndex: "重建索引",
build: "构建",
@@ -587,6 +858,7 @@ export const zhCN = {
customRequestBodyMustBeObject: "自定义请求体必须是 JSON 对象。",
saveBeforeIndex: "请先保存语义设置,再启动索引。",
extraBody: "扩展请求体",
batchSize: "批次大小",
keepExistingKey: "留空则保留现有 Key",
remoteProvider: "远程向量服务",
remoteProviderDesc:
@@ -652,6 +924,12 @@ export const zhCN = {
shellBgTitle: "后台进程",
shellSubtitle: "模型想要运行一条 Shell 命令",
shellBgSubtitle: "长时间运行 — 批准后继续运行",
pathTitle: "沙箱外文件访问",
pathSubtitle: "{intent} · 通过 {tool}",
pathRead: "读取",
pathWrite: "写入",
pathSandboxLabel: "沙箱",
pathAllowPrefixLabel: "允许前缀",
runOnce: "运行一次",
alwaysAllow: '始终允许 "{prefix}"',
deny: "拒绝",
@@ -715,4 +993,326 @@ export const zhCN = {
hoursAgo: "{n} 小时前",
daysAgo: "{n} 天前",
},
cards: {
applied: "已应用",
cacheHit: "缓存命中",
checkpointRewind: "检查点回退",
cost: "费用",
diffApply: "应用",
diffApplyChanges: "应用更改",
diffAwaiting: "待审阅",
diffDiscard: "丢弃",
done: "完成",
elapsed: "耗时",
error: "错误",
errorName: "错误",
failed: "失败",
hits: "命中",
memoryCountSuffix: "条记忆",
memoryName: "记忆",
output: "输出",
planDefaultTitle: "计划",
prompt: "提示词",
compactionMeta: "{chars} 字符",
compactionName: "已压缩历史",
reasoningComplete: "推理完成",
reasoningName: "推理",
result: "结果",
running: "运行中",
searchName: "搜索",
shellAlwaysAllow: "始终允许",
shellAwaiting: "待审批",
shellExecuteHint: "执行此命令?",
shellReject: "拒绝",
shellRun: "运行",
shellRunning: "运行中",
streaming: "输出中",
subagentDone: "子代理完成",
subagentDoneProgress: "子代理完成 ({pct}%)",
subagentFailed: "子代理失败",
subagentRunning: "子代理运行中",
},
planBadge: {
blocked: "已阻塞",
done: "完成",
failed: "失败",
pending: "待处理",
running: "运行中",
},
composer: {
atHeader: "提及文件",
close: "关闭",
commandPalette: "命令面板",
commands: "命令",
commandsLabel: "命令",
confirm: "确认",
imageFilterName: "图片",
insertFile: "插入文件",
insertImage: "插入图片",
interrupt: "中断",
mentionFiles: "提及文件",
mentionLabel: "提及",
newline: "换行",
noMatches: "无匹配",
placeholder: "输入提示词…",
queue: "队列",
queueCount: "{count} 个排队",
select: "选择",
send: "发送",
slashHeader: "斜杠命令",
switchModel: "切换模型",
switchEffort: "切换推理强度",
workspaceRoot: "工作区根目录",
},
contextPanel: {
allow: "允许",
ask: "询问",
autoApproveTitle: "自动审批",
cacheKey: "缓存",
contextTokens: "上下文 tokens",
fileInContext: "在上下文中",
fileModified: "已修改",
filesCount: "{count} 个文件",
filesTab: "文件",
filesTitle: "文件",
freeKey: "空闲",
itemCount: "{count} 个项目",
mcpConfigured: "已配置",
mcpConnecting: "连接中…",
mcpDisabled: "已禁用",
mcpEmpty: "无 MCP 服务器",
mcpFailed: "失败",
mcpReady: "就绪",
mcpReadyAll: "全部就绪",
mcpReadySome: "部分就绪",
mcpTitle: "MCP",
mcpTools: "工具",
memoryTab: "记忆",
memoryTitle: "记忆",
noFilesMsg: "上下文中无文件",
noMemoriesMsg: "无记忆",
reservedKey: "保留",
ruleReadOnly: "只读",
ruleReview: "审阅",
ruleShellAllowlist: "Shell 允许列表",
rulesTab: "规则",
ruleWritesAsk: "写入需询问",
ruleYolo: "YOLO",
scopeGlobal: "全局",
scopeProject: "项目",
toolsTab: "工具",
usedKey: "已用",
},
dragDrop: {
overlay: "拖放文件到此处",
},
extraCards: {
approve: "批准",
balance: "余额",
cache: "缓存",
cacheHit: "缓存命中",
contextWindow: "上下文窗口",
doctorTitle: "诊断",
output: "输出",
prompt: "提示词",
reasoning: "推理",
reject: "拒绝",
sessionCost: "会话成本",
sessionUsage: "会话用量",
topToolsUsage: "热门工具",
unknownKind: "未知",
memoryUser: "用户",
memoryFeedback: "反馈",
memoryProject: "项目",
memoryReference: "参考",
},
jobs: {
empty: "无后台任务",
exited: "已退出",
kbClose: "关闭",
kbToggle: "切换",
running: "运行中",
stop: "停止",
stopAll: "全部停止",
stopAllTip: "停止所有任务",
stopOne: "停止",
title: "后台任务",
},
live: {
deliveredWaiting: "等待下一条消息",
reasoning: "推理",
running: "运行中",
secondsAgo: "{n} 秒前",
you: "你",
},
markdown: {
copied: "已复制!",
copy: "复制",
externalLinkTitle: "在新标签中打开",
filePillTitle: "打开文件",
localLinkTitle: "打开链接",
},
palette: {
abort: "中止",
abortHint: "中止当前请求",
about: "关于",
clearChat: "清除对话",
clearChatHint: "清除对话",
closeTab: "关闭标签",
closeTabHint: "关闭当前标签",
copyConv: "复制对话",
copyConvHint: "复制对话为 Markdown",
copyLast: "复制上条回复",
copyLastHint: "复制上条助手消息",
countSuffix: "个项目",
empty: "无匹配命令",
exportMd: "导出为 Markdown",
exportMdHint: "导出对话为 Markdown 文件",
focusComposer: "聚焦编辑器",
footClose: "关闭",
footMove: "移动",
footRun: "运行",
groupAction: "操作",
groupNav: "导航",
groupSettings: "设置",
groupWorkspace: "工作区",
newChat: "新建对话",
newChatHint: "开始新对话",
newTab: "新建标签",
newTabHint: "打开新标签",
pickWorkspace: "切换工作区",
pickWorkspaceHint: "更改工作区",
searchPlaceholder: "搜索命令…",
settings: "设置",
settingsHint: "打开设置",
},
panel: {
renderError: "面板崩溃",
},
sidebarPanel: {
approvalRules: "审批规则",
cancel: "取消",
commandPalette: "命令面板",
daysAgo: "{n} 天前",
delete: "删除",
deleteSession: "删除会话",
hoursAgo: "{n} 小时前",
justNow: "刚刚",
loading: "加载中…",
messageCount: "{count} 条消息",
minutesAgo: "{n} 分钟前",
newChat: "新建对话",
noMatches: "无匹配",
noSessions: "无会话",
recent: "最近",
searchSessions: "搜索会话…",
sessionTitle: "会话",
settings: "设置",
weeksAgo: "{n} 周前",
},
statusbar: {
balance: "余额",
busy: "忙碌",
cache: "缓存",
cacheHit: "缓存命中",
jobs: "任务",
jobsTip: "后台任务",
offline: "离线",
online: "在线",
switchCurrency: "切换货币",
switchTheme: "切换主题",
switchWorkspace: "切换工作区",
themeDark: "深色",
themeLight: "浅色",
themeStyleGraphite: "石墨",
themeStyleEmber: "余烬",
themeStyleAurora: "极光",
themeStyleSandstone: "砂岩",
themeStylePorcelain: "瓷白",
themeStyleLinen: "亚麻",
themeStyleGlacier: "冰川",
themeStyleMidnight: "午夜",
thisTurn: "本轮",
tokens: "Tokens",
},
thread: {
activePlan: "活跃计划",
allowRead: "允许读取",
allowWrite: "允许写入",
alwaysAllow: "始终允许",
alwaysAllowPrefix: "始终允许 {prefix}",
approve: "批准",
approveRewrite: "批准重写",
cancel: "取消",
checkpointKind: "检查点",
checkpointSub: "保存当前状态",
checkpointTitle: "创建检查点",
collapse: "折叠",
continue: "继续",
copyMessage: "复制消息",
copyResponse: "复制回复",
execute: "执行",
keepOriginal: "保留原始",
keepSteps: "保留步骤",
optionCount: "{count} 个选项",
pathAccessKind: "路径访问",
planConfirmationKind: "计划审批",
planRevisionKind: "计划修订",
planRunning: "计划进行中",
planStepCount: "步骤 {done}/{total}",
readPathOutsideSandbox: "沙箱外读取路径",
refine: "优化",
reject: "拒绝",
revise: "修订",
revisionMeta: "修订",
rewritePlan: "重写计划",
risk: "风险评估",
riskMedium: "中等风险",
runBackgroundCommand: "后台运行",
runCommand: "运行命令",
shellConfirmationKind: "Shell 确认",
startPlan: "启动计划",
stop: "停止",
subagent: "子代理",
userChoiceKind: "用户选择",
writePathOutsideSandbox: "沙箱外写入路径",
you: "你",
},
workdir: {
browse: "浏览…",
cancel: "取消",
empty: "无工作区",
emptyDir: "无子目录。",
go: "前往",
goTip: "跳转到该路径",
loading: "加载中…",
openHere: "打开此目录",
pathPlaceholder: "绝对路径…",
promptWeb: "输入要打开的工作区绝对路径:",
searchPlaceholder: "搜索工作区…",
title: "工作区",
},
about: {
close: "关闭",
repo: "仓库",
sidebarLabel: "关于",
tagline: "AI 驱动的编程助手",
version: "版本",
},
effort: {
lowDesc: "最快 — 极少推理",
mediumDesc: "平衡",
highDesc: "默认 — vLLM / Azure 安全",
maxDesc: "DeepSeek 扩展;标准 OpenAI / vLLM 会拒绝",
},
editMode: {
plan: "计划",
planHint: "只读模式 · 所有写工具都不会派发",
review: "审阅",
reviewHint: "编辑和非允许列表的 shell 命令都会先询问",
auto: "自动",
autoHint: "编辑自动应用,shell 仍会询问",
yolo: "YOLO",
yoloHint: "编辑和 shell 都自动运行,绕过允许列表",
},
};
+81
View File
@@ -0,0 +1,81 @@
import type { SVGProps } from "react";
type IconProps = SVGProps<SVGSVGElement> & { size?: number };
function Ic({ size = 14, children, ...rest }: IconProps & { children: React.ReactNode }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
{...rest}
>
{children}
</svg>
);
}
export const I = {
plus: (p: IconProps) => (<Ic {...p}><path d="M12 5v14M5 12h14" /></Ic>),
search: (p: IconProps) => (<Ic {...p}><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></Ic>),
send: (p: IconProps) => (<Ic {...p}><path d="M4 12 20 4l-6 16-3-7-7-1Z" /></Ic>),
chev: (p: IconProps) => (<Ic {...p}><path d="m6 9 6 6 6-6" /></Ic>),
chevR: (p: IconProps) => (<Ic {...p}><path d="m9 6 6 6-6 6" /></Ic>),
check: (p: IconProps) => (<Ic {...p}><path d="m5 12 5 5L20 7" /></Ic>),
x: (p: IconProps) => (<Ic {...p}><path d="M6 6l12 12M18 6 6 18" /></Ic>),
terminal: (p: IconProps) => (<Ic {...p}><rect x="3" y="4" width="18" height="16" rx="2" /><path d="m7 9 3 3-3 3M13 15h4" /></Ic>),
brain: (p: IconProps) => (
<Ic {...p}>
<path d="M9 4a3 3 0 0 0-3 3v0a3 3 0 0 0-2 5 3 3 0 0 0 2 5 3 3 0 0 0 3 3h0a3 3 0 0 0 3-3V4" />
<path d="M15 4a3 3 0 0 1 3 3 3 3 0 0 1 2 5 3 3 0 0 1-2 5 3 3 0 0 1-3 3" />
</Ic>
),
list: (p: IconProps) => (<Ic {...p}><path d="M4 6h2M4 12h2M4 18h2M9 6h11M9 12h11M9 18h11" /></Ic>),
diff: (p: IconProps) => (<Ic {...p}><path d="M7 4v11a3 3 0 0 0 3 3h2M17 20V9a3 3 0 0 0-3-3h-2" /><circle cx="7" cy="20" r="2" /><circle cx="17" cy="4" r="2" /></Ic>),
globe: (p: IconProps) => (<Ic {...p}><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" /></Ic>),
link: (p: IconProps) => (<Ic {...p}><path d="M10 14a4 4 0 0 1 0-6l3-3a4 4 0 0 1 6 6l-2 2" /><path d="M14 10a4 4 0 0 1 0 6l-3 3a4 4 0 0 1-6-6l2-2" /></Ic>),
wrench: (p: IconProps) => (<Ic {...p}><path d="M14 7a4 4 0 1 0 4 4l3 3-3 3-3-3a4 4 0 0 1-4-4l-3-3-3 3 3 3a4 4 0 0 0 6 0" /></Ic>),
bot: (p: IconProps) => (<Ic {...p}><rect x="4" y="7" width="16" height="12" rx="3" /><path d="M12 3v4M8 12h.01M16 12h.01M9 16h6" /></Ic>),
archive: (p: IconProps) => (<Ic {...p}><rect x="3" y="3" width="18" height="5" rx="1" /><path d="M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M10 12h4" /></Ic>),
bookmark: (p: IconProps) => (<Ic {...p}><path d="M6 3h12v18l-6-4-6 4Z" /></Ic>),
warning: (p: IconProps) => (<Ic {...p}><path d="M12 3 2 21h20Z" /><path d="M12 10v5M12 18h.01" /></Ic>),
zap: (p: IconProps) => (<Ic {...p}><path d="M13 3 4 14h7l-1 7 9-11h-7Z" /></Ic>),
database: (p: IconProps) => (<Ic {...p}><ellipse cx="12" cy="5" rx="8" ry="3" /><path d="M4 5v6c0 1.7 3.6 3 8 3s8-1.3 8-3V5M4 11v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6" /></Ic>),
cpu: (p: IconProps) => (<Ic {...p}><rect x="5" y="5" width="14" height="14" rx="2" /><rect x="9" y="9" width="6" height="6" /><path d="M9 2v3M15 2v3M9 19v3M15 19v3M2 9h3M2 15h3M19 9h3M19 15h3" /></Ic>),
coin: (p: IconProps) => (<Ic {...p}><circle cx="12" cy="12" r="9" /><path d="M12 7v10M9 10h4a2 2 0 0 1 0 4H9" /></Ic>),
file: (p: IconProps) => (<Ic {...p}><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9Z" /><path d="M14 3v6h6" /></Ic>),
folder: (p: IconProps) => (<Ic {...p}><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z" /></Ic>),
image: (p: IconProps) => (<Ic {...p}><rect x="3" y="4" width="18" height="16" rx="2" /><circle cx="9" cy="10" r="2" /><path d="m3 18 5-5 4 4 3-3 6 6" /></Ic>),
paperclip: (p: IconProps) => (<Ic {...p}><path d="M21 12 12 21a5 5 0 0 1-7-7L14 5a3 3 0 0 1 4 4l-9 9a1 1 0 0 1-2-2l8-8" /></Ic>),
mic: (p: IconProps) => (<Ic {...p}><rect x="9" y="3" width="6" height="12" rx="3" /><path d="M5 11a7 7 0 0 0 14 0M12 18v3M9 21h6" /></Ic>),
sun: (p: IconProps) => (<Ic {...p}><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.5 1.5M17.5 17.5 19 19M5 19l1.5-1.5M17.5 6.5 19 5" /></Ic>),
moon: (p: IconProps) => (<Ic {...p}><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z" /></Ic>),
panel_l: (p: IconProps) => (<Ic {...p}><rect x="3" y="4" width="18" height="16" rx="2" /><path d="M9 4v16" /></Ic>),
panel_r: (p: IconProps) => (<Ic {...p}><rect x="3" y="4" width="18" height="16" rx="2" /><path d="M15 4v16" /></Ic>),
cog: (p: IconProps) => (<Ic {...p}><path d="M12 3.6 19.2 7.8v8.4L12 20.4 4.8 16.2V7.8Z" /><circle cx="12" cy="12" r="3.7" /></Ic>),
stop: (p: IconProps) => (<Ic {...p}><rect x="6" y="6" width="12" height="12" rx="2" /></Ic>),
play: (p: IconProps) => (<Ic {...p}><path d="M7 5v14l12-7Z" /></Ic>),
more: (p: IconProps) => (<Ic {...p}><circle cx="6" cy="12" r="1.6" fill="currentColor" /><circle cx="12" cy="12" r="1.6" fill="currentColor" /><circle cx="18" cy="12" r="1.6" fill="currentColor" /></Ic>),
pin: (p: IconProps) => (<Ic {...p}><path d="M15 3 9 9l-4 1 9 9 1-4 6-6ZM4 20l5-5" /></Ic>),
rotate: (p: IconProps) => (<Ic {...p}><path d="M3 12a9 9 0 1 0 3-6.7L3 8" /><path d="M3 3v5h5" /></Ic>),
branch: (p: IconProps) => (<Ic {...p}><circle cx="6" cy="4" r="2" /><circle cx="6" cy="20" r="2" /><circle cx="18" cy="8" r="2" /><path d="M6 6v12M6 14a6 6 0 0 0 6-6h4" /></Ic>),
at: (p: IconProps) => (<Ic {...p}><circle cx="12" cy="12" r="4" /><path d="M16 8v6a3 3 0 0 0 5-2 9 9 0 1 0-4 7" /></Ic>),
slash: (p: IconProps) => (<Ic {...p}><path d="M16 4 8 20" /></Ic>),
layers: (p: IconProps) => (<Ic {...p}><path d="m12 3 9 5-9 5-9-5Z" /><path d="m3 13 9 5 9-5M3 18l9 5 9-5" /></Ic>),
download: (p: IconProps) => (<Ic {...p}><path d="M12 4v12M6 12l6 6 6-6M4 20h16" /></Ic>),
upload: (p: IconProps) => (<Ic {...p}><path d="M12 20V8M6 12l6-6 6 6M4 4h16" /></Ic>),
history: (p: IconProps) => (<Ic {...p}><path d="M3 12a9 9 0 1 0 3-6.7L3 8M12 7v5l3 2" /></Ic>),
shield: (p: IconProps) => (<Ic {...p}><path d="M12 3 4 6v6c0 5 3.5 8 8 9 4.5-1 8-4 8-9V6Z" /><path d="m9 12 2 2 4-4" /></Ic>),
warn: (p: IconProps) => (<Ic {...p}><path d="M12 3 2 21h20Z" /><path d="M12 10v5M12 18h.01" /></Ic>),
help: (p: IconProps) => (<Ic {...p}><circle cx="12" cy="12" r="9" /><path d="M9.5 9a2.5 2.5 0 0 1 5 0c0 1.5-2.5 2-2.5 4M12 17h.01" /></Ic>),
refresh: (p: IconProps) => (<Ic {...p}><path d="M3 12a9 9 0 0 1 15-6.7L21 8M21 4v4h-4M21 12a9 9 0 0 1-15 6.7L3 16M3 20v-4h4" /></Ic>),
copy: (p: IconProps) => (<Ic {...p}><rect x="8" y="8" width="12" height="12" rx="2" /><path d="M4 16V6a2 2 0 0 1 2-2h10" /></Ic>),
};
export type IconKey = keyof typeof I;
-48
View File
@@ -1,48 +0,0 @@
export const TOKEN: string =
document.querySelector('meta[name="reasonix-token"]')?.getAttribute("content") ?? "";
export const MODE: "standalone" | "attached" =
(document.querySelector('meta[name="reasonix-mode"]')?.getAttribute("content") as
| "standalone"
| "attached"
| null) ?? "standalone";
export interface ApiOptions {
method?: string;
headers?: Record<string, string>;
body?: unknown;
}
export interface ApiError extends Error {
status: number;
body: unknown;
}
export async function api<T = unknown>(path: string, opts: ApiOptions = {}): Promise<T> {
const method = opts.method ?? "GET";
const url = `/api${path}${path.includes("?") ? "&" : "?"}token=${TOKEN}`;
const headers: Record<string, string> = { ...(opts.headers ?? {}) };
headers["X-Reasonix-Token"] = TOKEN;
if (opts.body !== undefined) headers["Content-Type"] = "application/json";
const res = await fetch(url, {
method,
headers,
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
});
const text = await res.text();
let parsed: unknown = null;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
parsed = { error: text };
}
if (!res.ok) {
const errMsg =
(parsed as { error?: string } | null)?.error ?? `${res.status} ${res.statusText}`;
const err = new Error(errMsg) as ApiError;
err.status = res.status;
err.body = parsed;
throw err;
}
return parsed as T;
}
-45
View File
@@ -1,45 +0,0 @@
export type BudgetState =
| { kind: "off"; spent: number }
| { kind: "running"; cap: number; spent: number; pct: number }
| { kind: "warn"; cap: number; spent: number; pct: number }
| { kind: "exhausted"; cap: number; spent: number; pct: number };
export function deriveBudgetState(
cap: number | null | undefined,
spent: number | null | undefined,
): BudgetState {
const safeSpent = typeof spent === "number" && spent >= 0 ? spent : 0;
if (typeof cap !== "number" || cap <= 0) {
return { kind: "off", spent: safeSpent };
}
const pct = (safeSpent / cap) * 100;
if (pct >= 100) return { kind: "exhausted", cap, spent: safeSpent, pct };
if (pct >= 80) return { kind: "warn", cap, spent: safeSpent, pct };
return { kind: "running", cap, spent: safeSpent, pct };
}
/** Default quick-cap menu — round dollar amounts users actually pick. */
export const QUICK_CAPS_USD: ReadonlyArray<number> = [1, 5, 10, 25, 50];
/** 1.5× / 2× / 4× the current cap, snapped to a "nice" round number per bucket. */
export function bumpSuggestions(currentCap: number): number[] {
if (currentCap <= 0) return [];
return [niceUp(currentCap * 1.5), niceUp(currentCap * 2), niceUp(currentCap * 4)];
}
function niceUp(n: number): number {
// Subtract a tiny epsilon before ceil so FP noise (0.4 * 1.5 = 0.6000…01)
// doesn't bump a value to the next bucket.
const eps = 1e-9;
if (n < 1) return Math.ceil((n - eps) * 10) / 10;
if (n < 10) return Math.ceil((n - eps) * 2) / 2;
if (n < 100) return Math.ceil(n - eps);
return Math.ceil((n - eps) / 5) * 5;
}
/** Tone class shared between the cockpit tile and the settings gauge. */
export function budgetTone(state: BudgetState): "" | "warn" | "err" {
if (state.kind === "exhausted") return "err";
if (state.kind === "warn") return "warn";
return "";
}
-13
View File
@@ -1,13 +0,0 @@
/** Browser extensions (userscripts, ad blockers) inject scripts that throw into our window. Their errors land in the global handlers as if they were ours — see #818. Filter them by origin. */
const THIRD_PARTY_ORIGIN_PREFIXES = [
"chrome-extension://",
"moz-extension://",
"safari-web-extension://",
"safari-extension://",
"ms-browser-extension://",
];
export function isThirdPartyError(error: unknown, filename?: string): boolean {
const hay = `${filename ?? ""}\n${(error as { stack?: string } | null)?.stack ?? ""}`;
return THIRD_PARTY_ORIGIN_PREFIXES.some((prefix) => hay.includes(prefix));
}
-68
View File
@@ -1,68 +0,0 @@
import htm from "htm";
import { h } from "preact";
import { useEffect, useState } from "preact/hooks";
import { isThirdPartyError } from "./bus-filter.js";
const html = htm.bind(h);
export const appBus = new EventTarget();
export const toastBus = new EventTarget();
export type ToastKind = "info" | "success" | "warn" | "error";
export function showToast(text: string, kind: ToastKind = "info", ttl = 3000): void {
toastBus.dispatchEvent(new CustomEvent("toast", { detail: { text, kind, ttl } }));
}
export interface ErrorReport {
error: unknown;
source: string;
info?: string;
ts: number;
}
export function reportAppError(error: unknown, source: string, info?: string): void {
console.error(`[reasonix dashboard] ${source}:`, error, info);
appBus.dispatchEvent(
new CustomEvent("error", { detail: { error, source, info, ts: Date.now() } }),
);
}
window.addEventListener("error", (ev) => {
if (!ev.error) return;
if (isThirdPartyError(ev.error, ev.filename)) return;
reportAppError(ev.error, "window", ev.message);
});
window.addEventListener("unhandledrejection", (ev) => {
if (isThirdPartyError(ev.reason)) return;
reportAppError(ev.reason, "promise");
});
interface Toast {
id: string;
text: string;
kind: ToastKind;
ttl: number;
}
export function ToastStack() {
const [toasts, setToasts] = useState<Toast[]>([]);
useEffect(() => {
const onToast = (ev: Event) => {
const detail = (ev as CustomEvent).detail as Omit<Toast, "id">;
const id = `${Date.now()}-${Math.random()}`;
const t: Toast = { id, ...detail };
setToasts((prev) => [...prev, t]);
setTimeout(() => setToasts((prev) => prev.filter((x) => x.id !== id)), t.ttl);
};
toastBus.addEventListener("toast", onToast);
return () => toastBus.removeEventListener("toast", onToast);
}, []);
if (toasts.length === 0) return null;
return html`
<div class="toast-stack">
${toasts.map((t) => html`<div key=${t.id} class="toast ${t.kind}">${t.text}</div>`)}
</div>
`;
}
-80
View File
@@ -1,80 +0,0 @@
export type HunkLineType = "add" | "del" | "ctx";
export interface HunkLine {
type: HunkLineType;
content: string;
oldLineNum?: number;
newLineNum?: number;
}
export interface Hunk {
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
lines: HunkLine[];
}
/** Parse a unified diff patch string into structured hunk arrays. No external deps. */
export function parseHunks(patch: string): Hunk[] {
if (!patch) return [];
const hunks: Hunk[] = [];
const rawLines = patch.split("\n");
let cursor = 0;
// Skip file headers (--- a/..., +++ b/...)
while (cursor < rawLines.length) {
const line = rawLines[cursor]!;
// Start of a hunk: @@ -oldStart[,oldLines] +newStart[,newLines] @@
const m = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
if (m) {
const oldStart = parseInt(m[1]!, 10);
const oldLen = m[2] !== undefined ? parseInt(m[2], 10) : 1;
const newStart = parseInt(m[3]!, 10);
const newLen = m[4] !== undefined ? parseInt(m[4], 10) : 1;
const lines: HunkLine[] = [];
let oldNum = oldStart;
let newNum = newStart;
cursor++;
while (
cursor < rawLines.length &&
!rawLines[cursor]!.startsWith("@@ ") &&
!rawLines[cursor]!.startsWith("diff ") &&
!rawLines[cursor]!.startsWith("--- ") &&
!rawLines[cursor]!.startsWith("index ")
) {
const l = rawLines[cursor]!;
if (l.startsWith("\\")) {
cursor++;
continue;
}
const ch = l[0]!;
const content = l.slice(1);
if (ch === "-") {
lines.push({ type: "del", content, oldLineNum: oldNum });
oldNum++;
} else if (ch === "+") {
lines.push({ type: "add", content, newLineNum: newNum });
newNum++;
} else {
lines.push({ type: "ctx", content, oldLineNum: oldNum, newLineNum: newNum });
oldNum++;
newNum++;
}
cursor++;
}
hunks.push({ oldStart, oldLines: oldLen, newStart, newLines: newLen, lines });
} else {
cursor++;
}
}
return hunks;
}
-158
View File
@@ -1,158 +0,0 @@
import htm from "htm";
import { Component, type ComponentChildren, h } from "preact";
import { useEffect, useState } from "preact/hooks";
import { t } from "../i18n/index.js";
import { MODE } from "./api.js";
import { type ErrorReport, appBus, reportAppError } from "./bus.js";
const html = htm.bind(h);
const REPO_URL = "https://github.com/esengine/reasonix";
function buildIssueBody({ error, source, info }: ErrorReport): string {
const ua = typeof navigator === "object" ? navigator.userAgent : "(unknown)";
const errMsg = (error as Error)?.message ?? String(error);
const stack = (error as Error)?.stack ?? "(no stack)";
return [
"**What happened**",
"(describe what you were doing — typing, switching tabs, clicking a tool path, etc.)",
"",
"**Error**",
"```",
`${source}: ${errMsg}`,
info ? `info: ${info}` : null,
"",
stack,
"```",
"",
"**Environment**",
`- Reasonix: ${MODE}`,
`- Browser: ${ua}`,
`- URL: ${location.pathname} (token redacted)`,
"",
"_Reported from the local dashboard's error overlay._",
]
.filter((l): l is string => l !== null)
.join("\n");
}
export function ErrorOverlay() {
const [err, setErr] = useState<ErrorReport | null>(null);
const [copied, setCopied] = useState(false);
useEffect(() => {
const onError = (ev: Event) => {
setErr((ev as CustomEvent).detail as ErrorReport);
setCopied(false);
};
appBus.addEventListener("error", onError);
return () => appBus.removeEventListener("error", onError);
}, []);
useEffect(() => {
if (!err) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setErr(null);
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [err]);
if (!err) return null;
const error = err.error as Error | undefined;
const errMsg = error?.message ?? String(error);
const stack = error?.stack ?? "(no stack)";
const issueUrl = `${REPO_URL}/issues/new?title=${encodeURIComponent(`[dashboard] ${errMsg.slice(0, 80)}`)}&body=${encodeURIComponent(buildIssueBody(err))}`;
const copyDetails = async () => {
try {
await navigator.clipboard.writeText(buildIssueBody(err));
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
/* clipboard blocked — user can still hit "report on GitHub" */
}
};
return html`
<div class="error-overlay">
<div class="error-overlay-card">
<div class="error-overlay-head">
<span class="error-overlay-icon">✦</span>
<div>
<div class="error-overlay-title">${t("error.title")}</div>
<div class="error-overlay-subtitle">${err.source} error · ${errMsg}</div>
</div>
</div>
<pre class="error-overlay-trace">${stack}</pre>
${
err.info
? html`<div class="error-overlay-info"><strong>info:</strong> ${err.info}</div>`
: null
}
<div class="error-overlay-help">
${t("error.body")}
</div>
<div class="error-overlay-actions">
<button class="primary" onClick=${copyDetails}>
${copied ? t("error.copied") : t("error.copyDetails")}
</button>
<a class="button" href=${issueUrl} target="_blank" rel="noopener noreferrer">
${t("error.reportOnGithub")}
</a>
<button onClick=${() => setErr(null)} style="margin-left: auto;">${t("error.dismiss")}</button>
</div>
</div>
</div>
`;
}
interface ErrorBoundaryProps {
children: ComponentChildren;
}
interface ErrorBoundaryState {
caught: boolean;
lastErr: Error | null;
attempts: number;
}
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { caught: false, lastErr: null, attempts: 0 };
}
static override getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
return { caught: true, lastErr: error };
}
override componentDidCatch(error: Error, info: { componentStack?: string }) {
reportAppError(error, "render", info?.componentStack ?? "");
const attempts = (this.state.attempts ?? 0) + 1;
if (attempts >= 3) {
this.setState({ attempts });
return;
}
setTimeout(() => this.setState({ caught: false, attempts }), 100);
}
override render() {
if (this.state.caught) {
if ((this.state.attempts ?? 0) >= 3) {
return html`
<div class="boot" style="flex-direction: column; gap: 12px;">
<div>${t("error.crashing", { name: "the error overlay has the trace" })}</div>
<button onClick=${() => this.setState({ caught: false, attempts: 0 })}>
${t("error.retry")}
</button>
</div>
`;
}
return html`<div class="boot">${t("error.recovering")}</div>`;
}
return this.props.children;
}
}
-232
View File
@@ -1,232 +0,0 @@
import { h } from "preact";
import { useState, useCallback, useEffect } from "preact/hooks";
import htm from "htm";
import { api, MODE } from "./api.js";
const html = htm.bind(h);
export interface TreeNode {
name: string;
path: string;
isDir: boolean;
children?: TreeNode[];
}
export interface OpenFile {
path: string;
name: string;
content: string;
language: string;
}
const EXT_ICONS: Record<string, string> = {
ts: "TS", tsx: "TS", js: "JS", jsx: "JS",
json: "{}", css: "#", scss: "#", html: "<>",
md: "MD", py: "PY", rs: "RS", go: "GO",
yaml: "Y", yml: "Y", toml: "T", xml: "<>",
svg: "<>", png: "[]", jpg: "[]", ico: "[]",
sh: "$", bash: "$", ps1: "$", bat: "$",
sql: "DB", graphql: "GQ", proto: "PB",
dockerfile: "D", makefile: "MK",
};
const EXT_LANG: Record<string, string> = {
ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript",
json: "json", css: "css", scss: "scss", html: "html",
md: "markdown", py: "python", rs: "rust", go: "go",
yaml: "yaml", yml: "yaml", toml: "toml", xml: "xml",
sh: "bash", bash: "bash", ps1: "powershell", bat: "batch",
sql: "sql", graphql: "graphql", proto: "protobuf",
dockerfile: "dockerfile", makefile: "makefile",
};
export function getFileIcon(name: string): { icon: string; cls: string } {
const ext = name.split(".").pop()?.toLowerCase() ?? "";
const icon = EXT_ICONS[ext] ?? "·";
const cls = ext || "file";
return { icon, cls };
}
export function getLanguage(name: string): string {
const ext = name.split(".").pop()?.toLowerCase() ?? "";
return EXT_LANG[ext] ?? ext;
}
function isBinaryExt(name: string): boolean {
const ext = name.split(".").pop()?.toLowerCase() ?? "";
const binary = new Set(["png", "jpg", "jpeg", "gif", "ico", "svg", "woff", "woff2", "ttf", "eot", "mp4", "webm", "mp3", "wav", "zip", "tar", "gz", "7z", "pdf"]);
return binary.has(ext);
}
interface ProjectTreeResult {
tree: TreeNode[];
}
export function useProjectTree() {
const [tree, setTree] = useState<TreeNode[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (MODE === "standalone") {
setLoading(false);
setTree(createDemoTree());
return;
}
let cancelled = false;
api<ProjectTreeResult>("/project-tree")
.then((r) => {
if (!cancelled) {
setTree(r.tree);
setLoading(false);
}
})
.catch((err) => {
if (!cancelled) {
setError((err as Error).message);
setLoading(false);
setTree(createDemoTree());
}
});
return () => { cancelled = true; };
}, []);
return { tree, loading, error };
}
interface FileReadResult {
content: string;
path: string;
size: number;
}
interface FileLoadingState {
[path: string]: boolean;
}
export function useFileTreeState(initialTree: TreeNode[]) {
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const [openFiles, setOpenFiles] = useState<OpenFile[]>([]);
const [activeFilePath, setActiveFilePath] = useState<string | null>(null);
const [loadingFiles, setLoadingFiles] = useState<FileLoadingState>({});
const toggleExpand = useCallback((path: string) => {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(path)) next.delete(path);
else next.add(path);
return next;
});
}, []);
const openFile = useCallback(async (node: TreeNode) => {
if (node.isDir) {
toggleExpand(node.path);
return;
}
if (isBinaryExt(node.name)) return;
const existing = openFiles.find((f) => f.path === node.path);
if (existing) {
setActiveFilePath(node.path);
return;
}
if (loadingFiles[node.path]) return;
setLoadingFiles((prev) => ({ ...prev, [node.path]: true }));
const lang = getLanguage(node.name);
if (MODE === "standalone") {
const mockContent = generateMockContent(node.name, lang);
setOpenFiles((prev) => [...prev, { path: node.path, name: node.name, content: mockContent, language: lang }]);
setActiveFilePath(node.path);
setLoadingFiles((prev) => {
const next = { ...prev };
delete next[node.path];
return next;
});
return;
}
try {
const encodedPath = node.path.split("/").map(encodeURIComponent).join("/");
const data = await api<FileReadResult>(`/file/${encodedPath}`);
setOpenFiles((prev) => [...prev, { path: node.path, name: node.name, content: data.content, language: lang }]);
setActiveFilePath(node.path);
} catch (err) {
console.error(`[file-tree] failed to load ${node.path}:`, err);
setOpenFiles((prev) => [...prev, { path: node.path, name: node.name, content: `// Failed to load file: ${(err as Error).message}\n`, language: lang }]);
setActiveFilePath(node.path);
} finally {
setLoadingFiles((prev) => {
const next = { ...prev };
delete next[node.path];
return next;
});
}
}, [openFiles, toggleExpand, loadingFiles]);
const closeFile = useCallback((path: string) => {
setOpenFiles((prev) => {
const next = prev.filter((f) => f.path !== path);
if (activeFilePath === path) {
const lastFile = next[next.length - 1];
setActiveFilePath(lastFile ? lastFile.path : null);
}
return next;
});
}, [activeFilePath]);
const activeFile = openFiles.find((f) => f.path === activeFilePath) ?? null;
return { expanded, openFiles, activeFilePath, activeFile, toggleExpand, openFile, closeFile, setActiveFilePath, loadingFiles };
}
function generateMockContent(name: string, lang: string): string {
const ext = name.split(".").pop()?.toLowerCase() ?? "";
if (ext === "json") return JSON.stringify({ name: "example", version: "1.0.0", dependencies: { react: "^18.0.0" } }, null, 2);
if (ext === "md") return "# Example Document\n\nThis is a sample markdown file.\n\n## Section\n\n- Item 1\n- Item 2\n\n```js\nconsole.log(\"hello\");\n```";
if (ext === "css") return "/* styles */\n.container {\n display: flex;\n padding: 16px;\n color: var(--fg-1);\n}";
if (ext === "html") return "<!doctype html>\n<html>\n<head><title>Example</title></head>\n<body>\n <h1>Hello</h1>\n</body>\n</html>";
if (ext === "py") return "def hello():\n print('Hello, World!')\n\nif __name__ == '__main__':\n hello()";
if (ext === "yaml" || ext === "yml") return "name: example\nversion: '1.0'\nservices:\n app:\n image: node:18\n ports:\n - '3000:3000'";
return `// ${name}\n// Language: ${lang}\n\nexport function example() {\n return \"Hello from ${name}\";\n}\n`;
}
export function createDemoTree(): TreeNode[] {
return [
{
name: "src", path: "src", isDir: true, children: [
{ name: "index.ts", path: "src/index.ts", isDir: false },
{ name: "app.tsx", path: "src/app.tsx", isDir: false },
{ name: "config.ts", path: "src/config.ts", isDir: false },
{
name: "components", path: "src/components", isDir: true, children: [
{ name: "Header.tsx", path: "src/components/Header.tsx", isDir: false },
{ name: "Sidebar.tsx", path: "src/components/Sidebar.tsx", isDir: false },
{ name: "Button.tsx", path: "src/components/Button.tsx", isDir: false },
]
},
{
name: "lib", path: "src/lib", isDir: true, children: [
{ name: "api.ts", path: "src/lib/api.ts", isDir: false },
{ name: "format.ts", path: "src/lib/format.ts", isDir: false },
]
},
]
},
{
name: "tests", path: "tests", isDir: true, children: [
{ name: "app.test.ts", path: "tests/app.test.ts", isDir: false },
{ name: "utils.test.ts", path: "tests/utils.test.ts", isDir: false },
]
},
{ name: "package.json", path: "package.json", isDir: false },
{ name: "tsconfig.json", path: "tsconfig.json", isDir: false },
{ name: "README.md", path: "README.md", isDir: false },
{ name: "styles.css", path: "styles.css", isDir: false },
{ name: "index.html", path: "index.html", isDir: false },
];
}
-69
View File
@@ -1,69 +0,0 @@
import { t } from "../i18n/index.js";
export function fmtUsd(n: number | null | undefined): string {
if (n === null || n === undefined) return "—";
if (n === 0) return "$0";
return `$${n.toFixed(n < 0.01 ? 6 : 4)}`;
}
/** Keep in sync with src/cli/ui/theme/tokens.ts USD_TO_CNY. */
const USD_TO_CNY = 7.2;
/** USD-internal cost rendered in the wallet's display currency. Undefined currency → CNY (matches CLI default). */
export function fmtCost(
usd: number | null | undefined,
currency: string | null | undefined,
fractionDigits?: number,
): string {
if (usd === null || usd === undefined) return "—";
const cur = currency ?? "CNY";
const amount = cur === "CNY" ? usd * USD_TO_CNY : usd;
if (amount === 0) return cur === "CNY" ? "¥0" : "$0";
const sym = cur === "CNY" ? "¥" : cur === "USD" ? "$" : `${cur} `;
const digits = fractionDigits ?? (Math.abs(amount) < 0.01 ? 6 : 4);
return `${sym}${amount.toFixed(digits)}`;
}
export function fmtPct(n: number | null | undefined): string {
if (n === null || n === undefined) return "—";
return `${(n * 100).toFixed(1)}%`;
}
export function fmtNum(n: number | null | undefined): string {
if (n === null || n === undefined) return "—";
return n.toLocaleString();
}
export function fmtBytes(n: number | null | undefined): string {
if (n === null || n === undefined) return "—";
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;
return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
export function fmtCompactNum(n: number | null | undefined): string {
if (n === null || n === undefined) return "—";
if (Math.abs(n) < 1000) return String(n);
if (Math.abs(n) < 1_000_000) {
const v = n / 1000;
return `${v % 1 === 0 ? v.toFixed(0) : v.toFixed(1)}K`;
}
if (Math.abs(n) < 1_000_000_000) {
const v = n / 1_000_000;
return `${v % 1 === 0 ? v.toFixed(0) : v.toFixed(1)}M`;
}
return `${(n / 1_000_000_000).toFixed(1)}B`;
}
export function fmtRelativeTime(iso: string | number | null | undefined): string {
if (!iso) return "—";
const ms = typeof iso === "number" ? iso : Date.parse(iso);
if (!Number.isFinite(ms)) return "—";
const dSec = (Date.now() - ms) / 1000;
if (dSec < 60) return t("fmt.justNow");
if (dSec < 3600) return t("fmt.minutesAgo", { n: Math.floor(dSec / 60) });
if (dSec < 86400) return t("fmt.hoursAgo", { n: Math.floor(dSec / 3600) });
if (dSec < 30 * 86400) return t("fmt.daysAgo", { n: Math.floor(dSec / 86400) });
return new Date(ms).toISOString().slice(0, 10);
}
-4
View File
@@ -1,4 +0,0 @@
import htm from "htm";
import { h } from "preact";
export const html = htm.bind(h);
-117
View File
@@ -1,117 +0,0 @@
import { useEffect, useState } from "preact/hooks";
import { TOKEN, api } from "./api.js";
type Listener = () => void;
export type DashboardLang = "en" | "zh-CN";
// [dashboardCode, backendCode] — add new languages here.
const LANG_REGISTRY: [DashboardLang, string][] = [
["en", "EN"],
["zh-CN", "zh-CN"],
];
const SUPPORTED = new Set(LANG_REGISTRY.map(([d]) => d));
const TO_BACKEND = new Map(LANG_REGISTRY);
const FROM_BACKEND = new Map(LANG_REGISTRY.map(([d, b]) => [b, d]));
const STORAGE_KEY = "rx.lang";
const listeners: Listener[] = [];
let currentLang: DashboardLang = loadFromStorage() ?? "en";
function loadFromStorage(): DashboardLang | null {
try {
const v = localStorage.getItem(STORAGE_KEY);
if (v !== null && SUPPORTED.has(v as DashboardLang)) return v as DashboardLang;
} catch {
/* private mode */
}
return null;
}
function toBackendLang(lang: DashboardLang): string {
return TO_BACKEND.get(lang) ?? lang;
}
function fromBackendLang(raw: string): DashboardLang {
return (FROM_BACKEND.get(raw) as DashboardLang) ?? "en";
}
/** Adopt server lang on startup; localStorage is render-cache only, never pushed back. */
export async function initLangFromServer(): Promise<void> {
try {
const res = await api<{ lang?: string }>("/settings");
const serverLang = res.lang ? fromBackendLang(res.lang) : null;
if (!serverLang || serverLang === currentLang) return;
currentLang = serverLang;
try {
localStorage.setItem(STORAGE_KEY, serverLang);
} catch {
/* ignore */
}
for (const cb of listeners) cb();
} catch {
/* offline — keep last-known value rendering */
}
}
export function getLang(): DashboardLang {
return currentLang;
}
export function setLang(lang: DashboardLang): void {
if (!SUPPORTED.has(lang)) return;
currentLang = lang;
try {
localStorage.setItem(STORAGE_KEY, lang);
} catch {
/* ignore */
}
for (const cb of listeners) cb();
// keepalive ensures the request completes even during page unload (refresh).
fetch(`/api/settings?token=${TOKEN}`, {
method: "POST",
headers: { "Content-Type": "application/json", "X-Reasonix-Token": TOKEN },
body: JSON.stringify({ lang: toBackendLang(lang) }),
keepalive: true,
}).catch((err) => console.error("[reasonix dashboard] lang persist:", err));
}
export function onLangChange(cb: Listener): () => void {
listeners.push(cb);
return () => {
const i = listeners.indexOf(cb);
if (i >= 0) listeners.splice(i, 1);
};
}
export function useLang(): DashboardLang {
const [lang, setLangState] = useState<DashboardLang>(currentLang);
useEffect(() => onLangChange(() => setLangState(currentLang)), []);
return lang;
}
type Nested = { [k: string]: string | Nested };
function get(translations: Nested | undefined, path: string): string | undefined {
let val: string | Nested | undefined = translations;
for (const part of path.split(".")) {
if (val === undefined || typeof val === "string") return undefined;
val = val[part];
}
return typeof val === "string" ? val : undefined;
}
export function createT(translations: Record<string, Nested>) {
return function t(path: string, params?: Record<string, string | number>): string {
let val = get(translations[currentLang] ?? translations.en, path);
if (val === undefined) val = get(translations.en, path);
if (val === undefined) return path;
if (!params) return val;
let result = val;
for (const [k, v] of Object.entries(params)) {
result = result.replaceAll(`{${k}}`, String(v));
}
return result;
};
}
-90
View File
@@ -1,90 +0,0 @@
import { useState, useCallback } from "preact/hooks";
export interface LineComment {
id: string;
file: string;
lineNumber: number;
content: string;
timestamp: number;
}
export interface LineCommentDraft {
file: string;
lineNumber: number;
content: string;
editingId?: string;
}
export function useLineComments() {
const [comments, setComments] = useState<LineComment[]>([]);
const [draft, setDraft] = useState<LineCommentDraft | null>(null);
const addComment = useCallback((file: string, lineNumber: number, content: string) => {
const id = `comment-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
setComments((prev) => [...prev, { id, file, lineNumber, content, timestamp: Date.now() }]);
setDraft(null);
}, []);
const updateComment = useCallback((id: string, content: string) => {
setComments((prev) => prev.map((c) => (c.id === id ? { ...c, content } : c)));
}, []);
const deleteComment = useCallback((id: string) => {
setComments((prev) => prev.filter((c) => c.id !== id));
}, []);
const startDraft = useCallback((file: string, lineNumber: number) => {
setDraft({ file, lineNumber, content: "" });
}, []);
const editComment = useCallback((id: string, content: string) => {
const comment = comments.find((c) => c.id === id);
if (comment) {
setDraft({ file: comment.file, lineNumber: comment.lineNumber, content, editingId: id });
}
}, [comments]);
const cancelDraft = useCallback(() => {
setDraft(null);
}, []);
const setDraftContent = useCallback((content: string) => {
setDraft((prev) => (prev ? { ...prev, content } : null));
}, []);
const submitDraft = useCallback(() => {
if (draft && draft.content.trim()) {
if (draft.editingId) {
updateComment(draft.editingId, draft.content.trim());
} else {
addComment(draft.file, draft.lineNumber, draft.content.trim());
}
setDraft(null);
}
}, [draft, addComment, updateComment]);
const commentsForFile = useCallback(
(file: string) => comments.filter((c) => c.file === file),
[comments],
);
const commentsForLine = useCallback(
(file: string, lineNumber: number) => comments.filter((c) => c.file === file && c.lineNumber === lineNumber),
[comments],
);
return {
comments,
draft,
addComment,
updateComment,
deleteComment,
startDraft,
editComment,
cancelDraft,
setDraftContent,
submitDraft,
commentsForFile,
commentsForLine,
};
}
-48
View File
@@ -1,48 +0,0 @@
export type IntervalUnit = "s" | "m" | "h";
export interface LoopRunStatus {
prompt: string;
intervalMs: number;
iter: number;
/** Wall-clock ms until the next fire — server reports a remaining duration, not an absolute. */
nextFireMs: number;
}
/** Quick-pick intervals in ms — covers the 95% of cases users actually run. */
export const INTERVAL_PRESETS_MS: ReadonlyArray<{ ms: number; label: string }> = [
{ ms: 30_000, label: "30s" },
{ ms: 60_000, label: "1m" },
{ ms: 5 * 60_000, label: "5m" },
{ ms: 15 * 60_000, label: "15m" },
{ ms: 60 * 60_000, label: "1h" },
{ ms: 6 * 60 * 60_000, label: "6h" },
];
const UNIT_TO_MS: Record<IntervalUnit, number> = {
s: 1_000,
m: 60_000,
h: 60 * 60_000,
};
const MIN_INTERVAL_MS = 5_000;
const MAX_INTERVAL_MS = 6 * 60 * 60_000;
/** Convert a "30" + "s" pair to ms, returning null if out of [5s, 6h]. */
export function parseCustomInterval(value: string, unit: IntervalUnit): number | null {
const n = Number.parseFloat(value);
if (!Number.isFinite(n) || n <= 0) return null;
const ms = Math.round(n * UNIT_TO_MS[unit]);
if (ms < MIN_INTERVAL_MS || ms > MAX_INTERVAL_MS) return null;
return ms;
}
/** Human-friendly "5m 12s" / "12s" / "2h 45m" — shows two largest non-zero units. */
export function formatRemaining(ms: number): string {
const safe = Math.max(0, Math.floor(ms / 1000));
const h = Math.floor(safe / 3600);
const m = Math.floor((safe % 3600) / 60);
const s = safe % 60;
if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`;
if (m > 0) return s > 0 ? `${m}m ${s}s` : `${m}m`;
return `${s}s`;
}
-169
View File
@@ -1,169 +0,0 @@
import hljs from "highlight.js/lib/common";
import { marked } from "marked";
export function escapeHtml(s: unknown): string {
if (s == null) return "";
return String(s)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
const SEARCH_REPLACE_RE = /<{7}\s*SEARCH\s*\n([\s\S]*?)\n={7}\s*\n([\s\S]*?)\n>{7}\s*REPLACE/;
export function renderSearchReplace(search: string, replace: string, file: string): string {
const safeSearch = typeof search === "string" ? search : String(search ?? "");
const safeReplace = typeof replace === "string" ? replace : String(replace ?? "");
const oldLines = safeSearch
.split("\n")
.map((l) => `<span class="diff-line del">- ${escapeHtml(l)}</span>`)
.join("\n");
const newLines = safeReplace
.split("\n")
.map((l) => `<span class="diff-line ins">+ ${escapeHtml(l)}</span>`)
.join("\n");
const header = file ? `<span class="diff-line hunk">▸ edit ${escapeHtml(file)}</span>\n` : "";
return `<pre class="diff-block">${header}${oldLines}\n${newLines}</pre>`;
}
export function renderUnifiedDiff(text: string): string {
const safe = typeof text === "string" ? text : String(text ?? "");
const lines = safe
.split("\n")
.map((l) => {
if (l.startsWith("+++") || l.startsWith("---")) {
return `<span class="diff-line meta">${escapeHtml(l)}</span>`;
}
if (l.startsWith("+")) return `<span class="diff-line ins">${escapeHtml(l)}</span>`;
if (l.startsWith("-")) return `<span class="diff-line del">${escapeHtml(l)}</span>`;
if (l.startsWith("@@")) return `<span class="diff-line hunk">${escapeHtml(l)}</span>`;
return escapeHtml(l);
})
.join("\n");
return `<pre class="diff-block">${lines}</pre>`;
}
const renderer = new marked.Renderer();
renderer.code = function reasonixCode(arg1: unknown, arg2?: string): string {
let text: unknown;
let lang: string | undefined;
if (arg1 && typeof arg1 === "object" && !Array.isArray(arg1)) {
text = (arg1 as { text?: unknown }).text;
lang = (arg1 as { lang?: string }).lang;
} else {
text = arg1;
lang = arg2;
}
if (text == null) text = "";
const codeText: string = typeof text === "string" ? text : String(text);
const sr = SEARCH_REPLACE_RE.exec(codeText);
if (sr) {
const [, search = "", replace = ""] = sr;
const file = typeof lang === "string" && lang.startsWith("edit:") ? lang.slice(5) : "";
return renderSearchReplace(search, replace, file);
}
if (lang === "diff") return renderUnifiedDiff(codeText);
if (lang && typeof lang === "string" && hljs.getLanguage(lang)) {
try {
const h = hljs.highlight(codeText, { language: lang, ignoreIllegals: true }).value;
return `<pre><code class="hljs language-${lang}">${h}</code></pre>`;
} catch {
/* fall through to auto */
}
}
try {
const auto = hljs.highlightAuto(codeText);
return `<pre><code class="hljs">${auto.value}</code></pre>`;
} catch {
return `<pre><code>${escapeHtml(codeText)}</code></pre>`;
}
};
marked.use({ renderer, gfm: true, breaks: false, pedantic: false });
export function renderMarkdownToString(text: string): string {
return marked.parse(text) as string;
}
const LANG_BY_EXT: Record<string, string> = {
ts: "typescript",
tsx: "typescript",
js: "javascript",
jsx: "javascript",
mjs: "javascript",
cjs: "javascript",
py: "python",
rs: "rust",
go: "go",
java: "java",
kt: "kotlin",
c: "c",
h: "c",
cpp: "cpp",
cc: "cpp",
hpp: "cpp",
cs: "csharp",
swift: "swift",
rb: "ruby",
php: "php",
sh: "bash",
bash: "bash",
zsh: "bash",
fish: "bash",
ps1: "powershell",
json: "json",
yaml: "yaml",
yml: "yaml",
toml: "ini",
xml: "xml",
html: "xml",
svg: "xml",
css: "css",
scss: "scss",
less: "less",
md: "markdown",
sql: "sql",
vue: "xml",
svelte: "xml",
tex: "latex",
proto: "protobuf",
dockerfile: "dockerfile",
};
export function langFromPath(path: string | null | undefined): string | null {
if (!path) return null;
const lower = path.toLowerCase();
if (lower.endsWith("dockerfile")) return "dockerfile";
const dot = lower.lastIndexOf(".");
if (dot < 0) return null;
const ext = lower.slice(dot + 1);
return LANG_BY_EXT[ext] ?? null;
}
export function renderHighlightedBlock(text: string, lang: string | null | undefined): string {
if (!text) return "";
const safeLang = lang && hljs.getLanguage(lang) ? lang : null;
try {
const out = safeLang
? hljs.highlight(text, { language: safeLang, ignoreIllegals: true })
: hljs.highlightAuto(text);
return `<pre class="md"><code class="hljs ${safeLang ? `language-${safeLang}` : ""}">${out.value}</code></pre>`;
} catch {
return `<pre><code>${escapeHtml(text)}</code></pre>`;
}
}
export function hlLine(text: string | null | undefined, lang: string | null | undefined): string {
if (text == null) return "";
if (text === "") return "";
try {
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(text, { language: lang, ignoreIllegals: true }).value;
}
return hljs.highlightAuto(text).value;
} catch {
return escapeHtml(text);
}
}
-46
View File
@@ -1,46 +0,0 @@
type SpecRecord = Record<string, unknown>;
function isRecord(value: unknown): value is SpecRecord {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function stringField(obj: SpecRecord, key: string): string | null {
const value = obj[key];
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function stringArgs(obj: SpecRecord): string[] {
const args = obj.args;
if (!Array.isArray(args)) return [];
return args.filter((arg): arg is string => typeof arg === "string" && arg.length > 0);
}
export function normalizeMcpSpec(spec: unknown): string | null {
if (typeof spec === "string") return spec;
if (!isRecord(spec)) return null;
const raw = stringField(spec, "raw") ?? stringField(spec, "spec");
if (raw) return raw;
const name = stringField(spec, "name") ?? stringField(spec, "label");
const command = stringField(spec, "command");
const url = stringField(spec, "url");
const transport = stringField(spec, "transport");
if (name && url) return `${name}=${transport === "streamable-http" ? "streamable+" : ""}${url}`;
if (name && command) return `${name}=${[command, ...stringArgs(spec)].join(" ")}`;
if (command) return [command, ...stringArgs(spec)].join(" ");
return null;
}
export function mcpSpecLabel(spec: unknown): string {
const text = normalizeMcpSpec(spec) ?? "";
const eq = text.indexOf("=");
return eq > 0 ? text.slice(0, eq) : text;
}
export function mcpSpecCommand(spec: unknown): string {
const text = normalizeMcpSpec(spec) ?? "";
const eq = text.indexOf("=");
return eq > 0 ? text.slice(eq + 1) : text;
}
-32
View File
@@ -1,32 +0,0 @@
import { useState, useCallback, useEffect } from "preact/hooks";
import { api } from "./api.js";
export interface FileDiff {
file: string;
additions: number;
deletions: number;
patch?: string;
status: "added" | "deleted" | "modified";
}
export function useReviewDiffs() {
const [diffs, setDiffs] = useState<FileDiff[]>([]);
const [loading, setLoading] = useState(false);
const loadDiffs = useCallback(async (ep: string = "/review-diffs") => {
setLoading(true);
try {
const data = await api<FileDiff[]>(ep);
setDiffs(Array.isArray(data) ? data : []);
} catch {
setDiffs([]);
} finally {
setLoading(false);
}
}, []);
const modifiedFiles = useCallback(() => new Set(diffs.map((d) => d.file)), [diffs]);
const modifiedCount = useCallback(() => diffs.length, [diffs]);
return { diffs, loading, modifiedFiles, modifiedCount, reload: loadDiffs };
}
+21
View File
@@ -0,0 +1,21 @@
const SESSION_PARAM = "session";
export function readSessionFromUrl(): string | null {
if (typeof window === "undefined") return null;
const raw = new URLSearchParams(window.location.search).get(SESSION_PARAM);
if (!raw) return null;
const trimmed = raw.trim();
return trimmed.length > 0 ? trimmed : null;
}
export function writeSessionToUrl(name: string | null): void {
if (typeof window === "undefined") return;
const url = new URL(window.location.href);
if (name && name.trim().length > 0) {
url.searchParams.set(SESSION_PARAM, name);
} else {
url.searchParams.delete(SESSION_PARAM);
}
if (url.href === window.location.href) return;
window.history.replaceState(null, "", url.href);
}
File diff suppressed because it is too large. Load diff
-45
View File
@@ -1,45 +0,0 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { type ApiError, api } from "./api.js";
export interface PollResult<T> {
data: T | null;
error: ApiError | Error | null;
loading: boolean;
refresh: () => Promise<void>;
}
export function usePoll<T = unknown>(path: string, intervalMs = 2000): PollResult<T> {
const [data, setData] = useState<T | null>(null);
const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState(true);
const refresh = useCallback(async () => {
try {
const next = await api<T>(path);
setData(next);
setError(null);
} catch (err) {
setError(err as Error);
} finally {
setLoading(false);
}
}, [path]);
useEffect(() => {
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
const tick = async () => {
if (cancelled) return;
await refresh();
if (cancelled) return;
timer = setTimeout(tick, intervalMs);
};
tick();
return () => {
cancelled = true;
if (timer) clearTimeout(timer);
};
}, [refresh, intervalMs]);
return { data, error, loading, refresh };
}
-15
View File
@@ -1,15 +0,0 @@
/** Pre-release with same core sorts BELOW the bare version — matches npm `latest` dist-tag semantics. */
export function compareVersions(a: string, b: string): number {
const [aCore = "0", aPre = ""] = a.split("-", 2);
const [bCore = "0", bPre = ""] = b.split("-", 2);
const aParts = aCore.split(".").map((p) => Number.parseInt(p, 10) || 0);
const bParts = bCore.split(".").map((p) => Number.parseInt(p, 10) || 0);
for (let i = 0; i < 3; i++) {
const diff = (aParts[i] ?? 0) - (bParts[i] ?? 0);
if (diff !== 0) return diff;
}
if (!aPre && !bPre) return 0;
if (!aPre) return 1;
if (!bPre) return -1;
return aPre < bPre ? -1 : aPre > bPre ? 1 : 0;
}
Loaded 100 of 1030 files, more files were not shown because too many files have changed in this diff. Show more