Compare commits

...
334 Commits
Author SHA1 Message Date
YHHandtest 157d6a90c9 fix(release): make sync-desktop-version idempotent (#889)
The CI sync step failed on v0.43.0 because the release commit had
already bumped Cargo.toml to the target version. The old guard fired
on `nextCargo === cargoToml` — true both when the regex didn't match
AND when the value was already correct. Switch to checking whether
the version line exists at all; re-syncing to the same value is
legitimate.

Co-authored-by: test <[email protected]>
2026-05-15 12:06:10 +08:00
YHHandtest 5fe0911ba6 release: 0.43.0 — desktop client GA + subagent pause/resume + skill max-iters (#888)
Headline release notes in CHANGELOG.md.

- Desktop client graduates from prerelease — installer pipeline hardened
  via v0.42.0-* (signed Win, signed+notarized macOS, Linux deb/AppImage,
  bundled Node sidecar, R2 mirrors, GH Pages landing).
- Subagent loop: pause/resume, iter cap 32 → 256 as checkpoint cadence
  (not a budget). partial_summary surfaces in paused result.
- Skills: max-iters frontmatter knob; /skill arg picker autocompletes.
- CLI: --profile <path> writes a V8 CPU profile for perf bug reports.
- TUI: context-usage pill in status row.
- Web: landing + download site live on docs/ via GH Pages.
- i18n: settings UI, dashboard tool descriptions, residual hardcoded
  strings — full sweep.
- ~20 desktop UX fixes (HiDPI clamp, @-mention drag-drop, font scale
  + family pickers, theme toggle, skill-running indicator, memory
  panel mid-turn refresh, plan-checkpoint dashboard modal, several
  keyboard / pause-state regressions caught in the field).
- Removes 0.41.0's ReadOnlyLoopTracker (auto-escalate on read-only
  sequences fired on legitimate skim reads).

Co-authored-by: test <[email protected]>
2026-05-15 11:57:46 +08:00
YHHandtest e6f021b120 feat(desktop): visible "skill running" indicator while a user skill executes (#884)
Today a skill_run dispatches via the palette and the user sees nothing
until the assistant response streams — no signal that "a skill kicked
this off" vs "a regular long turn." Closes #882.

Add two surfaces, both driven by client-side state (no protocol
churn):

1. Live status row — `InterruptBar` now reads `state.activeSkill` and
   labels itself `Skill · <name>` instead of `Reasoning` for the
   duration of the turn, with the same elapsed timer + esc-to-stop
   affordance.

2. User-message card chip — the synthetic user card injected by
   `start_skill` carries a `skill: { name, runAs }` field. `UserMsg`
   renders a warning-toned `/name` chip in the header (plus a
   subagent micro-badge when `runAs === "subagent"`).

State:
- `activeSkill: SkillOrigin | null` on `State`; set by `start_skill`,
  cleared on `$turn_complete`, `clear`, `$session_loaded`, `error`,
  and `rpc_exit`.
- `start_skill` action also pushes a user-card row tagged with the
  skill, so the thread now shows `/skillname` instead of being silent
  until the assistant replies.

No backend changes — `$turn_complete` is the natural cleanup signal,
no new event types needed.

Co-authored-by: test <[email protected]>
2026-05-15 11:42:53 +08:00
YHHandtest f074b8a390 fix(desktop): normalize workspace path for session sidebar filter (#883)
The sidebar's per-workspace session filter compared paths via strict
`===` against `meta.workspace`. On Windows that's fragile — drive
letter case, separator style (`\` vs `/`), and trailing slashes drift
between session writes and reads, so yesterday's sessions silently
disappeared from today's sidebar even though the .jsonl files were
still on disk.

Add `normalizeWorkspace` that resolves and canonicalizes the path
before comparison (forward-slash separators, lowercase drive letter
on win32). Apply on both sides of the filter so sessions whose meta
was written before this fix recover automatically — no migration
needed.

Sessions with no `meta.workspace` stay hidden, same as before;
resume by name still works.

Closes #878

Co-authored-by: test <[email protected]>
2026-05-15 11:23:26 +08:00
YHH 1f7ea48bee fix(desktop): surface user skills in the / autocomplete popup (#881)
The slash command popup hard-coded 9 built-in actions and never
folded in the user's `~/.reasonix/skills` and `.reasonix/skills`
entries — typing `/myskill` produced "no matches" even though the
skill loaded fine and showed up in the Skills tab. Skills also had
no execution path on the desktop side at all: `user_input` ships
text straight to the model loop, so a typed `/skill_name` reached
the model as plain text rather than triggering the skill.

- Add a `skill_run` RPC to the desktop protocol.
- Bridge handler resolves the skill via `SkillStore`, builds the
  same `# Skill: <name>\n> <desc>\n\n<body>` payload the CLI uses,
  and feeds it through `runTurn` so the skill enters the
  conversation as user-authored content.
- `App.tsx` merges `state.skills` into `slashCommands` so each
  user-authored skill shows up in the popup with its description
  and an invocation handler that fires `skill_run`.

Issue #854 also asked for a "skill is running" indicator. That's a
separate UX surface (status row / live row) and lands separately.

Closes #854 (autocomplete half) — follow-up issue for the indicator.
2026-05-15 11:17:44 +08:00
YHHandtest e949b804ab fix(dashboard): plans API timed out on users with many sessions (#880)
`/api/plans` walked every session via `listSessions()` (which calls
`countLines()` on every `.jsonl`) and then `listPlanArchives(name)`
per session (which re-scanned the same directory each time). On a
real developer machine with hundreds of sessions and large JSONL
files the handler ran past the 5s test timeout and got flagged in
CI as flaky.

Replace the per-session loop with a single dir-scan helper —
`listAllPlanArchives()` in `plan-store.ts` — that derives the
session name from the archive filename. The dashboard plans
handler now does O(N) work over plan-archive files instead of
O(sessions × archives) over the full session corpus.

Confirmed locally: full test suite drops from intermittent timeouts
to consistently green.

Co-authored-by: test <[email protected]>
2026-05-15 11:13:06 +08:00
YHHandtest e1106f0731 feat(desktop): font family picker, language picker, and fill missing i18n keys (#879)
Two follow-ups to #877 plus a long-standing typecheck cleanup:

Font family — sans / system / serif segmented control under appearance.
Driven by a new `--font-sans` CSS variable on the root element;
styles.css and the inline `IBM Plex Sans` reference in App.tsx now
read through `var(--font-sans, ...)`. Mono is left hardcoded so code
blocks and transcripts stay monospace either way.

Language — promote the existing `/lang` palette command into a 中文 /
English segmented control in the same section. Reads `useLang()` and
writes through `setLang()`; the slash command keeps working.

i18n cleanup — add the long-missing `contextPanel`, `extraCards`,
and `thread` namespaces (en + zh-CN). These keys were referenced in
code but absent from the dictionaries, surfacing as 8 TKey errors in
every `tsc --noEmit` run.

All settings persist in localStorage like theme and font-scale.

Co-authored-by: test <[email protected]>
2026-05-15 10:53:23 +08:00
YHH c8c21aba12 feat(desktop): font scale setting + always show API key/base URL in general settings (#877)
The API key + base URL inputs in settings were gated behind
`settings.baseUrl !== undefined` — so first-time users with no base
URL set never saw the inputs and couldn't change them from the UI.
Drop the guard; show the section whenever general is the active page.

Add a font-scale setting (small / medium / large) next to the theme
toggle. Persists in localStorage like theme, applies via
`document.documentElement.style.zoom` so every px-based size scales
without a CSS rewrite. Three presets — 0.875× / 1.0× / 1.125× —
cover the common high-DPI / cramped-display asks without a free-form
slider.
2026-05-15 10:35:04 +08:00
YHH a68af293a6 fix(tui): strip bidi + zero-width controls from pasted text (#876)
* fix(slash): /help hanging-indent wrap + fill btw/search-engine zh-CN keys

`/help` rendered broken on zh-CN: CJK summaries are double-wide so
long descriptions overflowed the terminal width and the continuation
landed at column 0, breaking the visual column alignment of the
command list. Two zh-CN entries (`btw`, `search-engine`) were also
missing, falling back to the hardcoded English summary even under
the Chinese locale.

- renderRow now wraps the description with `wrapToCells` (grapheme-
  safe, accounts for visual width) and hangs continuation lines at
  column 32 (2 indent + 28 name + 2 gap). Width budget matches the
  info card's BODY_LEFT_CELLS=7 chrome.
- Add zh-CN + EN entries for `slash.btw.description` and
  `slash.search-engine.description`.
- New regression test asserts every SLASH_COMMANDS entry has both an
  EN and a zh-CN `slash.<cmd>.description` key.

Closes #865

* fix(tui): strip bidi + zero-width controls from pasted text

A clipboard payload from a browser (e.g. copying a Bilibili tab title)
can carry bidi overrides (RLE/PDF/isolates), zero-width spaces, BOMs,
and soft hyphens. These render as 0 cells but still occupy buffer
offsets, so the composer's cursor and line-split math drift —
characters appear hidden, overlaid, or "lost" after submit.

Add `sanitizePasteText` and apply it at the paste dispatch in
`StdinReader.handleChunk`. The strip set covers bidi controls (LRE
through RLO, LRM/RLM, FSI/PDI), ZWSP, WJ, soft hyphen, BOM. ZWJ /
ZWNJ / variation selectors / combining marks are deliberately
preserved so emoji sequences and accented letters keep their semantics.

Closes #849
2026-05-15 10:23:47 +08:00
YHH 9ea2f874d9 fix(slash): /help hanging-indent wrap + fill btw/search-engine zh-CN keys (#875)
`/help` rendered broken on zh-CN: CJK summaries are double-wide so
long descriptions overflowed the terminal width and the continuation
landed at column 0, breaking the visual column alignment of the
command list. Two zh-CN entries (`btw`, `search-engine`) were also
missing, falling back to the hardcoded English summary even under
the Chinese locale.

- renderRow now wraps the description with `wrapToCells` (grapheme-
  safe, accounts for visual width) and hangs continuation lines at
  column 32 (2 indent + 28 name + 2 gap). Width budget matches the
  info card's BODY_LEFT_CELLS=7 chrome.
- Add zh-CN + EN entries for `slash.btw.description` and
  `slash.search-engine.description`.
- New regression test asserts every SLASH_COMMANDS entry has both an
  EN and a zh-CN `slash.<cmd>.description` key.

Closes #865
2026-05-15 10:20:05 +08:00
YHH 4032bd0ee7 fix(desktop): gate per-tab keyboard shortcuts on active so background tabs don't react (#874)
Every TabRuntime stays mounted (display:none on the inactive ones) and
each registers its own window-level keydown listener. Without an
`active` gate Cmd+N fires `newChat()` in every tab — both clear their
state, so the inactive tab's sidebar suddenly shows no active session
and any in-flight turn is aborted. The same path catches Cmd+L, Cmd+O,
Cmd+, and Escape-while-busy.

`useCommandPalette` had the same shape, so Cmd+K toggled every tab's
palette in parallel.

Add `active` to both listeners; only attach on the visible tab.
2026-05-15 10:11:22 +08:00
YHH e5e8779ce8 fix(desktop): catch unknown PauseKind to prevent silent agent-loop hangs (#873)
The pauseGate listener's if-chain in desktop.ts had no default
branch. Any new PauseKind added to pause-gate.ts without a matching
handler here would be silently dropped — the gate request stays
pending forever and the agent loop hangs waiting on a response that
never arrives, with no visible signal to the user.

Add a `never` cast at the end of the chain so a new kind without a
handler is a compile error, plus a runtime stderr warning + auto-
cancel via `pauseGate.cancel()` as the last-mile defense if a build
ever slips past the typecheck.
2026-05-15 10:02:34 +08:00
YHH b84d944fa5 fix(tui): drop ESC-stripped SGR mouse reports instead of inserting them (#872)
ConPTY occasionally strips the leading ESC off CSI sequences. Mouse
reports — `\x1b[<btn;col;rowM/m` — then arrive in the byte stream as
`[<btn;col;rowM/m`, slip past the escapeless-CSI lookahead (which only
knows arrow / page tails), and fall into the printable accumulator. The
composer receives the literal SGR text and the user has to backspace
through every wheel nudge.

Add `tryEscapelessSgrMouse` alongside the existing escapeless-paste and
escapeless-arrow guards. Recognised reports dispatch the same
mouseScroll/Click/Drag/Release events the with-ESC path already emits;
unmapped buttons are consumed and dropped. Share `decodeSgrMouseBody`
with `dispatchCsi` so both paths surface the same shape.

Closes #867
2026-05-15 09:56:11 +08:00
Orchard f014a3204c chore(desktop): surface theme toggle in settings, deduplicate settings entry point (#852) 2026-05-15 09:44:38 +08:00
YHH 941a6e4c7b fix(loop): preserve skill bodies verbatim across context fold (#871)
Without this, the fold summarizer paraphrased inline skill bodies into
prose. Past the fold threshold the model lost the explicit step-by-step
paradigm and drifted back to generic tool-thrashing mid-skill — visible
as the activity row flickering between error and thinking glyphs.

run_skill wraps its inline result in a <skill-pin name="..."> sentinel.
ContextManager.fold extracts every pinned block from the head before
summarizing, stubs the original tool message so the summarizer doesn't
paraphrase it, and re-attaches the bodies verbatim to the synthesized
assistant message. Repeat invocations dedupe by name; last one wins.
2026-05-15 09:44:25 +08:00
ForeverYoungPp d545e064c7 chore(loop): drop ReadOnlyLoopTracker — remove read-only loop auto-escalation (#681) (#860)
Remove the feature that auto-escalated flash→pro after 8 consecutive
  read-only tool calls without a write. Deleted:
  - src/loop/read-only-loop-tracker.ts (entire file)
  - All references in src/loop.ts (import, field, init, method, call site)
  - 3 related test cases in tests/loop.test.ts
  - i18n keys readOnlyLoopEscalation in EN.ts, zh-CN.ts, types.ts
2026-05-15 09:29:49 +08:00
wul7chaosN bc75e09573 feat(i18n): translate dashboard tool descriptions to zh-CN (#858) 2026-05-14 23:40:31 +08:00
YHH 30bed64aab fix(loop): yield reasoning before content so transition chunks don't fragment (#859) 2026-05-14 23:37:21 +08:00
esengine cfd9db28d1 fix(desktop): composer-foot overflows on narrow center column
Reported in #855 (v0.42.0-3 on Windows): with both side and context
panels open at moderate window widths, the composer footer (commands /
mention / Review-Auto-YOLO / model pill / send) extends past the
textarea's right edge and gets clipped by the right panel.

Root cause was the responsive rules collapsing labels and shrinking the
model pill keyed off viewport `max-width`, so a wide window with both
panels open never tripped them even though the actual composer column
was narrower than the no-panel case.

Switch to container queries against `.composer-inner` (now an
`inline-size` container named `composer`) so the same thresholds fire
on the column's own width regardless of which panels are open.
2026-05-14 08:21:31 -07:00
Evan-Pycraft bf5db976e4 feat(i18n): extract residual hardcoded CLI + desktop strings into the i18n system (#850) 2026-05-14 22:36:58 +08:00
esengine 06bae63a6f docs: repoint configuration.html CTAs to the new in-site pages
#848 added docs/architecture.html and docs/cli-reference.html but
left configuration.html's two "Architecture deep dive" / "CLI
reference" CTAs aimed at GitHub blob URLs — so the bouncing-out
behavior issue #623 was filed against still happens from that page.
Swap the two hrefs to the local pages and drop the now-irrelevant
target/rel attributes.
2026-05-14 07:26:14 -07:00
Dimas D. Angga dc33ef6b29 docs: render CLI reference and architecture pages in-site (#848)
Closes #623
2026-05-14 22:25:27 +08:00
YHH d7666c89eb fix(cli): flush profile before useQuit's process.exit so --profile actually writes (#847)
* fix(cli): await profile stop inside the action so the .cpuprofile actually lands

beforeExit async handlers aren't awaited by Node, and while the
inspector Session is connected the loop never empties anyway — on
Ctrl+C the process tore down before V8 flushed the profile, and the
writeFileSync never ran. Reproducer: --profile a TUI session, exit,
no file appears.

Moves stop+save into the commander action's try/finally so it runs
inside the explicit await chain. Ink's exitOnCtrlC resolves
waitUntilExit(), then finally awaits stopAndSaveCpuProfile() before
the action returns — Node then exits naturally with the inspector
session already disconnected.

While here: gzip the output and print drop-into-GitHub instructions
on save. Real .cpuprofiles are 5-20 MB raw, gzipped they fit inside
GitHub's 10 MB comment-attachment limit.

* fix(cli): flush profile before useQuit's process.exit so --profile actually writes

PR #846 set up --profile but no file landed on Ctrl+C from `reasonix
code`. Root cause was deeper than the commander-action try/finally:
the TUI's useQuit calls `process.exit(0)` directly (intentionally —
the singleton stdin reader would otherwise hang the terminal), which
skips the whole await chain. waitUntilExit() never resolves, the
action's finally never runs, V8 buffer drops on the floor.

Hooks the stop+save into the two TUI quit paths that call
process.exit:

- src/cli/ui/hooks/useQuit.ts (Ctrl+C / SIGINT) — awaits
  stopAndSaveCpuProfile() before process.exit(0).
- src/cli/commands/chat.tsx:187 (session-picker quit) — same.

stopAndSaveCpuProfile is a no-op when --profile isn't active so the
TUI's normal quit path adds nothing.

Refs #843.
2026-05-14 20:34:09 +08:00
YHH aa55552dd6 feat(cli): --profile flag records a V8 CPU profile for perf bug reports (#846)
Adds `--profile [path]` to `reasonix code` and `reasonix chat`. Starts a
V8 CPU profile on launch via node:inspector/promises, saves the
.cpuprofile to the given path (or cwd with a timestamped default) when
the process exits. Stops on SIGINT/SIGTERM/SIGHUP and on natural exit
via `beforeExit`.

Reason: #843-style perf reports come in vague ("卡了"). A real .cpuprofile
from the user's actual terminal + workload is the only way to tell
CPU-bound from terminal-emulator-bound. Profiling synthetic harnesses
on my box keeps showing 98%+ idle, so the bottleneck is elsewhere; this
flag lets users send back the actual evidence.

Bundles two reusable harnesses + an analyzer under scripts/perf/:
profile-tui-streaming.tsx (throttled, mimics real streaming),
profile-tui-sync.tsx (synchronous, measures raw reducer+commit), and
analyze-cpu-prof.mjs (top-N self/total with idle excluded).
2026-05-14 20:16:20 +08:00
YHH 44a266c15c perf(desktop): memoize message list so historical messages skip re-renders (#844) (#845)
Long conversations on the desktop got laggy because every streaming
chunk re-rendered the whole `state.messages.map(...)` tree. Each
historical `<AssistantMsg>` re-ran `<Markdown>` → `<ReactMarkdown>` +
`remark-gfm` on text that hadn't changed. At 50+ turns the per-chunk
cost stacked into thousands of redundant markdown parses per second.

- `UserMsg`, `AssistantMsg` (`desktop/src/ui/thread.tsx`) — wrapped
  in `React.memo`.
- `AssistantText` (`desktop/src/ui/cards.tsx`), `Markdown`
  (`desktop/src/Markdown.tsx`) — same.
- The three approval callbacks (`onApproveConfirm`, `onRejectConfirm`,
  `onAlwaysAllowConfirm`) were minted inline at the `<AssistantMsg>`
  call site on every render, defeating the memo's shallow compare.
  Hoisted them to stable `useCallback` refs.

The TUI and dashboard already have this memo discipline
(`src/cli/ui/cards/CardRenderer.tsx:26` and
`dashboard/src/components/chat-internals.ts:308`), so no changes
there.

Closes #844
Refs #843
2026-05-14 19:50:37 +08:00
YHH a924d8f7d6 feat(desktop): localize settings UI, add language picker, sync <html lang> (#841) (#842)
The desktop already had the full i18n machinery (en.ts / zh-CN.ts /
t() / useLang() / localStorage + browser autodetect) and most chrome
went through it, but three holes made the panel unusable for English
users:

- Settings UI was entirely hardcoded Chinese — side nav, page bodies,
  API-key section, shortcuts list — none of it touched t().
- The Language / langEn / langZhCn keys existed in both dictionaries
  but were never referenced; switching language required knowing the
  /lang slash command.
- index.html shipped a static `<html lang="zh-CN">`, so screen
  readers and `:lang()` CSS selectors saw Chinese regardless of UI
  language.

Adds a Language section to PageGeneral with en / zh-CN buttons,
routes every visible string in settings.tsx through t(), and pushes
`document.documentElement.lang` from the i18n module on load + on
setLang. index.html ships `lang="en"` as a neutral fallback; the
runtime overrides it from getLang() before paint.

Each Page* component pulls useLang() so language changes re-render
immediately without closing/reopening the modal.

Closes #841
2026-05-14 19:32:06 +08:00
YHH 474c27233f fix(dashboard): broadcast plan-checkpoint pause so the web UI shows the modal (#832) (#840)
The agent emits a `plan_checkpoint` pause request after each completed
step. The TUI handled it by setting `pendingCheckpoint` and rendering
the local Continue / Revise / Stop card, but the dashboard side was
silent — the broadcast effect that mirrors plan / edit-review /
revision modals over SSE had no checkpoint case. From the user's
perspective the web UI just froze: the model was waiting on a button
the page never rendered.

Also adds the missing branch to `getActiveModal` so a dashboard that
connects mid-checkpoint replays the modal instead of starting blank.

The dashboard modal component (`CheckpointModal`), the resolve route
(`/api/modal/resolve` with `kind: "checkpoint"`), and the App-side
`resolveCheckpointConfirm` resolver were already in place — only the
broadcast was missing.

Closes #832
2026-05-14 19:18:21 +08:00
YHH 1fc41bbe71 feat(subagent): include partial_summary in paused result (#838) (#839)
When a subagent yielded `paused`, the parent agent had no signal about
what was actually done — only the resume token and an iter count. That
forced the orchestrator to either resume blindly or accept partial
work blindly, defeating the point of pause-as-checkpoint.

Adds one no-tools call (`summarizePartialProgress`, pinned to flash
+ effort=high) before yielding `paused`. The call returns 3-6
sentences of progress / remaining / blockers, attached to the paused
event as `partialSummary`. Subagent JSON now surfaces it as
`partial_summary`.

The summary is NOT persisted to session messages — the resumed child
picks up clean state. Failure is non-fatal: pause still works, the
parent just gets the old opaque shape back.

Closes #838
2026-05-14 19:06:55 +08:00
YHH 50691f11f2 feat(tui): context-usage pill in status row (#828) (#837)
Adds a context-fill indicator to the bottom status row so the user can
tell at a glance how close the current prompt is to the model's
context window — same role claude-dashboard plays for Claude Code.

Rendered as `ctx 72%` by default, `ctx 72% · 144K/1M` at ≥90 cols,
and `ctx ████░░░░ 72% · 144K/1M` at ≥110 cols. Tier-colored: green
under 50%, amber 50–80%, red ≥80%.

Plumbed via the existing `turn.end` event (already carries
`usage.prompt` + optional `promptCap`); cap falls back to the model's
entry in DEEPSEEK_CONTEXT_TOKENS, then to DEFAULT_CONTEXT_TOKENS.
Opt-out lives next to the other status-row toggles
(`statusBar.showCtxUsage` in user config).

Closes #828
2026-05-14 18:52:43 +08:00
YHH 10dc6dae72 perf(desktop): paint UI shell before buildCodeToolset finishes (#836)
`desktopCommand` awaited `buildCodeToolset` inside `createTab` before
emitting ANY event. That bundled semantic bootstrap, MCP probes,
tokenizer cold-load, and runtime construction into 1.5–3s of dead
time during which the Tauri window had nothing to render — feels
much slower than the web dashboard (which piggybacks on an already-
warm CLI process).

Split into a synchronous skeleton + async toolset init:

- `createTabSkeleton(dir)` — sets `toolset: null`, `runtime: null`,
  `system: ""`. Returns instantly.
- `initTabToolset(tab)` — awaits `buildCodeToolset`, fills in
  `tab.toolset` / `tab.system`, builds the runtime if an API key is
  present, bridges MCP in the background.

Boot path fires `$tab_opened`, `$sessions`, `$settings`, `$mcp_specs`,
`$skills`, `$memory`, `$needs_setup?`, `$balance` IMMEDIATELY (all
disk-only or fire-and-forget). `initTabToolset` runs concurrently
and emits `$ready` + `$ctx_breakdown` on completion. UI's
`disabled={!state.ready}` keeps the composer locked until then —
existing safety, no new gate needed.

Subtler bits:
- `Tab.toolset` is now `Toolset | null`; the few hot paths that
  touch it (`buildRuntimeFor`, `bridgeTabMcp`, `closeTab`,
  `switchWorkspace`, settings-save preset change) gain a null guard.
  `buildRuntimeFor` keeps an explicit "called before init" throw —
  callers that need a runtime were already gated on `tab.runtime`.
- `setup_save_key` now tolerates a still-bootstrapping tab: skip
  the `buildRuntimeFor` branch, `initTabToolset`'s tail reads
  `loadApiKey()` after the new key was persisted and constructs the
  runtime there.
- `tab_open` (multi-tab) follows the same skeleton + lazy-init shape.

P0 from the desktop perf analysis; P1 (semantic / MCP lazy-load
inside `buildCodeToolset`) and P2 (Tauri-side splash before Node
spawn) stay separate.
2026-05-14 18:37:49 +08:00
YHH 2a72b0c7d8 fix(desktop): clamp the initial window to fit HiDPI / small monitors (#833)
The default 1024×720 logical-px window doesn't fit on a Windows
laptop at 200% scaling (1920×1080 panel → 960×540 effective logical
space): the window opens partially off-screen, the user has to drag
or resize to see the right edge / bottom rows. The minWidth=640 /
minHeight=400 floor also locked out 1366×768 @ 200% setups entirely
(683×384 effective).

Fix:
- main.rs setup hook: query the current monitor's logical size,
  clamp the window to 90% of available when 1024/720 overflows,
  then recenter.
- tauri.conf.json: drop minWidth → 480, minHeight → 320 (still
  comfortable on a normal display, lets the window actually meet
  its minimum on tight HiDPI setups). Add `center: true` so the
  window is centered on first launch.

The normal-DPI case (no overflow) is unchanged: the clamp branch
only fires when the configured size doesn't fit the monitor.

Refs #827.
2026-05-14 18:21:02 +08:00
YHH 4366860245 chore(desktop): drop the fake traffic-light dots from the titlebar (#830) (#831)
The three coloured dots (red / yellow / green) in the top-left of
the titlebar were pure decoration — no onClick handlers, no Tauri
window-API wiring, just `<span>`s styled to look like macOS
traffic-light buttons. Users (rightly) clicked them expecting
close / minimize / maximize and got nothing. Remove the markup, the
matching `.traffic` / `.dot` CSS, and the now-redundant `margin-left`
on `.brand` that compensated for the removed block.

Native window chrome handles min / max / close on every OS we ship to.
2026-05-14 17:59:52 +08:00
YHH 410afd80d2 chore(desktop): drop the fake traffic-light dots from the titlebar (#830)
The three coloured dots (red / yellow / green) in the top-left of
the titlebar were pure decoration — no onClick handlers, no Tauri
window-API wiring, just `<span>`s styled to look like macOS
traffic-light buttons. Users (rightly) clicked them expecting
close / minimize / maximize and got nothing. Remove the markup, the
matching `.traffic` / `.dot` CSS, and the now-redundant `margin-left`
on `.brand` that compensated for the removed block.

Native window chrome handles min / max / close on every OS we ship to.
2026-05-14 17:46:43 +08:00
YHH e16dc35659 fix(desktop): refresh the memory panel mid-turn after remember / forget (#829)
The right-hand memory panel only got an `\$memory` event on tab open
— so when the agent called `remember` (or `forget`) mid-turn the
file was written to disk but the panel stayed on the prior list
until the user reopened the tab.

Re-emit `\$memory` from the turn loop whenever a `remember` /
`forget` tool event flows past. Same shape as how we re-emit
sessions / balance on turn complete; just on the tool boundary
instead so the UI sees the new entry the moment it's written.
2026-05-14 17:34:43 +08:00
YHH 7854afd00f feat(desktop): @-mention UX — drag-drop, tree picker, file-index TTL (#826)
* fix(desktop): expire the @-mention file index after 10s

The file index cached at tab construction lived for the lifetime of
the tab — files deleted, renamed, or added inside the workspace never
showed up (or refused to disappear) in the @ picker. #816 reported
this on the desktop client.

Add a 10s TTL: the next @ query past that window triggers a rebuild.
Balances "fresh enough for edit-then-mention flows" against scanning
5000 files on every keystroke.

* feat(desktop): tree-style @ picker — bare @ shows workspace top level

Bare @ in the desktop composer used to flood the popup with a flat
fuzzy match across all 5000 files in the workspace. Mirrors the TUI's
@+Tab pattern: empty query lists the workspace root's top-level
entries, and Tab on a directory item enters it (replaces `@src` with
`@src/` and re-queries to show that directory's children). Enter on
a directory still picks the directory itself.

Backend side (mention_query treeWalk branch) landed in the previous
commit on this branch as part of the desktop.ts change set.

Part of #816.

* feat(desktop): drag-and-drop files / folders → @-mention

Files dragged onto the Reasonix desktop window now append as
@-mentions in the draft. Paths inside `workspaceDir` are normalised
to relative; everything else passes through as absolute. While the
drag is over the window, an overlay shows "Drop to attach as
@-mention" so the user knows we'll accept it.

Tauri 2's webview `onDragDropEvent` provides the path list — uses
the standard {enter, over, drop, leave} state machine, no native
plugin needed.

Part of #816.
2026-05-14 17:23:52 +08:00
YHH 5a24ddd23d fix(dashboard): swallow third-party-origin errors in the global overlay (#825)
The dashboard installs `window.addEventListener("error", ...)` and
`unhandledrejection` to surface app crashes through the error overlay.
Both handlers forwarded unconditionally — so when a user's browser ran
an ad-blocker userscript that threw `require is not defined`, the
overlay caught it and prompted the user to file an issue against
*us*. #818 is exactly that: a `ReferenceError` from
`chrome-extension://…/userscript.html?name=屏蔽广告…`, nothing to do
with the dashboard.

Filter by origin: if the error's stack or the ErrorEvent's filename
contains `chrome-extension://`, `moz-extension://`,
`safari-web-extension://`, `safari-extension://`, or
`ms-browser-extension://`, skip reporting. The error still propagates
to `console.error` via the browser's default behavior; we just don't
treat it as ours.

Closes #818
2026-05-14 17:04:13 +08:00
YHHandrokyplay 2284d32aa5 fix(code): honor the configured preset instead of hardcoding flash (#824)
`reasonix code` was passing `opts.model ?? "deepseek-v4-flash"` into
chatCommand + the system-prompt builder, so a user with preset=pro or
preset=auto in their config was silently downgraded to flash. Resolve
the preset (`loadPreset()` → `resolvePreset()`) and use its model id
instead — mirrors the same fix #819 landed on the desktop path.

Original implementation by @rokyplay in #820; cherry-picked here as a
standalone fix so it can land independently of the typeahead/steer
work in that PR.

Co-authored-by: rokyplay <[email protected]>
2026-05-14 16:54:07 +08:00
J3y0r 2e63d598de fix(cli): route bare project launches to code mode (#812)
* fix(cli): route bare project launches to code mode

Detect project-like working directories for bare reasonix invocations so filesystem tools are rooted at cwd, while preserving explicit chat and first-run setup behavior.

* fix(test): import React for plan confirm tests
2026-05-14 16:45:12 +08:00
YHH 4c654d0c9c feat(subagent): pause/resume + drop iter cap (checkpoint cadence, not budget) (#823)
Reframes subagent iters from "hard budget" to "checkpoint cadence":
the subagent yields a `paused` event when its per-window iter count
runs out, the parent decides to either accept the partial state or
call spawn_subagent again with `resume_session` to continue. Total
iters bounded only by parent's own budget + natural termination.

Built on the existing session-persistence layer — pause leaves
messages on disk, resume reloads them. Prompt-cache prefix is
byte-stable across pauses so resumption is essentially free.

Validated end-to-end against the real DeepSeek API: phase 1 spawns
with max_iters=2, subagent pauses with a resume_session; phase 2
resumes with that token, subagent completes the remaining 8 of 10
topics in the new window.

What changed:
- loop.ts + loop/types.ts: new onIterBudgetExhausted option
  (default "summarize" for top-level chat, "pause" for subagents);
  pause yields a `paused` LoopEvent role with the session name.
- subagent.ts:
  - Child loop runs with onIterBudgetExhausted=pause + minted
    session subagent-<runId>-<ts>.
  - SubagentResult gains paused / pausedSession.
  - formatSubagentResult on pause emits {success:false, paused:true,
    resume_session, note} — the note teaches the parent how to
    resume in-band.
  - spawn_subagent JSON arg gains resume_session; max_iters loses
    minimum/maximum (no clamp).
  - MIN/MAX/DEFAULT_MAX_ITERS gone; one internal DEFAULT_PAUSE_EVERY
    = 16. clampMaxIters → parseMaxIters (no clamp).
  - On resume, prepend a one-line nudge to the user task so the
    model doesn't read lingering "finalize NOW" hints from the
    previous window as still in force.
- skills.ts: frontmatter max-iters no longer clamped at a cap;
  values below 1 still fall back. Doc rewritten as pause cadence.

PR #822 widened the cap 32 → 256 as a measurement step. Real-API
probes showed the model picks sensible values across task sizes —
confirming the cap was theater. This PR removes the cap entirely
and replaces it with a mechanism that scales with whatever the
work actually needs.

Closes #783
2026-05-14 16:36:26 +08:00
YHH d3cc598acf fix(subagent): raise iter cap 32 → 256 (validated against real API) (#822)
* experiment(subagent): widen iter cap 32 → 256, add telemetry to evidence model picks

Goal: empirically test whether the model picks pathological values for
`max_iters` (the kind we worried about — 1 or 9999) when given a much
wider range. If real workloads consistently land in a sensible band
(say 5-64), the cap was always theater and the next PR can remove it.

Changes:
- `subagent.ts` MAX_MAX_ITERS 32 → 256; tool description updated to
  match. MIN stays at 1.
- `skills.ts` SKILL_MAX_ITERS_MAX 32 → 256; auto-injected skill docs
  reworded so authors don't read 32 as the natural ceiling.
- New `IterCapSource` field on SpawnSubagentOptions + a single-line
  stderr emitter so we can grep what each spawn resolved to and where
  the value came from (json-arg / type / frontmatter / default).
- App.tsx skill subagentRunner now propagates `skill.maxToolIters`
  (it didn't before — a latent divergence from the `reasonix code`
  setup path that meant chat-mode skills silently ignored their
  frontmatter `max-iters`).
- `REASONIX_ITER_CAP_TELEMETRY=off` opt-out; test setup turns it off
  so CI logs stay quiet.
- Tests updated to assert the new bound and to cover 128 (in-range).

Mid-experiment safety:
- Cap still exists at 256 — the pause/resume work is not yet shipped,
  so an extreme model pick can't burn through unbounded budget.
- 70% loop warning + 3-iter end-of-budget hint + budgetUsd cap all
  still in effect.

* remove iter-cap telemetry after real-API validation

Probe results (deepseek-v4-flash, max_iters arg picked by the model
against the new 256 ceiling):
  tiny task    → 3
  medium task  → 30
  large task   → 80   (also auto-escalated to pro mid-loop)
  unbounded    → 256  (hit the ceiling, but the prompt said "unbounded
                       audit, take as many tool calls as needed")

No pathological 1, no hallucinated 999 → real values, scales with the
task description. The cap-as-safety-theater hypothesis holds.

This commit drops the experiment-only scaffolding while keeping the
substantive change (32 → 256 cap + the App.tsx skill maxToolIters
propagation fix it surfaced):
- emitIterCapTelemetry function gone
- IterCapSource type, itersSource / itersRaw fields gone
- callers in App.tsx, setup.ts, subagent.ts no longer compute or pass
  the source tag
- scripts/iter-cap-experiment.mjs deleted
- REASONIX_ITER_CAP_TELEMETRY opt-out in tests/setup-lang.ts deleted
2026-05-14 16:11:45 +08:00
YHH e4d4ef06bb fix(shell): route 2>nul and 2>/dev/null to the OS null device (#821)
The native redirect parser called `pathMod.resolve(cwd, target)` for
every redirect target, so `2>nul` (Windows habit) and `2>/dev/null`
(POSIX habit) both opened a real file at `<cwd>/nul` or
`<cwd>/dev/null`. On Windows this materialized a stray `nul` file at
the project root containing whatever stderr was meant to be discarded
("File Not Found" from `dir`, typically).

Detect the two well-known aliases — case-insensitive `/dev/null` on
any platform, plus `nul` on win32 only (it is a legitimate filename
on POSIX) — and route them to `os.devNull` instead of the cwd.
2026-05-14 15:27:44 +08:00
YHH 9d769fd2ea fix(desktop): honor preset autoEscalate when building the loop (#819)
The desktop JSON-RPC entry built CacheFirstLoop without passing
autoEscalate, so it defaulted to true regardless of preset. Picking
`flash` in the UI (advertised as "cheapest · predictable") still let
the loop escalate flash → pro on hard turns, billing users at pro
rates. The TUI's applyPresetLive already wires autoEscalate from the
resolved preset; do the same in buildRuntimeFor.
2026-05-14 15:19:37 +08:00
YHH 5e9cfcb02b chore(docs): move landing + download site into docs/ for GitHub Pages (#817)
* chore(docs): move new landing + download site into docs/ for GitHub Pages

Routes:

- `/`            (docs/index.html)      — new editorial landing
- `/download.html` (docs/download.html) — smart-mirror download page
- `/configuration.html`                 — existing bilingual config guide,
                                          untouched, still served alongside

The new design's components moved from `download-site/src/` to
`docs/src/`; the index now also carries the SEO bundle from the
previous landing (canonical, hreflang, og:, twitter:, JSON-LD
SoftwareApplication + WebSite) so search rankings don't drop.

Nav gains a "Guide" link pointing at `configuration.html` since
the in-page #config section is a quick reference, not a replacement
for the full guide.

`_headers` / `_redirects` are dropped — those were Cloudflare Pages
features and don't apply to GitHub Pages.

`term-anim.js` was only used by the old landing; deleted.
`styles.css`, `guide.css`, `i18n.js`, `guide-i18n.js`, `motion.js`
stay because `configuration.html` still references them.

`sitemap.xml` gains the download page entry.

* feat(web): EN/中 language switch + restyle configuration guide to match

Three changes ride together:

- **Language switch.** New `src/i18n.jsx` exposes `LangProvider`, `useLang`,
  and a `t({zh, en})` helper. The nav now carries an EN/中文 toggle that
  persists to `localStorage` under `reasonix.lang` and reflects in
  `?lang=…` for deep-linking. Every prose string in nav, hero, install,
  agents (three pillars), features, config (MCP/Skills/Memory/Slash),
  community, roadmap, FAQ, footer, download page, mirrors grid, and CLI
  alt block is now bilingual. `configuration.html` uses the same storage
  key via `i18n.js`, so switching language on any page propagates to the
  others.

- **Guide restyle.** `configuration.html` no longer ships its own
  navy-palette chrome; it now loads `src/fonts.css` + `src/styles.css`,
  uses the same nav + footer markup as the new design (active "Guide"
  link in the accent colour), and `guide.css` was rewritten to use the
  new design tokens (--cream, --accent, --rule, --serif, --mono) so the
  article body — TOC, callouts, cmd tables, code blocks, CTA — sits
  cohesively inside the warm-sepia aesthetic of the rest of the site.

- **Live community stats.** Community card on the landing now fetches
  the real star count, fork count, and contributor list from the GitHub
  REST API, replacing the mockup's fixed 1,128 and 24-initial placeholder.
2026-05-14 14:56:31 +08:00
YHH c8b79ad0bd feat(web): landing + download site, ported from the design mockup (#815)
Adds `download-site/` — a static React (UMD + Babel standalone) site with
two routes:

- `/` (index.html) — editorial landing page: hero with an animated terminal
  replay of an actual reasonix code session, CLI install panel, three-pillar
  agent breakdown, feature grid, configuration explorer (MCP / Skills /
  Memory / Slash), community card with live GitHub stars + contributor wall,
  roadmap, FAQ.
- `/download` (download.html) — smart-mirror download page. On load, races
  HEAD probes against R2 and GitHub Releases, highlights the fastest as
  "Fastest", and offers a per-platform installer link. Three platform tabs
  (macOS / Windows / Linux) with first-launch caveats (Gatekeeper, SmartScreen,
  AppImage chmod + libfuse2).

Substitutions from the mockup:

- Version `0.30.5` → `0.42.0-3` everywhere (mirrors / hero / footer / nav /
  AppImage chmod example / terminal replay).
- File names match the actual `tauri-action` bundle output.
- Mirror list trimmed from {R2, Gitee, GitHub} to {R2, GitHub}; the Gitee row
  in the matrix went away when we dropped that mirror upstream.
- Hero stats updated (test count → 2837).
- Community card fetches real GitHub repo metadata + contributors from
  api.github.com instead of the hand-rolled chart and 24 placeholder initials.
- "新账号有免费额度" wording removed — DeepSeek pulled that perk in 2026-05.

Implementation notes:

- React + ReactDOM pinned to `cdn.jsdelivr.net` (better mainland-CN access
  than unpkg). Babel standalone same CDN.
- `src/fonts.css` is a system-font stack — no external font CDN. The Google
  Fonts <link> the mockup shipped with would degrade ugly on CN networks
  exactly where the page matters most.
- `tweaks-panel.jsx` (dev-only design knob panel) is not copied; `app.jsx`
  was simplified accordingly.
- `_headers` sets MIME type for `.jsx` (Babel needs `text/babel`-ish) and
  basic security headers.
- `_redirects` maps `/download` → `/download.html` for clean URLs.

Deploys to Cloudflare Pages — no build step, root dir = `download-site`,
auto-deploys on push to main. README covers the manual setup.
2026-05-14 12:51:28 +08:00
YHH f645fa3598 chore(release-mirror): drop Gitee mirror, R2 only (#814)
GitHub Actions → Gitee bandwidth is unreliable enough that even
small files (47 MB rpm, 49 MB deb) hit the 3-min per-file timeout.
The runners live in US Azure regions and the path back into
mainland China is throttled / lossy; that's structural and not
something a longer timeout or more careful retry logic will fix.

R2 (via Cloudflare's edge) is fast enough from China to serve as
the primary mirror for CN users, plus the download page's latency
probe picks the best mirror per visitor. Gitee was supposed to be
the CN-native fallback; without reliable upload there's nothing to
fall back to.

Removes the Mirror to Gitee step and the helper script. GITEE_TOKEN
secret can stay or be deleted at the maintainer's discretion — it's
no longer referenced.
2026-05-14 12:21:12 +08:00
YHH c27cee4e45 fix(release-mirror): 3-min hard timeout per Gitee upload (#813)
Last run got stuck for 15+ min uploading what should have been a
~50 MB file — Gitee accepted the connection then stalled, and
undici's default headersTimeout (5 min) wasn't aggressive enough
to free the loop, so the rest of the batch never ran.

Wrap each upload in an AbortController with a 3-min cap. Files
that don't complete in that window are reported as failures and
the loop moves on, matching the per-file error isolation added in
the previous fix.
2026-05-14 12:08:16 +08:00
YHH 6c38e27be1 fix(release-mirror): skip Gitee uploads over 90 MB + isolate per-file errors (#811)
Two robustness fixes on top of v0.42.0-3 mirror run #4:

- Gitee free accounts cap individual release assets at 100 MB. Our
  AppImage (118 MB) was hanging the upload until undici's 5-min
  HeadersTimeoutError fired, which crashed the whole script and
  left assets queued after it unmirrored. Now skip files > 90 MB
  with a clear log line; users still get those from GitHub / R2.
- Per-file uploads now catch their own errors and continue. A
  flaky single upload no longer kills the rest of the batch.
  Script still exits non-zero at the end if any upload failed, so
  the workflow stays red.

R2 mirror was already passing end-to-end on the prior run.
2026-05-14 11:49:09 +08:00
YHH d25482b257 fix(release-mirror): default Gitee release body when GitHub body is empty (#810)
Gitee's POST /repos/{owner}/{repo}/releases rejects an empty body
with 400 "发行版的描述不能为空" (release description cannot be empty).
The previous default kicked in only when the env var was unset; when
the GitHub release has no notes, the workflow passes RELEASE_BODY=""
which bypassed the `??` fallback.

Treat empty / whitespace-only body as "no body" and substitute a
link back to the GitHub release. Keeps mirror-only metadata
discoverable and lets the run succeed regardless of how thorough
the maintainer was with release notes.
2026-05-14 11:34:39 +08:00
YHH 6e9c704b0e fix(release-mirror): handle Gitee returning 200+null on missing tag (#809)
Gitee's GET /repos/{owner}/{repo}/releases/tags/{tag} returns
200 OK with the literal JSON body `null` when the tag has no
release yet, not 404 like every other release API. The script
read .id off that null and crashed before the create path could
run. Treat null/missing-id as "no release exists" and fall
through to the POST /releases create branch.
2026-05-14 11:28:51 +08:00
YHH d0947b3a3b fix(release-mirror): correct Gitee repo path + decouple Gitee/R2 (#808)
Two issues surfaced on the first real run (v0.42.0-3):

- Gitee path `reasonix/deep-seek-reasonix` 404'd; the actual repo is
  `reasonix/DeepSeek-Reasonix` (case-sensitive on Gitee). Fixed.
- Gitee failing took out R2 because step-level `if:` defaults to
  `success()`. Added `continue-on-error: true` to both mirror steps
  and `if: always() && ...` to R2 / its aws-cli setup so the two
  targets are now fully independent — one failing surfaces a failed
  workflow but doesn't suppress the other.

Summary step now reports per-mirror status (✓ / ✗ / skipped) and
exits non-zero if any required mirror failed, so the run stays red
in the Actions UI even though individual steps soft-failed.
2026-05-14 11:20:10 +08:00
douglarek eb792068b8 feat(slash): autocomplete skill names in /skill arg picker (#805)
Add argCompleter: "skills" to the /skill command so users see a
picker with available user-defined skills (project + global scope)
when typing '/skill ' — excludes built-in skills to reduce noise.

- Add "skills" to the argCompleter type union in SlashCommandSpec
- Register argCompleter on the skill command spec
- Add SkillStore-based resolver in useCompletionPickers
2026-05-14 10:45:04 +08:00
YHH 014595a816 ci(release): mirror published releases to Gitee + R2 (#804)
A new workflow fires on `release: published` (and is manually
runnable for backfills). It downloads the GH release assets,
creates / reuses a Gitee Release of the same tag, and uploads
each asset; in parallel it syncs the same files to R2 under
`<tag>/` and `latest/`.

Both mirror steps gate on their secrets being present, so the
workflow no-ops cleanly until tokens are configured. Required
secrets:
- GITEE_TOKEN
- R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ACCOUNT_ID, R2_BUCKET

Refs #802
2026-05-14 10:40:23 +08:00
YHH 3f277bd32b fix(desktop): bundled CLI loads on installed targets; drop CDN fonts (#806)
* fix(desktop): bundled CLI loads on installed targets; drop CDN fonts

Two unrelated issues both surfaced as a black-screen on the v0.42.0-2
release.

CLI sidecar: tsup was emitting `dist/cli/index.js` as an ESM bundle
with `commander`, `ink`, `undici`, etc. left external. That's fine
for `npm i -g reasonix` (npm brings the deps), but the desktop ships
`dist/cli/` as a static resource with no `node_modules` next to it,
so the spawned Node process died on `ERR_MODULE_NOT_FOUND` for the
first import and the IPC channel never came up → empty UI. Switch
the CLI entry to a self-contained bundle: `noExternal: [/.*/]` plus
`platform: "node"`, with `react-devtools-core` whitelisted as
external (it's an optional peer dep that ink dynamically pulls only
when devtools are enabled, which we never do).

undici's dispatcher uses `require()` at runtime; in ESM output the
esbuild shim refuses dynamic require. Banner-inject a `createRequire`
into `globalThis.require` so the shim picks it up.

Drop a one-line `dist/cli/package.json` with `{"type":"module"}` so
Node skips the CJS-first parse attempt and the
MODULE_TYPELESS_PACKAGE_JSON warning.

Fonts: `index.html` loaded IBM Plex from googleapis.com, which the
bundled CSP (`style-src 'self' 'unsafe-inline'; font-src 'self'
data:`) blocks. Switch to `@fontsource/ibm-plex-{sans,mono,serif}`
so the woff2s are bundled into `dist/assets/` at build time —
identical typeface, zero runtime network. The previously-imported
`@fontsource-variable/inter` + `jetbrains-mono` packages were dead
weight (CSS never referenced those families); removed.

Enable tauri's `devtools` feature while the desktop is prerelease —
F12 is what surfaced both bugs, and it stays useful while the
desktop is being shaken out. Revisit before stable.

* test(bundle-smoke): assert runtime deps are inlined, not external

Companion to the CLI bundling change: the smoke guardrail was the
inverse of what we now want — it asserted ink was kept external so
npm could resolve it from the user's tree. The desktop sidecar
runs from a static `dist/cli/` with no node_modules, so external
imports are exactly the failure mode we're guarding against now.

Flips the assertion: no `dist/cli/*.js` should `import from "commander"
| "ink" | "undici"` — those are the three that broke v0.42.0-2.
2026-05-14 10:37:19 +08:00
YHH 56137c95e9 perf(ui): incremental wrap cache for streaming cards (#800)
StreamingCard re-ran split('\n') + wrapToCells() over the whole
accumulated text on every chunk. wrapToCells walks each grapheme
through Intl.Segmenter (~3.7µs/char), so a 5000-char reply costs
18.5ms per frame at 20Hz — well over the 50ms budget.

Cache the wrap and re-fold only the last logical line on monotonic
append; fall back to a full recompute on shrink (abort), resize,
or any non-prefix change. ReasoningCard's StreamingPreview and
SettledPreview now share the parent's wrap result instead of
each running their own flatMap.

Also bumps the live token calibration interval from 500 to 1000
chars — the post-fix calibration frame became the dominant cost
and t/s precision is already an approximation.

Closes #798
2026-05-14 08:12:19 +08:00
YHH ec7e5f25ba fix(release): switch macOS to universal-apple-darwin, drop macos-13 shard (#799)
The macos-13 Intel runner pool on GH is heavily throttled — v0.42.0-1
sat queued for hours. Tauri 2 ships a `universal-apple-darwin` target
that lipos x86_64 + arm64 builds into a single fat binary, so one
Apple Silicon runner now produces a Mac DMG that installs on both
Apple Silicon and Intel.

Restructures the matrix entry so `rust` is the comma-separated list
fed to dtolnay/rust-toolchain (both real targets need installing for
the universal build) and `tauri` is the target name fed to
`cargo tauri build`. Other shards just repeat their triple in both
fields.

Drops the macos-x64 row entirely. The universal DMG covers the same
hardware that macos-x64 shard was producing for.
2026-05-14 07:19:48 +08:00
YHH b8afac331c fix(release): pass GITHUB_TOKEN to tauri-action so the draft release upload works (#796)
v0.42.0-0 run got past compile + bundle (MSI included — numeric
prerelease works as expected) but died at "GITHUB_TOKEN is required"
when tauri-action tried to create the draft release. The previous
codesign failure on v0.42.0-desktop.0 masked this: the build never
reached the upload phase, so nobody noticed the missing token.

tauri-action v0 needs GITHUB_TOKEN in env to call the GitHub API for
draft creation + asset upload. Wires `secrets.GITHUB_TOKEN` into all
three build-step variants (unsigned, Windows signed, macOS signed).

Windows matrix shard produced its full set of artifacts in the
previous run before failing the upload:
  Reasonix_0.42.0-0_x64_en-US.msi
  Reasonix_0.42.0-0_x64-setup.exe (NSIS)
  + .sig files for both
2026-05-14 01:05:08 +08:00
YHH dec8bd639e fix(release): expose secret presence via job-level env (step if: can't see secrets.*) (#795)
#794 used `secrets.WINDOWS_CERTIFICATE != ''` directly inside step
`if:` conditions. GitHub Actions rejects that at workflow-validation
time — secrets context isn't available to job/step conditionals.
Result: every push to main / PR branch produced a workflow-file-issue
failure run, and the v0.42.0-0 tag run never even started.

Lifts the presence check into a job-level `env:` that resolves at
job-start (where secrets context IS accessible). Steps gate on the
"true"/"false" string instead. Same three-way split as #794, just
working syntax.
2026-05-14 00:46:26 +08:00
YHH a4ebbb0de0 fix(release): split bundle step so unsigned builds skip codesign envs (#794)
Releasing v0.42.0-desktop.0 surfaced this: when an APPLE_* or
WINDOWS_CERTIFICATE secret is unset, GitHub Actions fills the env
var with an empty string, and tauri-action interprets "env defined"
as "try to sign". `security import` of an empty cert fails on macOS;
signtool fails the same way on Windows.

Splits the single Build Tauri bundle step into three mutually
exclusive variants gated on whether the certificate secret is
actually non-empty:

  - unsigned (Linux always; Win/macOS when no cert)
  - Windows signed (matrix.os == windows-latest && cert set)
  - macOS signed + notarized (startsWith macos- && cert set)

Today only the Tauri updater key is configured, so every shard takes
the unsigned path. Wiring stays in place for when code-signing
secrets land.
2026-05-14 00:38:00 +08:00
YHH 984704b175 docs(readme): announce the desktop client (prerelease) (#793)
README had no mention of the Tauri desktop bundle, so users wouldn't
know it exists. Adds a short section under Install: where to grab
installers, the prerelease caveat (unsigned bundles), and the two
one-line gotchas users hit on macOS (xattr) and Windows (SmartScreen).
2026-05-14 00:01:55 +08:00
YHH 33165742ea fix(desktop): kill Node child on Tauri exit, add rpc_kill command (#792)
The previous exit watcher took the Child by move and blocked on
child.wait(), with no way to interrupt it from outside. RpcHandle
stored only stdin, so the only thing keeping Node alive-or-not was
the stdin pipe closing on parent exit — fine in the common case but
leaks the child if Node is mid-tool-call when Tauri exits.

Replaces the watcher with a recv_timeout loop on a kill-signal mpsc:
RpcHandle holds the Sender, dropping the handle disconnects the
channel, the wait thread sees Disconnected and calls child.kill()
followed by wait() to reap. Natural exit (try_wait returns Some) is
detected on the 500 ms tick and clears RpcState so a future rpc_spawn
isn't blocked by stale state.

Tauri 2's process exit doesn't always run managed-state drops, so
RunEvent::ExitRequested also invokes rpc_kill explicitly — belt-and-
braces.

`rpc_kill` is exposed as a tauri command for a future UI affordance
(restart RPC button); not wired to a button yet.
2026-05-14 00:01:49 +08:00
YHH 37a85e5df0 feat(skills): max-iters frontmatter raises subagent tool budget (#791)
Skills that runAs=subagent were hard-capped at the spawn default of
16 tool calls — no way to raise it from the frontmatter. Review /
exploration playbooks with bigger codebases run out and stop with
"Tool budget exhausted at 16 calls". The setup.ts run_skill bridge
ignored skill.maxToolIters because the field didn't exist.

Adds `max-iters` to the parsed frontmatter (clamped to [1, 32] to
match the spawn_subagent JSON-schema bounds), wires it through to
spawnSubagent, and documents it in docs/configuration.html plus the
/skill new stub. Invalid / out-of-range values fall back: junk text
→ undefined (default 16), >32 → 32, <1 → 1.

Closes #783
2026-05-13 23:43:55 +08:00
J3y0r d77f86a60f docs(readme): add install instructions (#788)
Closes #784
2026-05-13 23:34:51 +08:00
YHH d4431ad2e5 chore(release): sync desktop version from tag, set minimum CSP (#789)
Two prerequisites for the desktop's first prerelease bundle.

- Cargo.toml + tauri.conf.json + desktop/package.json were all stuck
  at 0.0.0. tauri-action doesn't auto-rewrite them from the tag, so
  the artifact filenames would have been Reasonix_0.0.0_x64-setup.exe
  and the updater's version compare would be broken. New
  scripts/sync-desktop-version.mjs reads the tag (or GITHUB_REF_NAME /
  TAG env var) and writes the SemVer to all three files. Wired into
  release.yml between `npm ci` and the CLI build step.

- CSP was `null`. Switched to a minimum self-only policy with the
  usual escapes for inline styles, fonts, and Tauri IPC origins
  (`ipc:` + `http://ipc.localhost`). Only applied to the bundled
  build, dev server is untouched.

Updater pubkey was already set on a previous pass; nothing to do
there. Code-signing certs (Windows EV, macOS Developer ID) are a
later step — first prerelease can ship unsigned with the usual
SmartScreen / Gatekeeper warnings.
2026-05-13 23:29:32 +08:00
YHH 18d63c0a7a fix(desktop): wire path_access gate and scope right-panel to this session (#787)
* fix(desktop): wire path_access gate and scope right-panel to this session

Two desktop-side gaps from the same field report:

- path_access requests hung forever. desktop.ts's pauseGate listener
  handled run_command / run_background / choice / plan_* but had no
  case for path_access, so any outside-sandbox read (e.g. the model
  trying `/tmp/foo` on a Windows workspace) parked the tool call with
  no UI surface. Now emits `$path_access_required` and renders a
  PathAccessApprovalCard (allow once / always allow prefix / deny).
  Response reuses `confirm_response` since both gates return a
  ConfirmationChoice.

- The right-panel Files tab was dumping the entire workspace tree
  (up to 800 entries) overlaid with `git status` dots and polling
  every 5s, against the mockup's intent. That mockup was a curated
  "files in context" view — only files the agent has read or written
  this session, status `c` for reads and `m` for writes. Rewrote
  CtxFiles to consume the session-tracked list directly; dropped the
  `list_workspace_tree` / `git_status` invokes (Rust commands left
  in place but no longer called). Tree falls out naturally from the
  small flat list via parent-dir grouping. Status `m` never downgrades
  back to `c`.

multi_edit's per-edit paths are extracted so a batch refactor surfaces
all touched files.

* fix(desktop): rename global .caret → .stream-caret, drop dead tree rule

The streaming-text indicator's `.caret` was a global selector. The
old CtxFiles also used `<span className="caret">` for its expand
arrow, and `.tree .node .caret` only overrode width/height/display/
color/flex-shrink — `background: var(--accent)` and the 1Hz
`animation: caret` leaked through, painting a flashing accent square
next to every tree node. Renaming the streaming class breaks the
collision, and now-unused `.tree .node .caret` goes with it.
2026-05-13 23:29:12 +08:00
YHH 4844edbab8 fix(policy): yolo bypasses path_access too, parity with shell allowAll (#786)
YOLO mode already auto-allows shell tools via setup.ts's `allowAll`
getter, but filesystem tools went through `safePath` → `path_access`
gate unconditionally, so an outside-sandbox read like `/tmp/foo` would
still pause the loop waiting for user approval. autoResolveVerdict
now returns run_once for path_access in yolo (run_once rather than
always_allow so a transient YOLO session can't pollute the on-disk
allowlist).

CLI TUI also routes path_access through autoResolveVerdict so the
three surfaces (CLI / ACP / desktop) all converge on the shared rule.
2026-05-13 23:28:39 +08:00
YHH bb5a7f2d1b release: 0.41.0 — ACP graduates + read-only auto-escalate + REASONIX.md reload (#785)
52 commits since 0.40.0. Headline is the ACP three-stage rollout
(NDJSON framing → tool_call streaming → request_permission bridge)
plus three flags that close the headless-caller story: --transcript
for cost-tracking, --yolo to skip plan checkpoints without config
mutation, --mcp + --mcp-prefix so downstream adapters can bridge
their own MCP servers without touching the user's config.

Other shipped lifts: flash → pro auto-escalation on consecutive
read-only tool calls (caps the dead-end fishing-trip cost), read_file
outline support for Python / Go / Rust / Markdown, a wait_for_job
exit-only mode that turns a 5-minute download into ONE tool call,
/btw for side questions that don't pollute context, user-defined
memory types with priority + expiry, status-bar field toggles, and
a wave of desktop UI surfaces gaining real data.

Field-reported fixes: /new now reloads REASONIX.md without a restart
(#778 bug 2), the dashboard search toggle no longer one-way-traps
users whose config lacks an explicit "search" field (#778 bug 1),
preset switches preserve persisted reasoningEffort (#775), markdown
emits OSC-8 hyperlinks, embed batch responses tolerate missing inputs,
@-mention paths handle CJK, jobs settle running state across the
Windows taskkill window, and more.

Full notes in CHANGELOG.md.
2026-05-13 21:21:32 +08:00
YHH 2c3904f746 fix(settings): normalize search default to disk so dashboard toggle isn't a one-way trap (#782)
The dashboard's search toggle reads `cfg.search !== false` and treats
missing as on, so the button renders ON even when `~/.reasonix/config.json`
has no `"search"` field at all. A user who reads the config file first,
sees no entry, opens the dashboard expecting OFF, and clicks "to enable
it" actually goes `undefined → false` — which matches the report on
#778 (config still shows `"search": false` after the click).

GET now persists the resolved default (`true`) on first read when the
field is missing, so on-disk state always matches what the dashboard
displays. Subsequent clicks toggle a real boolean and the config
mirrors the button state from then on. Idempotent on configs that
already have an explicit search field.

Refs #778 (bug 1 of 2)
2026-05-13 21:06:38 +08:00
Vadim Smirnov 2d1de052d4 feat(acp): --mcp + --mcp-prefix for headless callers (#780)
`reasonix acp` is missing the MCP-server bridging that `reasonix run` and
`reasonix chat` already have. Headless ACP clients (Paperclip's
reasonix-local adapter, etc.) need to plumb domain-specific tool servers
to the agent without forking config — same shape as #766/#767.

Lifts the MCP load loop from run.ts:81-142 into a `loadMcpServers` helper
and calls it inside `buildSession` so the tools are bridged into the
toolset registry BEFORE the prefix is computed (matters for the cache key).

Failures stay non-fatal — a broken side-concern server logs to stderr and
the session keeps running.

Disposes spawned MCP children when the ACP server's stdin closes.

Closes #779.
2026-05-13 20:56:45 +08:00
YHH a187ffc7fb fix(loop): /new reloads REASONIX.md without restart (#781)
Editing REASONIX.md and running /new currently leaves the in-memory
system prompt pointing at the old content — applyMemoryStack runs once
at startup, gets baked into ImmutablePrefix.system, and clearLog()
doesn't touch the prefix to keep the prefix-cache warm.

Accept the cache miss when the user actually changed something. Add an
optional rebuildSystem closure on CacheFirstLoop; /new re-runs it,
compares against the current system, and only invalidates the cache
when the string changed. Closures captured at the chat / code entry
points point back at applyMemoryStack / codeSystemPrompt — same args,
fresh disk read.

A reload prints " · REASONIX.md / project memory reloaded" next to
the usual /new banner so the cache miss isn't surprising.

Refs #778 (bug 2 of 2)
2026-05-13 20:49:39 +08:00
YHH 1ca147ec1e feat(bg-jobs): exit-only wait_for_job mode for chatty long jobs (#777)
waitForJob currently races closedPromise + outputPromise + timer, so
any new output (curl progress, install spinner, watcher tick) wakes
the wait and the model fires another round-trip. On a 90s download
that's 30+ tool calls.

Add `waitFor: 'exit' | 'output-or-exit'`, default `'exit'` — drop
outputPromise from the race in exit mode. Raise timeoutMs cap from
30_000 to 300_000 (server-side block costs no tokens, so one 5-min
wait_for_job covers an end-to-end download). Update run_background +
wait_for_job descriptions and the code-mode shell-tool prompt to
steer the model toward bg-jobs for one-shot long work (curl/wget,
big installs, big builds), not just dev servers.

Closes #776
2026-05-13 20:16:34 +08:00
YHH 0b5e7dc06e fix(preset): don't clobber persisted reasoningEffort on preset switch (#775)
#770 reported that reasoningEffort silently reverted to "max" after
updating, requiring the user to re-set it via the dashboard every
time. Tracing it: the update wasn't the cause — every preset-apply
path was overwriting the persisted effort with the preset's default
(all three canonical presets bundle `reasoningEffort: "max"`). Any
click on a preset card in the desktop UI, any `/preset` slash, and
the ModelPicker outcome handler all called
`saveReasoningEffort(p.reasoningEffort)` and stamped "max" over
whatever the user had stored.

Three call sites now only persist `savePreset`; the live
`loop.configure({ reasoningEffort })` stays so the in-session bundle
effect is preserved. Persistence of effort becomes user-driven only
(dashboard effort dropdown or future explicit slash). Next-launch
`loadReasoningEffort()` then returns the user's stored choice
instead of the silently-rewritten preset default.

Adjacent fix in src/cli/commands/desktop.ts:buildRuntimeFor —
loadReasoningEffort() was being read for `ctx` but never passed to
the `CacheFirstLoop` constructor, so the desktop runtime loop
always ran at the default "max" regardless of the persisted value.
Now passed through.

Regression test in tests/preset-effort-isolation.test.ts mocks
saveReasoningEffort / savePreset and verifies the slash handler
calls savePreset but never saveReasoningEffort, while the live loop
still gets the preset's bundle effort applied.
2026-05-13 19:51:08 +08:00
Vadim Smirnov f035493bdf feat(acp): --yolo flag to bypass plan checkpoints without config mutation (#767)
Per-invocation override of editMode for plan-checkpoint gates only.
Mirrors the existing editMode = "yolo" semantics in
src/core/pause-policy.ts — shell, edit, and any future gates still
bridge to the client via session/request_permission.

Headless callers should not have to write to ~/.reasonix/config.json
just to skip plan modals when running unattended.

Refs: #765
2026-05-13 19:34:06 +08:00
YHH d39ee15210 chore: point Star History chart at canonical DeepSeek-Reasonix slug (#773)
The old `esengine/reasonix` URL still resolves via the GitHub redirect
but star-history.com follows the canonical slug, so the chart was
quietly diverging from the real star series after the repo rename.
Updates the link + three picture sources in both READMEs to
`esengine/DeepSeek-Reasonix` and drops the `timeline&logscale` style
in favour of the simpler `date` projection.
2026-05-13 19:30:11 +08:00
YHH b6df93b3fd chore: oosmetrics badges + weekly health-check workflow (#772)
Adds the three oosmetrics achievement badges (Top 2 in Agents, Top 3
in LLMs, Top 3 in CLI — all by 7-day velocity, as of 2026-05-12) to
both README.md and README.zh-CN.md, plus a scheduled GitHub Action
(weekly Monday 09:00 UTC + manual dispatch) that runs
oosmetrics/health-check-action@v1 to open a summary issue with rank
deltas + new achievements.

Workflow uses only the default GITHUB_TOKEN with issues:write — no
extra secrets to configure.
2026-05-13 19:21:14 +08:00
YHH 92c29a810a fix(desktop): drop stale literals from preset, plan badge, tool card (#771)
Three small UI surfaces were showing values that looked dynamic but
were actually frozen at build time or hardcoded — fine for a design
sketch, wrong for a live agent UI.

settings.tsx (preset cards):
  Dropped `speed` ("180 t/s" / "84 t/s") and `bench` ("MMLU 88.5" /
  "AIME 79.8") rows. These were build-time literals presented next
  to the contractual `ctx` / `out` caps, so users read all four as
  authoritative model metadata. ctx + out stay (those *are* contract).
  Re-add speed / bench when we have a source of truth that updates
  with the model, not as inline constants.

cards.tsx (PlanCardView badge):
  The "运行中" pill rendered unconditionally — a plan with every
  step `done` still flashed "running". Extracted `derivePlanBadge`
  to fold items into one of err / warn / run / ok / run for failed
  / blocked / active / all-done / todo respectively, reusing the
  existing `.pill-tag` color variants.

live.tsx (ToolRunningCard skeleton):
  Three `skel-line` placeholders rendered above the real `live-log`
  when both existed, so the user saw a fake gradient stack glued on
  top of actual streaming output. Switched to else-branch — skeleton
  only when there is nothing real to show.
2026-05-13 19:12:23 +08:00
Vadim Smirnov 1870dabede feat(acp): --transcript flag for headless cost capture (#766)
* feat(acp): --transcript flag for headless cost capture

Tees raw LoopEvents through writeRecord/recordFromLoopEvent during
session/prompt so headless ACP callers can parse usage, cost, and
prefixHash without driving the TUI. Reuses the JSONL shape chat and
code already emit; zero changes to transcript helpers.

Single-session-per-process — mirrors chat/code behavior; the JSONL
stays cleanly seekable.

Adds tests/fixtures/acp-driver.ndjson as scaffolding for future
end-to-end ACP smoke tests, per maintainer ack on #765.

Refs: #765

* test(acp): assert fixture sessionId is a placeholder

Adversarial review noted that piping acp-driver.ndjson as-is into
the binary produces ERR_INVALID_PARAMS "unknown session" with no
hint about the substitution requirement. Lock in the placeholder
contract so anyone editing the fixture sees the test fail with a
clear comment instead of discovering the trap at runtime.
2026-05-13 18:50:27 +08:00
YHH 13b49e0555 feat(read_file): multi-language outline (Python, Go, Rust, Markdown) (#769)
Auto-preview's symbol outline was TS-only. Any non-TS file longer
than 200 lines dropped into the preview path with no navigation map —
just head 80 + tail 40 and an opaque "N lines omitted" marker. The
model had nothing to range-read against, so for Python / Go / Rust /
Markdown files the "scope your read" workflow stopped working past
the threshold and the model either guessed or full-read.

Adds per-language regex extractors dispatched on extension:
- TS/JS/TSX/MJS/CJS — existing top-level export logic (parity preserved)
- Python — top-level def / class (indent-sensitive, skips methods)
- Go — top-level func / type / var / const, methods captured by name
- Rust — fn / struct / enum / trait / impl / mod / type / const / static,
  impl block target type extracted (incl. impl<T>, impl Trait for X)
- Markdown — headings at all levels, fenced code blocks ignored

Outline module lives in src/tools/fs/outline.ts. Header wording goes
from "N top-level exports" to "N symbols" so it fits all languages;
elision text follows. Per-entry shape unchanged for TS — the kind +
name still appear after the line marker, just no longer hardcoded to
"export".

Picked regex per language over tree-sitter because the published WASM
parsers are 5-50MB each — too much install weight for "show me the
top-level symbols". Tree-sitter remains a viable upgrade if the regex
extractors start hitting precision limits in real use.
2026-05-13 18:43:20 +08:00
YHH 101efd6b0e feat(loop): auto-escalate flash→pro on consecutive read-only tool calls (#681) (#768)
The existing flash→pro escalation only fires on "repair signals"
(SEARCH-mismatch / scavenged / truncated / repeat-loop). A model
stuck reading file after file without ever writing or producing a
final answer never trips that trigger — every read returns cleanly,
so from the harness's view the turn looks healthy while the user
watches the bill climb.

#681 hit this exact shape: 34 tool calls / 142 log messages, top-5
all `read_file`, ¥3.41 spent on flash before the user aborted. The
underlying issue is "flash too weak for this task"; the right fix is
to detect the stuck-in-reads pattern and switch to pro mid-step.

Adds `ReadOnlyLoopTracker` (default threshold 8, env-tunable via
`REASONIX_READONLY_LOOP_THRESHOLD`). Each successful tool result
either bumps the streak (read-only) or resets it (mutating). When
the streak crosses threshold, set `_escalateThisTurn = true` and
yield a one-shot warning — same escalation contract as the existing
failure-signal path. `autoEscalate=false` still blocks; the user
keeps that lever.

Threshold of 8 is on the conservative side — bursty read-heavy
tasks (e.g. "read these 5 files then edit one") still finish on
flash; the trigger only catches genuine unproductive loops.

Closes #681.
2026-05-13 17:57:19 +08:00
YHH eb3cc34dce fix(at-mention): allow CJK and other Unicode letters in @-mention paths (#764)
The picker's prefix regex was ASCII-only:

    /(?:^|\s)@([a-zA-Z0-9_./\-]*)$/

So `@中文/` failed the `$` anchor on the first non-ASCII byte and
`detectAtPicker` returned null. The picker disappeared, Tab had
nothing to drill into, and the user couldn't enter a Chinese-named
folder via @.

Swap the inner char class for `[\p{L}\p{N}_./\-]` with the `u` flag.
Same change on `AT_MENTION_PATTERN` so the expander recognises the
completed mention too.

Closes #749.
2026-05-13 17:17:58 +08:00
YHH 1c04ba1230 refactor(ui): extract HistoryTypingCapture so AppInner stops subscribing to pinned (#763)
#760 added the keystroke handler that lets users type blind while
scrolled up. It also added a `useChatScrollState((s) => s.pinned)`
subscription inside `AppInner`, which re-renders the whole subtree
every time scroll state ticks.

Move the handler into a leaf component the same way
`InputAreaWithHistoryHint` already isolates its `pinned` read. The
leaf renders `null` and registers `useKeystroke` against
`enabled && !pinned`; AppInner just hands it `input` / `setInput` /
`onReturnToBottom`. Behavior identical; AppInner now stays still on
scroll events again.
2026-05-13 17:08:37 +08:00
rokyplayandrokyplay 4e1ca3c7c4 fix(ui): capture keystrokes while scrolled up in history (#760)
When the user scrolls up to read chat history, PromptInput is unmounted
and keystrokes are silently dropped. Add an App-level keystroke handler
that captures printable characters, backspace, and Enter (returns to
bottom) when pinned=false, so the user can type blind while reading
history and see their input when they scroll back — Claude Code parity.

Co-authored-by: rokyplay <[email protected]>
2026-05-13 17:02:31 +08:00
ForeverYoungPp 6ba8223d18 fix(healing): stamp fallback id on bare tool_calls to prevent DeepSeek 400 (#713) 2026-05-13 16:58:56 +08:00
YHH d62ceac8f1 feat(desktop): bridge MCP per-tab and surface per-server status (#762)
Extract `createMcpRuntime` from `chat.tsx` into a non-tsx module
`cli/commands/mcp-runtime.ts` and import from both `chat` and `desktop`.
chat.tsx re-exports the public types for backwards compat.

In `desktop.ts`:

- Each `Tab` now owns an optional `mcpRuntime` plus a `mcpStatuses` map.
  `bridgeTabMcp` lazily constructs the runtime, wires a lifecycle sink
  that updates the per-spec status, and calls `reloadFromConfig` against
  the tab's loop so MCP tools register into the live prefix.
- `closeTab` calls `runtime.closeAll()` so MCP children exit cleanly.
- `mcp_specs_add` / `mcp_specs_remove` trigger `bridgeTabMcp` so live
  config edits reach the runtime without restarting the tab.
- `$mcp_specs` now carries `status` + optional `statusReason` /
  `toolCount` per spec. `bridged` stays as a coarse "all connected"
  flag.

The right-panel Tools tab renders the per-spec dot — green for
connected, yellow pending for handshake / configured, grey for failed /
disabled — and the row text shows the live state (tool count, failure
reason).

Closes #753.
2026-05-13 16:56:30 +08:00
YHH 0edf41c0d0 feat(desktop): surface memory store entries in the Memory tab (#761)
Lists project- and global-scope memory entries beside the chat. The
desktop command opens a `MemoryStore` per tab and emits the entries as
a new `$memory` event on tab open. Each row shows the scope badge +
description, matching the v4 mockup. Empty state keeps the existing
placeholder copy.

Refresh is currently tab-open only — when the agent writes a new
memory via `update_memory`, the panel reflects it on the next tab open
/ reload. Live refresh on tool result can come later if it bites.

Closes #754.
2026-05-13 16:47:46 +08:00
YHH 1e9ea2dd96 feat(desktop): per-file status dots in the right-panel Files tree (#759)
Modified files (yellow dot) and in-context files (green dot) now show
beside their row, matching the v4 mockup's `data-s="m"` / `data-s="c"`
hooks (CSS was already shipped).

- **Modified**: new Tauri command `git_status(root)` runs `git status
  --porcelain -z`, parses index/worktree codes into coarse kinds. The
  tab polls every 5s and on workspace switch; returns empty (silent)
  outside a git repo or when `git` is missing.
- **In context**: reducer scans `tool.intent` events for the known
  file-reading tools (`read_file`, `list_directory`, `directory_tree`,
  `search_files`, `get_file_info`, `glob_files`) and accumulates each
  path arg. `$session_loaded` rebuilds the set from loaded segments so
  resumed sessions show their dots without re-reading anything.

Closes #756.
2026-05-13 16:42:09 +08:00
YHH fb6085b4ab feat(desktop): add reserved-tokens bucket to the context meter (#758)
System prompt + tool specs are constant per tab. Compute their token
count via `countTokens` at tab open, emit as a new `$ctx_breakdown`
event (with `reservedTokens` field), and render the band on the right-
panel meter alongside cached / used / free.

Cache-hit/miss numbers from the API include the reserved prefix once
the cache warms up, so the visual subtracts `reserved` from those
buckets to keep the segments disjoint. With a cold cache, the
reserved tokens land in `cacheMiss`; subtract from `used` instead.
Off by at most one turn of arithmetic; not exact, but doesn't double-
count visually.

Closes #755.
2026-05-13 16:35:35 +08:00
ForeverYoungPp b5bed9b2b9 fix(changes-web): align Changes page chat with ChatPanel core logic and chat page functionality (#719)
- Add rAF coalescing for SSE assistant_delta events (reduce re-renders)
- Add autoScrollInFlight guard to prevent scroll interference
- Add SSE reconnect recovery (refetchCanonicalState + firstOpen)
- Cancel pending RAF on assistant_final and SSE cleanup
2026-05-13 16:19:12 +08:00
ForeverYoungPp 34a8a5bbed fix(web): poll /overview every 2.5s in Changes page chat (#720)
- Align with ChatPanel behavior — the stats bar now refreshes
- periodically instead of only fetching once at mount.
2026-05-13 16:17:46 +08:00
YHH ad6e1c1676 fix(desktop): replace MCP "loading" copy with "configured" (#752)
The desktop runtime doesn't actually bridge MCP yet — the
`$mcp_specs` event is emitted with `bridged: false` indefinitely, so
the Tools tab was painting every server as perpetually "loading". Read
the absence of bridging as the truthful "configured but not active in
this tab" state. When desktop-side MCP bridging lands (separate scope),
the `bridged: true` path already maps to "ready" with no further UI
change.

Part of #744.
2026-05-13 16:12:08 +08:00
YHH 87eec8f872 feat(desktop): expand/collapse dirs in the right-panel Files tree (#751)
Click a directory row to fold or unfold its descendants. Tracks a
`collapsed` set of paths and walks each entry up the parent chain
(reconstructed from the flat depth-first list) to decide visibility.
File rows lose their pointer cursor since they're not interactive.

Adds a `.caret` slot with chev / chev-right icons so the affordance is
visible. Dirs default to expanded — collapsing is opt-in and resets
when the workspace switches.

Part of #744 — depth-2 fetch from the Tauri side stays the same; lazy
deeper fetch can come later if anyone hits the bottom.
2026-05-13 16:06:07 +08:00
YHH 09799c7757 feat(desktop): wire the right-panel Files and Tools tabs to real data (#750)
The right context panel was a placeholder per #744. This first pass
wires the two tabs whose data is reachable without big new plumbing:

- Files: new Tauri command `list_workspace_tree(root, maxDepth)` walks
  the workspace up to depth 2, skipping hidden + standard noise dirs
  (`node_modules`, `target`, `dist`, `build`, `out`), capped at 800
  entries. Front-end renders the design's `.tree` markup with depth
  indentation, refetches on workspace switch.
- Tools: switched from the per-message tool-call histogram to the real
  MCP server list using `state.mcpSpecs` + `state.mcpBridged`. Each row
  shows transport + ready/loading + parse error if any.
- Memory: kept placeholder but pulled the inline styles into a shared
  `.ctx-empty` class.
- Rules: still editMode-driven (no per-pattern allowlist exposed to the
  desktop yet) but the items now reflect what each mode actually
  permits, instead of two hardcoded rows.
- Meter: bumped the context max from 128K to 1M to match the V4
  catalog.

Reserved-tokens bucket and a real file-tree expand interaction stay
deferred — both need event-shape / Tauri additions and were called out
as separate stages in #744.
2026-05-13 15:59:34 +08:00
YHH 8e3cf16427 fix(desktop): update model cards to v4 names and 1M context (#748)
The model picker still listed `deepseek-chat` / `deepseek-reasoner` with
128K / 64K context — both stale. The CLI canonicalized on
`deepseek-v4-flash` / `deepseek-v4-pro` (presets.ts) at 1M context
(telemetry/stats.ts) a while back; the desktop UI never caught up, so the
settings page contradicted the status-bar label ("DEEPSEEK-V4-FLASH").

Pull the model card metadata, composer preset labels, and the default
modelLabel fallback into line with the CLI source of truth.

Closes #745
2026-05-13 15:47:02 +08:00
YHH 928742947f fix(mcp): silence the race-leg derivative on initialize timeout (#747)
When `request()` did `Promise.race([transport.send(), promise.then(() => undefined)])`,
the `.then()` derivative was a fresh promise whose rejection only chained
through Promise.race's internal subscriber. On Node 20 that subscriber doesn't
reliably suppress unhandledRejection once the race has already settled — so
when send wins the race and the pending request later times out, the derived
chain rejects with no live handler and the CLI crashes mid-session.

Use the two-arg form `promise.then(() => undefined, () => undefined)` so the
derivative is always fulfilled. The original rejection still propagates to the
caller via `await promise` below.

Adds a regression test using a silent-server transport where `send()` resolves
immediately and the response never arrives — exactly the shape of the crash
report. The `unhandledRejection` handler must not fire.
2026-05-13 15:11:08 +08:00
YHH f6057313dd fix(jobs): settle running state on exit and after taskkill timeout (#746)
On Node ≥ 24, Windows child processes killed via `taskkill /T /F` often
never emit a `close` event — libuv's stdio handle lingers even though the
process is reaped. `JobRegistry.stop()` waited up to 5s on `closedPromise`,
gave up, then returned a snapshot with `running: true` even though we'd
just killed the process. Vitest then asserted on that ghost-running state
and the entire test (and pre-push verify) failed.

Two pieces:
- Settle the record on `exit` in addition to `close`. `exit` fires the
  moment the OS reaps the process, well before stdio drains.
- If neither fires by the SIGKILL deadline, assume the kill landed and
  mark the job dead anyway. We issued `taskkill /T /F`; trust it.

Same fallback in `shutdown()` for the multi-job case.
2026-05-13 15:09:15 +08:00
YHH 600bc396b8 feat(desktop): click the statusbar folder seg to switch workspaces (#741)
The bottom-bar folder indicator was display-only, while the model /
currency / theme / settings segs next to it are all clickable. Wire
the same WorkdirPop the title header uses so users can pick a recent
workspace (or browse for a new one) without scrolling back up.

Anchor the popover above the statusbar — extend the Anchor type with
`bottom`, and use `position: fixed; bottom: ...` when set so the
popover sits cleanly above the trigger instead of trying to render
below the viewport edge.
2026-05-13 13:46:27 +08:00
YHH 8baed6e378 fix(session): persist new sessions opened via /session (#740)
Picking "new" in the /session or launch picker called
`setActiveSession(undefined)`, propagating an undefined `session` to
`CacheFirstLoop`. `this.sessionName` became null, and every
`appendSessionMessage` short-circuited on the `if (this.sessionName)`
guard — the new chat never landed on disk.

Mint a fresh `${base}-${YYYYMMDDHHMMSS}` name at both pickers so the
loop has somewhere to write. Seconds-precision stamp avoids
back-to-back-click collisions; the base is the current session minus
any prior 12/14-digit timestamp suffix, falling back to `default`.

Closes #737
2026-05-13 13:36:51 +08:00
YHH 1d24ccd337 test(jobs): per-test 15s timeout for Windows kill paths (#739)
`stop()` and `shutdown()` legitimately need >5s on Windows because
`taskkill /T /F` is async and the SIGKILL race inside `stop()` waits
up to 5s for `close` to fire. Vitest's default 5s test timeout was
killing the test before `stop()` could return, masking the real
behavior with "Test timed out".

Bump the three affected tests to a 15s budget. The underlying paths
still complete in ~1-3s on healthy runs; the wider window only matters
when taskkill is slow to propagate.
2026-05-13 13:35:06 +08:00
YHH 7920b359e2 chore(plan): document magic numbers + swap stripAnsi for the standard package (#738)
Two follow-ups from the #734 merge that didn't justify another round
on the contributor's branch.

1. PlanConfirm.tsx — document what `EXPANDED_MODAL_OVERHEAD_ROWS = 12`
   and `EXPANDED_DETAIL_CHROME_ROWS = 4` actually count. Both are
   derived from the card chrome (header / step list / dividers /
   footer hints / picker); without the comment, the next person who
   reflows the modal won't know which constant to retune.

2. tests/plan-confirm.test.tsx — drop the inline
   `text.replaceAll("\x1b", "").replace(/\[[0-9;]*m/g, "")` helper for
   the `strip-ansi` package. The inline version only handled SGR
   subset; `strip-ansi` covers OSC 8 hyperlinks (which #730 now emits
   in plan markdown bodies) and CSI subparam edge cases. Promoted
   `strip-ansi` from a transitive dep (via `string-width`) to an
   explicit devDependency so the import doesn't break if the parent
   chain shifts.

Lockfile changed because `npm install` resynced the existing 0.39.1
→ 0.40.0 version drift and dropped now-orphaned `patch-package`
transitive entries — both pre-existing maintenance debt, no upgrades
on this project's own deps.
2026-05-13 12:55:56 +08:00
kabaka 74bdaf0d97 fix(plan): stabilize expanded approval modal layout (#734)
* fix(plan): stabilize expanded approval modal layout

Keep the expanded plan confirmation view from clipping or jumping while scrolling, and document the new Ctrl+P summary/detail toggle.

* fix(tests): restore React value imports for JSX runtime

Keep JSX-based Ink tests using value imports so Vitest can execute them during verify and push hooks.
2026-05-13 12:28:17 +08:00
YHH 5c54808ff1 feat(chat): /btw <question> — ask a side question without polluting context (#736)
Requested in #725. Borrowed from Claude Code: while you're deep in a
coding turn, sometimes you want to ask the model a quick unrelated
question without breaking the conversation flow or eating turns of
context budget. `/btw` runs the question against a fresh blank-slate
message list, displays the answer inline, and never touches
`loop.messages` — the next normal turn sees the same context it would
have seen if `/btw` had never been typed.

Implementation lives in the same App.tsx submit branch as `/resource`
and `/prompt`: intercept the command before the synchronous slash
dispatcher, call `loop.client.chat()` with `[system, user]` only,
push the answer through `log.pushInfo` with a `≫ btw` header.

The system prompt instructs the model to answer concisely, in plain
prose, with no tool calls or follow-up questions. The command runs at
the loop's current model (so `/preset flash` before `/btw` still saves
money on side questions).

Registry entry in `SLASH_COMMANDS` (chat group, `<question>` argsHint)
means the command surfaces in `/help`, the slash-suggestions palette,
and the `+ N advanced` count.

i18n strings:
- `app.btwUsage` — shown when `/btw` is typed bare
- `app.btwHeader` — the `≫ btw` answer-card header
- `app.btwFailed` — title for the warning card on API failure

Closes #725
2026-05-13 12:19:01 +08:00
YHH 12317dab8c fix(composer): keep the prompt cursor visible when the ticker suspends (#733)
Reported in #728: after a single round of dialogue the blue cursor in
the composer disappears and the user can no longer tell where typed
characters will land. Regression from #672, which traded the
hardcoded `cursorVisible = true` for `useSlowTick() % 2 === 0`.

The slow-tick frame is driven by Ink's shared animation timer, which
the TUI suspends whenever the conversation is idle:

  const tickerSuspended = modalOpen || (!busy && !isStreaming);

When the timer pauses, Ink's `useAnimation` stops advancing but keeps
returning the last frame value. If a streaming turn ran for an odd
number of seconds, the frame freezes on 1 (or 3, 5, …), so
`frame % 2 === 0` evaluates to `false` and the cursor stays blanked
indefinitely. The user only sees the cursor on the empty-input first
mount (frame 0) — every later idle state inherits whatever parity the
last active stretch happened to land on.

Add `useCursorBlink()` in `ticker.tsx` which combines the slow tick
with the ticker-active state: while suspended, force visible; while
active, blink each second as designed. Replace the single inline
expression in `PromptInput.tsx`.

Regression test in `tests/cursor-blink.test.tsx` mounts a probe inside
an active TickerProvider, advances fake timers past a slow tick so the
raw frame is odd, then rerenders with the provider suspended and
asserts the probe still reads `ON`. Without the active-guard it reads
`OFF` (the original bug).

Closes #728
2026-05-13 11:53:18 +08:00
YHH 79c7246a28 fix(embed): tolerate providers that drop inputs from a batch response (#732)
Reported in #727: SiliconFlow's `Qwen/Qwen3-VL-Embedding-8B` model
sometimes returns fewer entries in `data[]` than the number of inputs
in the request. Hit by index-build at chunk 8 of 72, with
`OpenAI-compatible response missing embedding at index 8`, which
hard-aborted the whole index pass — the user lost 71 already-embedded
chunks and had to switch models. The pure-text sibling
`Qwen/Qwen3-Embedding-8B` does not exhibit this.

The OpenAI-compat client used to validate full coverage with:

  for (let i = 0; i < out.length; i++) {
    if (!out[i]) throw new EmbeddingError(`... missing embedding at index ${i}`);
  }

That was correct against strict providers but wrong as a hard error
against providers that silently drop inputs. `embedAll`'s contract
already supports `Array<Float32Array | null>` and the index builder
already handles `null` slots by logging via `onError` and skipping
the chunk.

Change the OpenAI-compat path to match that contract:

- `requestOpenAICompatEmbeddings` now returns
  `Array<Float32Array | null>` instead of throwing on partial
  responses. Other validation (invalid index, non-array embedding,
  HTTP errors) still throws.
- `embedAllOpenAICompat` walks the returned array and routes each
  `null` slot through `opts.onError` so the index builder prints
  `! skipped path:start-end: provider dropped input N from the batch`
  for the dropped chunks and keeps going.
- `embedOpenAICompat` (single-text path) keeps the strict throw — if
  the provider rejects a single input there is nothing else to return.

Regression tests in `tests/semantic-embed-tolerant.test.ts` cover
both the SiliconFlow VL case (partial batch → partial result + per-
slot onError) and the single-text refusal (still throws).

Closes #727
2026-05-13 11:38:49 +08:00
YHH 4f247440f1 fix(wallet): pick the largest balance instead of balance_infos[0] (#731)
Reported in #724: when /user/balance returns both USD and CNY entries
(e.g. USD 4.99 top-up + dust CNY 0.47), the TUI status row, doctor
check, desktop kernel, and dashboard cockpit all rendered just the
first array entry — typically CNY in that order — making the account
look almost empty even though the user has real USD balance.

Five call sites were doing `balance_infos[0]!`:
- `src/cli/ui/useSessionInfo.ts` (initial fetch + refresh)
- `src/cli/commands/desktop.ts` (Tauri kernel `$balance` event)
- `src/cli/commands/doctor.ts` (api-reach check, both branches)

Add `pickPrimaryBalance(infos)` in `src/client.ts` that walks the array
and returns the entry with the largest `total_balance`. For the
common single-wallet account the behaviour is unchanged (the only
entry wins); for multi-wallet accounts the wallet the user actually
funded surfaces correctly.

`doctor`'s api-reach check additionally enumerates every wallet when
there are multiple, so a diagnostic now shows
`/user/balance ok — 4.99 USD + 0.47 CNY` instead of hiding one half.

The dashboard cockpit reads `stats.balance` which is constructed from
`balanceRef.current` (the primary surfaced by `useSessionInfo`), so
this fix propagates to the dashboard wire shape without separate
plumbing.

Unit tests in `tests/pick-primary-balance.test.ts` cover the empty
case, single-entry passthrough, the issue-#724 USD+CNY case, the
zero-USD fallback, and the tie-break invariant.

Closes #724
2026-05-13 11:32:00 +08:00
YHH 290d1d9db7 fix(markdown): emit OSC-8 hyperlinks so [text](url) is clickable in the TUI (#730)
Reported in #723: assistant replies containing `[text](url)` render as
blue underlined text but aren't actually clickable on hover — supporting
terminals (kitty, iTerm2, Windows Terminal, VSCode) need the OSC 8
hyperlink escape sequence around the label.

The `osc8()` helper in `src/cli/ui/markdown.tsx` was already named for
this — it just never emitted the escape. The `_target` parameter was
prefixed with an underscore because the function ignored it.

Wire it up properly:

- `osc8()` now wraps its child in `<Transform>` that emits
  `ESC ]8;; URL ESC \ ... ESC ]8;; ESC \` around the rendered text.
  Accepts `React.ReactNode` so it can wrap an `<Inline>` subtree (links
  with bold / em / codespan inside).
- The `case "link"` branch of `InlineToken` now routes through `osc8()`
  with `l.href` instead of a styled-but-inert `<Text>`.
- `SpanText` in `src/cli/ui/markdown-view.tsx` (used by PlanConfirm /
  PlanRefineInput) gets the same treatment so plan-modal links and
  file refs are also clickable.

Frame renderer at `src/frame/ansi.ts:146` already emits OSC 8
unconditionally; this matches that convention — terminals that don't
support OSC 8 silently discard the sequence.

Closes #723
2026-05-13 11:19:55 +08:00
YHH 77d1674419 fix(dashboard): memoise chat feed + rails to kill input-typing lag (#729)
Reported in #721: typing in the dashboard composer feels laggy on long
sessions. Root cause is that every keystroke commits to `input` state,
which forces ChatPanel to walk its entire vnode tree on each frame.

ChatMessage was already wrapped in memo (#560), so historical bubbles
short-circuit individually — but Preact still has to map() over every
message, evaluate the per-row `Boolean(streaming && streaming.id === m.id)`
discriminator, and diff each ChatMessage element. For a session with
100+ messages the per-keystroke work is enough to drop frames.

Move the message-list render into a `<ChatFeed>` sub-component and wrap
it in memo. With `messages` and `streaming` refs both stable while the
user is typing, memo bails the whole feed out — keystrokes no longer
touch the feed at all. SideRail and ChatStatusBar get the same
treatment so /overview poll churn and input edits don't repaint the
right-rail progress bars and statusbar.

Closes #721
2026-05-13 11:05:58 +08:00
YHH ddbe5d7036 docs(readme): thank AIGC Link for XiaoHongShu promotions (#726) 2026-05-13 09:55:51 +08:00
YHH 9957d2b6b4 feat(desktop): wire up stubbed UI surfaces; functional MCP + Skills pages (#722)
* feat(desktop): wire up stubbed UI surfaces, drop roadmap-only tabs

A pass over the desktop client looking for UI that *renders* without
actually doing anything. Found a fair amount of theater.

- context panel "工具" tab was showing a hardcoded list of fake MCP
  servers (filesystem/shell/search/edit, made-up tool counts, fake
  "ready" dots). Replace with real tool-call frequency from the
  current session's assistant messages; empty state when there are
  none yet.
- sidebar footer's "审批规则" and "设置" rows both invoked the same
  onOpenSettings callback. Route 审批规则 to the rules page via a new
  initialPage prop on SettingsModal; drop the stray ⌘, accelerator on
  the rules row since it doesn't open settings any more.
- settings nav had three pages whose body was literally a "在路线图上 /
  即将开放" card with no controls: MCP, Skills, and (kept) Memory.
  Drop MCP and Skills from the nav. Memory page stays — its copy
  about CLAUDE.md / AGENTS.md injection is at least true.
- add /export and /lang slash commands. The composer's slashIcon
  table already had icons for both — they were just never wired.
  /export reuses the existing exportConversation; /lang flips between
  en / zh-CN via the existing i18n setLang.
- ⌘, toggle, command palette, title bar, and status bar now go
  through a single openSettingsAt(page) helper so the modal opens on
  the right tab from each entry point.

* feat(desktop): restore MCP + Skills settings pages, now wired to backend

The previous commit on this branch dropped the MCP and Skills tabs as
roadmap-only placeholders. That was wrong — the CLI has both features
and the design mockup keeps tabs for them. Bring them back, properly
hooked up this time.

Backend (src/cli/commands/desktop.ts):
- new RPC commands: mcp_specs_get / mcp_specs_add / mcp_specs_remove
  / skills_get
- new emitted events: $mcp_specs (parsed specs + bridged flag) and
  $skills (project + global + builtin)
- specs are validated through parseMcpSpec before persisting; add /
  remove round-trip through readConfig / writeConfig
- skills load via SkillStore({ projectRoot: tab.rootDir }), so they
  follow the current workspace and re-emit on switchWorkspace
- both fire on initial $ready and on tab_open

MCP page (settings.tsx PageMCP):
- lists every configured spec with name + transport summary
- "移除" button → mcp_specs_remove
- input + 添加 button → mcp_specs_add (parser-validated)
- header notes that the desktop session doesn't itself bridge MCP
  yet, so changes take effect in TUI sessions; once we add the
  bridge in desktop.ts the bridged flag flips and the caveat
  disappears

Skills page (settings.tsx PageSkills):
- one card per skill: /name, scope, runAs, model override, full
  description, file path
- read-only — skills are markdown files on disk

* fix(desktop): settings body scrolls when content exceeds viewport

.settings is a grid (200px + 1fr) with fixed height; .settings-main is
flex column with .settings-head (intrinsic) + .settings-body (flex: 1,
overflow-y: auto). Skills page can render dozens of cards — once the
total exceeds the modal height, .settings-body wasn't scrolling
because .settings-main, a grid item with the default min-height: auto,
would let its content expand it past the grid track. The .settings
overflow:hidden then clipped the bottom instead of yielding a scroll
inside .settings-body.

Add min-height: 0 to .settings-main so the grid track bounds it, and
.settings-body's overflow-y:auto kicks in normally. All pages benefit;
Skills (variable count) and MCP (long URLs) are the visible wins.
2026-05-13 09:50:29 +08:00
YHH e1dbe9b312 feat(desktop): cmdk palette restyle, splash intro, workdir popover (#718)
The card-based UI rebuild had dropped the .palette-* styles, so Cmd+K
was rendering unstyled. Bring it back as .cmdk-* matching the mockup —
grouped (导航 / 动作 / 目录 / 设置), Search head icon, item-count footer.

While there: pull the rest of the mockup polish.

- splash intro on first launch (per session): plankton drift + whale
  silhouette glide + Reasonix wordmark reveal, ~3.3s, skippable by
  click / Esc / Enter / Space, sessionStorage-gated so HMR doesn't
  re-trigger it.
- workdir popover anchored to the main-head breadcrumb (also Cmd+O),
  lists Settings.recentWorkspaces, current dir checkmarked, falls back
  to the existing pickWorkspace dialog from a "browse local…" button.
- move the transient flashToast from bottom-center to bottom-right so
  it stops landing right on top of the Review/Auto/YOLO switch in the
  composer foot.

i18n: palette.group{Nav,Action,Workspace,Settings} + palette.countSuffix
+ workdir.{title,searchPlaceholder,empty,browse} for both en and zh-CN.
2026-05-13 00:08:36 +08:00
YHH f742e4aacd feat(acp): stage 3 — session/request_permission bridging shell + plan gates (#717)
Final ACP slice tracked in #103. Internal PauseGate requests
($confirm_required / $plan_required / $checkpoint_required /
$revision_required / choice) now surface to the ACP host as outbound
`session/request_permission` requests, and the host's response is
mapped back into the Reasonix verdict shape and resolved into the gate.
A Zed / JetBrains / AionUI host can now drive a real flow — including
shell command authorization forwarded to mobile via AionUI / Feishu —
end-to-end.

Mechanics:
  - AcpServer gains sendRequest(method, params) with id tracking +
    Promise-based resolution. Inbound responses (id + result|error,
    no method) route to the matching pending entry. close() rejects
    all in-flight outbound calls.
  - src/acp/gates.ts maps each PauseGate kind to the right
    PermissionOption list (allow_once / allow_always / reject_once)
    and converts the optionId in the response back into the internal
    verdict shape. Allow_always carries a command-prefix glob
    (`{firstWord} *`) or the path_access allowPrefix so the same
    decision auto-resolves next time via the existing pause-policy.
  - acpCommand registers a global pauseGate.on listener that uses
    AsyncLocalStorage to find the currently-running session and
    forwards the gate request. Gates outside any active session
    (rare — initialization races) get cancelled cleanly. The shared
    auto-resolve policy (review/auto/yolo) still runs first, so
    /run_command in yolo mode bypasses the host as expected.

13 new tests covering: outbound sendRequest happy-path and error
path, close() rejecting in-flight requests, permissionOptionsFor +
verdictFor mapping for shell / plan_proposed / plan_checkpoint /
plan_revision / choice, and an end-to-end requestPermissionForGate
round-trip via the live server.

Refs #103
2026-05-12 22:44:49 +08:00
OpenLucasKakaandzhongwj d6e0beb433 feat(chat): hint when no MCP servers are configured (#716)
Co-authored-by: zhongwj <[email protected]>
2026-05-12 22:43:41 +08:00
YHH 7ef6743005 feat(acp): stage 2 — tool_call / tool_call_update notifications (#715)
Builds on the stage-1 NDJSON foundation from #714. Internal tool events
now surface to ACP hosts as the corresponding session/update variants,
so a Zed / JetBrains / AionUI client sees real-time tool execution
matching what the TUI / desktop already show.

Mapping (in src/acp/dispatch.ts):
  - tool.preparing → tool_call (status=pending, kind classified from
    name)
  - tool.intent    → tool_call_update (in_progress) + a follow-up
    tool_call carrying rawInput (parsed from args JSON if valid, else
    the raw string)
  - tool.result    → tool_call_update (completed | failed) with the
    output wrapped as content[].content.text, clipped at 8000 chars
    with a truncation suffix

`toolKindFor()` maps internal tool names to the ACP-spec kinds:
read (read_file, glob, list_directory, …), edit (write_file,
multi_edit, …), search (search_content, search_files), execute
(run_command, run_background), other (everything else).

7 new tests in tests/acp.test.ts covering each variant + the
classification table + the clip threshold.

Refs #103
2026-05-12 22:23:44 +08:00
YHH ad7bac2a99 feat(acp): stage 1 — reasonix acp entrypoint, NDJSON framing, prompt round-trip (#714)
First slice of the ACP (Agent Client Protocol — agentclientprotocol.com)
support tracked in #103. Spawns reasonix as an ACP agent on stdio
NDJSON JSON-RPC 2.0; the cache-first loop and prefix hashing are
untouched, only the IO layer changes.

What stage 1 covers:
  - `reasonix acp` subcommand with --dir / --model / --preset / --budget
  - src/acp/ — JsonRpc types + NDJSON `AcpServer` (one object per line,
    no embedded newlines, per the transport spec)
  - initialize handshake with capability negotiation
  - session/new — builds a per-session CacheFirstLoop with its own
    toolset rooted at cwd (or the cwd from the request)
  - session/prompt — drives one turn, streaming `agent_message_chunk`
    and `agent_thought_chunk` via session/update notifications; returns
    `{ stopReason: end_turn | cancelled | error }` on completion
  - session/cancel — notification aborts the in-flight turn cleanly,
    leaving the session reusable for the next prompt

What's deferred to stage 2 / stage 3 (tracked in #103):
  - tool_call / tool_call_update notifications (stage 2)
  - session/request_permission for $confirm_required / $plan_required /
    $checkpoint_required gates (stage 3)
  - plan updates and authorize round-trips
  - session/load (loadSession capability advertised as false for now)

Tests: 10 in tests/acp.test.ts covering framing, method/notification
dispatch, parse-error response, internal-error response, and the
initialize handshake contract.
2026-05-12 22:18:02 +08:00
Evan-Pycraft b9ef471657 feat(config): add statusBar toggles to hide individual status row fields (#626) (#712) 2026-05-12 21:59:22 +08:00
YHH 0937c6c43b feat(memory): user-defined memory types with priority + expires (#711)
Hardcoded four types (user / feedback / project / reference) didn't scale
for teams whose memory bucket actually wants distinct categories — non-
negotiable security rules, design-system conventions, deploy checklists,
etc. Without a real type they all collapse into `reference` and the model
treats a security constraint with the same weight as a style note.

Changes:
  - MemoryEntry.type relaxed to `BuiltinMemoryType | (string & {})`; the
    four built-ins stay in BUILTIN_MEMORY_TYPES for UI / docs.
  - MemoryEntry gains optional `priority: low|medium|high` and
    `expires: project_end`. Both round-trip through frontmatter.
  - config.memory.customTypes — new ReasonixConfig field. Each entry can
    set a default priority + expires for its type name.
    loadMemoryTypeRegistry() merges built-ins with the config overlay
    (rejecting bad names and built-in collisions).
  - applyUserMemory now scans for high-priority entries (own field OR
    the type's config default) and prepends a `# HIGH PRIORITY
    constraints (must observe)` block with `!!! [scope/type/name]`
    headings ahead of the regular memory index — so security-class rules
    get the strongest framing the system prompt offers.
  - `/memory list --type X` filters by type; list rows get `⚠` for high
    and `·` for low priority.
  - `/memory clear project confirm` additionally removes any global-scope
    entry with `expires: project_end` (lifecycle tied to the project).
  - The `remember` tool drops its hardcoded enum, surfaces the config-
    declared custom types in its description, and accepts `priority` /
    `expires` parameters.

Behavior is fully backward compatible: existing memory files without the
new fields parse and inject exactly as before; an empty config produces
zero behavior change.

Closes #709
2026-05-12 21:37:12 +08:00
ForeverYoungPp 7a75d1b8f8 Changes panel fixes (#707)
* fix(changes-ui):remove dead + button, widen editor/diff line number gutters

* fix(changes): file tab click now exits review mode
2026-05-12 21:18:29 +08:00
Evan-Pycraft 046e5b6e79 feat(i18n): add marketplace zh-CN overlay + fix remaining TUI gaps (#706) 2026-05-12 21:16:27 +08:00
YHH 733aa8b6a1 feat(desktop): rebuild UI on the new card-based design system (#710)
Replace the ad-hoc components.tsx / toolRenderers.tsx tree with a card
system organized per kind (plan, reasoning, shell, tool, diff, error,
approval, etc.), each with a tone palette and built against the design
mock-ups in IBM Plex.

UI surface:
  - Composer gains a Review / Auto / YOLO mode switch wired to
    settings.editMode and a working preset dropdown (auto / flash / pro).
    Paperclip and image buttons now open a file picker and insert the
    pick as an @-mention. Narrow-width adaptation hides labels first,
    then shrinks the model pill, before anything overflows.
  - Title bar gets a real "more" menu (palette, export, clear, settings).
    Status bar exposes currency toggle (CNY / USD) instead of a no-op
    language toggle. ⌘B toggles the sidebar, ⌘⌥B the context panel.
  - YOLO triggers a hatched red sub-header strip under main-head with a
    one-click "back to Review" button, so the dangerous mode is never
    silent.
  - Toast styling that got lost in the stylesheet swap is restored.

Backend:
  - emitSessions includes meta.summary, and runTurn writes a 60-char
    summary on the first user input of a session, so the sidebar shows
    real chat titles instead of `desktop-202605121013-1`. Main-head H1
    falls back to the first user message of the in-flight session.

Everything is wired to the existing RPC contract (settings_save,
mention_query / preview / picked, session_load / delete, the five
pending kinds). No new transport.
2026-05-12 21:12:44 +08:00
esengine 9ce1acc7cc docs(readme): distinct badge colors + canonical contrib.rocks repo name
- vary the right-side color per badge so they stop reading as one dark blob; keep labelColor 161b22 for cohesion. add npm/CI/node logos. drop the static color override on CI so the badge reflects real build status.
- point contrib.rocks at the canonical esengine/DeepSeek-Reasonix; the old esengine/reasonix worked via GitHub redirect but contrib.rocks served a stale 9-author snapshot. switching the cache key forces a regen with all 18.
2026-05-12 04:58:40 -07:00
YHH 1b48ab59bc release: 0.40.0 — Tauri client (source only), checkpoint API, plan rail, CardStream fix (#705)
npm-only release. The Tauri desktop source is in the repo and the CLI
subcommand works, but installer bundles for macOS / Windows / Linux
don't ship this round (separate release once signing's settled).

Highlights:
- Tauri desktop client with multi-tab concurrent runtimes (#689)
  plus a near-full polish pass: wallet balance, version chip, active-
  plan rail, abortable pause-gates, edit-gate pill, en + zh-CN i18n,
  shared pause-policy module dedup'd with the CLI TUI (#701)
- checkpoint API + git-changes panel in the embedded dashboard (#682)
- outside-sandbox file access approval modal (#696)
- MCP loading pill + readiness gate on tool dispatch (#687)
- escalate-after flag for flash → pro threshold (#699)

Fixes:
- CardStream Maximum-update-depth crash, quantize window so boundary
  cards stop oscillating (#700, #702)
- `reasonix code` bridges config key to env + lazy subagent client so
  fresh installs can reach the setup wizard (#703)
- pinned-mode scroll shrinks coalesced (#666), generic CSI key decode
  (#692), shell-confirm preview clamp (#691), frontmatter BOM/folded
  lines (#690), MCP error classification (#688), and more
2026-05-12 19:16:58 +08:00
YHH 0ca2c6b021 fix(code): bridge config key into env + lazy subagent client (#703)
`reasonix code` crashed at boot with "DEEPSEEK_API_KEY is not set" for
two reasons stacked:

1. code.tsx never bridged ~/.reasonix/config.json → process.env the way
   chat.tsx / desktop.ts / run.ts do. A key the user stored via
   `reasonix setup` was invisible to `code`.

2. buildCodeToolset eagerly constructed a DeepSeekClient for the
   subagent runner. With no env key, the constructor throws — before
   chatCommand mounts the wizard that would prompt for one.

- code.tsx now calls loadDotenv() + bridges loadApiKey() into env at
  the top of codeCommand, mirroring chatCommand's setup
- setup.ts defers the subagent DeepSeekClient to first dispatch so
  toolset construction succeeds even when no key is configured yet
- new tests/code-setup-lazy-subagent.test.ts pins the invariant
2026-05-12 19:05:35 +08:00
YHH adf62e8a32 fix(tui): quantize CardStream window so boundary cards stop oscillating (#702)
Same shape as #549. In pinned mode scrollRows tracks maxScroll, and
maxScroll = inner.height - outer.height. The items useMemo depends on
both scrollRows and outer.height, so a sibling row toggling (ToastRail
appearing, ThinkingRow flipping) shifts outer.height by ±1 → window
moves → a card straddling the live↔spacer boundary flips → inner.height
changes by Δ → setMaxScroll → scrollRows changes → useMemo recomputes →
card flips back. With flash streaming compounding inside the same React
batch, the chain reaches MAX_NESTED_UPDATES and aborts inside ink's
useBoxMetrics (#700).

Quantize the window position to VISIBLE_BUFFER_ROWS buckets. Sub-bucket
scrollRows / outer.height wiggles now map to the same window, so items
is referentially-stable across them and the feedback loop dies on the
first re-render.

- extract computeCardStreamItems as a pure exported function for tests
- new tests/card-stream-items.test.ts asserts live-set stability across
  every sub-bucket scrollRows delta and a range of outer.height values

Closes #700
2026-05-12 18:51:40 +08:00
YHH 0b2a2959ea feat(desktop): wallet + version, plan rail, i18n, gate fixes (#701)
* fix(i18n): point session banners + overflow error at /new and /sessions

The top-level /forget command was removed in the slash refactor, but
the resumed-session and new-session banners + the context-overflow
error still told users to type it. Point them at the surviving paths
instead: /new for a fresh start, /sessions ([d] to delete) for
manage / rename / drop.

Closes #697

* feat(desktop): surface version + wallet balance, fix ⌘K Settings

Tauri shell had no visible version or DeepSeek balance, and ⌘K's
Settings was a stub toast despite SettingsPanel being mounted.

- $settings now carries VERSION → version chip in Sidebar brand
- new $balance event polls /user/balance on startup, after each
  turn, and after key/workspace changes → wallet card in Sidebar
- ⌘K Settings opens the existing panel; About shows real version
- ⌘K gains New/Close tab, Stop turn, Copy/Export reply, Pick workspace

* feat(desktop): localize UI strings (en + zh-CN) with live toggle

Tauri shell was a mix of English labels and Chinese hints with no
way to switch. Add a small React i18n module (localStorage + listener-
based re-render), seed en / zh-CN dictionaries, and surface a Language
picker in Settings.

- new desktop/src/i18n/{index,en,zh-CN}
- migrate ⌘K palette items, sidebar nav + wallet label, App toasts,
  composer placeholder + kbd hints, plan/choice modal placeholders
- Settings grows a Language section; auto-detect from navigator.language
  on first launch, sticky via reasonix.lang

* feat(desktop): active-plan rail + checkpoint card, abortable plan gates

Desktop dropped plan_checkpoint and plan_revision pause-gate requests on
the floor and abort only flipped the per-turn AbortController, so once
mark_step_complete fired the user was wedged with no UI response and no
way out.

- pause-gate: new cancel(id) using existing safeCancelVerdict
- desktop CLI: per-tab pendingGateIds + completedStepIds; abort now
  drains gates via cancel(id), emits $plan_cleared
- desktop CLI: emit $plan_required steps, $checkpoint_required (with
  done/total), $revision_required, $step_completed, $plan_cleared
- desktop UI: state grows activePlan, pendingCheckpoints,
  pendingRevisions; reducer wires resolve_plan(approve) → activePlan,
  resolve_revision(accepted) → swap remaining steps
- desktop UI: new ActivePlanRail above messages (collapsible, progress
  bar, per-step risk + result), CheckpointCard (continue/revise/stop),
  RevisionCard (accept/reject/cancel); Stop button in rail when busy
- i18n: plan / checkpoint / revision strings in en + zh-CN

* feat(desktop): localize Settings panel, drop ThinkingBar Stop button

Settings panel still rendered every section label, hint, and option
description in hardcoded English. Toggling the language picker did
nothing for the panel itself.

ThinkingBar had its own Stop pill on the right while the composer's
send button already turns into Stop when a turn is in flight. Two
buttons for the same action.

- migrate every SettingsSection label / hint / option name + desc
  through t(); editor presets and api-key inline buttons too
- new settings.* keys in en + zh-CN
- ThinkingBar: drop onStop prop + button + .thinking-bar-stop CSS
- App.tsx: stop passing onStop={abort} to ThinkingBar

* fix(desktop): yolo + plan-rail bugs; dedupe auto-resolve policy

Two real bugs from the desktop diverging from CLI TUI behavior:

1. YOLO still asked at every plan_checkpoint. Two causes:
   a. Desktop UI's editMode union used "default" but config.ts canonical
      values are "review" | "auto" | "yolo". loadEditMode() coerces
      anything else to "review", so picking "default" silently wrote
      review and every checkpoint paused.
   b. Even with the right wire value, the desktop's pauseGate.on listener
      had no auto-resolve branch — only CLI TUI App.tsx did.

2. ActivePlanRail never cleared. No "plan done" signal existed; rail
   lingered after the final mark_step_complete.

Fixes:

- new src/core/pause-policy.ts — one source of truth for editMode→gate
  rules; CLI TUI App.tsx and desktop CLI listener both call
  shouldAutoResolveCheckpoint / autoResolveVerdict instead of inlining
  the same `mode === "auto" || mode === "yolo"` check
- desktop CLI listener auto-resolves plan_checkpoint via the shared
  helper, still emitting $step_completed so the rail ticks
- desktop CLI emits $plan_cleared on turn_complete when all steps done
- desktop UI: editMode union retyped to "review" | "auto" | "yolo"
  end-to-end (App, Header pill, SettingsPanel, protocol); CSS class
  .edit-pill-default renamed to .edit-pill-auto
- ActivePlanRail: optional onDismiss × button for manual clear of plans
  that arrive with no structured steps (and thus no turn_complete trigger)
2026-05-12 18:38:07 +08:00
Dimas D. Angga 9cfe3d3ea6 feat(loop): make flash→pro escalation threshold configurable (#699)
The hardcoded threshold of 3 repair signals escalates too eagerly on long subagent runs where transient tool failures are expected and recoverable on flash. Exposing this via `escalation.failureThreshold` in config and `--escalate-after` on the CLI lets users tune escalation to their workload without forking the loop, while preserving the existing default and behaviour for everyone else.
2026-05-12 17:32:06 +08:00
YHH bb5bf676ac fix(i18n): point session banners + overflow error at /new and /sessions (#698)
The top-level /forget command was removed in the slash refactor, but
the resumed-session and new-session banners + the context-overflow
error still told users to type it. Point them at the surviving paths
instead: /new for a fresh start, /sessions ([d] to delete) for
manage / rename / drop.

Closes #697
2026-05-12 16:59:00 +08:00
YHH 08a41e7933 feat(sandbox): gate outside-sandbox file access through an approval modal (#696)
Filesystem tools now route any absolute-system path that escapes the
project sandbox (`/Users/foo`, `/etc/...`, `C:\Users\...`) through a
new PathConfirm modal: allow once / always allow this directory / deny.
Mirrors the existing run_command flow — a shared PauseGate kind
`path_access`, a per-project `pathAllowed` list persisted in
~/.reasonix/config.json, and a session-scoped run-once cache so
follow-up reads under an approved directory don't re-prompt.

Closes #684
2026-05-12 16:38:39 +08:00
ForeverYoungPp 581848181d feat(changes): checkpoint API + git changes panel with zero external deps (#682)
* feat: checkpoint API + git changes panel with zero external deps

* fix(changes): Cross-site scripting vulnerability as the output of this final HTML sanitizer step may contain double quotes when it reaches this attribute definition.

* fix(changes): The file may have changed since it was checked

* fix(comment): shorten block comment to comply with policy

* fix(file-read): TOCTOU race + path traversal guard
2026-05-12 16:01:18 +08:00
YHH 2a9959c3c1 fix(stdin): decode generic modifyOtherKeys / Kitty CSI envelopes (#692)
Reasonix enables xterm modifyOtherKeys=2 at startup. Under that mode,
terminals re-encode any printable key whose Ctrl variant would produce
a control byte — `@` (^@=NUL), `[` (^[=ESC), `\`, `]`, `^`, `_` — as
`\x1b[27;<mod>;<cp>~`. The parser only had hardcoded entries for the
Tab / Enter modifier sequences, so those printables hit lookupCsi,
returned null, and were dropped silently. Reported under ghostty on
Ubuntu 25.10; the same shape also affects any xterm-compatible host
that honors the mode.

Adds a generic decoder for both the xterm `27;mod;cp~` and Kitty
`cp;mod u` / `cp u` envelopes, mapping back to the keystroke that
would have arrived as a bare byte without the mode.

Closes #683
2026-05-12 15:52:09 +08:00
YHH 19ec49bebb fix(ui/shell-confirm): clamp long command preview so options stay visible (#691)
A 30-line python heredoc pushed the SingleSelect and footer past the
viewport so users couldn't see (or pick) "allow once / always / deny".
Clamp the preview to (totalRows - 18) lines with a "… N more lines
hidden" hint, leaving the action footer on screen at every terminal
height.

Closes #680
2026-05-12 15:26:15 +08:00
YHH 140f97fc72 fix(skills,memory): handle BOM, folded lines, and quoted values in frontmatter (#690)
* fix(skills,memory): handle BOM, folded lines, and quoted values in frontmatter

The three local copies of the frontmatter parser all skipped files with a
UTF-8 BOM, dropped indented continuation lines, and left wrapping quotes
in description values. Consolidates them into one parser that strips the
BOM, folds indented continuations onto the preceding key, and unwraps
matching single/double quotes after folding.

Closes #678

* fix(frontmatter): guard against prototype-pollution keys

The KEY_RE regex matches `__proto__` / `constructor` / `prototype`, so a
bracket write `data[key] = value` could mutate Object.prototype. Switch
the accumulator to a Map (no prototype to pollute), filter forbidden
keys at both the set and materialization sites, and return a
null-prototype object. Resolves CodeQL js/prototype-pollution-utility.
2026-05-12 15:26:09 +08:00
YHH 63472b6814 feat(desktop): introduce Tauri client with multi-tab concurrent runtimes (#689)
Native shell that drives a new `reasonix desktop` JSON-RPC subcommand
over stdio. Each tab owns an independent CacheFirstLoop, workspace,
session, and file/symbol index so two projects can stream in parallel
without crossing context.

Extracts buildCodeToolset into src/code/setup.ts so the desktop and
the `code` command share an identical tool surface. While extracting,
wires up web (web_search / web_fetch) and skill (run_skill +
subagent runner) tools — they were exported but never registered.

pauseGate confirm / choice / plan requests route via AsyncLocalStorage
so concurrent turns can't cross approvals. CacheFirstLoop._turn now
advances past loaded assistant messages on resume — the frontend's
turn-keyed message map would otherwise treat a fresh streaming
response as a duplicate of an historical message.

Release workflow builds Tauri bundles for linux-x64, macos-arm64,
macos-x64, windows-x64 on tag push and uploads to GitHub Releases.
Signing keys flow through env (Apple notary, Windows Authenticode,
Tauri updater); see desktop/SIGNING.md.
2026-05-12 15:14:31 +08:00
Dimas D. Angga e22904df0b fix(mcp): classify network, TLS, and HTTP errors in inspect failures (#688)
Raw Node error codes and bare HTTP status lines from SSE/Streamable-HTTP transports leave users guessing at the next step. Mapping DNS/connection/TLS codes and 401/403/404/5xx responses to targeted `try:` hints turns `reasonix mcp inspect` output into something users can act on without reading the source.
2026-05-12 10:53:19 +08:00
Dimas D. Angga c07739e817 feat(mcp): show loading pill and gate tool dispatch on readiness (#687)
Tool calls invoked during MCP handshake were surfacing transport errors because the bridge had no signal that the server was still connecting. A per-server readiness deferred lets dispatches wait (capped at 30s) instead of failing, and a status-bar pill makes the otherwise-invisible background load legible to the user.
2026-05-12 10:15:12 +08:00
Evan-Pycraft efdeb2559b feat(i18n): localize MCP lifecycle, slow toast, and external editor messages with zh-CN (#679) 2026-05-12 09:41:34 +08:00
YHH cd9f12a017 feat(tools/web): bucket 5xx separately with a transient-retry hint (#676)
#632 actionable-error work stopped at 429 + 403 — generic 5xx still
fell through to the catch-all "rephrase the query / switch engine"
message, which is the wrong advice for a transient server-side
failure. Add serverError5xx + fetchServerError5xx pointing the model
at a browser sanity-check and a 30s retry instead.

Existing webSearch 503 test tightened from `/web_search 503.*try:/`
to assert on the new `retry in 30s` substring; a parallel webFetch
502 test added in the same shape.

Credit to @MyPrototypeWhat — #671 surfaced the gap and the 503 test
case lands with this PR.
2026-05-11 20:12:37 +08:00
YHH 60f5b279dc chore(tools,loop): use process.stderr.write for readOnlyCheck warnings (#673)
#670 landed with console.warn for the buggy-readOnlyCheck surface, but
the rest of the project writes diagnostics via process.stderr.write
(see commit.ts, the mcp-stdio dropped-line trace, etc.). Align the two
catch blocks to match. Test updated to spy on process.stderr.write
instead of console.warn.

No behavior change — both routes land on stderr; this is purely a
consistency fix so future grep-for-diagnostics stays one-shot.
2026-05-11 19:42:50 +08:00
MyPrototypeWhat 7527917dca feat(tools,loop): warn when readOnlyCheck throws instead of swallowing it (#670)
Closes #629.

Two catch blocks treat a throwing readOnlyCheck as 'not read-only' and
move on:

- src/tools.ts isReadOnlyCall — used by plan-mode refusal
- src/loop.ts isMutating — used by the storm-breaker window

If the check itself has a bug, nobody sees it; the tool just silently
behaves as if it were mutating. Log the exception on console.warn at
each catch so the bug surfaces during development without changing
default-on-throw semantics.
2026-05-11 19:37:08 +08:00
MyPrototypeWhat 24e30719df Mcp debug log malformed (#669)
* feat(mcp): add REASONIX_DEBUG_MCP env var to surface dropped stdio lines

Closes #630.

The MCP stdio transport silently discards lines that fail to parse as
JSON-RPC, since servers typically emit non-JSON banners during startup.
That hides real wire-level bugs — truncated or corrupted frames produce
empty tool results with no clue why.

Gate a stderr trace behind REASONIX_DEBUG_MCP=1 so the noise only shows
up when a developer opts in.

* test(mcp): wait on child exit instead of fixed 250ms sleep

Fixed-time waits flake under cold Node spawns on slow CI (Windows
runners routinely exceed 250ms). The messages() iterator returns when
the transport closes, and Node guarantees stdout 'data' events fire
before 'close', so by the time the iterator returns every malformed
line has already been routed through the synchronous catch.

Also added a '0' case to actually distinguish 'off' from 'on' (the
prior 'truthy non-1' case only covered 'true', which was redundant
with the empty-string case).
2026-05-11 19:30:51 +08:00
YHH 185b4cb7e1 polish cards, composer cursor, shell modal info rows (#672)
* feat(cards): polish user / reasoning / task to match design tokens

UserCard: drop accent stripe — user is a conversational anchor, not
status. Use neutral CARD.user (muted ◇ + bg-elev pill) and prefix the
body with a fg.sub ↳ anchor.

ReasoningCard: tighten the four-tier render. Streaming → tail-3 with a
⋮ overflow marker (was tail-4, no marker). Settled-short shows the
whole body with anchor; settled-medium splits head + tail with a mid
`⋯ N lines elided` row. XL (≥800 tok) drops the head and surfaces a
`⋯ N ¶ + ~T tok scrolled past · /reasoning last` line — the head at
that scale is almost always restating a prompt the model has moved
past. Empty reasoning (model skipped thinking) renders a grayed
PILL_SECTION.empty pill + italic "no thinking — direct answer" hint
so the absence is explained, not silently missing. Body anchor ↳
shows only when the absolute start is visible.

TaskCard: section pill with status-mapped tones (task / taskDone /
taskFailed) replaces the bare glyph + "step N/M" prefix. Subtitle
becomes "N / M  Title". Step rows wrap the target in a PILL_PATH chip.

* feat(composer): blink the prompt cursor at 1Hz via slow tick

cursorVisible was hardcoded true. Drive it from useSlowTick() so the
block cursor toggles each second when the input is idle. During
typing, value/cursor changes already drive re-renders so the blink
doesn't interfere visibly.

* feat(shell-confirm): show cwd + timeout / wait info rows

The modal previewed the command but not where or for how long it would
run, leaving the user to infer cwd from session context and trust the
default 120s timeout silently. Surface both as faint info rows below
the `$ command` line — `cwd ~/projects/reasonix`, `timeout 120s` for
run_command, `wait 3s` for run_background when waitSec is set.

Threading: PausePayloadMap.run_command and run_background gain
optional cwd + timeoutSec / waitSec fields; shell.ts computes
effectiveTimeout before gate.ask so the modal sees the same number the
runtime will enforce; App.tsx pendingShell mirrors the wider payload.
Audit casts still see {command} — the extra fields are ignored at the
audit boundary on purpose.

tests/shell-tools.test.ts: the regression test now uses toMatchObject
to accept the wider payload while still asserting kind + command.
2026-05-11 19:27:36 +08:00
YHH 5b7eeb62e2 feat(status): surface preset in the status bar; pin model on manual pick (#668)
Two related UX failures landed together because users couldn't tell what
was actually controlling the model:

1. Users saw `● auto` in the StatusRow (which is the EDIT-GATE mode) and
   assumed it was the preset. Running `/preset pro` left both visible
   `auto` indicators (StatusRow + LiveRows ModePill) unchanged, because
   neither rendered the preset — usePresetMode's React-state mirror was
   never wired to the agent store, and the slash handler didn't call
   setPreset / dispatch at all.

2. People reach for `/model <id>` instead of `/preset` to switch models.
   `/model` only touched `loop.model`, leaving `autoEscalate` whatever
   the active preset had set — so `/model deepseek-v4-flash` from the
   default `auto` preset still let flash escalate to pro on hard turns.
   And nothing wrote `cfg.preset`, so relaunch silently reverted.

Changes:
- StatusRow: prefix the edit-gate mode label with `edits:` (new i18n key
  `statusBar.editsLabel`) and render a new `▴ <preset>` pill after it.
  Pill falls back to the short model name when the user is on a model
  outside the three presets. Hidden below 60 cols (same pattern as
  WALLET_MIN_COLS).
- `StatusBar.preset` + new `session.preset.change` event, reducer entry,
  and a mount-only useEffect in App that seeds the initial value from
  loop state so the first paint is correct.
- `/preset` slash handler now dispatches the preset change and persists
  via new `savePreset()` (mirrors saveReasoningEffort). `/model` does
  the same: turns off `autoEscalate` (manual pick = explicit pin),
  dispatches inferred preset (pro/flash/null), and persists when known.
- ModelPicker `kind:"select"` and `kind:"preset"` outcomes get the same
  treatment, plus the dashboard's `applyPresetLive`.

After: switching to pro via `/preset` or `/model` shows `▴ pro` in the
status bar, sticks across the session (no silent escalate-back), and
survives relaunch.
2026-05-11 18:32:45 +08:00
Dimas D. Angga 7ac18f541e fix(scroll): coalesce pinned-mode shrinks to stop double-Esc flicker (#666)
When an Esc abort tears down multiple subagent cards at once, each card's re-measurement called setMaxScroll synchronously, snapping scrollRows N times and bouncing the viewport past one screen. Holding a trailing-edge target on a microtask flush collapses the burst into one settled transition while keeping grows immediate so streaming output stays pinned without latency.
2026-05-11 17:46:48 +08:00
YHH fa3a97a107 fix(prompt): document OS-absolute paths, ban filesystem-refusal hallucinations (#667)
A user pasted `D:\VS_project\...\GraspAnalysisCommand.cpp` inside the
workspace; the model hallucinated "I cannot access the filesystem"
and ran `web_search` for a private local cpp file instead of just
calling `read_file`. The Path-conventions block only documented
POSIX-absolute as accepted, leaving Windows drive-letter paths to
the model's imagination — which here defaulted to "refuse".

`safePath` already accepts any shape that resolves inside the sandbox
(src/tools/filesystem.ts), so this is purely a prompt clarification
plus an explicit ban on the refusal patterns we observed in the wild:
shape-based refusals, "no filesystem access" claims, and `web_search`
fallbacks for local paths.
2026-05-11 17:35:18 +08:00
YHH daf539913b chore(release): 0.39.1 (#664)
Hotfix for 0.39.0 install failure: the `postinstall: patch-package`
hook + missing `patch-package` runtime dep + missing `patches/` in the
files array meant fresh `npm install` / `npx reasonix@latest` runs
crashed before the binary was usable. 0.39.0 has been deprecated on
npm and `latest` rolled back to 0.38.0.

Removes the patch-package machinery entirely — it can't work for a
published library since npm hoists `ink` out of reasonix's own
`node_modules`. The ink alt-screen render fix (#639) will return via
a forked ink + `npm:` alias (#663) in a later release.

Piggybacks three PRs that landed since 0.39.0:
- #632 fix(web): actionable web_search / web_fetch errors
- #661 feat(composer): Ctrl+X opens \$EDITOR
- #662 feat(composer): Ctrl+P / Ctrl+N picker navigation
2026-05-11 16:55:15 +08:00
YHH 6782e90baf feat(composer): Ctrl+P / Ctrl+N navigate input-prefix pickers when open (#662)
When any of the three input-prefix pickers is active — slash command
(`/`), @-mention file picker, or slash-argument enum picker — Ctrl+P
and Ctrl+N now move the highlighted row up/down, matching what ↑/↓
already do. Falls through to prompt-history recall when no picker is
open, so single-key bash parity is preserved.

Previously Ctrl+P/N always handed off to history recall regardless of
picker state — reported as keymap inconsistency in issue #647 (the
external-editor change is its own PR; this is the keymap half).

Implementation: `App.tsx` wraps `recallPrev` / `recallNext` from
`useInputRecall` in two memoized callbacks that consult atState /
slashArgMatches / slashMatches first (priority matching the existing
↑/↓ handler's order), and routes them into `PromptInput` instead of
the raw recall functions.

Closes #647
2026-05-11 16:45:33 +08:00
YHH f3a42511e9 feat(composer): Ctrl+X opens $EDITOR with the current input (#661)
Composes a long prompt in the user's preferred editor instead of
typing it inside the TUI. Match for opencode's `<C-x>e` and codex's
`<C-g>` (issue #647).

Editor resolution follows the standard Unix precedence: $GIT_EDITOR →
$VISUAL → $EDITOR. Picked an explicit GIT_EDITOR-style fallback over
hardcoding nano/notepad so the user's existing shell config carries
through. Missing-editor and non-zero-exit cases surface as a warning
card in the chat log; on success the buffer is replaced with whatever
the user saved (one trailing newline stripped, since most editors
auto-append one).

Implementation notes:
- New action flag in multiline-keys (`openExternalEditor: true`) so the
  pure reducer stays testable and PromptInput just signals up.
- App.tsx flips raw-mode off around the spawn so the editor can use
  cooked line-buffered input; bracketed-paste / alt-screen are managed
  by the editor itself via DEC mode 1049.
- Spawn uses `shell: true` so $EDITOR strings like `nvim --noplugin`
  or `code --wait` split correctly across platforms (same shape as the
  existing `commit.ts` editor invocation).

Refs #647 (the picker-keymap half of that issue is a separate change).
2026-05-11 16:39:04 +08:00
Dimas D. Angga 8aed2079ad fix(web): make web_search and web_fetch errors actionable (#632)
* fix(web): make web_search and web_fetch errors actionable

Bare HTTP status codes and terse refusal messages gave the model no signal about what to do next, leading it to either retry blindly or abandon the tool. Each error now carries a short " — try: …" tail tailored to the failure mode (429 backoff, 403 client-block, timeout, oversize body, unreachable SearXNG, invalid URL) so the model can self-correct without a human in the loop.

* style(tests): reformat web-tools assertions for biome

Biome's formatter flagged the existing single-line `expect(...).rejects.toThrow(...)` calls as needing the multi-line layout. Reformat to satisfy the formatter so `npm run lint` is clean.
2026-05-11 16:38:19 +08:00
YHH 791691c7e3 chore(release): 0.39.0 (#659) 2026-05-11 15:47:51 +08:00
YHH cf0e920916 fix(markdown): decode HTML entities in code blocks and inline code (#658)
The reporter showed a JSON snippet rendered as
`{ &quot;apiKey&quot;: &quot;...&quot; }` inside a code fence — the
model emitted literal HTML entities instead of `"`. marked passes the
entities through verbatim (its tokens carry the raw text, not HTML-
escaped output), and our renderer rightly hands that to the terminal
unchanged. Terminals don't render entities, so they leak as visible
`&quot;` / `&amp;` / `&lt;` etc.

This is a known LLM artifact: models sometimes HTML-escape inside code
blocks, especially on JSON / HTML / XML output, because their training
saw a lot of HTML-encoded code in web posts and docs. Both Claude Code
and Cursor decode entities at the rendering boundary; doing the same
here.

Scope: only code blocks and inline code spans (the contexts where
models leak entities the most). Prose paragraphs are left alone — if
someone genuinely writes "use the `&amp;` entity to escape ampersand"
in non-code text, the entity name stays visible. Numeric forms
(`&#34;` / `&#x22;`) and the five common named forms (quot / apos /
amp / lt / gt / nbsp) decode; unknown names pass through so we don't
corrupt prose that quotes entity names.

Closes #657
2026-05-11 15:38:08 +08:00
Evan-Pycraft 85ca307642 feat(i18n): localize MCP marketplace, browser, checkpoint picker, plan revise confirm, diff/replay tools with zh-CN (#654) 2026-05-11 15:25:18 +08:00
YHH 7aabb4a8fa fix(ui): render user-message cards verbatim, not through Markdown (#656)
UserCard ran every user message through `<Markdown>`, so pasting code
or stack traces into the composer caused the displayed card to silently
reinterpret markdown punctuation: `*foo*` rendered italic, `# title`
collapsed into an H1 (the `#` vanished), `[label](url)` rewrote to an
underlined link with the URL hidden, four-space-indented lines
restyled as a code block, etc. The model still received the full
verbatim text — but the user's visible round-trip (`what I sent` →
`what I see in history`) was wrong.

Render as a plain `<Text>` instead. Assistant turns keep Markdown
(that's the only place formatted output belongs).

Closes #655
2026-05-11 15:23:13 +08:00
YHH 4d3e868aed fix(tools): short-circuit a 2nd consecutive identical malformed call (#652)
In a real review session, the model called `read_file({})` (missing
required `path`), got the standard "missing required parameter ..."
error back, and the very next turn issued the *exact same* call — same
empty args, same tool. Same error came back. After the second rejection
it gave up tool-calling entirely and went to summary. The existing
StormBreaker uses a 6-call window with threshold=3 across all tools, so
the two-in-a-row malformed-args shape never tripped it.

ToolRegistry now tracks the per-tool fingerprint of the last call that
failed schema validation (JSON parse error or missing required param).
On the second consecutive identical malformed call to the same tool the
result switches to a sharper "same call just failed validation — DO NOT
retry with identical args" plus `consecutiveMalformed: true` so callers
can spot it programmatically. Any successful validation for that tool
clears its streak; per-tool tracking keeps interleaved unrelated tools
from interfering.

Closes #651
2026-05-11 15:05:19 +08:00
YHH 277098b6fb fix(net): honor HTTPS_PROXY / HTTP_PROXY / ALL_PROXY for all fetch calls (#650)
Node's built-in fetch is undici under the hood, but undici ignores the
standard proxy env vars unless you explicitly install a ProxyAgent on
its global dispatcher. Users behind a corporate or local proxy were
getting opaque connection failures from every network surface — DeepSeek
API, web search, model list refresh, version check — even with
HTTPS_PROXY set in their shell, because none of those calls ever saw the
env var.

src/net/proxy.ts reads HTTPS_PROXY → HTTP_PROXY → ALL_PROXY (upper-case
preferred, lower-case fallback — matches curl precedence) and installs
an undici ProxyAgent as the global dispatcher. Wired at the top of
src/cli/index.ts so every fetch closure constructed later (DeepSeek
client, web tools, doctor's reach check) inherits the dispatcher.

/doctor now reports the active proxy as a check row — username/password
in the URL are redacted before printing so the output is safe to paste
into bug reports.

Closes #646
2026-05-11 15:04:56 +08:00
YHH ec751a22a5 fix(config): loadEditMode preserves yolo instead of demoting it to review (#648)
EditMode is "review" | "auto" | "yolo", but loadEditMode's ternary only
recognized "auto" and dropped everything else — including yolo — to
"review". /mode yolo writes the right value to disk via saveEditMode,
but the next read silently downgrades it.

Downstream: src/cli/commands/code.tsx:111 registers the shell tool with
`allowAll: () => loadEditMode() === "yolo"`. Because that getter never
returns "yolo", the shell tool always falls through to the pauseGate,
and the user sees the approval modal even though they're "in yolo".
Same demotion bites the App's initial editMode state in
src/cli/ui/hooks/useEditGate.ts:38 on every relaunch.

Closes #644
2026-05-11 14:31:21 +08:00
YHH 32a90668bc fix(plan): add /plans done manual override + strengthen mark_step_complete prompt (#645)
Plan progress (the `N/M done` counter on the live card and the resume
banner) is only ever advanced by the model calling `mark_step_complete`
after each step. When the model skips that call — and DeepSeek doesn't
always make it — the counter stays at `0/N` even though the work is
finished, and on resume the user sees `0/9 done` next to a plan they
know they completed an hour ago. There was no escape valve.

Two changes:

1. New slash subcommand `/plans done <id>` (single step) and
   `/plans done all` (every remaining step). Updates completedStepIds,
   persists .plan.json, dispatches plan.step.complete so live UI ticks.
   Wired through new SlashContext callbacks that App.tsx owns, so the
   in-memory ref stays in sync with disk and the next mark_step_complete
   call (if it ever comes) won't re-add a duplicate.

2. Strengthened MARK_STEP_COMPLETE_DESCRIPTION — explicit MANDATORY
   marker, explanation of the visible failure mode (0/N on resume),
   and explicit "late is still better than never" so the model can
   recover at end-of-turn if it noticed it skipped earlier steps.

Closes #641
2026-05-11 14:20:27 +08:00
YHH 6f206e7853 fix(ui): reset chat scroll to bottom when a confirm modal mounts (#643)
If the user has scrolled up in the chat history and a pauseGate request
arrives — shell command, plan proposal, plan checkpoint, plan revision,
or ask_choice — the modal mounts at the bottom of the chat area, which
is off-screen below the scroll position. The picker captures arrow
keys, so the user can't scroll back down to see the options either,
and looks stuck.

Calling chatScroll.jumpToBottom() once at the top of the pauseGate
listener flips pinned back on; the modal's useReserveRows triggers
setMaxScroll, which snaps scrollRows to the new bottom under the
existing pinned-mode invariant.

Closes #642
2026-05-11 13:42:23 +08:00
YHH 940d8aab25 fix(render): force per-frame clear in alt-screen to kill log-update drift (#640)
[email protected]'s log-update tracks previousLineCount as logical newlines, not
visual rows. When any rendered line wraps because its visual width
exceeds terminal columns — which happens on CJK / ambiguous-width
content under East Asian terminals — the clear region on the next frame
undershoots the actual on-screen footprint and the bottom of the
previous frame survives. The reported symptom on Windows Terminal at
120×30 with zh-CN content is a duplicated status bar (two horizontal
separators stacked) and stale residue creeping up from below.

shouldClearTerminalForFrame already handles the overflow case, but it
gates on Yoga's outputHeight — which can itself undercount visual rows
for the same width-misjudgment reason, so the fallback misses exactly
the cases that trigger the bug.

Fix: in alt-screen mode, take the clearTerminal path unconditionally.
Alt-screen has no scrollback, so per-frame clear costs nothing visible;
incrementalRendering is already off (chat.tsx:571) so we're paying the
full-frame stdout cost regardless. Patched via patch-package so the fix
survives reinstalls until the same shape lands upstream.

Closes #639
2026-05-11 13:42:08 +08:00
YHH 5afac824ab fix(ci): use /pattern/i form in issue-labeler config (#637)
github/[email protected] compiles patterns with `new RegExp(str)`,
which doesn't accept the PCRE `(?i)` inline flag — it throws
`Invalid regular expression: Invalid group` on the first pattern
and the whole label job dies before tagging anything (run 25649833795).

Switch every entry to the `/pattern/i` literal form the action
parses out of slash-delimited strings. Behavior is unchanged
(still case-insensitive); the YAML just speaks JS regex now.

Validated locally: all 14 patterns compile, 17/17 realistic
issue fixtures match the expected labels.
2026-05-11 12:37:47 +08:00
YHH 73c974ef21 feat(memory): read AGENTS.md as fallback when REASONIX.md is absent (#636)
The agents.md open spec (Linux Foundation, 60k+ projects, broad
ecosystem support — Codex, Cursor, Aider, Gemini CLI, JetBrains
Junie, etc.) is the convergence point for "single agent-instruction
file at project root." Forcing a separate REASONIX.md next to an
existing AGENTS.md fragments memory and adds to the file-proliferation
problem the spec was designed to fix.

readProjectMemory now walks REASONIX.md → AGENTS.md → AGENT.md and
takes the first that exists. Writes (# quick-add, dashboard editor)
target whichever file is already on disk, defaulting to REASONIX.md
for fresh projects. AGENT.md drops out of FOREIGN_PLATFORM_FILE_MARKERS
since we now read it instead of flagging it as a foreign workspace.

Closes #635
2026-05-11 12:26:20 +08:00
YHH b81f5d132b chore(ci): add issue triage workflows (similarity + auto-label) (#634)
Two GitHub Actions that fire on `issues: [opened, edited]`:

- `issue-similarity.yml`: actions-cool/issues-similarity-analysis posts
  a comment with the top related issues (threshold 0.7) so a reporter
  notices duplicates like #633 → #624/#625 without us hand-replying
  every time.
- `issue-labeler.yml`: github/issue-labeler applies area / kind labels
  by regex on title + body. Config in `.github/issue-labeler.yml` covers
  bug / enhancement / documentation / question / dashboard / rendering.

Both use the default GITHUB_TOKEN — no secrets to provision. Judgment
labels (good first issue / rfc / tracking / duplicate / wontfix) stay
maintainer-driven.
2026-05-11 12:01:23 +08:00
YHH 8797ed185f feat(mcp): per-server env config via mcpEnv key (#627)
The catalog already declares `requiredEnv` (github → GITHUB_PERSONAL_ACCESS_TOKEN
and friends), and `StdioTransport` already accepts an env overlay — but the
bridge call sites never threaded one through. Users had to export the var in
their shell and relaunch.

Adds `mcpEnv: Record<serverName, Record<envName, string>>` to ReasonixConfig,
keyed off the `name=` prefix in the --mcp spec. Stdio specs merge the entry
over process.env at spawn; SSE / streamable-HTTP ignore it (no child process).
Empty-string values are dropped so a blank in config doesn't blank out a
real env var.

Also collapses the four duplicate `spec → transport` ternaries (chat, run,
mcp-inspect, reconnect) into one `buildTransportFromSpec` helper so future
transport additions land in a single place, and pipes the same env lookup
into `/mcp reconnect` so a respawn after a token rotation picks up the new
value.

`reasonix mcp install` now also prints the `mcpEnv.<name>` shape next to its
"needs:" line, pointing users at config.json directly instead of leaving
them to discover the key.

Closes #376
2026-05-11 11:06:03 +08:00
YHH 23a88e15fb feat(dashboard): pin port via --dashboard-port flag and config (#625)
Stable SSH tunnels need a deterministic port. Adds `--dashboard-port`
on `chat` and `code`, plus a `dashboard.port` config key, so the
embedded server binds to the same port across restarts. Resolution
order: flag > config > ephemeral (current behavior). Out-of-range
values warn + fall back; pinned-port EADDRINUSE surfaces through the
existing auto-start failure toast so the user knows the port is
contended instead of silently rolling onto a different one.

Closes #624
2026-05-11 10:39:52 +08:00
Dimas D. Angga faf8932826 feat(doctor): add --json flag for structured machine-readable output (#620)
* feat(doctor): add --json flag for structured machine-readable output

Enables programmatic consumption of doctor results by CI pipelines and tooling that need to parse health-check status without scraping human-formatted output. Each check now carries a stable `id` so downstream consumers can key off specific checks rather than brittle label strings, while exit-code semantics and the default text output remain unchanged.

* test(doctor): use vi.stubEnv for env isolation in --json tests

Vitest's `vi.stubEnv` and `vi.unstubAllEnvs` provide automatic restoration of environment variables between tests, eliminating the manual save/restore boilerplate that's easy to get wrong. Collapsing the multi-line import also keeps the test file consistent with single-line import style elsewhere.
2026-05-11 10:07:24 +08:00
Evan-Pycraft d78cd92a0b feat(i18n): localize setup wizard, theme picker, plan editor, MCP hub, and more with zh-CN (#622) 2026-05-11 09:37:53 +08:00
Wesley Viana 009ca9fa4a feat(tools): Validate tool call params agains json schema (#621) 2026-05-11 07:25:37 +08:00
YHH 22ea3af092 chore(release): 0.38.0 (#617) 2026-05-10 23:42:07 +08:00
YHH edbbb014ba feat(ui): /copy — vim-style copy mode + CLI reference docs (#616)
* feat(ui): add /copy — vim-style copy mode for SSH-friendly chat copy

Drag-select can't extend past the alt-screen viewport in SSH / mosh / tmux,
because the alt-screen has nothing scrollable above it. /copy gives users a
keyboard-driven path to yank chat text without depending on terminal selection.

j/k or arrows move the cursor by line, v starts/cancels a selection, y or
Enter writes the selection through OSC 52 (with the existing temp-file
fallback for >75 KB or terminals that don't honour OSC 52). g/G jump to
top/bottom; q/Esc exits without yanking.

Snapshot is taken at mount (frozen view), spans user / streaming / reasoning
cards; tool / diff / etc. are skipped. Headers are navigable but excluded
from yank, so cross-card selections come out clean.

Closes #614

* docs: add CLI reference — every subcommand, slash, keybinding

Until now /help and /keys were the only way to discover the full surface.
Both READMEs now link to docs/CLI-REFERENCE.md, which mirrors the in-app
content so it's greppable from the repo and indexable on the website.

Includes a copy/paste section with the SSH-alt-screen explanation and
both escape hatches (/copy and --no-alt-screen).

* docs(site): link CLI reference from index footer + configuration CTA

Adds a "CLI reference" entry in the index.html footer's Docs column and
in the configuration page's outro CTA cluster, pointing to the new
docs/CLI-REFERENCE.md. Mirrored in i18n.js + guide-i18n.js for both EN
and zh dictionaries.
2026-05-10 23:25:23 +08:00
YHH 6660244681 feat(tools): add delete/copy fs tools + compress shell descriptions (#615)
* feat(tools): add delete_file / delete_directory / copy_file

The model could only delete or copy files via run_command (rm/cp), but
neither rm nor cp is on BUILTIN_ALLOWLIST — every call hit the user
confirmation gate. Three new sandbox-scoped tools eliminate that
friction:

- delete_file(path)       — fs.unlink, refuses directories
- delete_directory(path)  — fs.rm recursive by default; recursive:false
                            falls back to fs.rmdir for empty-only
                            (Node's fs.rm without recursive rejects
                            every directory, so the empty-dir path
                            needs the rmdir variant)
- copy_file(source, dest) — fs.cp recursive, refuses overwrite

All three resolve through the existing safePath() check so paths
outside the sandbox are rejected the same way write_file / edit_file
already are. No description bloat — short single-line teaching plus
the parameter shapes are enough.

12 new tests cover happy paths, refusal conditions (directory /
file mismatch, non-empty refusal, overwrite refusal), parent-dir
auto-creation, sandbox escape rejection, and the read-only-mode skip
(allowWriting:false leaves all three out).

Also extend the plan-mode write-tool list in src/code/prompt.ts so
the model knows these will be bounced under /plan.

* perf(tools): compress run_command / run_background descriptions

Tool descriptions ship in every API request as part of the prefix.
run_command's description was the largest single contributor — six
bulleted constraint paragraphs spanning ~200 tokens, much of it
re-explaining the same shell semantics. run_background then claimed
"Same shell constraints as run_command" but proceeded to re-list a
subset of them anyway.

Compress without losing substance:

- run_command: lead with the one-line summary, then condense the six
  constraint bullets into one paragraph that lists supported /
  unsupported / cd-doesn't-persist with the same concrete examples
  but no prose padding. Drops ~120 tokens per request without losing
  any information the model needs.
- run_background: drop the duplicate constraint listing (still
  inherits from run_command), keep the Vite gotcha (high-value pitfall
  the model gets wrong) and the "use this for npm dev / uvicorn /
  tsc --watch" guidance. Drops ~60 tokens.

Net per-request prefix saving: ~180 tokens. Across a typical 50-turn
session that's ~9000 tokens off the parent prompt.
2026-05-10 22:41:21 +08:00
YHH 416537598a feat(loop): inject remaining-iter budget hint into parent tool results (#613)
The subagent loop has used a setResultAugmenter-driven budget tail since
0.36 — when within BUDGET_WARN_THRESHOLD of the per-spawn cap, every
tool result picks up `[budget: K of N tool calls left — wrap up soon]`,
and at 0 left a stronger finalize-NOW form. The parent CacheFirstLoop
exposed the same setResultAugmenter hook on the registry but never
wired a consumer, so the model running in the main session had zero
runtime visibility into its iter budget. The user-facing 70% warning
fires to the TUI, not to the model — when it hits iter 60 of 64 it
still has no signal it's about to be force-summarized.

Wire an analogous augmenter on the parent loop (threshold 5, slightly
wider than subagent's 3 since the parent's default 64-cap is 4× larger)
and reset the per-step counter at step entry so consecutive turns don't
accumulate. Constructor checks ToolRegistry.hasResultAugmenter first so
subagent's pre-installed child-registry augmenter survives — the
constructor must not clobber it.

Also flag wait_for_job as parallelSafe + stormExempt: concurrent waits
on different jobs are safe, and polling-loop is the intended pattern so
the storm breaker shouldn't trip on it.
2026-05-10 22:40:16 +08:00
YHH 56fcb2a5a4 feat(prompt): add audit-mode rails for review/critique tasks (#611)
* feat(prompt): add audit-mode rails for review/critique tasks

When the user asks Reasonix Code to audit its own architecture, the
existing "cite or shut up" rule covers absence claims but doesn't
catch the more common audit-mode failure: confident, well-structured
proposals built on factually wrong premises about runtime behavior,
fabricated quantities, or recommendations that contradict pinned
memory.

Adds a six-bullet section after "Cite or shut up": auto-preview is
for locating not auditing, flag→consumer trace before claiming
runtime behavior, no fabricated percentages, schema-cost accounting
for new-tool proposals, MEMORY.md as design constraint, and
user-facing ≠ model-facing as a category-error guardrail.

Closes #610.

* prompt: tighten rails #2 and #6 from real audit-session failure modes

Audit session run against the original 6-rail section (#610) showed
two failures the wording didn't catch:

1. **Inventory-claim hallucination.** Asked which tools have
   `stormExempt: true`, the model enumerated 6 file-system tools as
   having it — only 2 actually do. The rail said "trace flag to
   consumer", which the model interpreted as "for one named tool",
   not "for an inventory claim covering many tools." Add an explicit
   inventory clause: grep the flag, don't enumerate from memory.
2. **Library API → dead-code mischaracterization.** The model
   labeled `registerSubagentTool` "dead code from CLI perspective"
   on the basis of a clean grep in `src/cli/`. It's a deliberate
   library export consumed by embedders via `src/index.ts`. The
   rail enumerated three surfaces (slash / tools / UI); add a fourth
   (library) so library exports aren't mistaken for unused code.

Two-test bump on tests/code-prompt.test.ts so the tightened wording
can't silently regress.

* prompt: broaden rail #1 to cover doc / state claims, not just runtime

Second audit session run against the tightened rails (#611) showed
the same head-only-then-conclude failure mode again, this time on a
plan-doc file rather than runtime code: the model read the head of
docs/plans/architecture-refactoring-roadmap.md, saw "8 services
still use singletons", and asserted the plan was now stale —
without reading the rest of the doc to check for a "Status: done"
section that might have been there.

The original rail was scoped to "runtime behavior" because that was
the loop.ts dispatcher case from #610. The same blind spot applies
to any file: don't conclude what's in the elided middle off head +
tail. Broaden the wording to cover runtime behavior, current
architectural state, and doc freshness explicitly.

One test bump on tests/code-prompt.test.ts so the broader scope
can't silently regress to runtime-only.
2026-05-10 22:39:33 +08:00
YHH 0c67b6cee6 fix(i18n): add missing cardTitles.you key (#612)
UserCard rendered the literal "cardTitles.you" because the key was
referenced but never defined in EN/zh-CN/types.
2026-05-10 21:46:56 +08:00
YHH 13b738e6a7 fix(i18n): repair startup banner — restore comma separator and consolidate template (#609)
The split-string approach (codeRooted + session + nativeTools as separate
t() calls) dropped the comma+space between rootDir and session in both
EN and zh-CN, and locked the word order across languages. Fold the four
fixed segments into a single codeRooted template with {rootDir} /
{session} / {tools} / {semantic} placeholders so each locale owns its
full sentence and translators can reorder freely.

Add tests/startup-banner-i18n.test.ts to lock both rendered banners.
2026-05-10 21:32:15 +08:00
Evan-Pycraft 32a2e8df44 feat(i18n): localize web search errors, startup message, and doctor diagnostics with zh-CN (#606)
* feat(i18n): localize confirmation modals, HintRow, and remaining cards with zh-CN

* feat(i18n): localize pickers (SessionPicker, ModelPicker, SlashSuggestions, AtMentionSuggestions) with zh-CN

* feat(i18n): localize StatsPanel, WelcomeBanner, ctx-breakdown with zh-CN

* fix: adjust zh-CN translations based on user feedback

* feat(i18n): localize web search errors, startup message, and doctor diagnostics with zh-CN

* fix: remove duplicate namespaces from rebase and reformat
2026-05-10 21:25:03 +08:00
YHH 10831c694d fix(tui): stop subagent delta storm from re-rendering parent live stack (#608)
The subagent sink mirrors every child LoopEvent (assistant_delta /
reasoning_delta / tool_call_delta) into useSubagent's inner branch.
The map callback always allocated a new array reference, so React
re-rendered App.tsx + SubagentLiveStack on every child delta — with
3 parallel subagents streaming, that was 90+ no-op re-renders/sec
each forcing a Yoga layout pass. Closes #554.

Pull the inner/progress/phase logic into a pure reducer that returns
prev by reference when no row would change, and also memoize
ToolCard's spawn_subagent JSON.parse so the inflight-context tick
doesn't re-parse 8 KB on every passing tool start/finish.
2026-05-10 21:20:14 +08:00
Evan-Pycraft 0324029636 fix(i18n): add zh-CN for /cwd, /stop, /feedback, /theme slash descriptions (#603)
* feat(i18n): localize confirmation modals, HintRow, and remaining cards with zh-CN

* feat(i18n): localize pickers (SessionPicker, ModelPicker, SlashSuggestions, AtMentionSuggestions) with zh-CN

* feat(i18n): localize StatsPanel, WelcomeBanner, ctx-breakdown with zh-CN

* fix(i18n): add zh-CN for /stop, /feedback, /theme slash descriptions

* fix(i18n): add zh-CN for /cwd, /stop, /feedback, /theme slash descriptions

* fix: adjust zh-CN translations based on user feedback

* fix: inline DEFAULT_FOOTER t() lookup into render body to fix /language reactivity

* ci: retrigger build

* ci: trigger workflow

* fix: remove duplicate i18n keys (theme, hintClear) introduced during rebase
2026-05-10 21:01:19 +08:00
paramount-tandYHH 2698e6f3a8 fix(setup): validate DeepSeek API key before saving (#607)
Co-authored-by: YHH <[email protected]>
2026-05-10 20:55:20 +08:00
Dimas D. Angga 1436f5eed2 fix(composer): surface ^U clear on hint bar and i18n hint strings (#605)
The always-visible composer hint row hardcoded English labels and omitted the `^U` clear chord, leaving it undiscoverable without reading source. It also referenced a non-existent `composer.hint` key that would leak the literal path to users when no abort hint was active. Routing the row through `HintRow` with proper i18n keys keeps the chord vocabulary discoverable in both locales and removes the broken key fallback.
2026-05-10 19:35:46 +08:00
YHH 9d136b0713 feat(subagent): default-off delegation policy + per-session budget feedback (#604)
Layer 1: rewrite the "Delegating to subagents" section in code/prompt.ts
and the spawn_subagent tool description from "when to delegate" to
"default: don't delegate". Lead with the two narrow exceptions where a
spawn pays for itself (parallel fan-out, >10-read context blow-up) and
name the anti-patterns explicitly (single grep, 1-3 file cross-ref,
"keep my context clean for one question").

Layer 2: track per-session spawn count + cumulative subagent tokens in
the registerSubagentTool closure. After each spawn, append a hint to
the JSON tool result. Soft note from spawn 2 onward, strong "justify
the next spawn" hint past 5 spawns or 50k tokens. The hint surfaces
on the model side via the same shape as the existing per-child iter
budget hint (subagent.ts:189), so the model already knows how to read
it.

Layer 3 (single-call refusal gate) deferred until we see whether 1+2
moves the storm pattern in #415 / #553.

Closes #553.
2026-05-10 19:30:25 +08:00
paradoxSCH 2fc06c7a9b fix(tui): avoid retokenizing streaming replies per chunk (#598) 2026-05-10 18:46:04 +08:00
kabaka f0533783d9 feat(slash): implement shared group order and labels for slash commands (#596) 2026-05-10 18:25:29 +08:00
YHH 736e615c8e docs(changelog): add WelcomeBanner overlay fix to 0.37.0 entry (#595)
Rolling #594 into 0.37.0 since the version was bumped but not yet
tagged or published to npm. Tag will land on this commit so the
published 0.37.0 contains the fix, no 0.37.1 needed.
2026-05-10 14:55:15 +08:00
YHH 447a31cc3a fix(ui): hide WelcomeBanner when slash menu is open (#594)
The empty-state guard checked !hasConversation && !busy && !isStreaming
but missed the slash-suggestions overlay. Pressing `/` from the home
screen left the bordered welcome card mounted in the flex column while
SlashSuggestions rendered below, producing interleaved frame output
where the card border drew through the menu rows.
2026-05-10 14:51:00 +08:00
YHH 87eb8f168f chore(release): 0.37.0 (#593) 2026-05-10 14:46:28 +08:00
YHH 2af4cb3fdd fix(prompt): escalation contract names the actual session model (#592)
ESCALATION_CONTRACT was a const with `deepseek-v4-flash` baked in,
interpolated into three system prompts at module load. A pro session
got told it was running on flash, so when the user asked "which model
are you?", pro answered "flash" — accurately reading what the prompt
told it.

- Convert ESCALATION_CONTRACT → escalationContract(modelId): pro tier
  gets a short "you are the escalation tier" note (no <<<NEEDS_PRO>>>
  ladder, since pro can't escalate to itself); other tiers get the
  contract with the actual model id interpolated, plus an explicit
  "if asked which model you are, answer `<id>`" line.
- DEFAULT_SYSTEM (cli/index.ts) → defaultSystemPrompt(modelId), called
  per chat / run / bare-reasonix invocation against the resolved model.
- CODE_SYSTEM_PROMPT split: the public-API const stays at the
  historical flash phrasing for backward compat; codeSystemPrompt now
  takes opts.modelId and the code command threads in opts.model.
- DEFAULT_SUBAGENT_SYSTEM split into a memory-stable base + per-spawn
  contract appended against the spawn's resolved model id.

Closes #582
2026-05-10 14:35:42 +08:00
YHH 2813af8329 fix(skills): hard-fail install + surface skills missing description (#591)
A skill whose frontmatter omits `description:` was silently dropped
from the prefix index, but `/skill <name>` still ran it from disk —
so it worked in the install session and vanished in the next one,
with no diagnostic.

- POST /api/skills/<scope>/<name> now validates frontmatter via
  validateSkillFrontmatter() and returns 400 instead of writing a
  skill the model will never see.
- applySkillsIndex no longer filters out blank-description skills;
  it injects them with a placeholder line that names them and tells
  the model to flag the missing frontmatter to the user.

Closes #583
2026-05-10 14:22:46 +08:00
YHH 79da127680 fix(loop): /new archives prior transcript instead of destroying it (#590)
clearLog() truncated the live session jsonl in place, so users running
/new lost every previous turn — the dashboard's Sessions tab faithfully
reported one row because there was one file. Rotate the live jsonl plus
sidecars to <name>__archive_<ts> so the prior conversation survives in
Sessions. sessionName is unchanged, so the prefix cache stays warm.
The __archive_ infix sits outside the ${name}- resume-prefix matcher,
so archives don't get auto-resumed on next launch.

Closes #587
2026-05-10 14:12:57 +08:00
paradoxSCH 8fab388608 fix(dashboard): list flat-format skills (#589) 2026-05-10 14:04:37 +08:00
YHH 484c40a02c perf(boot): defer MCP bridging to App.tsx mount (#585)
chatCommand used to `await runtime.addSpec(raw)` once per server
before render() — every handshake (100ms-2s) blocked the alt-screen
from coming up, so users with MCP configured saw a black screen
on startup.

Now mcpRuntime exposes a setLifecycleSink(sink) hook. chatCommand
hands the empty mcpServers array off to App immediately; App.tsx
swaps in a log-routing sink on mount and fires runtime.addSpec
(spec, loop) for each requested spec in the background. As each
server bridges, hot-add pushes its tools into loop.prefix and
setLiveMcpServers refreshes the /mcp panel live. Lifecycle events
(handshake / connected / failed / slow) flow into the in-app log
instead of stderr — stderr writes during alt-screen would corrupt
the UI.

UI now paints immediately even with N MCP servers configured.
Servers that fail to connect just stay unavailable; their tools
never bridge — same end state as before, just without the wait.
2026-05-10 13:36:56 +08:00
YHH 54dd2ea8b4 feat(ui): boot splash with REASONIX logo + animated whale (#588)
Adds src/cli/ui/BootSplash.tsx — a full-screen splash that AppInner
returns from before its first real paint, gated by a 1.4s timer
(one whale-spout cycle). Two purposes:

- Hides the brief alt-screen-blank gap on cold launch (heavy
  AppInner first-paint cost stays under the splash).
- Brand mark always lands clean instead of flashing raw mount
  state.

Splash content:
- ANSI Shadow REASONIX wordmark (6-row block letters, brand color)
- Three-tone shaded whale silhouette (░ outline / ▒ midtone /
  ▓ inner) with eye, mouth, tail flukes
- 7-frame spout animation cycling at 200ms (idle → rising →
  peak with droplets → dispersing)
- Wave line below shifting one column per frame
- 'loading...' indicator with cycling dots

App.tsx wires bootReady state + setTimeout, returns <BootSplash />
until ready.
2026-05-10 13:34:05 +08:00
Evan-Pycraft 07bddea41c feat(i18n): localize status bar, input prompt, and edit mode hints with zh-CN (#584) 2026-05-10 13:31:34 +08:00
YHH 08b7ced357 refactor(ui): extract useLanguageReload from App.tsx (#581)
useLanguageReload() returns a counter that increments on
runtime language changes — same shape as before, just owns its
own useState + onLanguageChange subscription. Lets App.tsx drop
the onLanguageChange import.

Step 7/7 of #565 phase 1. App.tsx LOC unchanged (one import line
in, two hook lines out).
2026-05-10 12:48:38 +08:00
YHH ffcc0443f1 refactor(ui): extract usePresetMode from App.tsx (#580)
usePresetMode(model) bundles the three model-mode states:
- preset: "auto" | "flash" | "pro" (initial seeded from model)
- proArmed: /pro pending for next turn
- turnOnPro: current turn is on v4-pro (arming consumed or
  ⇧ pro auto-escalation fired)

App.tsx loses three useState calls plus the inline narratives.
The states and their setters are destructured back so handleSubmit
+ startDashboard's handlers stay structurally identical.

Step 6/7 of #565 phase 1. App.tsx 3701 -> 3695.
2026-05-10 12:45:13 +08:00
YHH 3426f5a126 refactor(ui): extract useHookList from App.tsx (#579)
useHookList(initialProjectRoot) returns hookList + a reloadHooks
helper that bundles loadHooks() + state replacement. The two
slash callbacks (`/hooks reload`, `/cwd`) and the dashboard
mutation surface now call reloadHooks(projectRoot) instead of
duplicating the loadHooks + setHookList pattern.

App.tsx drops the loadHooks + ResolvedHook imports along with
the inline initial-load comment and the three duplicate
load-and-set blocks.

Step 5/7 of #565 phase 1. App.tsx 3715 -> 3701.
2026-05-10 12:38:17 +08:00
YHH 39685d0ab3 refactor(ui): extract useWorkspaceRoot from App.tsx (#578)
useWorkspaceRoot(launchRoot) returns currentRootDir +
setCurrentRootDir + currentRootDirRef and runs the ref-mirror
effect. App.tsx loses one useState, one useRef, one useEffect,
and the long inline narrative explaining what each
rootDir-dependent surface reads.

The /cwd slash handler still composes the swap (re-register
tools + reload hooks + re-bootstrap semantic) — only the state
+ ref ownership moves into the hook.

Step 4/7 of #565 phase 1. App.tsx 3723 -> 3715.
2026-05-10 12:32:40 +08:00
YHH 6e723e2e60 refactor(ui): extract useEditGate from App.tsx (#577)
Bundles pendingEdits ref + pendingCount mirror + pendingTick +
syncPendingCount + editMode + editModeRef + saveEditMode
persistence + the 1.2s mode-flash effect into one hook in
src/cli/ui/hooks/. App.tsx loses three useState calls, two refs,
two effects, and several long inline narratives — those are now
single-line field docs on the EditGate interface.

Note: the tool interceptor stays in App.tsx for now — it's tangled
with review-modal state (pendingEditReview / editReviewResolveRef /
turnEditPolicyRef), which want their own hook in a follow-up.

Step 3/7 of #565 phase 1. App.tsx 3760 -> 3723.
2026-05-10 12:27:44 +08:00
YHH 59babbb604 refactor(ui): extract useToolProgressDisplay from App.tsx (#576)
Bundles ongoingTool / toolProgress / statusLine state + the
progressSink wiring + the turn-end clear() into one hook in
src/cli/ui/hooks/. Long inline narratives explaining the
pulse-spinner row / progress frame / silent-phase status line
move out of App.tsx; the hook's name carries the role.

Step 2/7 of #565 phase 1. App.tsx 3785 -> 3760.
2026-05-10 12:18:58 +08:00
YHH bcc64ff822 refactor(ui): extract useTerminalSetup from App.tsx (#575)
DECSET 2004 / modifyOtherKeys / DECSET 1007 setup+cleanup moves
to its own hook in src/cli/ui/hooks/. App.tsx no longer owns the
escape-sequence dance; the long inline narrative collapses to one
line documenting the only non-obvious choice (1007 over full
mouse tracking).

Step 1/7 of #565 phase 1. App.tsx 3816 -> 3785.
2026-05-10 12:12:44 +08:00
YHH 9a43aa214b perf(ui): card virtualization — only lay out visible cards (#574)
After A+B (#573) the App-level render cost on scroll was gone, but
Yoga still had to lay out every card in CardStream's inner Box on
every frame — for a 50-card history, that's hundreds of rows
re-measured per scroll tick.

This PR adds card-level virtualization. Each card is wrapped in a
MeasuredCard that captures its row height via useBoxMetrics and
reports it to the chat-scroll store. CardStream then walks the cards
once per render, computes the cumulative offset of each, and decides:

- live render the card (it's inside the viewport ± 30-row buffer, OR
  its height isn't cached yet so we need to measure it), or
- collapse it into a spacer Box of the cached height.

Adjacent collapsed cards merge into a single spacer, so the off-screen
ranges add up to one Yoga node above and one below the visible cards.
Total inner-Box height stays exact, so marginTop={-scrollRows} still
lands on the right rows and maxScroll is correct.

Edge cases:
- New cards (id not in heights map) always render live so the first
  measurement happens. Once cached, they collapse next frame.
- Streaming cards re-measure on every render — their height changes
  and the cache stays fresh through the same path.
- pruneCardHeights drops heights for cards that disappear from the
  list (resumed sessions, /clear), so the map can't grow unbounded.

For a session with 50 cards and ~600 row total height, only the ~5-10
cards under the viewport go through Yoga per scroll. The off-screen
work that was making long sessions feel sluggish is now gone.
2026-05-10 12:04:31 +08:00
YHH d61d6806c8 perf(ui): isolate chat scroll state from App.tsx + scroll polish (#573)
Wheel/arrow ticks were re-rendering all of AppInner — 3,800 lines and
122 hook calls — even though the actual UI delta was a single
marginTop change in CardStream. Each scroll paid the full hook-eval
tax before Yoga layout and Ink commit could even start.

The fix has two parts:

1. New chat-scroll store under src/cli/ui/state/. Same useSyncExternalStore
   pattern as the agent store — selectors subscribe per-slice, actions
   are stable refs. CardStream now reads scrollRows directly from it;
   App.tsx only takes the action callbacks (which never change identity).
   The "reading history" branch that depended on `pinned` moves into
   InputAreaWithHistoryHint, a leaf that subscribes to pinned in
   isolation. Net: scroll ticks no longer re-render App.tsx at all.

2. Visual polish.
   - Wheel/PgUp/PgDn step from 8 to 5 rows. Smaller jumps read as
     smoother continuous motion in a cell-based TUI.
   - The "↑ earlier" line is now a live position indicator
     ("↑ N / M rows above — K more · PgUp / wheel / ↑").
   - The indicator briefly switches to the accent color on every
     applied delta (scrollVersion bump), so the user gets visual
     confirmation the wheel registered before the new frame paints.

Removes the old src/cli/ui/hooks/useChatScroll.ts; nothing else used it.
2026-05-10 11:54:51 +08:00
YHH 5a4754ffc6 fix(ui): compress scroll-schedule comment to satisfy 3-line cap (#572)
Hotfix: the squash merge of #571 landed with a 5-line block comment
that violates tests/comment-policy.test.ts (cap is 3 lines). The
fixup commit was pushed to the branch after the auto-merge had
already fired, so it never made it onto main.
2026-05-10 11:35:18 +08:00
YHH a9314cf23a fix(ui): leading-edge scroll + chunkier wheel/page step (#571)
Wheel-up felt laggy because every tick paid a full 16 ms wait before
any visual feedback — schedule() was trailing-edge: first call started
a setTimeout, the actual setScrollRows didn't run until the timer
fired. With Ink's reconcile + Yoga layout on top of that, a single
wheel tick took 30-50 ms to land visibly.

Two changes:

1. Leading-edge schedule. First call applies the delta immediately
   (instant feedback on first wheel tick), opens a 16 ms window during
   which subsequent calls accumulate into pendingDelta, and lands one
   trailing flush. Fast scrolls still produce only one re-render per
   window, but the user no longer waits for a slow tick to feel.

2. Split arrow step from page/wheel step. SCROLL_ARROW_ROWS stays at
   3 (fine-grained ↑/↓). New SCROLL_PAGE_ROWS = 8 covers PgUp/PgDn
   and the wheel-via-DECSET-1007 path. Each wheel tick now travels
   roughly a third of a typical viewport instead of three lines.
2026-05-10 11:27:02 +08:00
YHH 26d2c527db fix(ui): default flush to 50ms, drop REASONIX_UI=plain escape hatch (#570)
Vertical-jitter reports were tracing back to the 16ms (60Hz) flush
default — on winpty/MINTTY/ConEmu/tmux/high-latency-SSH the cursor-up
repaint can't atomically swap the frame at that rate, so users see
the old frame's bottom rows briefly through every redraw. 50ms (20Hz)
is still continuous-feeling for streaming text and stops the bobbing
on every terminal we've seen affected. Override via REASONIX_FLUSH_MS
when running on a terminal with atomic frame swap.

REASONIX_UI=plain is removed: it was the nuclear escape hatch for the
same problem, but it suppresses every live row (streaming text, tool
spinner, plan progress, undo banner, subagent stack, status line) —
i.e., most of what makes the TUI useful. The slower default flush
addresses the same terminals without that tradeoff.
2026-05-10 11:15:19 +08:00
YHH 054d3989ed docs(site): bilingual config guide, README restructure, SEO + perf cleanup (#569)
Adds a dedicated configuration guide page (docs/configuration.html)
covering MCP, skills, memory, hooks, permissions, web search, and
the semantic index — bilingual (en/zh) with scrollspy TOC.

Landing page: hero gets a real-metric strip (counts up once when
scrolled into view), orbital SVG decoration, status pill. The
"Configure in five minutes" teaser block links into the guide.

README cleanup: pulls Configuration into prime real estate, collapses
the chat-vs-code / working-folder / first-skill detail into a
<details> block, drops the standalone Web Search section (now
covered by the guide), tightens install copy. Mirrored in zh-CN.

SEO: correct og:url (was pointing at the wrong repo path), canonical,
hreflang en/zh-CN/x-default, JSON-LD SoftwareApplication + WebSite
on landing, TechArticle + BreadcrumbList on guide, Twitter card
metadata. Adds docs/robots.txt and docs/sitemap.xml.

Perf: stripped scroll-reveal, card spotlight + 3D tilt, capability
marquee, backdrop-filter on metrics row, fractal-noise overlay,
content-visibility, gradient-text shimmer, and section-beam
animations after they made the page feel laggy. Background is now
fully static — dot grid, three glow blobs, horizon hairline.
Only one-shot animation left is the metric count-up; the brand
mark, status dot, and terminal caret keep their tiny scoped pulses.
2026-05-10 10:54:23 +08:00
YHH bcfb7e586d chore(release): 0.36.2 (#568) 2026-05-10 09:38:03 +08:00
YHH 122d2e0fc9 feat(ui): add /theme picker (#543) (#567)
Surfaces a SingleSelect modal for the terminal theme preference. Bare
\`/theme\` opens the picker; \`/theme <name>\` keeps its existing
"persist and report" behaviour. Moves the slash entry from the
advanced group to setup and adds high-contrast to the arg completer.

Adapted from J3y0r's PR — repointed onto current main (which had
since reformatted App.tsx around the InflightProvider wrap from
#566) and the count test in tests/ui-slash-suggestions.test.tsx
updated from 12 → 11 advanced commands now that /theme has moved
out of the advanced bucket.

Thanks @J3y0r for the contribution.
2026-05-10 09:31:51 +08:00
YHH cf122c357d fix(loop): derive tool-card running state from finally-guarded inflight set (#566)
Closes #557

Tool spinners occasionally kept spinning after the underlying work had
finished. The cause: status was set imperatively from paired tool_start
/ tool events, and every code path that exits a dispatch had to
remember to emit the closing event — normal return, throw, abort,
storm-breaker, network drop. Miss one and the card was stuck.

Switch the running flag to a derived view:

- New InflightSet (src/core/inflight.ts) with add / delete / has /
  subscribe + notify-on-mutation. Parallel finally-driven cleanup is
  the contract: the language guarantees finally on every exit path,
  so there's no closing event to forget.
- CacheFirstLoop holds one. runOneToolCall adds the call's id at
  function entry and deletes it in finally; the chunk-loop pre-adds
  before yielding tool_start so the very first card render already
  reflects the running state. clearLog drains the set on /new.
- LoopEvent.tool_start / tool now carry callId — same id used as the
  inflight key. TurnTranslator threads it into Scrollback.startTool,
  which uses it as the card id so the card and the inflight key match.
- InflightProvider + useIsInflight (src/cli/ui/state/inflight-context.tsx)
  expose the set as a React context backed by useSyncExternalStore.
  ToolCard's toolStatus consults the hook for "running"; card.done is
  no longer the spinner discriminator, only terminal flavor (ok /
  rejected / aborted / error).

Tests:
- tests/inflight.test.ts — InflightSet contract: idempotent add,
  notify-only-on-change, listener errors don't break the gate, clear,
  finally-on-throw, finally-on-abort, parallel allSettled.
- tests/loop-inflight.test.ts — runOneToolCall finally clears the
  set on success and on tool throw; tool_start carries callId
  matching the inflight key; clearLog drains.

Out of scope (follow-up): subagent runId in the same set; deriving
streaming/reasoning running flags. Both are mentioned in the issue
but live behind different leak surfaces; the tool-card path is the
one users see most.
2026-05-10 09:12:12 +08:00
YHH de4b342199 fix(dashboard): kill chat-tab freeze under long sessions / concurrent jobs (#560)
Chrome's "Page not responding" dialog fires on the dashboard chat tab
once a session accumulates enough messages. Repro condition: long
streaming turn or several concurrent jobs broadcasting at once.

Two cooperating bugs on the chat feed's hot path:

1. Every assistant_delta event hit setState synchronously. The model
   streams ~20 deltas/sec; each one re-rendered ChatPanel, which
   .map'd over every historical ChatMessage with no memoization, so
   each one re-ran marked.parse + (for tool messages) hljs syntax
   highlight on UNCHANGED content. Long sessions = N grows = main
   thread starves.
2. The `streaming` prop fed to historical ChatMessage flipped between
   `null` (no streaming) and `false` (streaming-but-not-this-message)
   across turns, so even with memo, `null !== false` would force
   every historical message to re-render every time streaming
   started or stopped.

Fix:

- Wrap ChatMessage in `memo` from preact/compat so historical messages
  with stable `msg` refs short-circuit re-renders.
- Cast the per-row streaming prop to a boolean so historical
  messages get a stable `false` and memo's shallow compare actually
  bails out across streaming-on/off transitions.
- Coalesce assistant_delta into a single rAF-batched setStreaming.
  Multiple deltas in the same frame collapse into one state commit;
  the streaming bubble's re-render rate is capped at the display
  refresh rate. assistant_final + SSE reconnect + unmount each
  cancel the pending flush so the buffer can't leak across turns.

Closes #551
2026-05-10 08:36:35 +08:00
YHH 6761a31697 fix(prompt): identity guard against foreign agent-platform workspaces (#550) (#555)
When the sandbox root contained another product's data dir (Hermes
Agent's SOUL.md, skills/, memories/, etc.), the model would browse
those files and infer it was a sub-profile or runtime layered on top of
the host product. The system prompt defines the assistant as a
standalone coding assistant; the workspace contents shouldn't override
that.

Two layers:

- Top-of-prompt identity section names the failure mode explicitly:
  workspace files describe the user's project, never what Reasonix is.
  Calls out SOUL.md / AGENT.md / PERSONA.md / foreign skills+memories
  trees / a foreign REASONIX.md as not-the-spec, and tells the model to
  answer "who are you?" from the prompt instead of running ls.
- detectForeignAgentPlatform(rootDir) flags the workspace at launch if
  one of those markers sits at the root, and the code-mode banner adds
  a one-line warning suggesting --dir <real-project>. Conservative
  signal: lone skills/ doesn't trigger (common in coding repos);
  skills/ + memories/ pair does.

Closes #550
2026-05-10 08:36:31 +08:00
YHH 94dc1926f2 fix(tui): flush pending modals + cancel pauseGate on Esc and /new (#552)
When a tool awaits pauseGate.ask (plan_checkpoint, plan_proposed, etc.),
the gate's promise ignores AbortSignal. Esc-during-busy fires
loop.abort(), but the awaiting tool fn never returns, so:

  - busy stays true forever — PromptInput stays disabled.
  - The pending modal (or its plan card) can't be dismissed.
  - /new is silently dropped by handleSubmit's `if (busy) return`,
    so the user can't even wipe the session to start over.

Add pauseGate.cancelAll() that resolves every outstanding request with
its kind's safe-cancel verdict (deny / cancel / stop / cancelled). Wire
it into a resetPendingModals helper that also clears every pending*
modal state, and call it from both Esc-during-busy and apply-slash-
result's clear branch. The awaiting tool fn now returns or throws
cleanly, busy clears, and the user can recover.
2026-05-10 08:08:51 +08:00
YHH 98183baf99 fix(tui): break scrollRows ↔ outer.height feedback that crashed CardStream (#549)
The "↑ earlier" hint was rendered conditionally on scrollRows > 0, as a
sibling of the measured outer Box. That tied outer.height to scrollRows:
toggling the hint changed outer.height by one row, which changed
maxScroll, which pinned-mode wrote back as scrollRows, which toggled
the hint again. With streaming content compounding inside the same
React batch, the chain reached MAX_NESTED_UPDATES = 50 and aborted with
"Maximum update depth exceeded" inside ink's useBoxMetrics.

Reserve the hint row unconditionally so outer.height is independent of
scrollRows. Trade is one row of permanent reservation; the loop is
gone.
2026-05-10 07:42:50 +08:00
YHH 614236eb03 chore(release): 0.36.1 (#548) 2026-05-10 00:25:02 +08:00
YHH b1efcfe091 fix(slash): use frequency-sorted list when picking by index on Enter (#547)
The picker UI sorts suggestions by usage count (slashUsage) but the
Enter-time substitution recomputed the list without it, so the list
the user navigated and the list dispatch indexed into were ordered
differently. The shared slashSelected index then dereferenced a
different command than the highlighted row.

Pass slashUsage through so both calls produce identical orderings.
2026-05-10 00:22:26 +08:00
YHH c2966f5c0e feat(tui): phase-aware label for the busy-fallback activity row (#546)
Refs #367
2026-05-10 00:17:14 +08:00
YHH 4dbb03ae36 docs(readme): explain when to pick chat over code (#545)
Closes #509
2026-05-09 23:55:30 +08:00
paradoxSCH 05491f16c6 fix(tui): clear ongoing tool on errors (#542)
Closes #535
2026-05-09 23:44:57 +08:00
YHH e2b3de7246 docs(changelog): add slash hook-order fix to 0.36.0 entry (#539)
Rolling PR #538 into 0.36.0 since the version was tagged but not yet
published to npm. Tag will be moved to this commit so the published
0.36.0 contains the fix, no 0.36.1 needed.
2026-05-09 23:09:01 +08:00
YHH d9cfeffd50 fix(slash): hoist hooks above early returns to stop "Rendered more hooks" crash (#538)
SlashSuggestions called useColor / useStdout / useState before two
early-return branches (matches === null, matches.length === 0), then
useEffect afterward. When matches flipped from non-null/non-empty to
either of the early-return states and back, React saw 4 hooks one
render and 3 the next — "Rendered more hooks than during the previous
render" crash, killing the whole TUI.

Hoist windowStart computation + the useEffect above the early
returns. Compute against `matches ?? []` so the math is well-defined
when matches is null (windowStart resolves to 0, the effect no-ops
because state already equals 0). The early-return JSX branches stay
unchanged below.

Regression test rerenders the component through
non-empty → null → empty → non-empty and asserts no throw.
2026-05-09 23:05:53 +08:00
YHH 67a1d6194b chore(release): 0.36.0 (#537)
* chore(release): 0.36.0

* test(status-row): pin status-line version assertion to live VERSION import

Hardcoded "v0.35.0" string broke on every release bump. Reading from
src/version.js means future releases don't need a coordinated test
edit alongside the package.json bump.

* test(mcp): bump startup-summary timeout to 15s — chronic flake under suite load

captureStartupState dynamically imports chat.js + tools.js inside the
test, which can blow past Vitest's 5s default when the worker pool is
saturated (148 test files, lots of cold cache). Passes in isolation,
flakes under `npm test` parallel load. 15s adds headroom without
slowing the happy path.
2026-05-09 22:58:29 +08:00
YHH 0a1c65d9db fix(tui): rescue unbracketed pastes so multi-line content stops firing N submits (#536)
Bracketed-paste markers (DECSET 2004) don't arrive on every host —
multiplexers strip them, some web-SSH gateways drop them, certain
Windows pipes never forward them. When they're missing, a multi-line
paste arrives as raw bytes; each \r in the chunk gets dispatched as
an Enter event; PromptInput submits the partial buffer; the loop
fires a fresh agent call per line. Reporter saw multi-line paste
trigger multiple submits in a row.

Heuristic rescue at the parser entry point: when a chunk in idle
state contains 2+ line breaks, OR a single line break with non-empty
text on both sides, AND no ESC bytes (would indicate a real key
sequence) AND no existing paste markers, wrap it in synthetic
\x1b[200~ … \x1b[201~ before processing. Routes through the existing
paste accumulator so it lands as ONE paste event with the whole blob.

Asymmetric tradeoff is intentional — a false-positive paste makes the
user re-press Enter; a false-negative paste fires N prompts and burns
N agent calls. The detector errs toward paste.

Bare \r and \r\n stay typed-Enter (terminal-converted CRLF is one
keystroke, not two breaks). "abc\r" stays typed-then-Enter, so a
fast typist's batched chunk still submits.

Updated the printable-coalescer split test to use \t since \r/\n now
route through the heuristic rescue when surrounded by text.

Closes #522
2026-05-09 22:46:25 +08:00
YHH ef2b50d873 fix(plan): pipe user feedback through the refine / approve / cancel gate (#534)
When the user picked Refine on PlanConfirm and typed their suggestion,
the model never saw the text. `handleStagedInputSubmit` built a rich
`synthetic` string with the feedback embedded but only resolved the
PauseGate with `{ type: "refine" }` — no payload. submit_plan threw
the bare `Error("user requested refinement")`, the model received
that as the tool result with zero context, and proposed a near-
identical plan, which fired PlanConfirm again. From the user's
perspective the suggestion was silently dropped.

The PlanVerdict union didn't even allow a feedback field, so the
omission was structural. The CheckpointVerdict pattern (already
shipping for revise-at-step) had the right shape; submit_plan just
never adopted it.

Pipe feedback through PlanVerdict for all three outcomes (refine /
approve / cancel) and surface it in the tool result string so the
model sees the user's exact words. Drop the dead `synthetic` that was
being built and discarded; keep `marker` and emit it via `pushInfo`
so the user gets a visible confirmation in chat scrollback right
after they hit Enter.

Closes #533
2026-05-09 22:32:46 +08:00
YHH 6cde945a01 fix(dashboard): resync canonical state on SSE reconnect (#532)
The /api/events endpoint snapshots only `busy-change` on (re)connect.
When the SSE connection drops mid-task — proxy timeout, browser
background-tab throttle, or Node event loop blocked past the 25s ping
window during heavy work — every assistant_delta / assistant_final /
tool / modal-up event fired during the disconnect window is lost.

EventSource auto-reconnects, but the new stream only carries new
events. If the disconnect happened before the end-of-turn
busy-change(false), the UI is wedged on "busy" forever and the
completed reply never appears. Reopening the dashboard URL was the
only escape, since fresh page load fetches /api/messages.

On reconnect (every onopen after the first), refetch /api/messages
and /api/modal to recover canonical state. Streaming + active-tool
slots reset since they're transient — the next delta will repopulate
streaming, the next tool_start will repopulate active-tool. First
open is skipped because the boot effect already fetched canonical
state.

Closes #521
2026-05-09 22:17:34 +08:00
YHH faf59cee4a fix(tui): wheel scroll on cloud/web terminals + drop render ghosting (#529)
* fix(tui): enable DECSET 1007 alternate-scroll so wheel scrolls on cloud/web terminals

Previously we relied on the implicit "terminal translates wheel→↑/↓ in
alt-screen" behavior. That only holds on local desktop terminals
(xterm/iTerm/Windows Terminal/Alacritty) where alt-scroll is on by
default. Web/cloud/SSH terminals (xterm.js, code-server, Cloud Shell,
mobile SSH clients, tmux without `mouse on`) don't ship with that
default, leaving the wheel as a dead key — the most common
"can't scroll" report.

Explicitly request the behavior via DECSET 1007 (alternate-scroll) on
mount, reset on unmount. Falls back silently on terminals that don't
recognize 1007. Native drag-select and right-click are untouched —
no Shift bypass needed.

`--no-mouse` opts out for the rare user who'd rather suppress the
sequence entirely.

* fix(tui): disable Ink incrementalRendering to drop render ghosting

Incremental render diffs against an internal "what's on screen"
snapshot. The diff drifts when:
  - string-width misjudges CJK / emoji ZWJ cell width and Ink
    miscomputes the affected region
  - async terminal-event bytes (DA replies, mouse, focus) interleave
    between Ink's cursor-positioning writes
  - terminal resize races a flush

When the diff drifts, stale rows survive the redraw — the residual
"ghost" class users have been reporting on cloud/web terminals.

Full-frame redraws sidestep the snapshot. Cost: more stdout bytes per
flush. At 60Hz default flush, local terminals are unaffected; remote
SSH only feels it during sustained high-rate streaming, where the
existing REASONIX_FLUSH_MS escape hatch can drop to 30Hz.
2026-05-09 21:57:53 +08:00
Evan-Pycraft 1e7be37a55 feat(i18n): localize card component labels with zh-CN (#526)
Replace hardcoded English strings in 8 card components (Ctx, Error, Reasoning, Search, Streaming, SubAgent, Tool, Usage) with t() calls. Pluralization handled at the call site via singular/plural key pairs (Chinese maps both to one form). Adds cardTitles + cardLabels namespaces to EN.ts / zh-CN.ts / types.ts.
2026-05-09 21:53:32 +08:00
zerone0x 7f54ae0678 feat(ui): suggest nearest slash commands on typos (#302)
Levenshtein-rank registered command names against unknown slash input; surface up to three closest candidates inline in the dispatch response. Falls back to the existing "(try /help)" hint when nothing is within distance threshold. Closes #17.
2026-05-09 21:08:53 +08:00
paradoxSCH bdf8faeb4e fix(shell): normalize Windows PATH env before spawn (#525)
Collapse case-variant PATH / PATHEXT keys (Path / PATH / path) into one normalized entry before passing env to child_process.spawn on Windows, and read PATH / PATHEXT case-insensitively in resolveExecutable so the spread env (which is a plain object, not the case-insensitive process.env Proxy) still resolves bins. Refs #520 — does not auto-close; awaiting reporter verification that Machine PATH inheritance is restored.
2026-05-09 20:34:37 +08:00
GuGuGaGa a9c407853a feat(wizard): add theme-picker step with live preview (#518)
Slot a theme step between language and apiKey so the rest of the wizard renders in the chosen theme. Live preview updates as the user navigates the list; default highlight lands on the currently-resolved theme; commit writes through writeConfig. Sample tile exercises tone.accent / tone.info / tone.ok / tone.warn / tone.err + fg.meta. Closes #492.
2026-05-09 20:26:34 +08:00
kabaka 959e9ffefd fix(slash): stabilize suggestions windowing + isolate status row layout (#516)
Rework SlashSuggestions windowing so grouped headers are budgeted into the visible row count and selection moves through commands without skipping group rows. Wrap StatusRow children with flexShrink/height/wrap=truncate so the status bar no longer collapses under the suggestion popup. Surface /language as a visible setup command. Filter order in suggestSlashCommands now also exposes code-group commands in bare browsing — flagged for follow-up if undesired.
2026-05-09 20:18:40 +08:00
YHH 012757567e perf(tui): raise streaming flush to 60Hz default for continuous text feel (#517) 2026-05-09 16:51:36 +08:00
YHH 453a3bc9d3 perf(tui): lower streaming flush from 30Hz to 20Hz default (#515)
We write to stdout at the streaming flush rate, and the terminal has
to interleave those writes with its own native drag-select highlight
repaints. At 30Hz (33ms) the terminal can't keep up — selection
feedback visibly lags during model output. Now that mouse mode is
off (#514) and users actually use drag-to-select again, this is the
load-bearing perf knob.

50ms (20Hz) still feels smooth on every modern terminal we test on
(WT, WezTerm, iTerm2, Alacritty, Ghostty) and cuts the write rate by
33%, leaving terminal repaint enough budget to keep selection
highlights snappy. `REASONIX_FLUSH_MS=33` brings the old behavior
back for anyone who actively prefers it.
2026-05-09 16:27:31 +08:00
YHH dbafd1632c fix(tui): drop xterm mouse tracking — restore native copy/paste, rebind keys (#514)
* fix(tui): drop xterm mouse tracking; ↑/↓ scroll chat, Ctrl+P/N owns prompt

Multiple users reported they can't copy text and can't scroll. Both
trace to the same root cause: we enabled DECSET 1000 + 1006 mouse
tracking so the wheel could route through `mouseScrollUp/Down`. The
side effect is that every terminal we know about then refuses to
start a native drag-select on click, blocks right-click, and on
ConPTY / multiplexer setups can drop the wheel events entirely (so
neither path scrolls).

Architecture flip:

- Don't enable mouse tracking. Bracketed paste + modifyOtherKeys stay.
- ↑/↓ at the App level always scroll chat, no buffer-state gating.
  Terminals translate the wheel to ↑/↓ in alt-screen mode, so the
  wheel still scrolls chat — for free, in every terminal.
- Ctrl+P / Ctrl+N take over what ↑/↓ used to do in PromptInput:
  cursor up/down inside a multi-line draft, falling back to prompt
  history when no cursor move is available (readline parity).
- /keys + tipMouseClipboard rewritten to reflect the new bindings;
  the old "hold Shift to drag-select" workaround is gone — drag
  works directly now.

Cost: power users who liked the wheel-scroll-while-typing affordance
have to switch to PgUp/PgDn or empty their prompt. Worth it given
how many users hit the copy-paste wall.

* fix(tui): update prompt hint row + stale comments to reflect ↑↓ scroll / Ctrl+P/N history binding

* fix(tui): don't scroll chat when a picker owns ↑/↓ (slash / @-mention / slash-arg / shell-confirm)
2026-05-09 16:09:28 +08:00
YHH 1aca86b424 fix(config): honor config.baseUrl + accept self-hosted key formats (#513)
Two compounding bugs sent self-hosted DeepSeek users back to the
official endpoint regardless of how they configured the client:

1. config.baseUrl was a dead field. Every `new DeepSeekClient()` call
   site (App.tsx, commit.ts, doctor.ts, run.ts) constructed the
   client without passing baseUrl, so it always fell back to the
   `DEEPSEEK_BASE_URL` env var or `https://api.deepseek.com`. The
   dashboard settings panel saved the value but nothing read it.

2. isPlausibleKey enforced the `sk-` prefix, so the wizard / setup /
   `/feedback` settings rejected any token that didn't look like an
   official DeepSeek key — even when the user had pointed baseUrl at
   their own deployment.

Adds `loadBaseUrl` (env > config > undefined) + `saveBaseUrl`, plumbs
the loader into all four client construction sites. Relaxes
isPlausibleKey to a generic typo guard (16+ chars, no whitespace) so
self-hosted token formats work; the real auth check is the first API
call against baseUrl.

Closes #502
2026-05-09 15:30:51 +08:00
YHH 5ce642aeeb fix(dashboard): use semver compare for up-to-date check (#512)
The dashboard health card, overview cockpit, and /feedback diagnostic
all decided "up to date" via `latest === installed` string equality.
That fires false-positive "needs update" / "(latest: 0.31.0)" pills
whenever the cached latest is older than the installed version — for
example after publishing 0.35.0 while the 24h cache still holds the
prior latest.

Switch all three sites to `compareVersions(installed, latest) >= 0`.
Add a tiny dashboard/src/lib/version.ts so the browser bundle has the
same comparator the CLI uses (no cross-package import).

Closes #510
2026-05-09 15:20:11 +08:00
YHH c888ab33d7 feat(update): respect install source instead of forcing npm global (#511)
`reasonix update` previously always emitted `npm install -g`, which
clobbered bun/pnpm/yarn installs and was unpredictable under nvm/fnm
where ambient npm may resolve to a different node runtime than the one
running the binary.

Detection (`detectInstallSource`) reads argv[1] and matches each
manager's unique global path segment:

  - `_npx/`, `.pnpm/...dlx/`, `npx/` UA → npx
  - `.bun/`, `bun/install/`              → bun
  - `pnpm/global/`                       → pnpm
  - `yarn/global/`, `.yarn/global/`      → yarn
  - `node_modules/reasonix/`             → npm
  - otherwise                            → unknown

Plan emits the matching command per source. For npm we additionally
pin `--prefix=<extracted-prefix>` so nvm/fnm runtime switches don't
redirect the install elsewhere. For unknown source we refuse with a
manual hint listing all four commands and exit 1 — no silent npm
fallback.

Closes #506
2026-05-09 14:58:31 +08:00
YHH 88514595ac fix(semantic): unblock Build when daemon is up but binary lookup fails (#507)
PATH refreshes per-shell on Windows, so a dashboard process started
before the Ollama install (or before a Terminal restart) inherits a
stale PATH and `where ollama` returns nothing — even when the daemon
the user launched from the tray icon is fully serving requests.

Two changes:

- findOllamaBinary falls back to %LOCALAPPDATA%\Programs\Ollama\
  ollama.exe when `where` fails. spawn() for `serve` / `pull` now uses
  the resolved path so those buttons survive a stale PATH too.

- ready no longer requires binaryFound. The embedding pipeline only
  talks to the HTTP API; the binary is only needed for daemon-start
  and model-pull, which have their own UI guards.

Closes #504
2026-05-09 14:38:04 +08:00
YHH 29020327fe chore(release): 0.35.0 (#505)
* chore(format): reuse fmtPct for cache-hit display; keep cachePct numeric

Drop the duplicate `formatCacheHitPct` helper added in #503 — `fmtPct`
in `dashboard/src/lib/format.ts` already does the same `(n*100).toFixed(1) + "%"`
shape and is the canonical formatter for the rest of the panels.

In `/status` (`observability.ts`), keep `cachePct` as a number through
`renderTinyBar` and only `.toFixed(1)` at the template-string boundary,
so we don't round-trip through string + `Number()`.

* chore(release): 0.35.0
2026-05-09 14:21:33 +08:00
kabaka 7642ad6ba2 fix(ui): improve cache hit percentage display and localization in dashboard (#503) 2026-05-09 14:11:13 +08:00
YHH e205c59775 feat(ui): /feedback + version badge in status row (#501)
* feat(ui): version badge in status row + /feedback opens issue with diagnostic clipboard

When a user hits a bug, the first question back is "what version" — and
the only way to find out today is to drop to the shell. Filing the
issue itself means leaving the TUI, finding the repo URL, then either
remembering or re-collecting version / OS / terminal / Node / locale /
model. Both papercuts are easy to fix from the prompt-input surface.

- StatusRow shows a `v<VERSION>` pill on the right cluster, gated to
  cols ≥ 70 so it doesn't crowd narrow terminals.
- New `/feedback` slash: gathers version + platform + os release +
  TERM_PROGRAM/TERM + Node + locale + model + sessionId, writes a
  paste-ready Markdown block to the clipboard via the existing
  `writeClipboard` helper, then opens the GitHub new-issue URL in the
  default browser via a new cross-platform `openUrl` (win32 cmd /c
  start, darwin open, linux xdg-open). No-ops under CI / when
  REASONIX_NO_OPEN is set.
- Diagnostic body contains exactly the seven advertised fields and
  nothing else — `tests/feedback.test.ts` pins the field set and asserts
  no API keys / file paths / transcript content can leak through.

Closes #499

* feat(ui): pre-fill /feedback issue body via URL + surface chip in status row

Two follow-ups so the affordance actually gets discovered and used:

- The issue page now opens with the diagnostic block already in the
  textarea via `?body=<urlencoded>`. Most users won't notice we copied
  to clipboard; pre-filling the URL is the obvious path. Clipboard
  stays as belt-and-suspenders for when the URL fails to open.
- StatusRow shows a `⚑ /feedback` hint after the version pill at
  cols ≥ 100 so users see the command exists. Narrower terminals (70–99
  cols) still get the version, just without the hint.
- Body length is capped at 6000 chars before encoding so a runaway
  diagnostic can't blow past the URL limit.

* feat(ui): expand /feedback diagnostic with flicker-relevant fields

The original block had version + platform + TERM_PROGRAM + Node + locale
+ model + session — fine for "agent ran the wrong tool" reports, but
useless for the rendering / flicker reports we actually field. Adds the
fields that come up first when triaging those:

- terminal size (cols×rows) — lots of repaint bugs only repro at
  specific widths
- env markers that change the rendering pipeline: COLORTERM,
  WT_SESSION, TMUX, SSH_TTY, WSL_DISTRO_NAME — TERM_PROGRAM alone can't
  distinguish cmd / WSL / SSH-tunnelled terminals
- theme name — different themes use different background fills, flicker
  is often theme-dependent
- edit / plan mode — decides which surfaces are mounted, changes
  repaint cadence
- latest version compare — surfaces "you're on an old build" without a
  follow-up question
- reasoning effort + MCP server count — incidentally cheap, occasionally
  load-bearing for cost / latency reports

Still no transcripts, paths, workspace name, or env outside the
hand-picked safe list. New tests pin the exact field set so future
fields can't sneak in unannounced.
2026-05-09 14:07:51 +08:00
YHH 874f0d1cc1 fix(dashboard): bump doc-chrome typography; widen sidebar column (#500)
The design-doc page chrome (`.toc` / `.section` / `.subsec`) was tuned
on a larger display and reads as too tight on a 13" laptop at 100%
zoom. Sidebar section headers at 10px with 0.14em tracking are the
worst offender — section labels also wrap mid-word in the 240px column.

- `.page` sidebar column: 240px → 260px so 2–3 word section labels fit.
- `.toc h1` 14 → 15px; `.toc .sub` 11 → 12px.
- `.toc-section` 10 → 12px and tracking 0.14em → 0.08em (lower so the
  size bump doesn't fight the letter-spacing).
- `.toc li a` 12.5 → 14px with `line-height: 1.4` and
  `overflow-wrap: anywhere` for graceful wraps on longer labels.
- `.section > .lede` 13 → 15px; `.subsec > p` 12.5 → 15px (line-height
  1.6 already applied).
- `.subsec > h3 .desc` 12 → 13px.
- `.swatch .hex` 10.5 → 11.5px; `.scale-row .lbl` 10.5 → 11.5px (and
  width 70 → 76px to keep the new monospace digits aligned).

Mirrored verbatim into `docs/design/agent-dashboard.html` per the
"keep CSS in lockstep with the mockup" comment at the top of app.css.

Closes #461
2026-05-09 13:17:56 +08:00
YHH 2462b1c278 feat(tools): create_skill + add_mcp_server — let the model scaffold from chat (#498)
Two new agent-facing tools so "add a skill that does X" / "wire up a
postgres MCP server" work as normal chat requests instead of forcing the
user out to slash commands:

- `create_skill` — pre-fills frontmatter (description / runAs /
  allowed-tools / model) from structured args and writes through a new
  SkillStore.createWithContent that reuses the same path resolution +
  collision check as `/skill new`.
- `add_mcp_server` — builds a `name=...` spec for stdio / sse /
  streamable-http transports, optionally hydrates from MCP_CATALOG,
  runs the existing preflight (filesystem sandbox-dir check), and
  appends to cfg.mcp via writeConfig. Refuses name collisions.
  Active on next launch — no live MCP client churn this session.

Both are registered alongside the existing native tools in
`reasonix code` so they're available wherever filesystem / shell are.

Closes #494
2026-05-09 13:06:29 +08:00
YHH d421970a27 fix(plan): surface open-questions block under the banner; i18n the plan flow (#497)
The banner already detected `Open Questions` / `Risks` / `Unknowns` headings
but the questions themselves were never shown — PlanConfirm rendered either
a step list or a 24-line body cap, both of which can hide the block. Refine
mode then reopened a blank input with no echo of the questions, so the user
either invented an answer or hit Enter and we asked the model to re-derive
its own questions on a follow-up turn.

- Extract the matching block (heading down to next same-or-shallower heading)
  via `extractOpenQuestionsSection` and render it under the banner regardless
  of steps / body cap.
- Forward the extracted block to `PlanRefineInput`, which now renders the
  questions above the input on `mode === "refine"`.
- Replace the blank-refine synthetic that asks the model to re-derive
  questions with one that tells it to pick safe defaults and call them out.
- Move all plan-flow strings (PlanConfirm / PlanRefineInput /
  PlanCheckpointConfirm / PlanStepList counter line) through `t()` under a
  new `planFlow` namespace in EN + zh-CN.

Closes #477
2026-05-09 12:56:47 +08:00
Prantik Medhi d1f491b29f fix(ui): render spawn_subagent output as markdown (#496) 2026-05-09 12:52:30 +08:00
YHH 3f6fb51b08 feat(search): per-file cap + histogram fallback for search_content (#495)
A single popular symbol could match 200+ lines in a big file (App.tsx,
loop.ts) and eat the entire byte budget before the walk reached any
other file. Truncation marker fired, every other matching file got
zero coverage, and the caller saw a wall of one file's hits with no
hint that distribution was wider than that.

Three knobs:

1. MAX_HITS_PER_FILE = 30. Beyond that, the per-file output ends with
   "[rel: N more matches in this file — re-grep with a tighter
   pattern or use read_file to see them]". One bullhorn file can no
   longer dominate the byte budget.

2. After each file completes, if printed bytes have crossed 80% of
   the byte budget, remaining files switch to histogram form
   ("rel: N matches"). A one-line notice marks the flip so the
   caller knows distribution from this point on is summary-only.

3. New `summary_only:true` arg skips line content entirely and
   returns just the histogram. Useful for "where does this exist at
   all" before drilling in with a targeted read_file.

Closes #489
2026-05-09 12:50:55 +08:00
YHH c63239ddb8 feat(subagent): tell the child its iter budget, warn near the cap (#493)
The child loop's tool-iter cap was enforced from the outside only;
the subagent's system prompt never said "you have N tool calls", and
the child had no way to know which iteration it was on. The visible
failure mode was an explore subagent burning all 20 iters mapping the
territory, then hitting the cap mid-thought and emitting a partial
summary the parent had to re-dispatch from.

Two pieces:

1. spawnSubagent now appends a one-paragraph budget notice to the
   child's system prompt — literal "Tool budget: you have N tool calls"
   with the resolved cap baked in. Applies to default, typed
   (explore/verify), and caller-supplied system prompts uniformly.

2. ToolRegistry gains setResultAugmenter(), a final-stage post-hook
   on dispatch. spawnSubagent installs one that counts dispatches and
   appends "[budget: K of N tool calls left — wrap up soon]" once the
   child is within 3 iters of the cap, escalating to "0 left —
   finalize NOW" on the last call.

Static prompt + dynamic countdown together: prompt sets expectation,
countdown forces reckoning when the budget is actually tight.

Closes #488
2026-05-09 12:50:28 +08:00
YHH ec5bfabde2 feat(tools): add top-level export outline to read_file auto-preview (#490)
When the auto-preview path fires (file > 200 lines, no head/tail/range
given), the head 80 + tail 40 slice rarely covers the full export list
of a real file. Callers had to follow up with a search_content grep to
locate "where is function AppInner defined" before they could pick a
useful range.

Now the auto-preview embeds a top-level outline between the head slice
and the omitted-marker — function / class / const / interface / type /
enum names with their line numbers, capped at 30 entries (first 25 +
last 5 + an elide marker). One round-trip, not three.

Closes #487
2026-05-09 12:43:01 +08:00
YHH a525182aff chore(release): 0.34.1 (#486) 2026-05-09 12:05:20 +08:00
YHH f795583cea perf(ui): coalesce chat-scroll events into one render per frame (#485)
Each PgUp / PgDn / arrow / wheel tick used to call setScrollRows
synchronously, so a single mouse-wheel gesture (10-30 events) triggered
10-30 full Yoga layout passes over the entire card tree. Layout cost
scales linearly with history length, which is what made long sessions
feel laggy.

Accumulate the delta into a ref and flush once per ~16ms. Net effect:
one setState per scroll burst regardless of event volume. jumpToBottom
cancels any pending delta so End still feels instant.

Closes #482
2026-05-09 12:01:33 +08:00
YHH bb971bd403 chore(release): 0.34.0 (#484) 2026-05-09 11:39:14 +08:00
YHH 06204c760e fix(dashboard): stop pushing localStorage lang back to server on init (#483)
The dashboard's initLangFromServer() had two branches when localStorage
disagreed with the server config:

  1. If `rx.langExplicit` was set (user picked a language in dashboard
     panel at some point) → POST localStorage value back to server
  2. Otherwise → adopt the server value

Branch 1 silently clobbered CLI-side `/language` changes. Sequence:

  - User picks zh-CN in dashboard once → rx.langExplicit=1, rx.lang=en
    (or whichever)
  - User later runs `/language zh-CN` in the CLI → server config is
    now zh-CN
  - User opens dashboard tab (or browser restores it from a previous
    session) → init runs → POSTs localStorage's old value back, server
    flips to en, CLI's choice is lost on next launch

Server config is the single source of truth. localStorage is purely a
render-cache to avoid first-paint flicker — never push it back.

Removes EXPLICIT_KEY / isExplicit / markExplicit entirely; the stale
key in existing users' localStorage is harmless dead data.
2026-05-09 11:33:49 +08:00
YHH c504707af8 feat(ui): /keys reference + first-run mouse/clipboard tip (#481)
Two layers around the new TipCard:

1. /keys — make the slash command real
   It was already referenced in the edit-gate tip's footer ("Run /keys
   anytime for the full list") but no handler existed; typing /keys hit
   the unknown-command branch. Add the spec under "info", a handler
   that pushes a multi-section TipCard with the full reference, and a
   `postKeys` callback on SlashContext wired to log.pushTip.

   The reference is sectioned: keyboard / mouse / copy-paste /
   edit-gate. Each section has its own subtitle and aligned key column.

2. First-run mouse + clipboard tip
   SGR mouse tracking captures the wheel for chat scroll but also eats
   the terminal's native right-click-paste — without explanation users
   think the prompt is broken. Add a one-time tip mirroring the
   edit-gate pattern: pushed on first launch, suppressed thereafter via
   a `mouseClipboardHintShown` flag.

TipCard now supports multiple sections (single-section tips just have
one un-titled section). The previously-shipped tipEditBindings is
re-wrapped in a single section; behavior unchanged.

i18n: keysReference (4 sections, ~25 rows) + tipMouseClipboard (1
section, 3 rows) + handlers.basic.keysNeedsTui in EN.ts and zh-CN.ts;
matching shape in types.ts. The i18n /keys row already existed but its
description was outdated — refreshed in both languages.
2026-05-09 11:06:23 +08:00
YHH f0a552bed5 feat(ui): structured TipCard variant for onboarding hints (#480)
The edit-gate one-time tip currently renders as raw multi-line text
inside a stepProgress LiveCard — `✓` glyph (success semantic, wrong
for educational content) plus a manually-inlined `▸ TIP:` prefix,
columns aligned with hand-counted spaces that wrap badly on narrow
terminals, and the "shown once" disclaimer crammed into the body
parenthetical.

Replace it with a dedicated `TipCard` kind:
- Single `ⓘ` glyph in accent color, no duplicated prefix
- Topic + "shown once" badge in a header row (justified)
- Each row is its own `<Text>` with real column alignment driven by
  stringWidth (works for CJK widths too)
- Footer separated from body by a blank row, dim color
- No border — tips are scrollback content, not modal

i18n: `tipEditBindings` becomes a structured `{topic, rows, footer}`
object across types.ts / EN.ts / zh-CN.ts. New helper `tObj<T>(path)`
in i18n/index.ts for non-string entries; the existing `t()` is
unchanged. Adds a tiny `tipShownOnce` string for the badge.

Adds a `pushTip()` method on Scrollback alongside `pushInfo()`; the
new `tip.show` event flows through the same reducer / dispatch pipeline
as every other card kind.
2026-05-09 10:54:52 +08:00
YHH bb5b124817 @-picker rebuild + mouse-wheel chat scroll (#479)
* feat(at-picker): rebuild as file browser with streaming search

Empty / trailing-slash queries (`@`, `@src/`) browse one directory level
with a single readdir — folders selectable, drill via Tab. Any non-slash
filter (`@foo`, `@auth/log`) kicks off a cancelable streaming walk across
the full tree, batching matches into the popup as they're found, with a
`searching… N scanned` footer while in flight.

Replaces the upfront 500-file walk that was unusable on large repos —
on a 5k-file tree the cap evicted ~90% of paths before ranking, leaving
the picker effectively empty.

- walkFilesStream: cancelable streaming walker; powers search mode
- listDirectory: single-level browse, no recursion; powers browse mode
- parseAtQuery: splits `dir/filter` with trailing-slash awareness
- listFilesWithStatsAsync now delegates to walkFilesStream (no behavior
  change for existing callers)
- expandAtUrls + helpers split into at-mentions-url.ts to keep
  at-mentions.ts under the 800-line ceiling

Closes #478

* fix(scroll): route mouse wheel via SGR mouse tracking

Enable DECSET 1006 + 1000 at startup so the terminal reports wheel
events as `\x1b[<btn;col;row;M` mouse sequences instead of translating
them to ↑/↓ key presses. The chat-scroll handler routes the resulting
mouseScrollUp/Down events to scrollback, bypassing the arrow-key path
entirely — the wheel now scrolls chat regardless of buffer state, while
↑/↓ keys retain their existing PromptInput bindings (history recall on
empty buffer, cursor motion otherwise).

The SGR mouse parser already lived in stdin-reader.ts; this just
turns on the terminal-side feature so events actually flow.

Cost: terminal-native drag-to-select needs a modifier (Shift on Windows
Terminal / Alacritty / WezTerm, Option on iTerm2) — same trade-off as
tmux, Claude Code, Cursor's terminal.
2026-05-09 10:28:28 +08:00
J3y0r 636ad7e551 feat(ui): add theme manager support (#452)
Closes #449

- Theme runtime via useColor() hook + ThemeProvider context
- Built-in themes: default, dark, light, tokyo-night, github-dark, github-light, plus auto/high-contrast
- Persisted via config: theme.name, with auto resolving against terminal background
- /theme slash command (advanced group) with arg completer

Merged through #453 slash refactor (theme placed in advanced group) and #424 semantic config additions.
2026-05-08 18:19:22 -07:00
YHH 1c360ac81b chore(release): 0.33.2 (#476) 2026-05-09 09:02:01 +08:00
YHH c120ed3a39 fix: ↑/↓ on empty buffer recall history; doctor finds tokenizer (#468) (#475)
Two bugs in one issue.

1. **↑/↓ stopped recalling history.** 9254d3a unbound history from
   arrows because Windows Terminal + ConPTY can translate mouse-wheel
   events to ↑/↓ keystrokes — wheel-up was clobbering the prompt with
   a recalled message. The fix moved history to Ctrl+P / Ctrl+N.

   That was the right call for legacy ConPTY users but broke the
   universal CLI muscle memory for everyone else (bash / zsh / fish
   all bind ↑ to history). Linux / macOS / modern Windows Terminal
   users don't have the wheel-translation problem in the first place.

   Restore ↑/↓ on empty buffer = history; keep Ctrl+P / Ctrl+N as
   the wheel-immune fallback. The App-level keystroke handler still
   routes ↑/↓ to chat-scroll once the user is unpinned (subsequent
   wheel events keep scrolling), so the only regression for legacy
   ConPTY is the FIRST wheel-up from a pinned position recalls a
   prompt. Documented; ⌃P/N is one keystroke away.

   Drops the now-dead `chatScrollHandoff` plumbing.

2. **Doctor reported "tokenizer not found" when it was installed.**
   The tokenizer ships under `data/` in the npm tarball and the
   runtime resolver in tokenizer.ts has three candidates including a
   `createRequire("reasonix/package.json")` probe — finds it
   reliably. The doctor had its own resolver that walked
   `dist/cli/commands/doctor.js → ../../../data/`, which broke after
   the lazy-import refactor in #467 emitted the doctor at
   `dist/cli/doctor-HASH.js` (one level shallower). Walked above the
   package root and reported missing.

   Reuse the runtime resolver (now exported) so the two paths can
   never disagree.
2026-05-09 08:58:10 +08:00
YHH 42f75c7478 chore(release): 0.33.1 (#474) 2026-05-09 08:24:46 +08:00
YHH 34b8275f20 feat(ui): wallet pill on status row + tighter prompt hints (#473)
The status row was reading status.cost (turn) and status.cacheHit
but ignoring two fields the reducer already populates:
status.sessionCost (running USD total) and status.balance (DeepSeek
wallet, refreshed on every submit). balanceColor() with red/orange
thresholds even sat in tokens.ts unused.

New WalletPill segment renders right of the cache pill:
  ⛁ ¥1.20 spent  /  ¥45.32 left
with thresholded color on the balance number. Shown only when
the terminal is ≥90 cols and at least one of the two values is
known, so narrow sessions don't wrap.

PromptInput: friendlier placeholder copy ("ask anything") and the
hint footer now uses keycap/label spacing (⇧⏎ instead of
shift/alt+⏎) for a less command-line-jargon read.
2026-05-09 08:21:09 +08:00
YHH b40db0f469 chore(release): 0.33.0 (#472) 2026-05-09 08:06:19 +08:00
YHH 4029b7dc25 fix(ui): drop dead toolHistoryRef leak — every tool result retained for session lifetime (#465) (#471)
The /tool slash command was removed in #453 but its supporting
plumbing was left behind: every tool result was still being pushed
into a useRef array, with no consumer ever reading it. Long-running
sessions accumulated full Read/Grep/Bash output indefinitely and ran
out of heap.

#465 reports a JS heap OOM after ~2.6 hours on v0.31.0; this leak
matches the failure shape (mark-compacts ineffective, 4GB ceiling).
2026-05-09 07:59:25 +08:00
YHH 9c69513650 fix(/cwd): re-bootstrap semantic_search on workspace swap (#470)
#459 follow-up. When `/cwd` swaps the workspace root, FS/shell/memory
tools were re-registered against the new path but `semantic_search`
kept pointing at the OLD root — meaning queries silently searched
the previous project's index, or the tool stayed registered when
the new dir had no index at all.

Split semantic re-bootstrap from the sync `reregisterTools` callback:
- `reregisterTools` stays sync (FS/shell/memory must land before the
  next tool dispatch).
- New `reBootstrapSemantic(root) => Promise<{ enabled }>` reads disk
  to probe index compatibility, registers `semantic_search` if found,
  unregisters it otherwise.

App.tsx fires the async tail with `void ...then(postInfo)` so the
slash dispatch returns synchronously (matches the codebase's
fire-and-forget pattern documented in slash/dispatch.ts). User sees:

  ▸ workspace switched to /new/path
  ▸ semantic_search re-pointed at /new/path        ← if compatible
  ▸ semantic_search disabled (no compatible index in /new/path)
                                                   ← if not

Same machinery handles the launch path — `code.tsx` now calls
`reBootstrapSemantic(rootDir)` instead of bootstrap directly so
the unregister-on-skip behavior is exercised on every entry path.
2026-05-09 07:27:03 +08:00
YHH df8f146b79 perf(cli): lazy-import dashboard server + strategic App marks (#469)
Stage 2 follow-up to #464. Continuing the profile-driven trims.

The dashboard server module (src/server/index.ts plus its ~4200 LOC
of transitive dashboard code) was being eagerly imported into App.tsx
even when --no-dashboard was set or auto-start hadn't fired. Move it
to a dynamic import inside startDashboard's startup IIFE — it's
already async, so the await import() is free in the structural
sense.

Measurable hot-path delta is small (~4ms within noise) but it shaves
real bytes off the first-paint module graph and removes a synchronous
dependency on the entire server tree. Cold paths benefit too.

Also adds two strategic marks (`app_render_start`, `app_inner_start`)
for future profiling. They're harmless when the env var is off and
expose the React-component-body boundary in the dump, which makes
the existing `first_paint` delta self-explanatory.

Findings from the deeper investigation (now reverted as noisy diagnostics):
- App's disk-hitting useState initializers (loadHooks, loadSlashUsage,
  loadEditMode, hydrateCardsFromMessages) are all sub-ms each.
  Deferring them buys nothing measurable.
- The 280-300ms gap between `app_inner_start` and `first_paint` is
  React reconciliation + Ink's terminal commit + the first useEffect
  flushing. Trimming further requires reducing initial render
  complexity, not deferring side work.

Stage 3 (CI budget gate) remains deferred — the platform-dependent
nature of these numbers makes a hard threshold fragile. Profile
harness is already documented in-tree via the env-var hint
(`REASONIX_PROFILE_STARTUP=0 to silence`).
2026-05-09 07:17:26 +08:00
YHH e6b247939c perf(cli): lazy-import per-command modules (Stage 2 of #464) (#467)
Stage 1 (#466) showed module-load was 57% of cold-start cost (436ms
of 764ms total on this Windows box). Every `reasonix <subcommand>`
invocation was eagerly loading every other command's module —
including chat.tsx → App.tsx → React/Ink. `reasonix version` paid
for the chat UI it doesn't need.

Move every `import { fooCommand } from "./commands/foo.js"` into a
dynamic `await import()` inside the relevant `.action()`. tsup
splits these into separate chunks automatically; Node only loads
them when the user invokes that subcommand.

Measured impact:

  reasonix code (hot path, 5 runs avg): 778ms vs 764ms baseline
    → +14ms regression (within measurement noise; the 388ms that
      used to live in `cli_module_loaded` now lives in
      `code_command_enter` since code.tsx is dynamic-imported)

  reasonix version: ~140ms vs ~440ms baseline → 290ms saved
  reasonix --help:  ~140ms vs ~440ms baseline → 290ms saved

Cold-path commands (version, --help, doctor, commit, sessions,
events, replay, diff, mcp *, update, index) all benefit. They
no longer pay the ink/react/dashboard import cost.

Hot path (`code` / `chat`) is roughly neutral. Real wins on hot
path will come from trimming first_paint (316ms, 41% of total) —
follow-up.

Test fix: bundle-smoke.test.ts asserted `from "ink"` lived in
dist/cli/index.js specifically; with code-splitting the import
moves to a chunk file. Updated assertion to scan all dist/cli/*.js.
The semantics are preserved — ink stays external (not bundled),
just no longer in the entry chunk.
2026-05-09 01:07:57 +08:00
YHH 424a9301f4 perf(cli): startup-profile instrumentation (Stage 1 of #464) (#466)
#464 plan was profile-first; this lands Stage 1.

Adds src/cli/startup-profile.ts with markPhase/dumpStartupProfile
gated behind REASONIX_PROFILE_STARTUP=1. When unset (default), every
call is a no-op — zero cost in normal runs.

Marks placed at:
- cli_module_loaded — top of the bin entry, after all transitive imports
- chat_command_enter / config_loaded
- mcp_launch / mcp_connected_M_of_N (only when MCP specs exist)
- code_command_enter — top of `reasonix code`
- semantic_bootstrap_start / _done_(enabled|skipped)
- ink_render_call — just before `render(<Root/>)`
- first_paint — App's first useEffect after mount, also dumps the profile

Baseline collected on this Windows box (no MCP, semantic index already
built):

  436ms  cli_module_loaded             (+436)
    3ms  code_command_enter            (+3)
    2ms  semantic_bootstrap_start      (+2)
    2ms  semantic_bootstrap_done_enabled  (+2)
    3ms  chat_command_enter            (+2)
    0ms  config_loaded                 (+0)
    2ms  ink_render_call               (+1)
  316ms  first_paint                   (+316)
  ─── 764ms total

Read: module-load (Node + transitive imports) is 57% of total, first
paint (Ink render + React commit) is 41%. Everything else is noise.
Stage 2 should target lazy-loading heavy import dependencies that
land synchronously today (DeepSeek client, Ink, dashboard server,
embedding provider). MCP serial setup hypothesis from the issue
needs a real config to confirm — punted until we have a measured
multi-MCP run.

Stage 3 (CI budget assertion) deferred until Stage 2 trims have
landed and we have stable numbers to set thresholds against.
2026-05-09 00:55:08 +08:00
YHH b171848250 fix(ux): fuzzy at-mention ranking + /cwd slash for #459 parts 1+2 (#463)
#459 is a meta-issue with three first-five-minutes UX papercuts.
This lands two of them; startup-perf (part 3) needs profiling
first and gets a separate issue.

## Part 1: at-mention picker — subsequence fallback

The picker rejected anything that wasn't a substring match, so
typing `atmnt` for `at-mentions` returned nothing. Adds a fuzzy-
subsequence scorer as a fallback after substring lookup misses.
Substring hits still win — class 0/1/2 cap at 29_999, subseq
starts at 30_000. Fuzzy scoring rewards consecutive runs and
basename-anchored matches, penalizes total path length.

Files walking + cap-aware UI hints already existed (the audit
showed them at useCompletionPickers.ts:102 and
AtMentionSuggestions.tsx:55–77). The missing piece was ranking.

## Part 2: /cwd slash command

The plumbing was already there: `codeMode.reregisterTools(root)`
exists in code.tsx, App.tsx already comments "/cwd mutates this
state to swap the workspace mid-session". The slash command
itself was just never wired.

Wires it end-to-end:
- SlashContext gets a `switchCwd(path) => { ok, info }` hook.
- App.tsx implements switchCwd: stat + isDirectory check,
  reregisterTools(newPath), setCurrentRootDir, reload hooks.
- New `/cwd` (alias `/sandbox`) command in the code group.
- Handler in handlers/edits.ts.
- EN + zh-CN strings added.

Out of scope: semantic-index re-bootstrap on cwd swap (current
bootstrap runs once in code.tsx). Tracked as a follow-up.

## Part 3 (deferred)

Slow startup needs profiling before redesign. Will open a separate
issue with a concrete "mark phases, defer post-mount" plan.
2026-05-09 00:41:14 +08:00
YHH cf393f7f9e feat(tools): glob, search_content context lines, cross-file multi_edit (#462)
Three quality polishes to the filesystem toolbelt, all small, all
addressing real friction the model hits often.

glob — new tool. Mtime-sorted file walk with picomatch glob syntax
(**/, *.{ts,tsx}, etc.). Default sort=mtime desc so "what did I
touch lately" works out of the box; sort=name for deterministic
listings. Skips deps by default, capped at 200 results (1000 max)
with overflow notice. Different from search_files (substring on
basename) and search_content (greps file bodies).

search_content — new `context: N` param mirroring `grep -C N`.
Output uses ripgrep convention: `:` after the line number on hits,
`-` on context lines, `--` separating non-adjacent windows.
Adjacent windows merge automatically so a hit at line 42 and 44
with context:1 produces one continuous block. Capped at 20 lines
on each side to keep the maxListBytes budget intact.

multi_edit — reshape from single-file `{ path, edits: [...] }` to
cross-file `{ edits: [{ path, search, replace }, ...] }`. Reads
each touched file once, applies edits in array order against an
in-memory buffer (so a later edit can match text inserted by an
earlier one), validates everything, then writes all touched files.
ANY validation failure → ZERO writes (true atomicity at the
validation layer; sequential disk writes after that). Output
header now reports both "N edits across M files".

This is a hard schema break for multi_edit, but it shipped
unreleased six hours ago — no consumers to migrate.

Test coverage: 24 new cases (glob: 6, context: 4, multi_edit: 8
covering single + cross + atomic + missing-file). 2243 pass on
verify.
2026-05-09 00:29:28 +08:00
YHH 771443c670 feat(tools): todo_write — lightweight in-session task tracker (#460)
submit_plan is the heavy gate (user approval, per-step checkpoints,
plan-mode toggle); ask_choice is the branching primitive. Neither
covers "I have 4 things to do, let me record them and tick them off
as I go" — that's prose-list territory today, which means lost
context the moment the loop folds history.

todo_write fills the gap: replace-set semantics, no approval pause,
no file writes. Validated: at most one in_progress, status enum,
non-empty content+activeForm. readOnly=true so it stays callable in
/plan mode (recording intent during planning is exactly when it's
most useful).

Wired into reasonix code with an onTodosUpdated callback hook for
future TUI surfacing (live progress strip, etc.). System prompt
gains a "When to track multi-step intent" section telling the model
to reach for it on 3+ step tasks instead of inlining "1. ... 2. ..."
in prose.
2026-05-09 00:15:09 +08:00
YHH 747651e55d feat(tools): multi_edit — atomic batch SEARCH/REPLACE in one file (#458)
N edit_file calls for a single-file rename burns a tool round-trip
per site and isn't atomic — a mid-batch failure leaves the file half-
edited. multi_edit takes an array of {search, replace} entries,
applies them sequentially against an in-memory buffer, and only
writes once all succeed. Any failure (search not found, ambiguous
match, empty search) → no edits are written.

Per-edit rules match edit_file: exact whitespace-sensitive search,
must be unique at the moment that edit applies. Sequential semantics
mean edit N+1 can match text that edit N inserted.

Closes a concrete pain point flagged when surveying the toolbelt
against typical multi-site refactor flows.
2026-05-09 00:04:33 +08:00
YHH d4a4c599b5 chore(release): 0.32.0 (#456) 2026-05-08 23:22:24 +08:00
YHH 192a63b8d2 fix(at-mentions): expand @<dir> to a listing; recover symlink-to-file in picker (#455)
Closes #451

UI flicker (section 3 of #451) is already tracked in #412.

1. expandAtMentions treated `@<dir>` as a `not-file` skip — the model
   never saw what was in the directory. It now resolves the path, walks
   the project root with the existing gitignore layers, filters to
   entries under the directory, and inlines a `<directory>` block
   capped at DEFAULT_AT_DIR_MAX_ENTRIES (200). `@docs/` and `@docs`
   resolve to the same key, so trailing-slash typing doesn't double-fire.

2. listFilesWithStatsSync / listFilesWithStatsAsync called only
   ent.isFile(), which returns false for symlinks. Symlinked source
   files were silently dropped from the picker. Both walkers now stat
   through symlinks; symlinks-to-files come back, symlinks-to-dirs
   stay dropped (cycle risk), broken links stay dropped (nothing to
   point at).
2026-05-08 23:14:23 +08:00
YHH 58f4544d23 fix(plan): dock active plan card; auto/yolo skips per-step checkpoint (#454)
Two related plan-mode UX gaps.

1. PlanLiveRow had nothing to dock. `case "plan_proposed"` dropped the
   gate payload's steps/summary, and the approve path never dispatched
   plan.show — so no card with variant: "active" ever existed and the
   filter in isActivePlanInFlight returned null. Stash steps/summary in
   the existing refs on plan_proposed, materialize the active card on
   approve, and drop+re-show on revise-accept so the dock tracks tail
   rewrites instead of silently going stale.

2. "Checkpoint — step done" fired after every mark_step_complete even
   in auto/yolo, defeating the whole point of those modes (shell and
   edit-gate already self-skip). plan_checkpoint now checks editModeRef
   and, in auto/yolo, resolves the gate with "continue" without UI.
   Per-step rollback snapshot still runs so /restore granularity stays.
2026-05-08 23:01:08 +08:00
YHH 76e42ac665 slash: unified preset+model picker, grouped suggestions, kill 11 commands + harvest/branch (#453)
* slash: unified preset+model picker, grouped suggestions, kill 11 commands + harvest/branch

The slash surface was 58 commands deep with no organization, two confusable
options for "fresh start" (/clear vs /new), separate preset and model commands
that solved the same user question ("what AI am I using"), and two heavy
features that almost nobody opted into. Pulled all of that apart.

Picker

* ModelPicker now shows the 3 presets at the top with cost/headline copy and
  the model catalog below; auto-detects which preset the loop currently matches
  (model + effort + autoEscalate) so the cursor lands on the active row. Both
  /preset (no arg) and /model (no arg) open it.

SlashSuggestions

* SlashCommandSpec gains a `group` field (chat / setup / info / session /
  extend / code / jobs / advanced). Suggestion palette renders section headers
  on a bare /; advanced rows hide behind a "+ N advanced · type to search"
  footer until the user types a letter. /help walks the same registry, so
  there's one source of truth.

Telemetry

* New ~/.reasonix/slash-usage.json counter (read-modify-write, atomic rename)
  feeds suggestSlashCommands so frequent commands sort first within a prefix.
  emitSlashInvoked is now wired to the events.jsonl sidecar.

Removals (commands)

* /models, /keys, /resume, /semantic — redundant with picker / /help / /doctor.
* /clear merged into /new (now an alias) — the visual-only clear was the most
  common confusion source ("why does /clear keep my context?").
* /effort, /rename, /forget, /apply-plan, /think, /tool, /mcp browse — second
  pass; either covered by other UI (sessions picker has rename/delete; preset
  locks effort) or self-described as fallback / debug.

Removals (features)

* /harvest and the Pillar-2 plan-state extractor (src/harvest.ts).
* /branch and the parallel-sample selector (src/consistency.ts,
  src/loop/branch.ts). Streaming/branching coupling, BranchCard,
  branch_start/progress/done events, transcript planState/harvestedTurns,
  --harvest/--branch CLI flags, all gone.
* benchmarks/harvest/ deleted; ARCHITECTURE.md collapsed from four pillars
  to three; README + zh-CN + dashboard/PARITY updated.

i18n

* Cleared dead keys for every removed command (handlers.basic.helpHelp..helpExit,
  keys*, semantic, resume*, models*, harvest*, branch*, effort*, think*, tool*,
  apply-plan*, slash.harvest, slash.branch, ui.harvest*, ui.branch*).

Tests: 138 files / 2192 tests pass. Public API drops harvest, runBranches,
TypedPlanState, BranchSummary, etc.; consumers using those break intentionally.

* ci: drop harvest-bench dry-run step

Follows the harvest feature removal — benchmarks/harvest/ no longer exists,
so the CI step was breaking on ERR_MODULE_NOT_FOUND. τ-bench dry-run stays.
2026-05-08 22:31:52 +08:00
kabaka a9471ae8e1 feat(semantic): OpenAI-compatible embedding provider (#424)
Configurable API URL / key / model / request body for embeddings, replacing the Ollama-only setup. Adds a provider abstraction in src/index/semantic/embedding.ts, index identity check + abort wiring through the builder, API-key redaction in dashboard/status output, and en-US + zh-CN strings for the new provider UI.
2026-05-08 22:13:01 +08:00
YHH f9a1d0912d chore(release): 0.31.0 (#450) 2026-05-08 20:23:00 +08:00
YHH 3f3b5e2fe7 i18n(slash): localize 4 lagging slash handlers (#448)
Most handler files were already 80%+ i18n'd from prior work, but
four files had drift:

  - web-search-engine.ts — 0 t() calls, the entire help text plus
    switch confirmation was hardcoded English. Whole new
    handlers.webSearchEngine namespace (~12 keys).
  - mcp.ts — 5 hardcoded usage / unknown-server / "(none)" /
    reconnect-not-wired strings; added under handlers.mcp.
  - plans.ts — the archive row template ("✓ {when} {N} steps · …"),
    "complete" verb, and the /stop abort line. Added under
    handlers.plans.
  - semantic.ts — code-mode-only refusal + "checking…" status.
    Added under handlers.semantic. Note this file uses two t()
    instances side-by-side — the local @/index/semantic/i18n one
    stays for the existing slashHeader/slashEnabled keys, and the
    main @/i18n/index t (aliased as tMain) is added for the two new
    strings.

zh-CN translations included for all ~22 new keys.

Test plan: full suite 2301 pass, tsc + biome clean.
2026-05-08 20:14:24 +08:00
YHH 0990491584 i18n(app): localize ~26 user-facing strings in App.tsx (#447)
Two patterns rolled into one PR:

1. Wire seven existing ui.* keys that had been defined in EN.ts /
   zh-CN.ts but never actually called: ephemeralSession,
   resumedSession, newSession, restoredEdits, resumedPlan,
   tipEditBindings, dashboardAutoStartFailed. The keys had drifted
   into dead code — same pattern that bit the loop.* namespace
   before #445.

2. New app.* namespace (~24 keys) covering every other hardcoded
   user-facing string in App.tsx:
   - walk cancel (with / without remaining count)
   - edit-mode cycle (review / auto / yolo)
   - reject / auto-approve / flip-to-auto messages
   - dashboard stopped, /restore code-mode-only
   - hash-memory note (with translated scope + verb)
   - bash-mode + memory-write failures
   - hook headers (UserPromptSubmit, Stop)
   - @mentions / @url expansion + failure
   - shell confirm (deny / always-allow / running / starting)
   - checkpoint saved
   - plan continue / stop / revise

zh-CN translations for all 31 new keys.

Test plan: full suite 2301 pass, tsc + biome clean.
2026-05-08 20:01:27 +08:00
YHH 40628d0025 i18n(hooks/summary): localize hook outcome and force-summary text (#446)
Two small follow-on batches after #445:

1. hooks.formatHookOutcomeMessage — was hardcoded
   \`hook \${tag} \\`\${cmd}\\` \${decision}\${truncTag}\`. Pulls
   the structural words (\"hook\", decision verb, \" (output truncated
   at 256KB)\") into a new \`hooks.*\` namespace. The technical bits
   (tag, cmd) stay verbatim — they're identifiers, not prose.

2. loop/force-summary.ts — three user-visible strings:
   - \"summarizing what was gathered…\" (status during summary call)
   - the fallback when the model emits hallucinated tool-call markup
     instead of prose
   - the error template when the fallback summary itself crashes

New \`summary.*\` namespace covers all three. zh-CN translations included.

Decision verbs (block / warn / timeout / error) are translated via a
small \`hooks.decision\${Capitalize}\` lookup so the formatter still
takes \`outcome.decision\` (the typed enum) as input.

Test plan: full suite 2301 pass; tsc + biome clean.
2026-05-08 19:50:23 +08:00
YHH 346bb35cb8 i18n(loop): localize 14 user-facing yields in step() (#445)
Yields like 'session budget exhausted', 'aborted at iter X/Y',
'preflight: request ~X/Y tokens', and the post-turn fold/forcing-
summary status lines were all hardcoded English. The loop.* i18n
namespace had 7 keys defined but never wired — placeholders from a
previous attempt that drifted away from the actual call sites.

This PR replaces the dead namespace with 20 keys that match the
actual yield shapes, wires t() at every site, and adds zh-CN
translations.

Categories covered:
  - budget (exhausted / 80% warning)
  - /pro armed
  - aborted-at-iter / tool-budget-warning
  - preflight (status + folded / no-fold-left)
  - escalation (flash → pro / auto-escalation)
  - storm-broken (stuck retry loop / suppressed-N-times)
  - history compaction (status + folded / aggressively-folded)
  - forcing summary (context-guard exit)

Behavior preserved: tests pin runtime to EN, so existing assertions
on the English text still pass. The dead loop.* keys (budgetWarning,
budgetRefusal, contextWarning, escalationWarning, toolFailure,
interrupted, loopStopped) had zero callers across src/ and tests/
and are removed as part of the namespace cleanup.
2026-05-08 19:38:39 +08:00
YHH 97a93cf4f5 i18n(loop/errors): localize DeepSeek error messages (#444)
formatLoopError, reasonPrefixFor, and errorLabelFor were all
hardcoded English. A Chinese user hitting a 503 / 401 / context
overflow saw raw English (and on top of that, the new 5xx outage
notice from #440 was also English).

Move the strings to a new errors.* i18n namespace covering:
  - context overflow (with V4/legacy limit mention)
  - 401 auth / 402 balance / 422 param / 400 bad request
  - 5xx head + reachable / unreachable / two action variants
  - reason prefix and label for budget/aborted/context-guard/stuck
  - "(no message)" fallback for empty error bodies

zh-CN translations included. Existing tests still cover EN (vitest
setupFile pins runtime to EN); two new tests flip to zh-CN to confirm
runtime switch actually translates.

Stacked on #440 — merge that first.
2026-05-08 19:28:18 +08:00
YHH d837ddaf43 fix(loop): friendly DeepSeek 5xx error with reachability probe (#440)
* fix(loop): friendly DeepSeek 5xx error with reachability probe

Raw `DeepSeek 503: <body>` was bubbling straight to the UI. Users on
flaky DS days couldn't tell if it was DS-side (their service was
overloaded) or Reasonix-side (we crashed). The header comment in
loop/errors.ts even claimed retry.ts swallowed all 5xx — but retry.ts
returns the last response instead of swallowing, so 5xx did reach the
formatter and just fell through to a passthrough branch.

Now formatLoopError takes an optional probe result. The catch in
step() detects 5xx, fires a 1.5s `/user/balance` probe, and passes
the result back. Three message variants:
  - no probe         → DS-side outage notice + retry hints
  - probe reachable  → "main API answered, /chat/completions failing"
  - probe down       → "DS unreachable from your network — check net"

All three include "this is a DeepSeek-side problem, not Reasonix" and
a status-page link so users know where to look.

* test: avoid CodeQL js/regex/missing-regexp-anchor on URL substring match

Use toContain('status.deepseek.com') instead of /status\.deepseek\.com/
— same assertion semantics, dodges CodeQL's high-severity false positive
on unanchored URL regex.
2026-05-08 19:22:58 +08:00
YHH c56cd9d9a0 i18n(dashboard): translate the plan 'idle' status pill (#443)
Plans whose completionRatio is 0 (submitted but no steps marked
complete yet) showed a hardcoded English "idle" pill — surrounding
"active" / "done" pills already used t().

Add plans.idle to en.ts ("idle") and zh-CN.ts ("未开始"), and route
the idle branch of statusPill() through t().
2026-05-08 19:22:21 +08:00
YHH db194cb833 feat(wizard): first-launch language picker + i18n the wizard (#442)
Two related fixes for non-English first-runs:

1. Add a language step at the very start of the setup wizard.
   Cursor defaults to detectSystemLanguage() result. Selection saves
   immediately, so all later wizard steps render in the chosen
   language. Re-runs (`reasonix setup`) start there too — cursor
   defaults to currently saved language so Enter is a no-op for
   users who don't want to change it.

2. Localize every hardcoded string in the wizard via a new wizard.*
   i18n namespace (~30 keys, EN + zh-CN). Previously a Chinese user
   who hit /language partway through never saw zh-CN copy because
   the wizard rendered raw English. Now language → applies → review
   step renders in zh-CN.

Why this matters: Intl.DateTimeFormat().resolvedOptions().locale
isn't always correct (terminal env strips LANG, CI returns "C", etc.),
and the prior workflow only let users discover /language *after*
finishing setup in English.

Tests: ink-testing-library renders the Wizard and confirms the
language step is shown first with both options visible, in EN and
zh-CN. wizard.test.ts → wizard.test.tsx (now contains JSX).
2026-05-08 19:22:17 +08:00
YHH d817f1b965 docs(dashboard): PARITY.md audit — bucket E of #369 (#439)
Closing audit of the #369 split: every slash command tagged with how
the dashboard handles it (panel / chat-box / tui-only).

Findings after C + D:

* ~20 slashes have a dedicated panel or modal — Settings (presets,
  effort, model, /pro, budget gauge, loop control, language), MCP,
  Permissions, Hooks, Skills, Memory, Plans, Sessions, Usage, plus
  the C-bucket pickers (SessionPicker, CheckpointPicker, MCP
  marketplace, plan replay viewer).
* ~38 slashes work as-is via the chat box — short text outputs
  (/help, /keys, /status, /cost, /context, /think, /retry, /compact,
  /update, /doctor, /init, /semantic, …) plus admin / code-mode
  niches (/walk-around, /resource, /prompt, …). No structured-output
  gaps remain after C + D — the long-standing Memory / Permissions /
  Hooks / Skills / Plans / Usage panels already cover every command
  whose payload warranted a dedicated UI.
* Stays TUI-only by design: /exit (no live process to kill from web),
  the raw keyboard shortcuts (Esc / Shift+Tab / Ctrl-L / Ctrl-O / u
  / space).

Bucket A and B turned out empty after the C/D work — no commands
need a chat-box rendering tweak, and no commands need a new
structured-output panel. PARITY.md is the source of truth going
forward; add a row when a new slash lands.

This wraps up #369 — the umbrella issue closes with this PR.
2026-05-08 18:39:40 +08:00
YHH 9ea76a3ef9 feat(dashboard): loop control panel — start / stop / countdown (#433) (#438)
Final stage of #428. Adds a Loop section to SettingsPanel for the
auto-resubmit timer.

Design — two states from one component:

* Idle → 6 quick interval buttons (30s / 1m / 5m / 15m / 1h / 6h) plus
  a custom field with s/m/h unit selector, a multi-line prompt
  textarea, and a Start button. Cost hint reads "each iteration costs
  ~$X.XXXX (last turn)" pulled from /api/overview stats so the user
  knows what an unattended overnight loop will run.
* Running → live countdown ("fires in 1m 24s"), iter counter, the
  prompt verbatim (max 120px scroll for long prompts), and a Stop
  button.

Implementation:

* dashboard/src/lib/loop-control.ts — pure helpers: INTERVAL_PRESETS_MS
  table, parseCustomInterval (s/m/h → ms with 5s..6h clamp),
  formatRemaining (5m 12s / 2h 45m / 0s for races past zero).
* SettingsPanel polls /api/loop/status every 5s; a separate 1s tick
  interpolates the countdown locally between syncs (clamps to 0 if
  the next-fire moment passes between polls).
* Page-reload mid-loop reads /api/loop/status and re-renders the
  running panel from server state — no double-start risk because the
  Start button only renders in idle state.

Wraps up bucket D — all four targeted slashes (/pro, /budget, /model,
/loop) are now panel-driven.
2026-05-08 18:00:17 +08:00
YHH 136ed9ff58 feat(dashboard): editable model picker in settings (#432) (#437)
Fourth stage of #428. Replaces the read-only active-model code line
with a select driven by /api/models, plus an inline pricing line.

* New /api/models GET — returns the cached model catalog
  (string[] | null), the live current model, and the DEEPSEEK_PRICING
  table so the SPA can render input/output USD per 1M tok without a
  second source.
* DashboardContext.getModels callback; App.tsx ref-mirrors useSessionInfo's
  models so the dashboard server (frozen at boot time) sees fresh
  catalog without re-mint.
* SettingsPanel ModelRow component: graceful fallback to the existing
  read-only display when the catalog is null/empty (network failure
  or in-flight). Live model is always selectable, even if the catalog
  hasn't echoed it yet (preset overrides, custom IDs).
* Save flows through the existing D-1 applyModelLive path — same as
  /model <id> slash.

Closes #432
2026-05-08 17:56:18 +08:00
YHH 5dbcd1b73b feat(dashboard): budget gauge + cockpit tile (#431) (#436)
Third stage of #428. Replaces a typed-input form with a state-driven
budget gauge that reads at a glance and turns the common bumps into
single clicks.

Design:

* Off → quick-cap row ($1 / $5 / $10 / $25 / $50) + custom field. No
  number to type for the common case.
* Running (<80%) → spend / cap progress bar + bump suggestions
  (1.5× / 2× / 4× current cap, snapped to a "nice" round number per
  size bucket) + Clear.
* Approaching (≥80%) → amber tone + "loop will refuse past 100%" line
  + bump suggestions promoted to primary buttons.
* Exhausted (≥100%) → red tone + "next turn refused" line + same
  bumps.

Implementation:

* dashboard/src/lib/budget.ts — pure helpers: BudgetState union,
  deriveBudgetState, bumpSuggestions, budgetTone, QUICK_CAPS_USD.
  niceUp() subtracts an FP epsilon before ceil so 0.4 × 1.5 doesn't
  bump 0.6 to 0.7.
* SettingsPanel: BudgetSection consumes derived state and renders
  off / running / warn / exhausted variants. Same gauge shape across
  all three live states (just colour + helper text differ).
* Overview cockpit: budgetKpi reuses deriveBudgetState + budgetTone
  so threshold logic lives in one place.
* /api/settings GET adds sessionSpendUsd from ctx.getStats so the
  panel renders without a second /overview round-trip.
* 12 new unit tests for the derivation and bump rounding.
2026-05-08 17:52:12 +08:00
YHH 447d1d7049 feat(dashboard): compute panel section — /pro one-shot (#430) (#435)
* feat(dashboard): server surface for /pro / /budget / /model / /loop (#429)

First stage of #428 (bucket-D of #369). Server-side plumbing for the
slash-only knobs the web should drive directly: /pro arming, /budget,
/model, and /loop. No SPA UI yet — D-2..D-5 each ship a panel section
against this surface.

* /api/settings GET exposes proNext / budgetUsd / model from live
  loop state alongside the existing persisted fields.
* /api/settings POST validates and routes each new field to the
  matching ctx.*Live callback. budgetUsd accepts null for "off".
* /api/loop/{status,start,stop} (new endpoint) drives the auto-resubmit
  timer the same way the /loop slash does. start enforces 5s..6h range
  and a non-empty prompt.
* DashboardContext gets matching callbacks: applyModelLive,
  setProNextLive, setBudgetUsdLive, getLoopRunStatus, startAutoLoop,
  stopAutoLoop.
* App.tsx wires each callback against existing live methods on
  CacheFirstLoop and the useLoopMode hook. No new state.

/harvest and /branch are deletion-bound features and are deliberately
out of scope here — see #428 follow-up.

Closes #429

* feat(dashboard): compute panel section — /pro one-shot (#430)

Second stage of #428. Adds a Compute section to SettingsPanel for the
/pro one-shot toggle.

* Single-row section under the existing Defaults block: button toggles
  arm / disarm — same path as the slash; auto-disarms after the next
  turn fires.
* Section header lives even with one row so D-4 (model picker) and any
  future compute knobs cluster here naturally.
* i18n: en + zh-CN strings for the section + row + helper note.

/harvest and /branch were originally bundled into this stage but
dropped — both are deletion-bound features.

Closes #430
2026-05-08 17:47:05 +08:00
YHH 042d2c4f6a feat(dashboard): server surface for /pro / /budget / /model / /loop (#429) (#434)
First stage of #428 (bucket-D of #369). Server-side plumbing for the
slash-only knobs the web should drive directly: /pro arming, /budget,
/model, and /loop. No SPA UI yet — D-2..D-5 each ship a panel section
against this surface.

* /api/settings GET exposes proNext / budgetUsd / model from live
  loop state alongside the existing persisted fields.
* /api/settings POST validates and routes each new field to the
  matching ctx.*Live callback. budgetUsd accepts null for "off".
* /api/loop/{status,start,stop} (new endpoint) drives the auto-resubmit
  timer the same way the /loop slash does. start enforces 5s..6h range
  and a non-empty prompt.
* DashboardContext gets matching callbacks: applyModelLive,
  setProNextLive, setBudgetUsdLive, getLoopRunStatus, startAutoLoop,
  stopAutoLoop.
* App.tsx wires each callback against existing live methods on
  CacheFirstLoop and the useLoopMode hook. No new state.

/harvest and /branch are deletion-bound features and are deliberately
out of scope here — see #428 follow-up.

Closes #429
2026-05-08 17:46:31 +08:00
YHH f8143f7098 feat(dashboard): viewer modal kind for /replay (#421) (#427)
Final stage of #416. /replay [N] now broadcasts a read-only viewer
modal to the web dashboard so the plan archive (summary + steps +
markdown body) is visible alongside the existing TUI scrollback card.

* New `viewer` member on the ActiveModal discriminated union — sibling
  to `picker`, but read-only: only `close` flows back through
  /api/modal/resolve. Splitting them keeps the picker schema clean
  rather than carrying empty `actions: []` on every viewer payload.
* useViewerBroadcast helper alongside usePickerBroadcast.
* App.tsx intercepts result.replayPlan, packages a snapshot
  (title with #idx/total · relative time, structured steps with
  done/queued status, markdown body, archive basename as meta), and
  feeds it to the hook. The existing log.showPlan call is unchanged
  so the TUI scrollback card still renders.
* SPA ViewerModal renders the steps as a list (✓ for done, · for
  queued) plus the markdown body and a single Close button.
* Server tests cover the dispatcher: close happy path, rejection of
  non-close actions, 503 when the resolver is not wired.

Wraps up bucket-C of #369. All five originally TUI-only pickers
(/resume, /restore, /mcp browse) plus the read-only /replay viewer
are now drivable from the web with no TUI keyboard required.
2026-05-08 13:33:33 +08:00
YHH 6fcf3a6cba feat(dashboard): wire McpMarketplace through picker protocol (#420) (#426)
* feat(dashboard): picker modal kind for web parity (#417)

First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.

* New `picker` member on the `ActiveModal` discriminated union plus
  `PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
  rename / new / install / uninstall / load-more / refine / cancel.
  `refine` and `load-more` keep the picker open so the TUI's filter
  state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
  rows, action buttons gated on `modal.actions`, and rename / new
  inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
  C-2..C-5 picker components only need the hook to participate.

No picker is migrated yet — that arrives in C-2 (#418).

* feat(dashboard): wire SessionPicker through picker modal protocol (#418)

Second stage of #416. SessionPicker (the simplest existing TUI picker —
no pagination, no async, ~5 actions) now broadcasts modal-up snapshots
to the web dashboard and resolves pick / delete / rename / new / cancel
from /api/modal/resolve.

* SessionPicker.tsx accepts an optional `pickerPorts` prop bundle and
  feeds usePickerBroadcast a snapshot mapped from the existing sessions
  list (id=name, badge=branch, meta=turns/cost).
* App.tsx wires a memoized pickerPorts (broadcast + resolver/snapshot
  refs from C-1) and passes it to the picker mount.
* TUI keystroke handling unchanged — broadcast is purely additive.

Validates the C-1 (#417) protocol foundation against a real picker with
no dashboard-side regressions.

* feat(dashboard): checkpoint picker for /restore (#419)

Third stage of #416. Bare /restore (no name argument) now opens an
interactive CheckpointPicker — covering both the TUI side (the command
was text-only before) and the web dashboard via the picker modal
protocol from C-1.

* New CheckpointPicker.tsx mirrors SessionPicker shape: arrow-key
  navigation, ⏎ to restore, [d] to forget, esc to quit. Rows show
  short id + name + relative age + file count / size.
* /restore handler returns openCheckpointPicker:true when called with
  no argument; /restore <name|id> still resolves directly to keep the
  one-shot path working.
* App.tsx mounts the picker, gates hotkeys behind it, and routes
  outcome → restoreCheckpoint / deleteCheckpoint with a summary line
  on success.
* usePickerBroadcast wires the same modal-up/down + resolvePicker
  pipeline as C-2; web sees pick / delete / cancel actions.

* feat(dashboard): wire McpMarketplace through picker protocol (#420)

Fourth stage of #416. /mcp browse now broadcasts a picker snapshot to
the web dashboard with installed/source-tagged badges, popularity
meta, and the full action set: install / uninstall / refine /
load-more / cancel.

* installOrToggle split into doInstall + doUninstall so the web's
  explicit `install` / `uninstall` actions don't accidentally toggle
  on the wrong button (TUI Enter still toggles for keyboard
  ergonomics).
* Snapshot builder extracted to a pure
  `buildMarketplacePickerSnapshot` so the entry-to-item mapping can
  be unit-tested without mounting Ink + the registry network call.
* refine and load-more keep the picker open (per C-1 design); cancel
  closes it via the existing onClose hook.
* hasMore wired from `state.handle.cache.pagination.nextCursor` so
  the dashboard's "Load more" button only shows when more pages exist.
* McpHub forwards pickerPorts from App.tsx to the marketplace tab;
  the live tab is unchanged.
2026-05-08 13:19:39 +08:00
YHH 1934e2598c feat(dashboard): checkpoint picker for /restore (#419) (#425)
* feat(dashboard): picker modal kind for web parity (#417)

First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.

* New `picker` member on the `ActiveModal` discriminated union plus
  `PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
  rename / new / install / uninstall / load-more / refine / cancel.
  `refine` and `load-more` keep the picker open so the TUI's filter
  state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
  rows, action buttons gated on `modal.actions`, and rename / new
  inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
  C-2..C-5 picker components only need the hook to participate.

No picker is migrated yet — that arrives in C-2 (#418).

* feat(dashboard): wire SessionPicker through picker modal protocol (#418)

Second stage of #416. SessionPicker (the simplest existing TUI picker —
no pagination, no async, ~5 actions) now broadcasts modal-up snapshots
to the web dashboard and resolves pick / delete / rename / new / cancel
from /api/modal/resolve.

* SessionPicker.tsx accepts an optional `pickerPorts` prop bundle and
  feeds usePickerBroadcast a snapshot mapped from the existing sessions
  list (id=name, badge=branch, meta=turns/cost).
* App.tsx wires a memoized pickerPorts (broadcast + resolver/snapshot
  refs from C-1) and passes it to the picker mount.
* TUI keystroke handling unchanged — broadcast is purely additive.

Validates the C-1 (#417) protocol foundation against a real picker with
no dashboard-side regressions.

* feat(dashboard): checkpoint picker for /restore (#419)

Third stage of #416. Bare /restore (no name argument) now opens an
interactive CheckpointPicker — covering both the TUI side (the command
was text-only before) and the web dashboard via the picker modal
protocol from C-1.

* New CheckpointPicker.tsx mirrors SessionPicker shape: arrow-key
  navigation, ⏎ to restore, [d] to forget, esc to quit. Rows show
  short id + name + relative age + file count / size.
* /restore handler returns openCheckpointPicker:true when called with
  no argument; /restore <name|id> still resolves directly to keep the
  one-shot path working.
* App.tsx mounts the picker, gates hotkeys behind it, and routes
  outcome → restoreCheckpoint / deleteCheckpoint with a summary line
  on success.
* usePickerBroadcast wires the same modal-up/down + resolvePicker
  pipeline as C-2; web sees pick / delete / cancel actions.
2026-05-08 13:19:12 +08:00
YHH 03804e6170 feat(dashboard): wire SessionPicker through picker modal protocol (#418) (#423)
* feat(dashboard): picker modal kind for web parity (#417)

First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.

* New `picker` member on the `ActiveModal` discriminated union plus
  `PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
  rename / new / install / uninstall / load-more / refine / cancel.
  `refine` and `load-more` keep the picker open so the TUI's filter
  state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
  rows, action buttons gated on `modal.actions`, and rename / new
  inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
  C-2..C-5 picker components only need the hook to participate.

No picker is migrated yet — that arrives in C-2 (#418).

* feat(dashboard): wire SessionPicker through picker modal protocol (#418)

Second stage of #416. SessionPicker (the simplest existing TUI picker —
no pagination, no async, ~5 actions) now broadcasts modal-up snapshots
to the web dashboard and resolves pick / delete / rename / new / cancel
from /api/modal/resolve.

* SessionPicker.tsx accepts an optional `pickerPorts` prop bundle and
  feeds usePickerBroadcast a snapshot mapped from the existing sessions
  list (id=name, badge=branch, meta=turns/cost).
* App.tsx wires a memoized pickerPorts (broadcast + resolver/snapshot
  refs from C-1) and passes it to the picker mount.
* TUI keystroke handling unchanged — broadcast is purely additive.

Validates the C-1 (#417) protocol foundation against a real picker with
no dashboard-side regressions.
2026-05-08 13:18:46 +08:00
YHH b3f0aee657 feat(dashboard): picker modal kind for web parity (#417) (#422)
First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.

* New `picker` member on the `ActiveModal` discriminated union plus
  `PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
  rename / new / install / uninstall / load-more / refine / cancel.
  `refine` and `load-more` keep the picker open so the TUI's filter
  state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
  rows, action buttons gated on `modal.actions`, and rename / new
  inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
  C-2..C-5 picker components only need the hook to participate.

No picker is migrated yet — that arrives in C-2 (#418).
2026-05-08 13:17:58 +08:00
YHH 1ffa27975c docs(issues): split off display/rendering template, collect terminal host (#412) (#413)
Flicker reports keep landing without the one piece of info that
discriminates the bug — the terminal host (VSCode/Cursor xterm.js vs
standalone Windows Terminal / iTerm2 / etc.). The shell field on the
generic bug template was the wrong axis. New template asks for host +
version, env vars (TERM_PROGRAM/VSCODE_INJECTION/WT_SESSION), and ships
copy-paste diagnostic snippets so users do not have to know how to
introspect their own terminal.
2026-05-08 10:18:01 +08:00
YHH d63509ad85 refactor(ui): quiet chat-screen chrome (#411)
Two stacked rules + five-segment status row + per-card breathing room
made history scroll read as scattered fragments. Tighten three things:

- Settled cards drop the marginTop the active form keeps, so scrollback
  collapses to flat lines instead of one blank between every card.
- ModeStatusBar drops its dashed rule; StatusRow's solid rule already
  separates the chat from bottom chrome.
- StatusRow drops session-cost + wallet segments (StatsPanel and
  UsageCard already surface those); only turn cost + cache stay.
- Settled CardHeader filters faint string meta (1.2KB / 2.34s / exit N
  on OK cards) and drops the right slot so spinners don't linger in
  scrollback. Colored badges (rejected, retry) still render.

ui-status-row-balance reduced to the cells StatusRow now renders;
wallet/session currency coverage stays in ui-stats-panel-currency
and ui-usage-card-balance.
2026-05-08 09:45:50 +08:00
YHH 459a370b7c docs(readme): canonical install + subcommand cheatsheet (#408) (#409)
The Install block dropped readers at `npx reasonix code` with no
mention of the global-install path, and the README never named the
five subcommands a new user actually has to choose from. The website
already has a CLI panel but the section had no anchor, so the README
couldn't link to it.

- Name `npx` as the recommended path; point users at `reasonix update`
  if they want the global install.
- Add a five-row cheatsheet (code / chat / run / doctor / update) so
  newcomers don't have to guess. Defer the long tail (replay / diff /
  events / stats / index / mcp / prune-sessions) to `--help` and the
  CLI panel on the website.
- Mirror in zh-CN.
- Add `id="cli"` to the website's CLI section so the README link
  resolves.
2026-05-08 09:11:08 +08:00
Wesley Viana 39e69c2cab chore: improve loop.ts tests (#271)
* chore: improve loop.ts tests

* undo uncessary - change

* drive auto-escalation tests through step() instead of private-field access
2026-05-08 08:52:55 +08:00
ctharveyandCharles H 0d89ab84ef test(mcp): cover startup summary states (#396)
Co-authored-by: Charles H <[email protected]>
2026-05-08 08:43:47 +08:00
YHH ecb1bfb051 fix(prompt): inline short single-line pastes verbatim (#397) (#406)
Bracketed-paste content was always converted to a `[paste #N · …]`
sentinel chip, even when the user pasted a single word or a number.
That made the composer feel hostile to common one-shot paste usage —
copying an identifier or a URL out of another window and dropping it
mid-sentence shouldn't leave a chip in the buffer.

Inline the content verbatim when it has no newline AND fits under
INLINE_PASTE_THRESHOLD (200 chars); fall back to the sentinel chip
for anything longer or multi-line. The model still receives the full
paste text either way — this is display-only.
2026-05-08 08:40:34 +08:00
YHH db2ca97eb0 fix(permissions): match Windows project keys case-insensitively (#402) (#405)
projects[] is keyed by absolute rootDir, so on Windows two sessions
that resolve the same physical directory to different drive-letter or
component casing (PowerShell's `F:\Reasonix` vs bash/MINGW's
`f:\reasonix`) miss the persisted "always allow" entry from the prior
session and re-prompt every turn.

Add findProjectKey() that prefers the exact match and, on win32,
falls back to a case-insensitive scan. Use it in load / add / remove
/ clear so any-cased rootDir consolidates onto the existing key
instead of forking a duplicate. Non-Windows lookups remain
case-sensitive — Linux paths really are.
2026-05-08 08:40:15 +08:00
YHH 47f207119f fix(ui): refresh model badge on dashboard preset change and /pro turns (#403) (#404)
Two paths bypassed the cards' model snapshot:
- Dashboard preset change (POST /settings → applyPresetLive) reconfigured
  the loop but never dispatched session.model.change, so subsequent
  reasoning/streaming cards still rendered the old model badge.
- /pro consumed a single-turn escalation without telling the cards, so
  the armed turn ran on v4-pro but the badge stayed on the base model.

applyPresetLive now dispatches session.model.change. reasoning.start /
streaming.start carry an optional model id; the loop's currentCallModel
getter feeds it through TurnTranslator.flushBuffers so the badge tracks
the model that actually produced the output.
2026-05-08 08:39:51 +08:00
ctharveyandCharles H 6ccca2be0b fix(search): honor abort during recursive fs scans (#400)
Co-authored-by: Charles H <[email protected]>
2026-05-08 08:14:54 +08:00
YHH f422a94dfa chore(release): 0.30.5 (#395)
Three contributor-led follow-ups: storm guard exempts safe inspector
reads (#388 by @ctharvey), wait_for_job replaces polling loops with
one blocking call (#390 by @ctharvey), and /skill new finally
provides the missing scaffold for user skills (#394).
2026-05-08 00:51:13 +08:00
YHH ee5961fe70 feat(skills): /skill new scaffolds a stub + README walkthrough (#394)
* feat(skills): /skill new scaffolds a stub + README walkthrough (#366)

User feedback: wanted to install a frontend-writing skill, "no
discoverable entry point". The /skill list empty state told users
WHERE skills live but not HOW to author one — and there's no remote
registry to install from.

Adds the missing creation step:

- /skill new <name>          → writes <project>/.reasonix/skills/<name>.md
- /skill new <name> --global → writes ~/.reasonix/skills/<name>.md

The stub carries the minimal frontmatter (name + description) plus
a comment block listing the optional knobs (runAs, allowed-tools,
model). Refuses to overwrite existing files; rejects invalid names
via the existing isValidSkillName regex.

Empty /skill list now surfaces the new scaffold + an explicit "no
remote registry yet" line so users don't keep hunting for a
marketplace that doesn't exist. Catalog + README in EN + zh-CN
gain the "author your first skill" path. The /skill list footer
mentions /skill new alongside show / run.

* fix(skills): atomic create with wx flag — close TOCTOU race CodeQL flagged

CodeQL flagged the existsSync→writeFileSync sequence as a potential
file-system race. Switch to writeFileSync with `flag: "wx"` so the
existence check IS the atomic write — if a parallel process landed
the file between our check and write, EEXIST surfaces and we report
the conflict instead of silently overwriting.

Keep the folder-form pre-check for a cleaner error message when the
collision is on the dir-style skill (`<name>/SKILL.md`).
2026-05-08 00:31:22 +08:00
ctharveyandCharles H 15b4060e68 feat(jobs): add wait_for_job tool for background jobs (#390)
Co-authored-by: Charles H <[email protected]>
2026-05-08 00:10:09 +08:00
ctharveyandCharles H 9ec5b99e07 feat(storm): add stormExempt flag to exempt obvious reads from the loop guard (#388)
Co-authored-by: Charles H <[email protected]>
2026-05-08 00:09:21 +08:00
YHH e93c4ffde3 chore(release): 0.30.4 (#392)
Sweep of the 0.30.2 / 0.30.3 launch-day bug + onboarding queue:
resume now restores cache+context+cost (#364), model pill follows
/model + /preset switches (#372), bare /model opens an interactive
picker (#371), three more Shift+Tab encodings for PowerShell /
modifyOtherKeys / Kitty (#373), defensive stdin drain on exit kills
the fish/bash escape-leak (#365), and --dir / pinned workspace get
surfaced in the welcome banner, /status, sandbox errors, and the
README (#370).
2026-05-08 00:04:33 +08:00
YHH 0e4cba3670 fix(tty): drain pending feature-detection replies on exit (#365) (#391)
Reporter saw `^[]11;rgb:...^[\^[[33;1R^[[?62;1;4c` printed by fish /
bash right after exiting reasonix. Those bytes are RESPONSES — OSC 11
bg-color, CPR cursor-position, DA1 device-attributes — sent by the
terminal in reply to queries the runtime / a dep emitted during
session startup. The dist bundle has none of those query bytes
itself, so the source is bun's tty feature-detection path or a
transitive dep doing color-scheme detection.

Whoever sent them, the responses sat in stdin's queue until reasonix
exited. The parent shell then read them and rendered the bytes as
input.

Add `drainTtyResponses(50ms)` and call it in chat.tsx's exit finally,
after `runtime.closeAll()`. Best-effort: sets raw mode, reads-and-
discards anything still queued for 50ms, restores cooked. No-op when
stdin isn't a TTY or raw mode isn't available.

0.30.3's alt-screen default is the upstream mitigation (DECSET 1049
flushes the input queue on most terminals); this is the program-side
mitigation that's independent of which terminal the user is in.
2026-05-07 23:53:35 +08:00
YHH d0b251d43a feat(ui): surface --dir / pinned workspace for first-time users (#370) (#389)
User feedback (multiple data points): beginners hit the default
cwd-scoped behavior and conclude Reasonix can't read folders other
than where they launched it. The capability already exists via
`reasonix code --dir <path>`, but nothing in the UI tells you so
until you read --help.

Three onboarding surfaces now make it discoverable:

- WelcomeBanner shows a "▸ workspace · /path  (relaunch with --dir
  <path> to switch)" line in code mode. Visible only on the empty
  state, so it doesn't survive past the first turn.

- `/status` includes a workspace line:
    workspace /path · pinned at launch (relaunch with --dir <path>
    to switch)

- The filesystem sandbox-escape error now points the user at --dir
  instead of just dropping a raw "path escapes sandbox root":
    path escapes sandbox root (X): Y — workspace is pinned at
    launch; quit and relaunch with `reasonix code --dir <path>` to
    work in a different folder

Plus a Getting Started callout in both READMEs explaining --dir and
why mid-session switching isn't a thing (message log + memory paths
get tangled with stale roots, so the design pins at launch).

No new slash command, no /cwd. The agent's system prompt already
says mid-session switching was removed by design.
2026-05-07 23:37:39 +08:00
YHH daebf3d571 feat(ui): /model with no arg opens an interactive picker (#371) (#387)
`/model <id>` required typing the model id by hand and `/models` was
a separate read-only listing. New users had no obvious way to switch
without prior knowledge of the catalog.

Bare `/model` now opens a modal picker that mirrors SessionPicker's
shape: arrow-key list, ⏎ confirm, [r] refresh the API catalog, esc
cancel, current model marked. The list seeds from the live DeepSeek
catalog (`useSessionInfo` already fetches it on mount); when the
catalog hasn't loaded yet the picker falls back to the four known
DeepSeek ids so it's never empty on first open. The current model
is always included even when the API didn't return it.

Confirming a row routes through `loop.configure({ model })` AND the
`session.model.change` event added in #372 — so the badge on the
NEXT card pill reflects the new selection.

`/model <id>` typed entry continues to work for power users.
2026-05-07 22:54:33 +08:00
YHH 28119cad01 fix(input): recognize PowerShell / modifyOtherKeys / Kitty Shift+Tab variants (#373) (#386)
Recognized only the bare xterm `\x1b[Z` back-tab. PowerShell 7.x on
some Windows hosts emits the modifier-encoded `\x1b[1;2Z`; modern
Windows Terminal in modifyOtherKeys mode (which we enable on
startup) emits `\x1b[27;2;9~`; the Kitty keyboard envelope is
`\x1b[9;2u`. None of these matched, so the edit-mode cycle was
silently dropped on PowerShell.

Add all three variants to `stdin-reader.ts` CSI_TAIL_MAP and to the
Ink-fallback `key-normalize.ts` recovery table. `/mode` slash command
remains as a typed fallback for any future terminal that emits a
form we haven't seen yet.
2026-05-07 07:10:06 -07:00
YHH 3c24c0f1e1 fix(ui): /model + /preset update active model so the next card pill is fresh (#372) (#385)
`state.session.model` was set once in `initialState()` and never
mutated. `/model <id>` and `/preset {auto,flash,pro}` only routed
through `loop.configure({ model })`, never into the agent store —
so the next `streaming.start` / `reasoning.start` / "thinking · X"
card snapshotted the launch-time model id, even when the model that
actually answered the turn was different.

Add a typed `session.model.change` event the model handlers dispatch
through `ctx.dispatch`. Reducer mutates `state.session.model` (with
referential identity preserved when the id is unchanged) and the
existing snapshot logic in `makeReasoningCard` / `makeStreamingCard`
picks up the new value automatically. Cards already opened keep
their captured model — that snapshot is intentional so mid-turn
escalation doesn't relabel completed reasoning.
2026-05-07 07:04:04 -07:00
YHH 7edcb07465 fix(stats): persist cache totals + lastPromptTokens across resume (#364) (#384)
`SessionMeta` only carried `totalCostUsd` and `turnCount`, so on every
resume `/status` showed:

- 0 context — `lastPromptTokens` came from `turns[0]?.usage`, and
  `turns` is empty before the first live turn fires
- 0% cache hit — `aggregateCacheHitRatio` summed `turns[]` only

The next API call would still read the cached prefix and answer
correctly (turn 1 in the user's log shows 366,976 / 367,085 cache
hits), but the panel reported "no context" until that call landed.

Persist the missing fields after each turn (`patchSessionMeta`) and
seed them on resume (`stats.seedCarryover`). `aggregateCacheHitRatio`
and `summary().lastPromptTokens` now fall through to the carryover
when no live turn has run yet.
2026-05-07 06:46:18 -07:00
YHH 04b12e9f2d chore(release): 0.30.3 (#382)
Ink 7 + React 19 chat scroll rewrite (#380), configurable web_search
backend with SearXNG (#338), MCP filesystem sandbox preflight + wizard
mkdir confirm (#362, PR #379), README URL fix (#375), bug template
update (#378).
2026-05-07 06:29:05 -07:00
YHH b07b86ee2f feat(ui): row-precision virtual scroll on Ink 7 + React 19 (#380)
* feat(ui): row-precision virtual scroll on Ink 7 + React 19

Bump ink 5.2→7.0.2 + react 18.3→19.2; drop react-reconciler/yoga-layout.
Retire src/renderer/ (cell-diff + ink-compat shim) — Ink 7 ships native
equivalents for every motivation: alternateScreen, useAnimation,
useWindowSize, useBoxMetrics, synchronized output, incrementalRendering.

Default to alt-screen so the resize-ghost / scroll-yank class of bugs
disappears. `--no-alt-screen` opts back into scrollback for users who
need chat output preserved in shell history on exit.

Row-precision virtual scroll with reading mode: scrolling away from
bottom hides PromptInput and replaces it with a "📖 reading history —
End / PgDn to return" indicator. PgUp/PgDn/End owned by App; ↑/↓ on
an empty buffer hand off to chat scroll via PromptInput; App takes ↑/↓
directly when busy or in reading mode (PromptInput can't process them).
Wheel events translate to ↑/↓ in raw mode, so the same paths cover wheel.
Ctrl+P/N keeps the prompt-history binding (wheel-immune).

Drop <Static> — incompatible with alt-screen (no scrollback to shelter
committed cards across resize-reflow). React.memo on CardRenderer plus
the reducer's reference-stable card array skips reconciler cost on
unchanged cards. CardStream renders all cards inside an overflow:hidden
Box; inner Box's marginTop=-scrollRows shifts content; useBoxMetrics
reports inner/outer heights so App can clamp scroll bounds.

CardStream.isSettled covers task / plan / subagent kinds. PromptInput's
useReserveRows quantizes to 4-row buckets so per-keystroke layout doesn't
churn. TickerProvider migrated to Ink 7's useAnimation. Modal-open
condition collapsed from 14 OR'd checks into one reused boolean.

Migrate inline tests (markdown, plan-confirm) off the cell-diff renderer
to ink-testing-library. Remove dead alt-screen.ts; strip stale comments
referencing removed scrollback-mode workarounds.

* test(ui): provide fake stdin for Ink 7 raw-mode check in CI

Ink 7 calls setRawMode on stdin during render(); CI's process.stdin
isn't a TTY so it throws "Raw mode is not supported". Pass a minimal
EventEmitter-based fake stdin (setRawMode no-op, isTTY=true) alongside
the existing fake stdout. Affects four tests that import render directly
from ink for in-process render-and-assert: ui-session-picker-currency,
ui-stats-panel-currency, ui-usage-card-balance, ui-status-row-balance.

* test(ui): extract makeFakeStdin/Stdout to shared tests/helpers/ink-stdio
2026-05-07 06:14:37 -07:00
dacec354 7ba3d086ff chore(issue-template): add shell/terminal fields, update model examples (#378) 2026-05-07 05:33:20 -07:00
YHH 1a7d74f3f0 fix(mcp): preflight filesystem sandbox dir + offer mkdir in wizard (#362) (#379)
The official @modelcontextprotocol/server-filesystem refuses to start
when its sandbox directory is missing and prints a raw Node stack
trace, leaving the user without an actionable next step.

- preflightStdioSpec validates every positional path arg before
  spawn and throws a one-line error: "create it with: mkdir -p '<path>'"
- The first-run / reconfigure wizard now stat()s the directory the
  user typed for filesystem MCP and offers Y/Enter to mkdir -p,
  N/Esc to enter a different path.
2026-05-07 05:31:09 -07:00
dacec354 0f7dcd026a fix(readme): correct website URLs — /reasonix/ → /DeepSeek-Reasonix/ (#375) 2026-05-07 04:43:08 -07:00
dacec354 12998d246d feat(web): configurable web_search backend with SearXNG support (#338)
Adds SearXNG as an alternative web_search engine, switchable via /search-engine slash command or ~/.reasonix/config.json. Mojeek stays the default — zero risk for existing users.
2026-05-07 02:02:06 -07:00
YHH 43d437fd38 chore(release): 0.30.2 (#361) 2026-05-06 23:06:55 -07:00
YHH 62813e3d6d fix(dashboard): cost displays follow wallet currency, not hardcoded USD (#360)
CLI shows session cost in the wallet's currency (¥ for CNY wallets,
$ for USD), but the dashboard always used `fmtUsd()` which prints
the raw stored USD with a `$`. CNY users saw `$0.5190` in the
dashboard for the same session that read `¥0.024` in the CLI — both
the symbol AND the magnitude diverged because no conversion happened.

- New `fmtCost(usd, currency, fractionDigits?)` helper in
  `dashboard/src/lib/format.ts`. Mirrors the CLI's `formatCost()` —
  CNY converts via `USD_TO_CNY = 7.2`, USD passes through, undefined
  defaults to CNY.
- `overview.ts` current-session cost + cost-trend day average now
  thread `c.balance?.currency` into `fmtCost()`.
- `chat.ts` SideRail cost / budget rows and ChatStatusBar
  turn / session cost rows pull currency from `stats.balance[0]`.
- Existing `fmtUsd()` kept as-is for places where USD is intentional
  (Claude-equivalent comparisons in usage.ts) — those stay USD because
  Claude's API is USD-priced regardless of the user's wallet.
2026-05-06 23:00:56 -07:00
YHH a29a0ac157 feat(ui): ctrl-o expands the live streaming card to full tail (#335, #337) (#359)
Pain point @dacec354 raised twice: while the model writes a long plan
or todo list, the streaming card only shows the last 4 lines, so the
content scrolls past before you can read it. And once a long reply
settles, you may want to fold it back down — but `<Static>` already
flushed the bytes to scrollback so that half can't be unwound.

This collapses both requests into one keystroke: `ctrl-o` toggles
"expanded" mode on the live streaming card. Expanded shows the last
60 visual lines (capped so the card can't swallow the whole viewport)
plus a `⋯ N earlier lines above` hint when content overflows.
Collapses back to the 4-line preview. Auto-resets to collapsed at the
end of every turn so each new reply starts compact.

The same `(LIVE)` constraint covers #337's fold-toggle ask: only
not-yet-committed cards are addressable. Settled cards live in Ink's
`<Static>` which writes terminal scrollback once, no take-backs.

The `expanded ⌃o` / `preview ⌃o` pill in the card header advertises
the keybind so users discover it without reading docs.
2026-05-06 22:48:35 -07:00
YHH ccdbfb3a28 fix(ui): reasoning spinner survived reasoning.end when a later card existed (#358)
`splitCardStream` only treated the LAST card as live; everything before
it was committed to Ink's `<Static>`. When the model streamed reasoning
THEN content (or kicked off a tool card), the reasoning card was
no longer last — so it got frozen into `<Static>` while still
`streaming: true`. `reasoning.end` later set `streaming: false` on
the cards array, but `<Static>` doesn't re-render frozen items, so the
"reasoning…" header kept its spinner indefinitely.

Fix: live-vs-committed split now scans for the FIRST unsettled card
and keeps everything from there onward in the live tree. Cards only
move into `<Static>` once they're settled AND every earlier card is
too — preserving the in-order append contract `<Static>` requires.

`suppressLive` semantic preserved: still hides the trailing live card
when the modal owns the screen.

Two new regression tests cover the reasoning + streaming case (must
stay live) and the all-settled case (must commit in order).
2026-05-06 22:33:06 -07:00
YHH 1805b0c647 fix(ui): SessionPicker honors wallet currency instead of hardcoded ¥ (#312) (#357)
Same bug shape as the StatusRow / UsageCard / StatsPanel set that #272
already fixed — `SessionPicker` was still doing
`¥${totalCostUsd * USD_TO_CNY}` so USD-wallet users saw ¥-formatted
costs in the session list.

- `SessionMeta` gains `balanceCurrency?: string`. App.tsx writes the
  live wallet currency alongside `totalCostUsd` on each turn save, so
  every persisted session knows what currency its cost is denominated
  in.
- `SessionPicker` accepts a `walletCurrency` prop and falls back to
  each row's `meta.balanceCurrency`. Prop wins (live value > stored).
  In-app picker (`/sessions`) gets the live ref from App; pre-mount
  picker in `chat.tsx` doesn't have a balance fetched yet, so it
  relies on the stored per-session value.
- Cost rendering routes through the shared `formatCost()` helper that
  the rest of the cost UI already uses.
- Regression test asserts USD wallet → `$0.05`, CNY wallet → `¥0.36`,
  no-prop + stored-USD → `$0.05`, neither → unchanged `¥0.36`.
2026-05-06 22:22:11 -07:00
YHH 4032930fed feat(ui): live tokens/s on streaming reply + space pauses 5s undo (#334, #337) (#356)
- StreamingCard renders a `42 t/s` pill in the live header and a
  `1.2k tok · 42 t/s` summary on the settled card. Computed via the
  bundled DeepSeek tokenizer; gated below 4 tokens / 500 ms so the
  pill never shows obviously-bogus rates while the first chunk lands.
  Re-renders piggyback on the slow tick so the rate keeps updating
  even when chunks stall briefly.
- The auto-mode undo banner now accepts a `space` keystroke to pause
  the 5-second countdown indefinitely. While paused the bar freezes
  at the captured fraction, the badge swaps to "Ns · paused", and
  pressing space again resumes from where it stopped. The hint row
  on edit-mode entry mentions both `u` and `space`.

The `u` and `space` keybinds share the same modal-and-prompt-empty
gating, so neither steals input while the user is typing.
2026-05-06 22:08:19 -07:00
YHH b03e11bf41 chore(release): 0.30.1 (#355) 2026-05-06 21:15:07 -07:00
ctharveyandCharles H 0b91250c44 fix(ui): suppress live card redraw while picker modal is open (#353)
Co-authored-by: Charles H <[email protected]>
2026-05-06 21:09:55 -07:00
YHH 5bcc3b6389 fix(renderer): drop cell-diff aliasing, run prod on real Ink (#346) (#354)
Aliasing `from "ink"` → ink-compat in the CLI bundle made every
TUI bug invisible to `npx tsx` repros and forced cell-diff regressions
onto users only. Issue #346 (ShellConfirm ghost rendering) was a pure
cell-diff bug; the cleanest fix is to remove the alias and let
production take real Ink the same way source mode does.

- tsup: drop the `ink` alias and `noExternal` for ink/ink-text-input;
  bundle keeps `from "ink"` external
- package.json: ink + ink-text-input move to runtime dependencies
- markdown-view: switch the only `inkCompat.*` namespace user back to
  `import { Box, Text } from "ink"`
- bundle-smoke: invert the alias assertion to expect ink stays external

useCursor() in PromptInput keeps its cell-diff import; without a
CursorContext provider it no-ops, so it's harmless under real Ink.
2026-05-06 21:01:59 -07:00
YHH 0f7f7c24c2 docs(benchmarks): real-world cache-hit case study (#351)
Anonymized DeepSeek dashboard from a real Reasonix user
(2026-05-01, used with permission): 435M input tokens, 99.82%
cache hit, ~$12/day on v4-flash vs ~$61 the same workload would
cost without the cache.

Lives at benchmarks/real-world-cache/ alongside an explanation of
the four mechanisms (ImmutablePrefix + AppendOnlyLog +
VolatileScratch + auto-compact) that produce the hit rate. README
gets a NOTE callout pointing at it — answers the recurring "isn't
this just DeepSeek's prefix cache?" pushback with concrete numbers
instead of a re-derived napkin.
2026-05-06 18:54:57 -07:00
YHH 6379bc0628 chore(release): 0.30.0 (#349) 2026-05-06 18:06:28 -07:00
YHH 82c5627123 fix(renderer): use CHA absolute for column moves in cell-diff (#346) (#348)
Switch the X-axis branch of `moveTo()` from CUF (relative cursor right,
`\x1b[NC`) to CHA (absolute column, `\x1b[N+1G`). Y-axis stays on
CUU/CUD since we don't track absolute terminal rows.

Relative column moves accumulate drift across frames: if any earlier
write miscounted cell width — wide-char disagreement (`▸` U+25B8 in
"narrow" fonts that render 2-cell), `▎` ambiguous-width on terminals
that font-detect East Asian width, OSC8 hyperlinks parsed as visible
chars, etc. — the cursor's actual column desyncs from what the
renderer thinks. The next CUF lands at the wrong column, ghost-rows
get written into hint lines, and the modal "shifts" as users navigate
(symptom in #346 issue screenshots).

Anthropic's Claude Code TUI hit the same class of bug
(anthropics/claude-code#14208) and the fix was the same: prefer CHA
over CUF/CUB so column targeting is immune to per-cell width
miscounts. Fix is invisible on terminals where our width math was
already correct; on terminals where it wasn't, no more accumulating
drift.
2026-05-06 18:02:08 -07:00
YHH e991644416 feat(slash): first-class command aliases (#332) (#347)
Add `aliases?: readonly string[]` to SlashCommandSpec so /quit + /q
resolve to /exit, /? to /help, /reset to /new, /lang to /language —
all from a single declaration on the spec instead of ad-hoc handler
mirrors scattered across handlers/basic.ts + handlers/language.ts.

dispatch, suggestSlashCommands and detectSlashArgContext all route
through one resolveSlashAlias() built from SLASH_COMMANDS at module
init. Suggestion rows surface aliases dimly (` · /quit /q`) so they
stay discoverable without polluting the autocomplete list with
duplicates. Dashboard /api/slash response now exposes the field too.
2026-05-06 18:01:54 -07:00
YHH 39dbe19bcd chore(release): 0.29.1 (#345) 2026-05-06 17:07:23 -07:00
YHH c1e8a933d3 fix(markdown): row-group the table fallback layout (#340) (#344)
When a markdown table is too wide for the viewport, FallbackTable
flattens it into key/value lines. The previous implementation
iterated headers first, then rows-within-each-header — so a 3×N
table came out as N "Component:" lines, then N "What:" lines,
then N "Manual TCs:" lines. The user couldn't tell which value
belonged to which row.

Reproduction (issue #340): a planning table for 9 components
rendered as 9 grouped Component lines, 9 grouped What lines,
9 grouped Manual TCs lines — visually a list, not a table.

Swap loop order: iterate rows first, then write all columns
inside each row block, separated by a blank row between rows.
Output now reads top-to-bottom as one logical row at a time.
2026-05-06 16:55:20 -07:00
YHH b401913910 fix(plan): show plan body in PlanConfirm modal (#336) (#343)
When the model called submit_plan with a markdown body but no
structured steps, the Approve plan modal showed only the
warning banner + the choice list — the actual plan content
was hidden behind the collapsed tool-call card in scrollback.
Users had no way to see what they were approving without
hunting up through the transcript.

- Render the plan body via MarkdownView when no steps are
  supplied. Steps still take precedence when present (they
  are the canonical structured view).
- Cap inline preview at 24 lines; surface "… N more lines
  above in scrollback" when the body exceeds that. Reserve
  budget grows with whichever body section is being shown.

Tests cover the three branches: body-only, steps-present,
and truncated-body-with-overflow-hint.
2026-05-06 16:44:59 -07:00
YHH 5662b57a4b fix(stats): carry session cost / turn count across resume (#333) (#342)
The TUI's session-cost figure ($X session) reset to $0 on every
resume because SessionStats was rebuilt empty even when the disk
meta still held the cumulative totalCostUsd from prior runs.

Reproduction (issue #333): hello → exit → resume → expense
accumulator displays 0 instead of the prior session total.

The persistence path was already correct — App.tsx writes
`{ totalCostUsd, turnCount }` into the session meta after every
turn. Only the read-back was missing.

- SessionStats gains a `seedCarryover()` once-at-construction hook
  that adds prior totals to the in-memory totalCost / summary.turns
  without polluting the live `turns[]` array (which intentionally
  holds only this run's per-turn records).
- CacheFirstLoop now calls `loadSessionMeta()` on resume and seeds
  the carryover when prior messages exist. Fresh sessions are
  unaffected — undefined meta fields short-circuit the seed.

Tests cover the carryover math (telemetry.test.ts) and the
end-to-end loop wiring (session.test.ts).
2026-05-06 16:38:13 -07:00
YHH e40e1911cc fix: issue #330 — markdown osc8 garbage + cell-diff shrink-row leak (#341)
* fix(markdown): stop linkifying "e.g" / "i.e" / drop OSC 8 garbage (#330)

Two coupled bugs in the markdown file-ref linkifier:

1. FILE_REF_RE matched English abbreviations because the extension
   class was `{1,6}` — `e.g`, `i.e`, `a.m` all qualified.
2. `osc8()` baked OSC 8 escape bytes (\x1b]8;;...\x07) into Text
   content. The cell-diff renderer's wrapLine strips zero-width chars
   (ESC, BEL) but keeps the printable body, so terminals received
   plain `]8;;file://e.ge.g]8;;` characters — visible garbage on
   any terminal, with no working hyperlink anywhere.

The fix:

- Tighten FILE_REF_RE post-match: require either path-shape (slash),
  line-number suffix, or extension >= 2 chars. `src/foo.ts`,
  `package.json`, `util.c:42` still match; bare `util.c` no longer
  does (acceptable — rare in prose).
- Strip the OSC 8 escape from `osc8()` — keep color + underline
  styling so file refs stand out, but do not emit hyperlink bytes.
  The renderer would need per-span hyperlink propagation through
  nested HostText flattening to support real OSC 8; that's a
  separate refactor. Until then, no link beats broken link.
- Plumb a `hyperlink` prop on ink-compat Text so the future
  per-span fix has a place to land.

Regression test mounts Markdown through the reconciler and asserts
the byte stream never contains `]8;;` for `e.g` / `i.e` samples.

* fix(renderer): trail-clear shrunk rows in cell-diff (#330)

Defensive against terminal-state desync. The cell-diff renderer
skips cells where prev and next are byte-equal — including the
trailing EMPTY cells of a row that shrank. If the terminal's
actual state diverged from prev (e.g. a stray ESC body slipped
through earlier rendering), those skipped trailing cells retain
stale chars from prior frames.

This was the second half of issue #330: with the markdown OSC 8
garbage previously sourcing the desync, the option-list modal
rendered "allow always" + "mand, ask again next time" leftover
on rows that originally held a longer hint.

- New `clearToEOL` patch type → serializes to `\x1b[K`
- After diffEach, sweep rows: if next's row ends earlier than
  prev's content extent, emit clearToEOL past the last visible
  cell. Bounded — at most one clearToEOL per row that shrank.
- Two regression tests cover the modal-shrink case and verify
  no clearToEOL is emitted for same-width swaps.
2026-05-06 16:32:00 -07:00
YHH fdea3bb837 fix(dashboard): wire up filter chips + mark static indicators (#331)
The .chip-f class has cursor:pointer + a hover style, so every chip
looked clickable. In skills, plans, and hooks the chips were laid out
as filter buttons (one hardcoded "active") but had no onClick — clicks
did nothing. Other panels reused chip-f for non-interactive count
indicators, which had the same misleading hover affordance.

Real filters wired:

- skills: All / Project / Global / Builtin filters the list by scope
- plans: All / Active / Done filters by completion status
- hooks: Resolved + each event filters the matrix to rows whose hooks
  fire on the selected event (matrix columns still show all events)

Static indicators marked with the new `chip-f.static` modifier (cursor
default, no hover lift). Sessions count, permissions Project/Builtin
counts, usage records/log size, tools total + plan-mode flag, chat
mode label, semantic index status, and semantic config-tag chips all
no longer pretend to be clickable.

CSS: new `.chip-f.static` + `.chip-f.static:hover` rules disable the
interactive affordances without duplicating the chip styling.
2026-05-06 08:58:58 -07:00
639 changed files with 74297 additions and 18835 deletions

No files matched your search

+12 -5
View File
@@ -4,6 +4,10 @@ about: Something is broken
labels: bug
---
> **Screen flicker, garbled output, leftover artifacts, cursor jumping?**
> Use the **Display / rendering issue** template instead — it asks for the
> terminal-specific info we need to diagnose those.
**What happened**
A clear and concise description.
@@ -14,10 +18,13 @@ What you expected to happen.
Steps or minimal code that reproduces it.
**Environment**
- Reasonix version:
- Node version:
- OS:
- DeepSeek model (e.g. `deepseek-chat`, `deepseek-reasoner`):
- Reasonix version (`reasonix --version`):
- Node version (`node --version`):
- OS (Windows 11 / macOS 14 / Ubuntu 24.04 / …):
- Shell (bash, zsh, fish, PowerShell 7, PowerShell 5.1, cmd, …):
- Terminal app (Windows Terminal, iTerm2, Alacritty, kitty, WezTerm, **VSCode integrated**, **Cursor integrated**, Hyper, …):
- DeepSeek model (e.g. `deepseek-v4-flash`, `deepseek-v4-pro`):
**Logs / transcript**
If using the CLI, attach the relevant chunk of `--transcript`.
If using the CLI, attach the relevant chunk of `--transcript`, or run
`reasonix doctor` and paste the output.
+109
View File
@@ -0,0 +1,109 @@
---
name: Display / rendering issue
about: Screen flicker, garbled output, leftover artifacts, cursor jumping
labels: bug, rendering
---
> Display problems almost always come from the **terminal emulator**, not
> the shell. Please fill the terminal section carefully — `bash vs PowerShell`
> tells us very little; `VSCode integrated terminal vs Windows Terminal`
> tells us everything.
**Symptom** (tick all that apply)
- [ ] Whole screen flickers / flashes during streaming response
- [ ] Lines tear or only half-redraw
- [ ] Stale output left behind after a frame updates
- [ ] Cursor jumps to wrong column or vanishes
- [ ] Mojibake / wrong-width characters (e.g. `□`, half-width emoji)
- [ ] Other (describe below)
**When it happens**
- [ ] During assistant streaming (token-by-token output)
- [ ] When tool cards expand / collapse
- [ ] During scroll-up / scrollback
- [ ] On terminal resize
- [ ] On launch / on quit
- [ ] Other (describe below)
**Terminal — the important part**
Where exactly are you running `reasonix`?
- [ ] **VSCode** integrated terminal — VSCode version: `?`
- [ ] **Cursor** integrated terminal — Cursor version: `?`
- [ ] **Windows Terminal** — version: `?`
- [ ] **cmd.exe** (legacy console host)
- [ ] **PowerShell ISE** (note: ISE doesn't support ANSI — most things will look broken)
- [ ] **iTerm2** / **Terminal.app** / **Alacritty** / **kitty** / **WezTerm** / **Hyper**
- [ ] tmux / screen / mosh — and inside which outer terminal? `?`
- [ ] Other:
> 💡 **How to find your VSCode / Cursor version**
> `Help → About` (Windows/Linux) or `Code → About Visual Studio Code` (macOS).
> Paste the whole panel — version + commit + Electron + xterm.js if shown.
**Diagnostic dump — copy/paste output**
Run **one** of the snippets below in the same terminal where you saw the
issue, and paste the output here:
<details><summary>PowerShell (Windows)</summary>
```powershell
reasonix --version; node --version
$PSVersionTable.PSVersion.ToString()
[System.Environment]::OSVersion.VersionString
"TERM=$env:TERM"
"TERM_PROGRAM=$env:TERM_PROGRAM"
"TERM_PROGRAM_VERSION=$env:TERM_PROGRAM_VERSION"
"COLORTERM=$env:COLORTERM"
"WT_SESSION=$env:WT_SESSION"
"VSCODE_INJECTION=$env:VSCODE_INJECTION"
"WSL_DISTRO_NAME=$env:WSL_DISTRO_NAME"
```
</details>
<details><summary>bash / zsh (macOS / Linux / WSL / Git Bash)</summary>
```bash
reasonix --version; node --version
uname -a
echo "TERM=$TERM"
echo "TERM_PROGRAM=$TERM_PROGRAM"
echo "TERM_PROGRAM_VERSION=$TERM_PROGRAM_VERSION"
echo "COLORTERM=$COLORTERM"
echo "WT_SESSION=$WT_SESSION"
echo "VSCODE_INJECTION=$VSCODE_INJECTION"
echo "WSL_DISTRO_NAME=$WSL_DISTRO_NAME"
```
</details>
```
<paste output here>
```
**VSCode / Cursor users only — terminal settings**
Open Settings (`Ctrl+,`), search `terminal.integrated.gpuAcceleration`,
report current value: `auto` / `on` / `canvas` / `off` — `?`
Already tried any of:
- [ ] Switching `gpuAcceleration` to a different value
- [ ] Detaching the terminal (drag tab into its own window)
- [ ] Running the same command in a non-VSCode terminal — did it still flicker? `yes / no`
**Reproduction**
Steps that reliably trigger it (commands run, files edited, was a tool
streaming a long response, was the window being resized, …):
1.
2.
3.
**Screen recording (strongly preferred)**
A 5–10s GIF or MP4 is worth 1000 words for rendering bugs. Drop it in
this comment box — GitHub uploads attachments inline.
+25
View File
@@ -0,0 +1,25 @@
bug:
- '/\b(crash|crashed|crashes|panic|panicked|stack trace|stacktrace|traceback)\b/i'
- '/\b(broken|doesn''?t work|not working|stopped working|regression)\b/i'
- '/\b(throws? (an? )?error|uncaught|unhandled)\b/i'
enhancement:
- '/\b(feature request|would (be nice|like|love)|please add|please support)\b/i'
- '/\b(add (a |the )?(flag|option|config|setting|switch)|allow (configuring|disabling|enabling))\b/i'
- '/\b(can (we|you|reasonix) (add|support)|proposal|propose adding)\b/i'
documentation:
- '/\b(docs?\b|documentation|readme|getting started|tutorial|wiki|man page)\b/i'
- '/\b(missing (docs?|documentation)|undocumented)\b/i'
question:
- '/\b(how (do|to|can) (i|we|you)|is it possible|is there a way|why does|why is)\b/i'
- '/\b(question:|q:)\s/i'
dashboard:
- '/\b(dashboard|\/dashboard|web UI|web companion|browser)\b/i'
- '/\blocalhost:|127\.0\.0\.1/i'
rendering:
- '/\b(flicker|flickering|render artifact|redraw|repaint|ghost row|ghosting|screen tear)\b/i'
- '/\b(TUI (glitch|artifact|garbled)|terminal (glitch|garbled|broken display))\b/i'
-3
View File
@@ -48,6 +48,3 @@ jobs:
# DEEPSEEK_API_KEY in CI.
- name: τ-bench harness dry-run
run: npx tsx benchmarks/tau-bench/runner.ts --dry --out /tmp/tau-dry.json
- name: Harvest-bench harness dry-run
run: npx tsx benchmarks/harvest/runner.ts --dry --out /tmp/harvest-dry.json
+22
View File
@@ -0,0 +1,22 @@
name: Issue auto-label
on:
issues:
types: [opened, edited]
permissions:
issues: write
contents: read
jobs:
label:
runs-on: ubuntu-latest
steps:
- uses: github/[email protected]
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
configuration-path: .github/issue-labeler.yml
enable-versioned-regex: 0
include-title: 1
include-body: 1
sync-labels: 0
+20
View File
@@ -0,0 +1,20 @@
name: Issue similarity check
on:
issues:
types: [opened, edited]
permissions:
issues: write
jobs:
similarity:
runs-on: ubuntu-latest
steps:
- uses: actions-cool/issues-similarity-analysis@v1
with:
filter-threshold: 0.7
title-excludes: ""
comment-title: "### Possibly related issues"
comment-body: "- #${number} · ${title}"
show-footer: false
+17
View File
@@ -0,0 +1,17 @@
name: oosmetrics Health Check
on:
schedule:
- cron: "0 9 * * 1"
workflow_dispatch:
permissions:
issues: write
jobs:
report:
runs-on: ubuntu-latest
steps:
- uses: oosmetrics/health-check-action@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+74
View File
@@ -0,0 +1,74 @@
name: Release mirror
on:
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: "Tag to mirror (e.g. v0.42.0)"
required: true
type: string
permissions:
contents: read
jobs:
mirror:
name: Mirror release assets to R2
runs-on: ubuntu-latest
env:
HAS_R2: ${{ secrets.R2_ACCESS_KEY_ID != '' && secrets.R2_SECRET_ACCESS_KEY != '' && secrets.R2_ACCOUNT_ID != '' && secrets.R2_BUCKET != '' }}
steps:
- uses: actions/checkout@v4
- name: Resolve tag
id: tag
shell: bash
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
echo "name=${{ inputs.tag }}" >> "$GITHUB_OUTPUT"
else
echo "name=${{ github.event.release.tag_name }}" >> "$GITHUB_OUTPUT"
fi
- name: Download release assets from GitHub
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
mkdir -p assets
gh release download "${{ steps.tag.outputs.name }}" \
-R "${{ github.repository }}" \
-D assets
- name: Configure AWS CLI for R2
if: env.HAS_R2 == 'true'
run: |
aws configure set aws_access_key_id "${{ secrets.R2_ACCESS_KEY_ID }}"
aws configure set aws_secret_access_key "${{ secrets.R2_SECRET_ACCESS_KEY }}"
aws configure set region auto
- name: Mirror to R2
if: env.HAS_R2 == 'true'
env:
R2_ACCOUNT_ID: ${{ secrets.R2_ACCOUNT_ID }}
R2_BUCKET: ${{ secrets.R2_BUCKET }}
TAG: ${{ steps.tag.outputs.name }}
run: |
ENDPOINT="https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com"
aws s3 cp assets/ "s3://${R2_BUCKET}/${TAG}/" \
--recursive \
--endpoint-url "$ENDPOINT"
aws s3 cp assets/ "s3://${R2_BUCKET}/latest/" \
--recursive \
--endpoint-url "$ENDPOINT"
- name: Summary
if: always()
run: |
{
echo "## Mirror result"
echo ""
echo "- Tag: \`${{ steps.tag.outputs.name }}\`"
echo "- R2: ${{ env.HAS_R2 == 'true' && '✓ mirrored' || 'skipped (no R2 secrets)' }}"
} >> "$GITHUB_STEP_SUMMARY"
+153
View File
@@ -0,0 +1,153 @@
name: Release
on:
push:
tags: ["v*"]
workflow_dispatch:
inputs:
tag:
description: "Tag to publish (e.g. v0.40.0). Required when running manually."
required: true
type: string
permissions:
contents: write
jobs:
bundle:
name: bundle (${{ matrix.target.label }})
strategy:
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.
- { 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: 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
# job-level env. Treat "true"/"false" strings as booleans downstream.
env:
HAS_APPLE_CERT: ${{ secrets.APPLE_CERTIFICATE != '' }}
HAS_WIN_CERT: ${{ secrets.WINDOWS_CERTIFICATE != '' }}
steps:
- uses: actions/checkout@v4
- name: Resolve tag
id: tag
shell: bash
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
echo "name=${{ inputs.tag }}" >> "$GITHUB_OUTPUT"
else
echo "name=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
fi
- name: Setup Node 22
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
- name: Setup Rust (${{ matrix.target.rust }})
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target.rust }}
- name: Rust cache
uses: Swatinem/rust-cache@v2
with:
workspaces: desktop/src-tauri -> target
key: ${{ matrix.target.label }}
- name: Install Linux bundle deps
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y \
libwebkit2gtk-4.1-dev \
libgtk-3-dev \
libayatana-appindicator3-dev \
librsvg2-dev \
patchelf
- name: Install root deps
run: npm ci
- name: Sync desktop version from tag
run: node scripts/sync-desktop-version.mjs "${{ steps.tag.outputs.name }}"
- name: Build CLI bundle (dist/)
run: npm run build
- name: Install desktop deps
working-directory: desktop
run: npm ci
- name: Download bundled Node runtime
working-directory: desktop
run: npm run bundle:node
# 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
# certificate being non-empty so unsigned prereleases don't trip
# `security import` / `signtool` on missing certs.
- name: Build Tauri bundle (unsigned)
if: >-
(matrix.target.os != 'windows-latest' || env.HAS_WIN_CERT != 'true')
&& (!startsWith(matrix.target.os, 'macos-') || env.HAS_APPLE_CERT != 'true')
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
with:
projectPath: desktop
tagName: ${{ steps.tag.outputs.name }}
releaseName: Reasonix ${{ steps.tag.outputs.name }}
releaseDraft: true
prerelease: false
args: --target ${{ matrix.target.tauri }}
- name: Build Tauri bundle (Windows, signed)
if: matrix.target.os == 'windows-latest' && env.HAS_WIN_CERT == 'true'
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
with:
projectPath: desktop
tagName: ${{ steps.tag.outputs.name }}
releaseName: Reasonix ${{ steps.tag.outputs.name }}
releaseDraft: true
prerelease: false
args: --target ${{ matrix.target.tauri }}
- name: Build Tauri bundle (macOS, signed + notarized)
if: startsWith(matrix.target.os, 'macos-') && env.HAS_APPLE_CERT == 'true'
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
with:
projectPath: desktop
tagName: ${{ steps.tag.outputs.name }}
releaseName: Reasonix ${{ steps.tag.outputs.name }}
releaseDraft: true
prerelease: false
args: --target ${{ matrix.target.tauri }}
+14
View File
@@ -33,4 +33,18 @@ sessions/
.reasonix/semantic-skip
# Scratch entry regenerated each time scripts/bundle-codemirror.mjs runs.
scripts/.cm-entry.mjs
# Personal bun lockfile — project uses npm officially.
bun.lock
# Local portable Node/npm used for development on machines without npm.
.tools/
.npm-cache/
# Tauri desktop shell build artifacts.
desktop/src-tauri/target/
desktop/src-tauri/gen/
desktop/src-tauri/binaries/
# Design mock-up reference (local, not part of repo)
.design-ref/
*.cpuprofile
+1916
View File
File diff suppressed because it is too large. Load diff
+122 -26
View File
@@ -7,7 +7,9 @@
&nbsp;·&nbsp;
<a href="./README.zh-CN.md">简体中文</a>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/reasonix/">Website</a>
<a href="https://esengine.github.io/DeepSeek-Reasonix/">Website</a>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/configuration.html">Guide</a>
&nbsp;·&nbsp;
<a href="./docs/ARCHITECTURE.md">Architecture</a>
&nbsp;·&nbsp;
@@ -15,14 +17,20 @@
</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=0d1117&labelColor=161b22" 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&color=0d1117&labelColor=161b22" alt="CI"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/reasonix.svg?style=flat-square&color=0d1117&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=0d1117&labelColor=161b22" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" 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=0d1117&labelColor=161b22&logo=github" alt="GitHub 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=0d1117&labelColor=161b22&logo=github" 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=0d1117&labelColor=161b22&logo=github" alt="Discussions"/></a>
<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://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>
</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/>
@@ -41,30 +49,113 @@
> [!TIP]
> **Cache stability isn't a feature you turn on; it's an invariant the loop is designed around.** That's the whole reason Reasonix is DeepSeek-only — every layer is tuned to the byte-stable prefix-cache mechanic.
> [!NOTE]
> **Real user, single day (2026-05-01):** 435M input tokens, **99.82% cache hit**, ~$12 instead of the ~$61 the same workload would cost with no cache on `v4-flash` — see the [case study](./benchmarks/real-world-cache/README.md). DeepSeek provides the cacheable bytes; the four mechanisms in [Pillar 1](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) are how Reasonix keeps them cacheable across long sessions.
<br/>
## Install
Requires Node ≥ 22. Works on macOS · Linux · Windows (PowerShell · Git Bash · Windows Terminal).
Install Reasonix globally if you want the `reasonix` command available on your `PATH`:
```bash
cd my-project
npx reasonix code # paste a DeepSeek API key on first run; persists after
npm install -g reasonix
reasonix code my-project # paste a DeepSeek API key on first run; persists after
```
Requires Node ≥ 22. Tested on macOS · Linux · Windows (PowerShell · Git Bash · Windows Terminal). Get a [DeepSeek API key →](https://platform.deepseek.com/api_keys) · `reasonix code --help` for flags.
Or run it once without installing globally:
```bash
cd my-project
npx reasonix code # always uses the latest package by default
```
Grab a [DeepSeek API key →](https://platform.deepseek.com/api_keys) · `reasonix code --help` for flags.
If you use Reasonix daily, global install is the simplest path. If you just want to try it, use `npx`.
| Command | When |
|---|---|
| `reasonix code [dir]` | The coding agent. **Start here.** |
| `reasonix chat` | Plain chat — no filesystem or shell tools. |
| `reasonix run "task"` | One-shot, streams to stdout. Good for pipes. |
| `reasonix doctor` | Health check: Node, API key, MCP wiring. |
| `reasonix update` | Upgrade Reasonix itself. |
Other subcommands (`replay` · `diff` · `events` · `stats` · `index` · `mcp` · `prune-sessions`) are in `reasonix --help` and the [CLI reference](https://esengine.github.io/DeepSeek-Reasonix/#cli).
### Desktop client (prerelease)
A native Tauri client for users who want a GUI over the same loop. Multi-tab, the right-panel shows files the agent has read or edited this session, the same cost / cache / token meters live at the bottom. Same DeepSeek API key, same `~/.reasonix` config — the desktop bundles its own Node runtime, no separate `npm install` step.
Download platform installers from [GitHub Releases](https://github.com/esengine/DeepSeek-Reasonix/releases). The desktop ships as a **prerelease**: the loop and protocol are the same as the CLI, but the UI is still being polished and the installers aren't code-signed yet.
- **macOS** — first launch hits Gatekeeper. One-time fix: `xattr -dr com.apple.quarantine /Applications/Reasonix.app` (or right-click → Open → confirm).
- **Windows** — SmartScreen warns "Unknown publisher". Click **More info → Run anyway**.
- **Linux** — `.deb` and `.AppImage` ship plain, no extra step.
The CLI remains the canonical surface. Anything that lands in the CLI is also available from the desktop's composer.
<details>
<summary><strong>Working in another folder · chat vs. code · author a skill</strong></summary>
**Working in a different folder.** Reasonix scopes filesystem tools to the launch directory; pass `--dir` to retarget. Mid-session switching isn't supported by design (memory paths would tangle with stale roots) — quit and relaunch.
```bash
npx reasonix code --dir /path/to/project
```
**Picking `chat` vs `code`.** `code` is the default and the only mode with filesystem / shell tools and SEARCH/REPLACE review. `chat` is the lighter, tools-off shell — reach for it when you want a thinking partner with MCP attached but no disk access.
| What you get | `code` | `chat` |
|---|---|---|
| Filesystem tools + `edit_file` | ✓ | — |
| SEARCH/REPLACE → `/apply` review | ✓ | — |
| Shell tool (gated) | ✓ | — |
| Plan mode · `/todo` · `/skill new` · `/mcp add` | ✓ | — |
| Memory (`remember` / `recall_memory`) | project + global | global only |
| MCP servers from config · web search · `ask_choice` | ✓ | ✓ |
| Coding system prompt | ✓ | generic |
| Session scope | per-directory | shared default |
**Author your first skill.** No remote registry — write them directly. Edit the file (`description:` frontmatter + body), then `/skill list`. Add `runAs: subagent` to spawn an isolated subagent loop instead of inlining the body.
```bash
/skill new my-skill # <project>/.reasonix/skills/my-skill.md
/skill new my-skill --global # ~/.reasonix/skills for cross-project use
```
</details>
<br/>
## Configuration
One JSON file at `~/.reasonix/config.json` plus per-project overrides under `<project>/.reasonix/`. The full bilingual reference — every key, every slash command, the on-disk shape of skills/memory/hooks — lives at:
> 📘 **[Configuration Guide](https://esengine.github.io/DeepSeek-Reasonix/configuration.html)** · [中文](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh)
| Topic | Quick read |
|---|---|
| [MCP servers](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#mcp) | stdio · SSE · Streamable HTTP. One spec format works for both `config.json` and `--mcp`. |
| [Skills](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#skills) | Markdown playbooks the model can invoke. `inline` or `subagent` mode. |
| [Memory](https://esengine.github.io/DeepSeek-Reasonix/configuration.html#memory) | User-private knowledge pinned into the prefix. `user` / `feedback` / `project` / `reference` types. |
| [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 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/>
## What makes Reasonix different
The loop is organized around four pillars. Each one solves a problem generic agent frameworks don't even see — because they were designed for a different cache mechanic.
<p align="center">
<a href="./docs/ARCHITECTURE.md"><img src="docs/assets/pillars.svg" alt="Reasonix four pillars — Cache-first loop, R1 thought harvesting, Tool-call repair, Cost control" width="880"/></a>
</p>
The loop is organized around three pillars. Each one solves a problem generic agent frameworks don't even see — because they were designed for a different cache mechanic.
<sub align="center">
Click any card to read the full architecture writeup → [Pillar 1](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) · [Pillar 2](./docs/ARCHITECTURE.md#pillar-2--r1-thought-harvesting-opt-in) · [Pillar 3](./docs/ARCHITECTURE.md#pillar-3--tool-call-repair) · [Pillar 4](./docs/ARCHITECTURE.md#pillar-4--cost-control-v06)
Click through to the full architecture writeup → [Pillar 1 — Cache-first loop](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) · [Pillar 2 — Tool-call repair](./docs/ARCHITECTURE.md#pillar-2--tool-call-repair) · [Pillar 3 — Cost control](./docs/ARCHITECTURE.md#pillar-3--cost-control-v06)
</sub>
@@ -87,8 +178,10 @@ Click any card to read the full architecture writeup → [Pillar 1](./docs/ARCHI
| Cost profile | **low per task** | premium | subscription + use | varies |
| DeepSeek prefix-cache | **engineered** | not applicable | not applicable | incidental |
| Embedded web dashboard | yes | — | n/a (IDE) | — |
| 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) | 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.
@@ -97,9 +190,10 @@ For live cache-hit rates, costs, and methodology, see [`benchmarks/`](./benchmar
## Documentation
- [**Architecture**](./docs/ARCHITECTURE.md) — the four pillars, cache-first loop, harvesting, scaffolds
- [**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
- [**Benchmarks**](./benchmarks/) — τ-bench-lite harness, transcripts, cost methodology
- [**Website**](https://esengine.github.io/reasonix/) — getting started, dashboard mockup, TUI mockup
- [**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
- [**Code of Conduct**](./CODE_OF_CONDUCT.md) · [**Security policy**](./SECURITY.md)
@@ -115,7 +209,7 @@ Scoped starter tickets — each with background, code pointers, acceptance crite
**Open Discussions — opinions wanted:**
- [#20 · CLI / TUI design](https://github.com/esengine/reasonix/discussions/20) — what's broken, what's missing, what would you change?
- [#21 · Dashboard design](https://github.com/esengine/reasonix/discussions/21) — react against the [proposed mockup](https://esengine.github.io/reasonix/design/agent-dashboard.html)
- [#21 · Dashboard design](https://github.com/esengine/reasonix/discussions/21) — react against the [proposed mockup](https://esengine.github.io/DeepSeek-Reasonix/design/agent-dashboard.html)
- [#22 · Future feature wishlist](https://github.com/esengine/reasonix/discussions/22) — what would you build into Reasonix next?
**Already using Reasonix and willing to help others discover it?** Publish blog posts, articles, screenshots, talks, or videos to [**Show and tell**](https://github.com/esengine/reasonix/discussions/categories/show-and-tell). The project has no marketing budget — community word of mouth is how new users find it. Sustained advocates earn the badge below, displayed next to the contributors wall once awarded:
@@ -130,7 +224,7 @@ Scoped starter tickets — each with background, code pointers, acceptance crite
<p align="center">
<a href="https://github.com/esengine/reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/reasonix&max=100&columns=12" alt="Contributors to esengine/reasonix" width="860"/>
<img src="https://contrib.rocks/image?repo=esengine/DeepSeek-Reasonix&max=100&columns=12" alt="Contributors to esengine/DeepSeek-Reasonix" width="860"/>
</a>
</p>
@@ -150,11 +244,11 @@ Scoped starter tickets — each with background, code pointers, acceptance crite
## Star History
<a href="https://www.star-history.com/?repos=esengine%2Freasonix&type=timeline&logscale=&legend=top-left">
<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/reasonix&type=timeline&theme=dark&logscale&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
<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>
@@ -166,4 +260,6 @@ Scoped starter tickets — each with background, code pointers, acceptance crite
<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>
</p>
+89 -23
View File
@@ -7,7 +7,9 @@
&nbsp;·&nbsp;
<strong>简体中文</strong>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/reasonix/">官方网站</a>
<a href="https://esengine.github.io/DeepSeek-Reasonix/">官方网站</a>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh">配置指南</a>
&nbsp;·&nbsp;
<a href="./docs/ARCHITECTURE.md">架构文档</a>
&nbsp;·&nbsp;
@@ -15,14 +17,20 @@
</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=0d1117&labelColor=161b22" 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&color=0d1117&labelColor=161b22" alt="CI"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/reasonix.svg?style=flat-square&color=0d1117&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=0d1117&labelColor=161b22" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" 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=0d1117&labelColor=161b22&logo=github" alt="GitHub 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=0d1117&labelColor=161b22&logo=github" 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=0d1117&labelColor=161b22&logo=github" alt="Discussions"/></a>
<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://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>
</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 — Agents 速度榜 Top 2"/></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 — LLMs 速度榜 Top 3"/></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 — CLI 速度榜 Top 3"/></a>
</p>
<br/>
@@ -50,21 +58,78 @@ cd my-project
npx reasonix code # 首次运行粘贴 DeepSeek API Key,之后会记住
```
要求 Node ≥ 22。已在 macOS · Linux · Windows(PowerShell · Git Bash · Windows Terminal)测过。[去拿 DeepSeek API Key →](https://platform.deepseek.com/api_keys) · 完整 flag 看 `reasonix code --help`。
要求 Node ≥ 22。在 macOS · Linux · Windows(PowerShell · Git Bash · Windows Terminal)都跑得顺。[去拿 DeepSeek API Key →](https://platform.deepseek.com/api_keys) · 完整 flag 看 `reasonix code --help`。
`npx` 是推荐路径 —— 不用全局安装,每次都拿最新版。如果你天天用、想把 `reasonix` 装到 `PATH`,跑一次 `reasonix update`。
| 命令 | 何时用 |
|---|---|
| `reasonix code [dir]` | 编码 agent。**先用这个。** |
| `reasonix chat` | 纯聊天 —— 不挂文件系统 / shell 工具。 |
| `reasonix run "task"` | 一次性,结果流到 stdout。适合 shell 管道。 |
| `reasonix doctor` | 体检:Node 版本、API Key、MCP 接线。 |
| `reasonix update` | 升级 Reasonix 本身。 |
其他子命令(`replay` · `diff` · `events` · `stats` · `index` · `mcp` · `prune-sessions`)在 `reasonix --help` 和 [CLI 参考](https://esengine.github.io/DeepSeek-Reasonix/#cli)。
<details>
<summary><strong>切换工作区 · chat vs. code · 写第一个 Skill</strong></summary>
**切换工作区。** Reasonix 把文件系统工具作用域绑定在启动目录,传 `--dir` 可以指别处。中途切换是有意不支持的(消息日志和 memory 路径会和旧根目录混在一起)—— 退出再启动。
```bash
npx reasonix code --dir /path/to/project
```
**`chat` 还是 `code`?** `code` 是默认入口、唯一带文件系统 / shell 工具和 SEARCH/REPLACE 审阅的模式。`chat` 是更轻量的纯对话壳——想要一个挂着 MCP 但没有磁盘权限的“思路助手”时用它。
| 你拿到什么 | `code` | `chat` |
|---|---|---|
| 文件系统工具 + `edit_file` | ✓ | — |
| SEARCH/REPLACE → `/apply` 审阅 | ✓ | — |
| Shell 工具(带 gate) | ✓ | — |
| Plan 模式 · `/todo` · `/skill new` · `/mcp add` | ✓ | — |
| Memory(`remember` / `recall_memory`) | 项目 + 全局 | 仅全局 |
| 配置里的 MCP · web 搜索 · `ask_choice` | ✓ | ✓ |
| 编码导向系统提示词 | ✓ | 通用 |
| Session 作用域 | 按目录 | 共享默认 |
**写第一个 Skill。** 暂无在线市场——自己写。编辑文件(`description:` frontmatter + 正文),然后 `/skill list` 就能看到。frontmatter 加 `runAs: subagent` 会以隔离 subagent 跑,而不是把正文内联进父 prompt。
```bash
/skill new my-skill # <project>/.reasonix/skills/my-skill.md
/skill new my-skill --global # ~/.reasonix/skills,跨项目共用
```
</details>
<br/>
## 配置
一个全局 JSON 文件 `~/.reasonix/config.json`,加上项目级 `<project>/.reasonix/` 下的覆盖。完整的双语参考 —— 每一个 key、每一条斜杠命令、skills / memory / hooks 在磁盘上的形状 —— 都在这里:
> 📘 **[配置指南](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh)** · [English](https://esengine.github.io/DeepSeek-Reasonix/configuration.html)
| 主题 | 速读 |
|---|---|
| [MCP 服务器](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh#mcp) | stdio · SSE · Streamable HTTP。`config.json` 和 `--mcp` 共用同一种 spec 格式。 |
| [Skills](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh#skills) | 模型可以调用的 markdown 剧本。`inline` 或 `subagent` 两种模式。 |
| [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。 |
| [语义索引](https://esengine.github.io/DeepSeek-Reasonix/configuration.html?lang=zh#index) | `reasonix index` —— 本地 Ollama,或任何 OpenAI 兼容的 embedding 接口。 |
<br/>
## Reasonix 的不同之处
整个循环围绕四根支柱组织。每一根解决的都是通用 agent 框架根本看不见的问题 —— 因为它们是为另一种缓存机制设计的。
<p align="center">
<a href="./docs/ARCHITECTURE.md"><img src="docs/assets/pillars.zh-CN.svg" alt="Reasonix 四大支柱 — 缓存优先循环、R1 思维提取、工具调用修复、成本控制" width="880"/></a>
</p>
整个循环围绕三根支柱组织。每一根解决的都是通用 agent 框架根本看不见的问题 —— 因为它们是为另一种缓存机制设计的。
<sub align="center">
各支柱完整说明 → [Pillar 1](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) · [Pillar 2](./docs/ARCHITECTURE.md#pillar-2--r1-thought-harvesting-opt-in) · [Pillar 3](./docs/ARCHITECTURE.md#pillar-3--tool-call-repair) · [Pillar 4](./docs/ARCHITECTURE.md#pillar-4--cost-control-v06)
各支柱完整说明 → [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>
@@ -98,8 +163,9 @@ npx reasonix code # 首次运行粘贴 DeepSeek API Key,之后会记住
## 文档
- [**架构**](./docs/ARCHITECTURE.md) —— 四大支柱、缓存优先循环、思维提取、脚手架
- [**CLI 参考**](./docs/CLI-REFERENCE.md) —— 每个 shell 子命令、每个 slash 命令、每个快捷键
- [**基准测试**](./benchmarks/) —— τ-bench-lite harness、transcript、成本方法论
- [**官方网站**](https://esengine.github.io/reasonix/) —— 入门、Dashboard 设计稿、TUI 设计稿
- [**官方网站**](https://esengine.github.io/DeepSeek-Reasonix/) —— 入门、Dashboard 设计稿、TUI 设计稿
- [**贡献指南**](./CONTRIBUTING.md) —— 注释规则、错误处理、用现成库不手写
- [**行为准则**](./CODE_OF_CONDUCT.md) · [**安全策略**](./SECURITY.md)
@@ -115,7 +181,7 @@ npx reasonix code # 首次运行粘贴 DeepSeek API Key,之后会记住
**正在征集意见的 Discussions:**
- [#20 · CLI / TUI 设计](https://github.com/esengine/reasonix/discussions/20) —— 哪里坏了、哪里少东西、哪里你会怎么改?
- [#21 · Dashboard 设计](https://github.com/esengine/reasonix/discussions/21) —— 对着[设计稿](https://esengine.github.io/reasonix/design/agent-dashboard.html)拍砖
- [#21 · Dashboard 设计](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)。项目没有营销预算,新用户主要通过社区口碑找到这里。持续参与传播的用户将获得下方这枚徽章,颁发后会展示在贡献者墙旁:
@@ -130,7 +196,7 @@ npx reasonix code # 首次运行粘贴 DeepSeek API Key,之后会记住
<p align="center">
<a href="https://github.com/esengine/reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/reasonix&max=100&columns=12" alt="esengine/reasonix 贡献者" width="860"/>
<img src="https://contrib.rocks/image?repo=esengine/DeepSeek-Reasonix&max=100&columns=12" alt="esengine/DeepSeek-Reasonix 贡献者" width="860"/>
</a>
</p>
@@ -150,11 +216,11 @@ npx reasonix code # 首次运行粘贴 DeepSeek API Key,之后会记住
## Star 趋势
<a href="https://www.star-history.com/?repos=esengine%2Freasonix&type=timeline&logscale=&legend=top-left">
<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/reasonix&type=timeline&theme=dark&logscale&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
<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>
-106
View File
@@ -1,106 +0,0 @@
# Harvest eval harness (Pillar 2)
Measures Pillar 2 (R1 Thought Harvesting) the same way `tau-bench/`
measures Pillar 1 (Cache-First Loop): isolate one variable, produce
numbers anyone can reproduce.
## What's different from τ-bench-lite?
Deliberately different task shape:
| | τ-bench-lite | harvest-bench |
|---|---|---|
| task style | multi-turn tool-use | single-turn reasoning |
| user simulator | yes (LLM) | no |
| DB state | yes | no |
| checker | DB-predicate | regex + set/value compare |
| target | Pillar 1 | Pillar 2 |
| model | deepseek-chat (default) | deepseek-reasoner (only R1 has `reasoning_content` for harvest to work on) |
The two harnesses answer different questions:
- **τ-bench-lite**: *"Does Cache-First actually cut cost on real tool-use
workflows?"* (yes — 47.7pp cache, −39% cost on 48-run data.)
- **harvest-bench**: *"Does the extra V3 harvest call add measurable
value above plain R1?"* (TBD — run it to find out.)
## Modes
Three modes isolate one variable each:
| mode | model | harvest | what it measures |
|---|---|---|---|
| `baseline` | deepseek-chat | off | floor reference — V3 at its best |
| `reasoner` | deepseek-reasoner | off | raw R1 gain over V3 on reasoning |
| `reasoner-harvest` | deepseek-reasoner | on | R1 + the extra V3 harvest call |
Deltas:
- `baseline → reasoner` answers "is R1 worth the price on these
problems?"
- `reasoner → reasoner-harvest` answers "is the harvest call worth
its incremental cost?"
## Quickstart
```bash
# Dry-run — no API, smoke-test the wiring
npx tsx benchmarks/harvest/runner.ts --dry
# Full run (live DeepSeek, costs ~$0.20-0.60 for 6 tasks × 3 modes × 1 repeat)
export DEEPSEEK_API_KEY=sk-...
npx tsx benchmarks/harvest/runner.ts
# Tighter run with 3 repeats (~$0.60-2.00)
npx tsx benchmarks/harvest/runner.ts --repeats 3
# Only the hard tasks (skip the easy floor)
npx tsx benchmarks/harvest/runner.ts --task pseudoprime_base2
npx tsx benchmarks/harvest/runner.ts --task derangements_d7
npx tsx benchmarks/harvest/runner.ts --task euler_quadratic_break
# Bump per-call timeout (reasoner + harvest occasionally blow past the 120s default)
npx tsx benchmarks/harvest/runner.ts --timeout 600
# Per-run transcripts so you can reasonix replay / diff them
npx tsx benchmarks/harvest/runner.ts --repeats 3 --transcripts-dir transcripts/
# Render report
npx tsx benchmarks/harvest/report.ts benchmarks/harvest/results-*.json
```
## Tasks (v0.3 seed)
Split into two bands:
**Easy band** — V3 chat solves these, so baseline has a real pass rate and the bench has a reference floor.
| id | shape | why |
|---|---|---|
| `mod7_list` | number theory, 29-element list | R1 often tries enumeration first, then reaches for modular arithmetic — clean rejectedPaths signal |
| `flips_until_3heads` | probability, single integer | classic recurrence; R1 either derives or recalls, harvest should see hypotheses diverge |
| `three_hats` | logic puzzle, one-word answer | pure deduction chain, tests harvest's ability to extract the nested reasoning |
**Hard band** — picked specifically for known V3 failure modes. If R1 systematically beats V3 on these, and harvest further beats R1-only, we have our Pillar 2 story.
| id | shape | why V3 tends to fail |
|---|---|---|
| `pseudoprime_base2` | smallest Fermat pseudoprime to base 2 = **341** | V3 often answers 561 (Carmichael) or some other composite it remembers — R1 actually checks 2^n mod n |
| `derangements_d7` | D_7 = **1854** | V3 approximates via n!/e and rounds wrong, or recalls D_6/D_8; R1 uses the recurrence D_n=(n−1)(D_{n−1}+D_{n−2}) |
| `euler_quadratic_break` | smallest n where n²+n+41 is composite = **40** | V3 frequently confuses with n²−n+41 (first fails at 41); R1 checks small n systematically |
Adding a new task: see `tasks.ts`. Any checker that's deterministic is
fair game — extract numeric/list/text with regex, compare with set
equality or string matching.
## Non-goals
- **No LLM-as-judge.** Brittle and expensive; defeats the point of a
reproducible bench. If a checker is too hard to write deterministically,
the task doesn't belong here.
- **No tool-use tasks.** Those live in `tau-bench/`. Different story.
- **No multi-turn.** v0.3 harness is single-turn Q/A. Multi-turn reasoning
eval is separate scope.
- **No benchmark-data cherry-picking.** When results come in, we publish
them whether they validate Pillar 2 or not. "harvest didn't help on
these 3 tasks" is still useful information.
-82
View File
@@ -1,82 +0,0 @@
# Reasonix harvest eval (Pillar 2)
**Date:** 2026-04-21T16:44:21.011Z
**Tasks:** 6 · repeats × 1 · modes: baseline, reasoner, reasoner-harvest
**Reasonix version:** 0.2.2
## Summary by mode
| mode | runs | pass rate | cache hit | cost / run | harvest turns | subgoals | uncertainties |
|---|---:|---:|---:|---:|---:|---:|---:|
| baseline | 6 | 100% | 39.5% | $0.001371 | 0.0 | 0.0 | 0.0 |
| reasoner | 6 | 100% | 74.2% | $0.004170 | 0.0 | 0.0 | 0.0 |
| reasoner-harvest | 6 | 83% | 61.6% | $0.003304 | 0.8 | 2.8 | 1.3 |
## Deltas
- **baseline → reasoner**
- pass rate: 0pp
- cost: ×3.04 (each run costs more)
- harvest signal / run: 0.0 subgoals, 0.0 uncertainties
- **baseline → reasoner-harvest**
- pass rate: -17pp
- cost: ×2.41 (each run costs more)
- harvest signal / run: 2.8 subgoals, 1.3 uncertainties
## Per-task breakdown
| task | mode | rep | verdict | cache | cost | sg | un | note |
|---|---|---:|:---:|---:|---:|---:|---:|---|
| mod7_list | baseline | 1 | ✅ | 86.5% | $0.001361 | 0 | 0 | |
| mod7_list | reasoner | 1 | ✅ | 86.5% | $0.004797 | 0 | 0 | |
| mod7_list | reasoner-harvest | 1 | ✅ | 86.5% | $0.003045 | 4 | 2 | |
| flips_until_3heads | baseline | 1 | ✅ | 92.8% | $0.001198 | 0 | 0 | |
| flips_until_3heads | reasoner | 1 | ✅ | 92.8% | $0.002830 | 0 | 0 | |
| flips_until_3heads | reasoner-harvest | 1 | ✅ | 92.8% | $0.001691 | 4 | 0 | |
| three_hats | baseline | 1 | ✅ | 57.7% | $0.001514 | 0 | 0 | |
| three_hats | reasoner | 1 | ✅ | 57.7% | $0.009340 | 0 | 0 | |
| three_hats | reasoner-harvest | 1 | ✅ | 57.7% | $0.009651 | 3 | 2 | |
| pseudoprime_base2 | baseline | 1 | ✅ | 0.0% | $0.001894 | 0 | 0 | |
| pseudoprime_base2 | reasoner | 1 | ✅ | 75.3% | $0.003128 | 0 | 0 | |
| pseudoprime_base2 | reasoner-harvest | 1 | ❌ | 0.0% | $0.000000 | 0 | 0 | This operation was aborted |
| derangements_d7 | baseline | 1 | ✅ | 0.0% | $0.001273 | 0 | 0 | |
| derangements_d7 | reasoner | 1 | ✅ | 71.9% | $0.003492 | 0 | 0 | |
| derangements_d7 | reasoner-harvest | 1 | ✅ | 71.9% | $0.002843 | 3 | 2 | |
| euler_quadratic_break | baseline | 1 | ✅ | 0.0% | $0.000985 | 0 | 0 | |
| euler_quadratic_break | reasoner | 1 | ✅ | 61.0% | $0.001431 | 0 | 0 | |
| euler_quadratic_break | reasoner-harvest | 1 | ✅ | 61.0% | $0.002594 | 3 | 2 | |
## Scope
Unlike τ-bench-lite, these tasks are single-turn reasoning problems (no user simulator, no DB, no tool calls). Checkers are deterministic — regex + set / value compare, never an LLM judge. The point is to isolate whether the Pillar 2 harvest step adds measurable value above plain reasoner usage.
Interpretation: `baseline` (chat / V3) is a floor. `reasoner` shows the raw R1 gain. `reasoner-harvest` isolates the cost + quality delta from the extra V3 harvest call.
## Findings (v0.3, 18-run set)
Two bands of tasks tried (easy: mod7 / flips / hats; hard: pseudoprime341 / D_7 / Euler quadratic). The hard band was chosen for *known V3 failure modes*. Result:
1. **V3 chat passed all six tasks, including the three "hard" ones.** DeepSeek V3 knew 341 is the smallest base-2 pseudoprime, computed D_7=1854, and identified n=40 as the first Euler-polynomial failure. The tasks are well-known enough to be in training; the trap-answer variants (561, 265, 41) that the checkers specifically reject didn't fire.
2. **Reasoner cost 3.04× baseline for identical pass rates (6/6 both sides).** On this task set, R1 adds cost and latency without measurable quality. The cache-hit story *does* extend to reasoner (74.2% mean), so Pillar 1 generalizes to R1 — but that's not a Pillar 2 story.
3. **Harvest produced real signal** (mean 2.8 subgoals, 1.3 uncertainties per run where it fired) but didn't improve outcomes. One run hit the 300s timeout (bumped from 120s), suggesting reasoner-harvest latency is still unpredictable on some problems.
### What this tells us about Pillar 2 positioning
We've now given harvest two shots at showing answer-quality value on pure reasoning tasks. Both times V3 ate its lunch. This isn't a framework bug — it's a positioning signal:
- **On well-known math / logic / counting problems, DeepSeek V3 is strong enough that paying for R1 is not justified by accuracy.** Pillar 2's "smart preset" cost multiplier (10×) quoted in the README is real but for most single-question Q/A it buys nothing.
- **Harvest's plausible value surfaces are not "better math answers".** More likely: (a) transparency / auditability for developers, (b) planning support when tools are in the mix, (c) driving branch-sampling on cases where uncertainty correlates with wrongness. None of those are tested here.
### Recommendation
Don't ship v0.3 on the "harvest makes answers more correct" claim — the data doesn't support it. Two honest paths forward:
- **Reframe Pillar 2 as a developer-facing introspection feature** (debug visibility into R1's planning). Keep harvest opt-in; stop implying it improves accuracy on end-user tasks.
- **Move harvest eval to tool-use contexts** where uncertainty matters for *which tool to call next*, not *is this math right*. That's a new task shape — different harness, not a bigger task set here.
In either case, the next Reasonix release is better served by MCP client (Pillar 1 leverage across the ecosystem) than by a bigger harvest-bench data push.
### Notes
- Cache hit on baseline runs surprised me (39.5% mean). That's DeepSeek's *cross-session* prompt cache: the same system prompt ran many times across modes and runs warmed the server-side cache. Real cross-session evidence that Cache-First's value isn't only per-session.
- 5-subgoals cap still hit uniformly. `HarvestOptions.maxItems` default is 5; harvest is truncating. Moot unless we find a setting where that matters.
-229
View File
@@ -1,229 +0,0 @@
/** Render a harvest-bench results.json into a markdown report. CLI usage in README. */
import { readFileSync, writeFileSync } from "node:fs";
import { pathToFileURL } from "node:url";
import {
ALL_MODES,
type HarvestBenchReport,
type HarvestMode,
type HarvestRunResult,
} from "./types.js";
interface CliArgs {
input: string;
outPath: string;
}
function parseArgs(argv: string[]): CliArgs {
const out: CliArgs = { input: "", outPath: "benchmarks/harvest/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/harvest/report.ts <results.json> [--out report.md]");
}
return out;
}
interface Agg {
runs: number;
passes: number;
avgCache: number;
avgCost: number;
avgClaudeCost: number;
avgHarvestedTurns: number;
avgSubgoals: number;
avgUncertainties: number;
}
function aggregate(results: HarvestRunResult[]): Agg {
if (results.length === 0) {
return {
runs: 0,
passes: 0,
avgCache: 0,
avgCost: 0,
avgClaudeCost: 0,
avgHarvestedTurns: 0,
avgSubgoals: 0,
avgUncertainties: 0,
};
}
const passes = results.filter((r) => r.verdict === "pass").length;
const mean = (fn: (r: HarvestRunResult) => number) =>
results.reduce((s, r) => s + fn(r), 0) / results.length;
return {
runs: results.length,
passes,
avgCache: mean((r) => r.cacheHitRatio),
avgCost: mean((r) => r.costUsd),
avgClaudeCost: mean((r) => r.claudeEquivalentUsd),
avgHarvestedTurns: mean((r) => r.harvestedTurns),
avgSubgoals: mean((r) => r.totalSubgoals),
avgUncertainties: mean((r) => r.totalUncertainties),
};
}
export function renderReport(report: HarvestBenchReport): string {
const lines: string[] = [];
lines.push("# Reasonix harvest eval (Pillar 2)");
lines.push("");
lines.push(`**Date:** ${report.meta.date}`);
lines.push(
`**Tasks:** ${report.meta.taskCount} · repeats × ${report.meta.repeatsPerTask} · modes: ${report.meta.modesRun.join(", ")}`,
);
lines.push(`**Reasonix version:** ${report.meta.reasonixVersion}`);
lines.push("");
// Per-mode summary
lines.push("## Summary by mode");
lines.push("");
lines.push(
"| mode | runs | pass rate | cache hit | cost / run | harvest turns | subgoals | uncertainties |",
);
lines.push("|---|---:|---:|---:|---:|---:|---:|---:|");
for (const mode of ALL_MODES) {
const rs = report.results.filter((r) => r.mode === mode);
const a = aggregate(rs);
if (a.runs === 0) continue;
lines.push(
`| ${mode} | ${a.runs} | ${pct(a.passes, a.runs)} | ${pct1(a.avgCache)} | $${a.avgCost.toFixed(6)} | ${a.avgHarvestedTurns.toFixed(1)} | ${a.avgSubgoals.toFixed(1)} | ${a.avgUncertainties.toFixed(1)} |`,
);
}
lines.push("");
// Pairwise deltas that actually answer the question
lines.push("## Deltas");
lines.push("");
const modes = ALL_MODES.filter((m) => report.results.some((r) => r.mode === m));
if (modes.length >= 2) {
const baseline = aggregate(report.results.filter((r) => r.mode === modes[0]));
for (let i = 1; i < modes.length; i++) {
const mode = modes[i]!;
const agg = aggregate(report.results.filter((r) => r.mode === mode));
const passDelta =
agg.passes / Math.max(agg.runs, 1) - baseline.passes / Math.max(baseline.runs, 1);
const costRatio = baseline.avgCost > 0 ? agg.avgCost / baseline.avgCost : 0;
lines.push(`- **${modes[0]} → ${mode}**`);
lines.push(` - pass rate: ${(passDelta * 100).toFixed(0)}pp`);
lines.push(
` - cost: ×${costRatio.toFixed(2)} (each run costs ${costRatio > 1 ? "more" : "less"})`,
);
lines.push(
` - harvest signal / run: ${agg.avgSubgoals.toFixed(1)} subgoals, ${agg.avgUncertainties.toFixed(1)} uncertainties`,
);
lines.push("");
}
}
// Per-task breakdown
lines.push("## Per-task breakdown");
lines.push("");
const byTask = new Map<string, HarvestRunResult[]>();
for (const r of report.results) {
const list = byTask.get(r.taskId) ?? [];
list.push(r);
byTask.set(r.taskId, list);
}
lines.push("| task | mode | rep | verdict | cache | cost | sg | un | note |");
lines.push("|---|---|---:|:---:|---:|---:|---:|---:|---|");
for (const [taskId, runs] of byTask) {
for (const r of runs) {
const mark = r.verdict === "pass" ? "✅" : r.verdict === "fail" ? "❌" : "•";
lines.push(
`| ${taskId} | ${r.mode} | ${r.repeat} | ${mark} | ${pct1(r.cacheHitRatio)} | $${r.costUsd.toFixed(6)} | ${r.totalSubgoals} | ${r.totalUncertainties} | ${truncate(r.checkNote ?? "", 40)} |`,
);
}
}
lines.push("");
lines.push("## Scope");
lines.push("");
lines.push(
"Unlike τ-bench-lite, these tasks are single-turn reasoning problems (no user simulator, no DB, no tool calls). Checkers are deterministic — regex + set / value compare, never an LLM judge. The point is to isolate whether the Pillar 2 harvest step adds measurable value above plain reasoner usage.",
);
lines.push("");
lines.push(
"Interpretation: `baseline` (chat / V3) is a floor. `reasoner` shows the raw R1 gain. `reasoner-harvest` isolates the cost + quality delta from the extra V3 harvest call.",
);
return lines.join("\n");
}
/** Findings prose lives in report.md (hand-written after rendering); this stub keeps the function shape. */
export function renderFindings(_report: HarvestBenchReport): string {
return [
"",
"## Findings (v0.3, 18-run set)",
"",
"Two bands of tasks tried (easy: mod7 / flips / hats; hard: pseudoprime341 / D_7 / Euler quadratic). The hard band was chosen for *known V3 failure modes*. Result:",
"",
'1. **V3 chat passed all six tasks, including the three "hard" ones.** DeepSeek V3 knew 341 is the smallest base-2 pseudoprime, computed D_7=1854, and identified n=40 as the first Euler-polynomial failure. The tasks are well-known enough to be in training; the trap-answer variants (561, 265, 41) that the checkers specifically reject didn\'t fire.',
"2. **Reasoner cost 3.04× baseline for identical pass rates (6/6 both sides).** On this task set, R1 adds cost and latency without measurable quality. The cache-hit story *does* extend to reasoner (74.2% mean), so Pillar 1 generalizes to R1 — but that's not a Pillar 2 story.",
"3. **Harvest produced real signal** (mean 2.8 subgoals, 1.3 uncertainties per run where it fired) but didn't improve outcomes. One run hit the 300s timeout (bumped from 120s), suggesting reasoner-harvest latency is still unpredictable on some problems.",
"",
"### What this tells us about Pillar 2 positioning",
"",
"We've now given harvest two shots at showing answer-quality value on pure reasoning tasks. Both times V3 ate its lunch. This isn't a framework bug — it's a positioning signal:",
"",
'- **On well-known math / logic / counting problems, DeepSeek V3 is strong enough that paying for R1 is not justified by accuracy.** Pillar 2\'s "smart preset" cost multiplier (10×) quoted in the README is real but for most single-question Q/A it buys nothing.',
'- **Harvest\'s plausible value surfaces are not "better math answers".** More likely: (a) transparency / auditability for developers, (b) planning support when tools are in the mix, (c) driving branch-sampling on cases where uncertainty correlates with wrongness. None of those are tested here.',
"",
"### Recommendation",
"",
"Don't ship v0.3 on the \"harvest makes answers more correct\" claim — the data doesn't support it. Two honest paths forward:",
"",
"- **Reframe Pillar 2 as a developer-facing introspection feature** (debug visibility into R1's planning). Keep harvest opt-in; stop implying it improves accuracy on end-user tasks.",
"- **Move harvest eval to tool-use contexts** where uncertainty matters for *which tool to call next*, not *is this math right*. That's a new task shape — different harness, not a bigger task set here.",
"",
"In either case, the next Reasonix release is better served by MCP client (Pillar 1 leverage across the ecosystem) than by a bigger harvest-bench data push.",
"",
"### Notes",
"",
"- Cache hit on baseline runs surprised me (39.5% mean). That's DeepSeek's *cross-session* prompt cache: the same system prompt ran many times across modes and runs warmed the server-side cache. Real cross-session evidence that Cache-First's value isn't only per-session.",
"- 5-subgoals cap still hit uniformly. `HarvestOptions.maxItems` default is 5; harvest is truncating. Moot unless we find a setting where that matters.",
"",
].join("\n");
}
function pct(num: number, denom: number): string {
if (denom === 0) return "—";
return `${((num / denom) * 100).toFixed(0)}%`;
}
function pct1(x: number): string {
return `${(x * 100).toFixed(1)}%`;
}
function truncate(s: string, n: number): string {
return s.length > n ? `${s.slice(0, n)}…` : s;
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
const raw = readFileSync(args.input, "utf8");
const report = JSON.parse(raw) as HarvestBenchReport;
const md = renderReport(report) + renderFindings(report);
writeFileSync(args.outPath, md, "utf8");
console.log(`wrote ${args.outPath} (${report.results.length} runs)`);
}
function isMain(): boolean {
const entry = process.argv[1];
if (!entry) return false;
return import.meta.url === pathToFileURL(entry).href;
}
if (isMain()) {
main().catch((err) => {
console.error(err);
process.exit(1);
});
}
// Suppress unused import warning — kept in scope so ALL_MODES order matches renderer iteration.
export type { HarvestMode };
-305
View File
@@ -1,305 +0,0 @@
{
"meta": {
"date": "2026-04-21T16:44:21.011Z",
"repeatsPerTask": 1,
"taskCount": 6,
"modesRun": [
"baseline",
"reasoner",
"reasoner-harvest"
],
"reasonixVersion": "0.2.2"
},
"results": [
{
"taskId": "mod7_list",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Alright, let's go step-by-step.\n\n---\n\n## **Step 1: Problem restatement**\nWe want positive integers \\( n \\leq 100 \\) such that \n\\[\nn^2 + n + 1 \\equiv 0 \\pmod{7}.\n\\]\n\n---\n\n## **Step 2: Try residues modulo 7**\nLet \\( n \\equiv r \\pmod{7} \\), where \\( r \\in \\{0, 1, 2, 3, 4, 5, 6\\} \\).\n\nWe compute \\( r^2 + r + 1 \\mod 7 \\):\n\n- \\( r = 0 \\): \\( 0 + 0 + 1 = 1 \\) → not divisible by 7.\n- \\( r = 1 \\): \\( 1 + 1 + 1 = 3 \\) → no.\n- \\( r = 2 \\): \\( 4 + 2 + 1 = 7 \\equiv 0 \\) → yes.\n- \\( r = 3 \\): \\( 9 + 3 + 1 = 13 \\equiv 6 \\) → no.\n- \\( r = 4 \\): \\( 16 + 4 + 1 = 21 \\equiv 0 \\) → yes.\n- \\( r = 5 \\): \\( 25 + 5 + 1 = 31 \\equiv 3 \\) → no.\n- \\( r = 6 \\): \\( 36 + 6 + 1 = 43 \\equiv 1 \\) → no.\n\nSo \\( n \\equiv 2 \\pmod{7} \\) or \\( n \\equiv 4 \\pmod{7} \\).\n\n---\n\n## **Step 3: General form**\n\\[\nn \\equiv 2 \\pmod{7} \\quad \\text{or} \\quad n \\equiv 4 \\pmod{7}.\n\\]\n\nThat means \\( n = 7k + 2 \\) or \\( n = 7k + 4 \\) for some integer \\( k \\ge 0 \\).\n\n---\n\n## **Step 4: Positive integers \\( n \\leq 100 \\)**\n**Case 1:** \\( n = 7k + 2 \\), \\( n \\leq 100 \\), \\( k \\ge 0 \\).\n\n\\( 7k + 2 \\leq 100 \\) → \\( 7k \\leq 98 \\) → \\( k \\leq 14 \\).\n\nSo \\( k = 0, 1, 2, \\dots, 14 \\) gives \\( n = 2, 9, 16, \\dots, 100 \\).\n\nCheck \\( n=100 \\): \\( 7 \\times 14 + 2 = 98 + 2 = 100 \\) okay.\n\n---\n\n**Case 2:** \\( n = 7k + 4 \\), \\( n \\leq 100 \\), \\( k \\ge 0 \\).\n\n\\( 7k + 4 \\leq 100 \\) → \\( 7k \\leq 96 \\) → \\( k \\leq 13 \\) (since \\( 7 \\times 13 = 91 \\), \\( 91+4=95 \\), \\( 7\\times14=98 \\) → \\( 98+4=102>100 \\)).\n\nSo \\( k = 0, 1, 2, \\dots, 13 \\) gives \\( n = 4, 11, 18, \\dots, 95 \\).\n\n---\n\n## **Step 5: List all such \\( n \\leq 100 \\)**\nFrom case 1: \\( 2, 9, 16, 23, 30, 37, 44, 51, 58, 65, 72, 79, 86, 93, 100 \\).\n\nFrom case 2: \\( 4, 11, 18, 25, 32, 39, 46, 53, 60, 67, 74, 81, 88, 95 \\).\n\nCombine and sort:\n\n\\[\n2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100.\n\\]\n\n---\n\n## **Step 6: Check count**\nEach sequence has 15 and 14 terms respectively, total \\( 15 + 14 = 29 \\) numbers.\n\nCheck: \\( n=2 \\) works? \\( 4+2+1=7 \\) yes. \\( n=4 \\) works? \\( 16+4+1=21 \\) yes. \\( n=100 \\) works? \\( 10000+100+1=10101 \\), divide by 7: \\( 10101/7 = 1443 \\) yes.\n\n---\n\n**Final answer:**\n\\[\n\\boxed{2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100}\n\\]\n\n---\n\nAnswer: 2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100",
"turns": 1,
"cacheHitRatio": 0.8648648648648649,
"costUsd": 0.0013612800000000003,
"claudeEquivalentUsd": 0.018687,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "mod7_list",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The condition \\(n^2 + n + 1\\) divisible by 7 is equivalent to \\(n^2 + n + 1 \\equiv 0 \\pmod{7}\\). Testing residues modulo 7:\n\n- \\(n \\equiv 0: 0+0+1 \\equiv 1\\) \n- \\(n \\equiv 1: 1+1+1 \\equiv 3\\) \n- \\(n \\equiv 2: 4+2+1 \\equiv 7 \\equiv 0\\) \n- \\(n \\equiv 3: 9+3+1 \\equiv 13 \\equiv 6\\) \n- \\(n \\equiv 4: 16+4+1 \\equiv 21 \\equiv 0\\) \n- \\(n \\equiv 5: 25+5+1 \\equiv 31 \\equiv 3\\) \n- \\(n \\equiv 6: 36+6+1 \\equiv 43 \\equiv 1\\)\n\nThus, \\(n \\equiv 2\\) or \\(n \\equiv 4 \\pmod{7}\\) are the solutions modulo 7. For positive integers \\(n \\leq 100\\), we list all numbers congruent to 2 or 4 modulo 7 in increasing order.\n\nAnswer: 2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100",
"turns": 1,
"cacheHitRatio": 0.8648648648648649,
"costUsd": 0.00479742,
"claudeEquivalentUsd": 0.032982,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "mod7_list",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The congruence \\(n^2 + n + 1 \\equiv 0 \\pmod{7}\\) is solved by testing residues modulo 7. The solutions are \\(n \\equiv 2\\) and \\(n \\equiv 4 \\pmod{7}\\). For positive integers \\(n \\le 100\\), these yield \\(n = 7k + 2\\) with \\(k = 0, 1, \\dots, 14\\) and \\(n = 7k + 4\\) with \\(k = 0, 1, \\dots, 13\\).\n\nAnswer: 2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100",
"turns": 1,
"cacheHitRatio": 0.8648648648648649,
"costUsd": 0.00304542,
"claudeEquivalentUsd": 0.020982,
"harvestedTurns": 1,
"totalSubgoals": 4,
"totalUncertainties": 2,
"totalHypotheses": 2,
"totalRejectedPaths": 2
},
{
"taskId": "flips_until_3heads",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Alright, let's reason through this step-by-step.\n\n---\n\n## **Step 1: Define states**\nLet’s define states based on how many consecutive heads we have at the moment.\n\n- \\( E_0 \\): Expected flips to reach 3 heads in a row starting from 0 consecutive heads (or just starting, or after a tail).\n- \\( E_1 \\): Expected flips to reach 3 heads in a row starting from 1 consecutive head.\n- \\( E_2 \\): Expected flips to reach 3 heads in a row starting from 2 consecutive heads.\n\nWe want \\( E_0 \\).\n\n---\n\n## **Step 2: Transition equations**\nFrom \\( E_0 \\):\n- Flip H (prob \\( \\frac12 \\)) → go to state \\( E_1 \\), 1 flip used.\n- Flip T (prob \\( \\frac12 \\)) → stay in \\( E_0 \\), 1 flip used.\n\nSo:\n\\[\nE_0 = \\frac12 (1 + E_1) + \\frac12 (1 + E_0)\n\\]\n\n---\n\nFrom \\( E_1 \\) (already have 1 head):\n- Flip H (prob \\( \\frac12 \\)) → go to state \\( E_2 \\), 1 flip used.\n- Flip T (prob \\( \\frac12 \\)) → go to state \\( E_0 \\), 1 flip used.\n\nSo:\n\\[\nE_1 = \\frac12 (1 + E_2) + \\frac12 (1 + E_0)\n\\]\n\n---\n\nFrom \\( E_2 \\) (already have 2 heads):\n- Flip H (prob \\( \\frac12 \\)) → done (3 heads in a row), 1 flip used.\n- Flip T (prob \\( \\frac12 \\)) → go to state \\( E_0 \\), 1 flip used.\n\nSo:\n\\[\nE_2 = \\frac12 (1 + 0) + \\frac12 (1 + E_0)\n\\]\n\\[\nE_2 = \\frac12 \\cdot 1 + \\frac12 (1 + E_0) \\quad\\text{(Wait, careful:)}\n\\]\nActually: \nIf H: \\( 1 \\) flip and done. \nIf T: \\( 1 \\) flip and then \\( E_0 \\) more.\n\nSo:\n\\[\nE_2 = \\frac12 \\cdot 1 + \\frac12 (1 + E_0)\n\\]\nCheck: \nH: 1 flip → total 1, done. Contribution: \\( \\frac12 \\times 1 \\). \nT: 1 flip + \\( E_0 \\) more → total \\( 1 + E_0 \\). Contribution: \\( \\frac12 \\times (1 + E_0) \\).\n\nYes:\n\\[\nE_2 = \\frac12 \\cdot 1 + \\frac12 (1 + E_0) = \\frac12 + \\frac12 + \\frac12 E_0 = 1 + \\frac{E_0}{2}.\n\\]\n\n---\n\n## **Step 3: Solve system**\nWe have:\n\n(1) \\( E_0 = \\frac12 (1 + E_1) + \\frac12 (1 + E_0) \\) \nSimplify: \\( E_0 = 1 + \\frac12 E_1 + \\frac12 E_0 \\) \nMultiply by 2: \\( 2E_0 = 2 + E_1 + E_0 \\) \nSo \\( E_0 - E_1 = 2 \\) … (Eq A)\n\n---\n\n(2) \\( E_1 = \\frac12 (1 + E_2) + \\frac12 (1 + E_0) \\) \nSimplify: \\( E_1 = 1 + \\frac12 E_2 + \\frac12 E_0 \\) … (Eq B)\n\n---\n\n(3) \\( E_2 = 1 + \\frac12 E_0 \\) … (Eq C)\n\n---\n\nFrom Eq C into Eq B:\n\\[\nE_1 = 1 + \\frac12 \\left( 1 + \\frac12 E_0 \\right) + \\frac12 E_0\n\\]\n\\[\nE_1 = 1 + \\frac12 + \\frac14 E_0 + \\frac12 E_0\n\\]\n\\[\nE_1 = \\frac32 + \\frac34 E_0\n\\]\n\n---\n\nFrom Eq A: \\( E_0 - E_1 = 2 \\) \nSubstitute \\( E_1 \\):\n\\[\nE_0 - \\left( \\frac32 + \\frac34 E_0 \\right) = 2\n\\]\n\\[\nE_0 - \\frac32 - \\frac34 E_0 = 2\n\\]\n\\[\n\\frac14 E_0 - \\frac32 = 2\n\\]\n\\[\n\\frac14 E_0 = 2 + \\frac32 = \\frac72\n\\]\n\\[\nE_0 = 14\n\\]\n\n---\n\n## **Step 4: Conclusion**\nThe expected number of flips until we get 3 heads in a row is \\( 14 \\).\n\n---\n\n**Answer:** 14",
"turns": 1,
"cacheHitRatio": 0.927536231884058,
"costUsd": 0.00119823,
"claudeEquivalentUsd": 0.016467,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "flips_until_3heads",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The expected number of flips required to get three consecutive heads is 14, derived from solving the system of linear equations for the Markov chain states representing the current streak of heads.\n\nAnswer: 14",
"turns": 1,
"cacheHitRatio": 0.927536231884058,
"costUsd": 0.00283024,
"claudeEquivalentUsd": 0.019512,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "flips_until_3heads",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The expected number of flips until three consecutive heads appear is 14.\n\nAnswer: 14",
"turns": 1,
"cacheHitRatio": 0.927536231884058,
"costUsd": 0.00169144,
"claudeEquivalentUsd": 0.011712,
"harvestedTurns": 1,
"totalSubgoals": 4,
"totalUncertainties": 0,
"totalHypotheses": 2,
"totalRejectedPaths": 0
},
{
"taskId": "three_hats",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Let's break this down step by step.\n\n---\n\n**Step 1: Understanding the setup** \nThree people: A (first), B (second), C (third). \nEach hat is red (R) or blue (B). \nThey know: at least one hat is red. \nEach sees the other two hats, not their own. \nThey are asked in order: \"Do you know your hat color?\" \nA answers no, B answers no, C answers yes. \nWe want C’s hat color.\n\n---\n\n**Step 2: From A’s perspective when asked** \nA sees B and C. \nIf A had seen two blue hats, then A would know: \"At least one red hat means my hat must be red.\" \nSo A says \"no\" → A did **not** see two blue hats. \nThus A sees at least one red hat on {B, C}.\n\nPossible cases for what A sees (B, C): \n(R, R), (R, B), (B, R) — all have at least one red.\n\n---\n\n**Step 3: B’s reasoning when asked** \nB hears A say \"no\". \nB sees A and C. \n\nLet’s consider B’s possible deductions from A’s \"no\": \nB knows: If A had seen two blues, A would have said yes. Since A said no, A saw at least one red among B and C. \nBut B sees A and C. \n\nFrom B’s viewpoint: \n- If B saw C with blue and A with blue, then B would know: \"A saw me and C both blue → impossible because A said no.\" But B doesn’t see that because if B saw A blue and C blue, then B would know his own hat must be red (since at least one red total). But then B would answer yes. \nSo B’s \"no\" means B did **not** see A and C both blue. \n\nAlso, B considers: Could my hat be blue? Let’s check: \nSuppose B sees A red, C blue. Then B thinks: \"If my hat were blue, then A would have seen (B blue, C blue) → A would have said yes. But A said no, so my hat cannot be blue.\" \nSo if B saw (A red, C blue), B would deduce: \"My hat must be red.\" Then B would answer yes. \nBut B said no → so B did **not** see (A red, C blue).\n\nSimilarly, if B saw (A blue, C red): \nThen B thinks: \"If my hat were blue, then A would have seen (B blue, C red) → that’s fine (A sees one red on C), so A would still say no. If my hat were red, then A would see (B red, C red) → A would still say no. So I don’t know.\" That’s consistent with B saying no. \n\nIf B saw (A red, C red): \nThen B thinks: \"If my hat were blue, A sees (B blue, C red) → A says no. If my hat were red, A sees (B red, C red) → A says no. So I don’t know.\" That’s also consistent with B saying no.\n\nSo B says no in cases: \nB sees (A blue, C red) or (A red, C red). \nB would say yes if B saw (A red, C blue) — but that didn’t happen. \n\n---\n\n**Step 4: C’s reasoning** \nC hears A says no, B says no. \nC sees A and B. \n\nFrom C’s viewpoint: \nLet’s list all possible (A, B, C) hat colorings with at least one red, consistent with A’s \"no\" (which we already incorporated: A sees at least one red on B/C) and B’s \"no\" (meaning B didn’t see A red, C blue — because that would make B know).\n\nPossible cases for (A, B) that C could see: \n\n1. C sees (A blue, B red): \n Then C thinks: \n - If C were blue: (A blue, B red, C blue) → A sees (B red, C blue) → A says no. B sees (A blue, C blue) → B sees two blues? Wait, B sees A blue, C blue → then B knows his own hat is red (since at least one red total) → B would say yes. But B said no → contradiction. So C cannot be blue. \n So C must be red. \n\n2. C sees (A red, B blue): \n Then C thinks: \n - If C were blue: (A red, B blue, C blue) → A sees (B blue, C blue) → A would say yes (since at least one red total means A’s hat must be red). But A said no → contradiction. So C cannot be blue. \n So C must be red. \n\n3. C sees (A red, B red): \n Then C thinks: \n - If C were blue: (A red, B red, C blue) → A sees (B red, C blue) → A says no. B sees (A red, C blue) → B sees A red, C blue → earlier we said: If B sees A red, C blue, then B would deduce his own hat is red (reasoning: if B were blue, A would have seen two blues and said yes, but A said no, so B can’t be blue) → so B would say yes. But B actually said no → contradiction. So C cannot be blue. \n - If C were red: (A red, B red, C red) → A sees (B red, C red) → A says no. B sees (A red, C red) → B says no. Works fine. \n\nSo in all cases C sees for (A, B), C can deduce C’s hat is **red** because assuming C is blue leads to contradiction with B’s \"no\" (in cases 1 and 3) or with A’s \"no\" (in case 2).\n\n---\n\n**Step 5: Conclusion** \nC answers yes, and C’s hat must be red.\n\n---\n\nAnswer: red",
"turns": 1,
"cacheHitRatio": 0.5765765765765766,
"costUsd": 0.0015142700000000003,
"claudeEquivalentUsd": 0.020748,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "three_hats",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Answer: red",
"turns": 1,
"cacheHitRatio": 0.5765765765765766,
"costUsd": 0.009340119999999999,
"claudeEquivalentUsd": 0.064068,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "three_hats",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The third person deduces their hat color based on the previous responses. Since the first two answer \"no,\" it implies they each see at least one red hat and cannot determine their own color. Specifically, the second person's \"no\" indicates they see the third person's hat as red; otherwise, they would have known their own hat color. Therefore, the third person's hat must be red.\n\nAnswer: red",
"turns": 1,
"cacheHitRatio": 0.5765765765765766,
"costUsd": 0.0096511,
"claudeEquivalentUsd": 0.066198,
"harvestedTurns": 1,
"totalSubgoals": 3,
"totalUncertainties": 2,
"totalHypotheses": 3,
"totalRejectedPaths": 3
},
{
"taskId": "pseudoprime_base2",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Alright, let's go step-by-step.\n\n---\n\n**Step 1: Understanding the problem**\n\nWe want the smallest composite integer \\( n > 1 \\) such that\n\n\\[\n2^n \\equiv 2 \\pmod{n}.\n\\]\n\nEquivalently, \\( 2^{n-1} \\equiv 1 \\pmod{n} \\) for composite \\( n \\).\n\nThis means \\( n \\) is a **Fermat pseudoprime to base 2**.\n\nWe check composite numbers starting from the smallest.\n\n---\n\n**Step 2: Check small composites**\n\n- \\( n = 4 \\): composite. \n\\( 2^4 = 16 \\), \\( 16 \\mod 4 = 0 \\), not \\( 2 \\). So \\( 2^4 \\equiv 0 \\not\\equiv 2 \\pmod{4} \\). Fails.\n\n- \\( n = 6 \\): composite. \n\\( 2^6 = 64 \\), \\( 64 \\mod 6 = 4 \\), not \\( 2 \\). Fails.\n\n- \\( n = 8 \\): composite. \n\\( 2^8 = 256 \\), \\( 256 \\mod 8 = 0 \\), not \\( 2 \\). Fails.\n\n- \\( n = 9 \\): composite. \n\\( 2^9 = 512 \\), \\( 512 \\mod 9 \\): \n\\( 512 \\div 9 \\), \\( 9 \\times 56 = 504 \\), remainder \\( 8 \\), not \\( 2 \\). Fails.\n\n- \\( n = 10 \\): composite. \n\\( 2^{10} = 1024 \\), \\( 1024 \\mod 10 = 4 \\), not \\( 2 \\). Fails.\n\n---\n\n**Step 3: Try n = 15**\n\n\\( n = 15 \\): composite. \n\\( 2^{15} = 32768 \\). \nCheck mod 15: \nWe can use mod arithmetic: \n\\( 2^4 = 16 \\equiv 1 \\pmod{15} \\)?? Wait, check: \\( 16 \\mod 15 = 1 \\), yes. \nSo \\( 2^{15} = (2^4)^3 \\times 2^3 = 1^3 \\times 8 = 8 \\pmod{15} \\). \nSo \\( 2^{15} \\equiv 8 \\not\\equiv 2 \\pmod{15} \\). Fails.\n\n---\n\n**Step 4: Try n = 21**\n\n\\( n = 21 \\): composite. \nMod 21: \n\\( 2^6 = 64 \\equiv 1 \\pmod{21} \\)? Check: \\( 64 \\div 21 = 3 \\times 21 = 63 \\), remainder 1, yes. \nSo \\( 2^{21} = (2^6)^3 \\times 2^3 \\equiv 1^3 \\times 8 = 8 \\pmod{21} \\). Not 2. Fails.\n\n---\n\n**Step 5: Try n = 22**\n\n\\( n = 22 \\): composite. \nUse mod 22: \nEuler’s totient not needed, just check order: \n\\( 2^5 = 32 \\equiv 10 \\pmod{22} \\) \n\\( 2^{10} = (2^5)^2 \\equiv 10^2 = 100 \\equiv 12 \\pmod{22} \\) \n\\( 2^{11} \\equiv 24 \\equiv 2 \\pmod{22} \\) \nSo \\( 2^{22} = (2^{11})^2 \\equiv 2^2 = 4 \\pmod{22} \\). Not 2. Fails.\n\n---\n\n**Step 6: Try n = 25**\n\n\\( n = 25 \\): composite. \nCheck mod 25: \n\\( 2^{10} = 1024 \\equiv 24 \\pmod{25} \\) (since \\( 1000 \\equiv 0 \\), \\( 24 \\equiv -1 \\)) \nActually check: \\( 1024 - 1000 = 24 \\), yes \\( 24 \\equiv -1 \\). \nSo \\( 2^{20} \\equiv 1 \\pmod{25} \\). \nThus \\( 2^{25} = 2^{20} \\times 2^5 \\equiv 1 \\times 32 = 7 \\pmod{25} \\). Not 2. Fails.\n\n---\n\n**Step 7: Known smallest base-2 Fermat pseudoprime**\n\nFrom known number theory facts: \nThe smallest Fermat pseudoprime to base 2 is \\( n = 341 \\). \nBut let's check smaller ones just in case I’m skipping one.\n\n---\n\n**Step 8: Try n = 91**\n\n91 = 7 × 13. \nCheck mod 7: \\( 2^{91} \\equiv (2^6)^{15} \\times 2^1 \\equiv 1^{15} \\times 2 = 2 \\pmod{7} \\). \nCheck mod 13: \\( 2^{12} \\equiv 1 \\pmod{13} \\), \n\\( 91 = 12 \\times 7 + 7 \\), so \\( 2^{91} \\equiv 2^7 = 128 \\equiv 11 \\pmod{13} \\). \nFor \\( 2^{91} \\equiv 2 \\pmod{91} \\), we need \\( 2^{91} \\equiv 2 \\) mod 7 and mod 13. \nMod 13 we got 11, not 2. So fails.\n\n---\n\n**Step 9: Try n = 341**\n\n341 = 11 × 31. \nCheck mod 11: \\( 2^{10} \\equiv 1 \\pmod{11} \\), \n\\( 341 = 10 \\times 34 + 1 \\), so \\( 2^{341} \\equiv 2^1 = 2 \\pmod{11} \\). Good. \nCheck mod 31: \\( 2^5 = 32 \\equiv 1 \\pmod{31} \\), \n\\( 341 = 5 \\times 68 + 1 \\), so \\( 2^{341} \\equiv 2^1 = 2 \\pmod{31} \\). \nSo \\( 2^{341} \\equiv 2 \\) mod 11 and mod 31, hence mod 341. \nThus \\( 341 \\) works.\n\n---\n\n**Step 10: Check smaller than 341**\n\nKnown list: 341 is smallest. Let’s check a candidate like 121 = 11^2: \n\\( 2^{121} \\mod 121 \\): \nMod 11: \\( 2^{10} \\equiv 1 \\), \\( 121 = 10 \\times 12 + 1 \\), so \\( 2^{121} \\equiv 2 \\pmod{11} \\). \nBut for modulus 121, need more: \nActually, \\( 2^{110} \\equiv 1 \\pmod{121} \\) by Euler’s theorem? Not exactly, but known: 121 is not a pseudoprime base 2. Quick check: \n\\( 2^{121} - 2 \\) divisible by 121? Probably not. Let’s skip detailed check; known fact is 341 is smallest.\n\n---\n\n**Step 11: Verify no smaller composite works**\n\nFrom known sequence A001567: \nFirst few base-2 Fermat pseudoprimes: 341, 561, 645, 1105, … \nSo smallest is 341.\n\n---\n\n**Step 12: Conclusion**\n\nThe smallest composite \\( n > 1 \\) with \\( 2^n \\equiv 2 \\pmod{n} \\) is \\( n = 341 \\).\n\n---\n\n**Answer:** 341",
"turns": 1,
"cacheHitRatio": 0,
"costUsd": 0.0018940500000000002,
"claudeEquivalentUsd": 0.02577,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "pseudoprime_base2",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The smallest composite integer \\(n > 1\\) satisfying \\(2^n \\equiv 2 \\pmod{n}\\) is \\(n = 341\\). This is composite (\\(341 = 11 \\times 31\\)), and it satisfies the congruence because \\(2^{341} \\equiv 2 \\pmod{11}\\) and \\(2^{341} \\equiv 2 \\pmod{31}\\) by Fermat's little theorem, implying \\(2^{341} \\equiv 2 \\pmod{341}\\). All smaller composite integers (e.g., 4, 6, 8, 9, 10, 15, 21) fail to satisfy the condition.\n\nAnswer: 341",
"turns": 1,
"cacheHitRatio": 0.7529411764705882,
"costUsd": 0.0031281200000000003,
"claudeEquivalentUsd": 0.02154,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "pseudoprime_base2",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "fail",
"checkNote": "This operation was aborted",
"finalAgentMessage": "",
"turns": 0,
"cacheHitRatio": 0,
"costUsd": 0,
"claudeEquivalentUsd": 0,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0,
"errorMessage": "This operation was aborted"
},
{
"taskId": "derangements_d7",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Alright, let's go step-by-step.\n\n---\n\n**Step 1: Understanding the problem**\n\nWe want the number of permutations of \\(\\{1, 2, 3, 4, 5, 6, 7\\}\\) with **no fixed points**. \nA fixed point means \\(\\pi(i) = i\\) for some \\(i\\). \nA permutation with no fixed points is called a **derangement**. \nThe number of derangements of \\(n\\) elements is denoted \\(D_n\\) or \\(!n\\).\n\n---\n\n**Step 2: Formula for derangements**\n\nThe formula for \\(D_n\\) is:\n\n\\[\nD_n = n! \\sum_{k=0}^{n} \\frac{(-1)^k}{k!}\n\\]\n\nFor \\(n=7\\):\n\n\\[\nD_7 = 7! \\left( \\frac{1}{0!} - \\frac{1}{1!} + \\frac{1}{2!} - \\frac{1}{3!} + \\frac{1}{4!} - \\frac{1}{5!} + \\frac{1}{6!} - \\frac{1}{7!} \\right)\n\\]\n\n---\n\n**Step 3: Compute step-by-step**\n\nFirst, \\(7! = 5040\\).\n\nNow compute the sum:\n\n\\[\n\\sum_{k=0}^{7} \\frac{(-1)^k}{k!} \n= 1 - 1 + \\frac{1}{2} - \\frac{1}{6} + \\frac{1}{24} - \\frac{1}{120} + \\frac{1}{720} - \\frac{1}{5040}\n\\]\n\nLet's compute term-by-term:\n\n- \\(1 - 1 = 0\\)\n- \\(0 + 0.5 = 0.5\\)\n- \\(0.5 - \\frac{1}{6} \\approx 0.5 - 0.1666667 = 0.3333333\\)\n- \\(0.3333333 + \\frac{1}{24} \\approx 0.3333333 + 0.0416667 = 0.375\\)\n- \\(0.375 - \\frac{1}{120} \\approx 0.375 - 0.0083333 = 0.3666667\\)\n- \\(0.3666667 + \\frac{1}{720} \\approx 0.3666667 + 0.0013889 = 0.3680556\\)\n- \\(0.3680556 - \\frac{1}{5040} \\approx 0.3680556 - 0.0001984 = 0.3678572\\)\n\nSo the sum is approximately \\(0.367857142857...\\)\n\n---\n\n**Step 4: Multiply by \\(7!\\)**\n\n\\[\nD_7 = 5040 \\times 0.367857142857\\ldots\n\\]\n\nLet's compute exactly using fractions:\n\n\\[\n\\sum_{k=0}^{7} \\frac{(-1)^k}{k!} \n= \\frac{1}{2!} - \\frac{1}{3!} + \\frac{1}{4!} - \\frac{1}{5!} + \\frac{1}{6!} - \\frac{1}{7!}\n\\]\n\nWrite with common denominator \\(7! = 5040\\):\n\n- \\(\\frac{1}{2!} = \\frac{2520}{5040}\\)\n- \\(\\frac{1}{3!} = \\frac{840}{5040}\\)\n- \\(\\frac{1}{4!} = \\frac{210}{5040}\\)\n- \\(\\frac{1}{5!} = \\frac{42}{5040}\\)\n- \\(\\frac{1}{6!} = \\frac{7}{5040}\\)\n- \\(\\frac{1}{7!} = \\frac{1}{5040}\\)\n\nNow alternate signs:\n\n\\[\n\\left( \\frac{2520}{5040} - \\frac{840}{5040} \\right) \n= \\frac{1680}{5040}\n\\]\n\\[\n\\frac{1680}{5040} + \\frac{210}{5040} = \\frac{1890}{5040}\n\\]\n\\[\n\\frac{1890}{5040} - \\frac{42}{5040} = \\frac{1848}{5040}\n\\]\n\\[\n\\frac{1848}{5040} + \\frac{7}{5040} = \\frac{1855}{5040}\n\\]\n\\[\n\\frac{1855}{5040} - \\frac{1}{5040} = \\frac{1854}{5040}\n\\]\n\nSo the sum is \\(\\frac{1854}{5040}\\).\n\n---\n\n**Step 5: Multiply by \\(7!\\)**\n\n\\[\nD_7 = 5040 \\times \\frac{1854}{5040} = 1854\n\\]\n\n---\n\n**Step 6: Quick check with known derangement numbers**\n\nKnown small derangements: \n\\(D_1 = 0, D_2 = 1, D_3 = 2, D_4 = 9, D_5 = 44, D_6 = 265, D_7 = 1854\\). \nYes, matches known sequence.\n\n---\n\n**Final answer:**\n\nAnswer: 1854",
"turns": 1,
"cacheHitRatio": 0,
"costUsd": 0.00127253,
"claudeEquivalentUsd": 0.017292,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "derangements_d7",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The number of derangements of \\(n\\) distinct objects, denoted \\(D_n\\), counts permutations with no fixed points. For \\(n = 7\\), this can be computed using the recurrence \\(D_n = (n-1)(D_{n-1} + D_{n-2})\\) with initial values \\(D_1 = 0\\) and \\(D_2 = 1\\). \nThus: \n\\(D_3 = 2(1+0) = 2\\), \n\\(D_4 = 3(2+1) = 9\\), \n\\(D_5 = 4(9+2) = 44\\), \n\\(D_6 = 5(44+9) = 265\\), \n\\(D_7 = 6(265+44) = 1854\\).\n\nAnswer: 1854",
"turns": 1,
"cacheHitRatio": 0.7191011235955056,
"costUsd": 0.00349167,
"claudeEquivalentUsd": 0.024027,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "derangements_d7",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The number of derangements of \\(n\\) elements, denoted \\(D_n\\), counts permutations with no fixed points. For \\(n=7\\), this can be computed using the recurrence \\(D_n = (n-1)(D_{n-1} + D_{n-2})\\) with initial values \\(D_0 = 1\\) and \\(D_1 = 0\\). Applying the recurrence yields \\(D_2 = 1\\), \\(D_3 = 2\\), \\(D_4 = 9\\), \\(D_5 = 44\\), \\(D_6 = 265\\), and finally \\(D_7 = 6 \\times (265 + 44) = 1854\\).\n\nAnswer: 1854",
"turns": 1,
"cacheHitRatio": 0.7191011235955056,
"costUsd": 0.0028434299999999997,
"claudeEquivalentUsd": 0.019587,
"harvestedTurns": 1,
"totalSubgoals": 3,
"totalUncertainties": 2,
"totalHypotheses": 2,
"totalRejectedPaths": 2
},
{
"taskId": "euler_quadratic_break",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Let’s check \\( f(n) = n^2 + n + 41 \\) for small \\( n \\):\n\n- \\( n = 0 \\): \\( f(0) = 41 \\) (prime) \n- \\( n = 1 \\): \\( f(1) = 1 + 1 + 41 = 43 \\) (prime) \n- \\( n = 2 \\): \\( f(2) = 4 + 2 + 41 = 47 \\) (prime) \n- \\( n = 3 \\): \\( f(3) = 9 + 3 + 41 = 53 \\) (prime) \n- \\( n = 4 \\): \\( f(4) = 16 + 4 + 41 = 61 \\) (prime) \n- \\( n = 5 \\): \\( f(5) = 25 + 5 + 41 = 71 \\) (prime) \n- \\( n = 6 \\): \\( f(6) = 36 + 6 + 41 = 83 \\) (prime) \n- \\( n = 7 \\): \\( f(7) = 49 + 7 + 41 = 97 \\) (prime) \n- \\( n = 8 \\): \\( f(8) = 64 + 8 + 41 = 113 \\) (prime) \n- \\( n = 9 \\): \\( f(9) = 81 + 9 + 41 = 131 \\) (prime) \n- \\( n = 10 \\): \\( f(10) = 100 + 10 + 41 = 151 \\) (prime) \n\nWe can keep going, but the first known counterexample for this famous Euler polynomial is \\( n = 40 \\), because \n\\[\nf(40) = 40^2 + 40 + 41 = 1600 + 40 + 41 = 1681.\n\\] \nCheck if \\( 1681 \\) is prime: \n\\( 1681 = 41^2 \\) (since \\( 41 \\times 41 = 1681 \\)), so it’s composite.\n\nBut wait — let’s check if there’s a smaller \\( n \\) where \\( f(n) \\) is composite. \nWe can test \\( n = 41 \\): \n\\( f(41) = 41^2 + 41 + 41 = 1681 + 82 = 1763 \\), which is \\( 41 \\times 43 \\) (since \\( 1763/41 = 43 \\)), so composite. But \\( n = 41 \\) is larger than \\( n = 40 \\).\n\nCheck \\( n = 39 \\): \\( f(39) = 1521 + 39 + 41 = 1601 \\). Test divisibility: not divisible by primes up to \\( \\sqrt{1601} \\approx 40 \\), seems prime. \n\nCheck \\( n = 40 \\) is indeed the first composite? Let’s check \\( n = 1 \\) to \\( 39 \\) quickly for a smaller counterexample: \nWe can note \\( f(n) = n(n+1) + 41 \\). If \\( 41 \\mid f(n) \\), then \\( 41 \\mid n(n+1) \\). \nThat happens when \\( n \\equiv 0 \\pmod{41} \\) or \\( n \\equiv 40 \\pmod{41} \\). \nThe smallest positive such \\( n \\) is \\( n = 40 \\) (since \\( n=41 \\) is larger). \nSo for \\( n = 40 \\), \\( f(40) = 40 \\times 41 + 41 = 41 \\times 41 \\) is composite. \n\nCheck \\( n = 0 \\) to \\( 39 \\): no multiple of 41 except \\( n=0 \\) (which gives 41, prime). So \\( n=40 \\) is indeed the first nonnegative integer where \\( f(n) \\) is composite.\n\nThus smallest \\( n \\) is \\( 40 \\), \\( f(40) = 1681 = 41^2 \\).\n\n**Answer:** 40",
"turns": 1,
"cacheHitRatio": 0,
"costUsd": 0.00098535,
"claudeEquivalentUsd": 0.013365,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "euler_quadratic_break",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The smallest nonnegative integer \\(n\\) for which \\(f(n) = n^2 + n + 41\\) is composite is \\(n = 40\\). At this value, \\(f(40) = 40^2 + 40 + 41 = 1681 = 41^2\\), which is not prime.\n\nAnswer: 40",
"turns": 1,
"cacheHitRatio": 0.6095238095238096,
"costUsd": 0.0014309199999999998,
"claudeEquivalentUsd": 0.0099,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "euler_quadratic_break",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The polynomial \\(f(n) = n^2 + n + 41\\) is known to produce primes for \\(n = 0, 1, 2, \\dots, 39\\). At \\(n = 40\\), we have \\(f(40) = 40^2 + 40 + 41 = 1681\\), and \\(1681 = 41^2\\), which is composite. Therefore, \\(n = 40\\) is the smallest nonnegative integer where \\(f(n)\\) fails to be prime.\n\nAnswer: 40",
"turns": 1,
"cacheHitRatio": 0.6095238095238096,
"costUsd": 0.0025938099999999998,
"claudeEquivalentUsd": 0.017865,
"harvestedTurns": 1,
"totalSubgoals": 3,
"totalUncertainties": 2,
"totalHypotheses": 3,
"totalRejectedPaths": 2
}
]
}
-291
View File
@@ -1,291 +0,0 @@
/** Harvest-bench runner — writes results.json. CLI flags + sample invocations in benchmarks/README.md. */
import { type WriteStream, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import {
CacheFirstLoop,
DeepSeekClient,
ImmutablePrefix,
claudeEquivalentCost,
loadDotenv,
} from "../../src/index.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../src/transcript/log.js";
import { TASKS } from "./tasks.js";
import type {
HarvestBenchMeta,
HarvestBenchReport,
HarvestMode,
HarvestRunResult,
HarvestTask,
} from "./types.js";
import { ALL_MODES } from "./types.js";
loadDotenv();
interface CliArgs {
taskFilter: string | null;
modes: HarvestMode[];
repeats: number;
outPath: string | null;
transcriptsDir: string | null;
/** Per-HTTP-call timeout in ms. Default 300_000 (5 min) — reasoner + harvest runs legitimately need this. */
timeoutMs: number;
dry: boolean;
verbose: boolean;
}
function parseArgs(argv: string[]): CliArgs {
const out: CliArgs = {
taskFilter: null,
modes: [...ALL_MODES],
repeats: 1,
outPath: null,
transcriptsDir: null,
timeoutMs: 300_000,
dry: false,
verbose: false,
};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "--task") out.taskFilter = argv[++i] ?? null;
else if (a === "--mode") {
const v = (argv[++i] ?? "").toLowerCase() as HarvestMode;
if ((ALL_MODES as string[]).includes(v)) out.modes = [v];
} else if (a === "--repeats") out.repeats = Number.parseInt(argv[++i] ?? "1", 10);
else if (a === "--out") out.outPath = argv[++i] ?? null;
else if (a === "--transcripts-dir") out.transcriptsDir = argv[++i] ?? null;
else if (a === "--timeout") {
// Accept seconds for humans, convert to ms internally.
const secs = Number.parseInt(argv[++i] ?? "300", 10);
if (Number.isFinite(secs) && secs > 0) out.timeoutMs = secs * 1000;
} else if (a === "--dry") out.dry = true;
else if (a === "--verbose" || a === "-v") out.verbose = true;
}
return out;
}
function modelForMode(mode: HarvestMode): string {
if (mode === "baseline") return "deepseek-chat";
return "deepseek-reasoner";
}
function harvestForMode(mode: HarvestMode): boolean {
return mode === "reasoner-harvest";
}
async function runOnce(
task: HarvestTask,
mode: HarvestMode,
rep: number,
client: DeepSeekClient,
transcriptStream: WriteStream | null,
): Promise<HarvestRunResult> {
const model = modelForMode(mode);
const harvest = harvestForMode(mode);
const prefix = new ImmutablePrefix({ system: task.systemPrompt });
const loop = new CacheFirstLoop({
client,
prefix,
model,
harvest,
stream: false,
});
const prefixHash = prefix.fingerprint;
let harvestedTurns = 0;
let totalSubgoals = 0;
let totalUncertainties = 0;
let totalHypotheses = 0;
let totalRejectedPaths = 0;
let finalText = "";
let errorMessage: string | undefined;
if (transcriptStream) {
writeRecord(transcriptStream, {
ts: new Date().toISOString(),
turn: 1,
role: "user",
content: task.prompt,
});
}
try {
for await (const ev of loop.step(task.prompt)) {
if (transcriptStream && ev.role !== "assistant_delta") {
writeRecord(transcriptStream, recordFromLoopEvent(ev, { model, prefixHash }));
}
if (ev.role === "assistant_final") {
finalText = ev.content;
if (ev.planState) {
if (
ev.planState.subgoals.length +
ev.planState.hypotheses.length +
ev.planState.uncertainties.length +
ev.planState.rejectedPaths.length >
0
) {
harvestedTurns++;
totalSubgoals += ev.planState.subgoals.length;
totalHypotheses += ev.planState.hypotheses.length;
totalUncertainties += ev.planState.uncertainties.length;
totalRejectedPaths += ev.planState.rejectedPaths.length;
}
}
} else if (ev.role === "done") {
finalText = ev.content || finalText;
break;
} else if (ev.role === "error") {
throw new Error(ev.error ?? "loop error");
}
}
} catch (err) {
errorMessage = (err as Error).message;
}
const verdict = errorMessage
? { verdict: "fail" as const, note: errorMessage }
: task.check(finalText);
return {
taskId: task.id,
mode,
repeat: rep + 1,
verdict: verdict.verdict,
checkNote: verdict.note,
finalAgentMessage: finalText,
turns: loop.stats.turns.length,
cacheHitRatio: loop.stats.aggregateCacheHitRatio,
costUsd: loop.stats.totalCost,
claudeEquivalentUsd: loop.stats.turns.reduce((s, t) => s + claudeEquivalentCost(t.usage), 0),
harvestedTurns,
totalSubgoals,
totalUncertainties,
totalHypotheses,
totalRejectedPaths,
errorMessage,
};
}
function runDry(args: CliArgs): HarvestBenchReport {
const tasks = filterTasks(args.taskFilter);
const results: HarvestRunResult[] = [];
for (const task of tasks) {
// Exercise each checker with a deliberately wrong reply so we know
// the wiring is live — not a pass on empty.
const sanity = task.check("Answer: this is not the right answer at all");
console.log(`[${task.id}] checker exercises ok (sanity verdict=${sanity.verdict})`);
for (const mode of args.modes) {
results.push({
taskId: task.id,
mode,
repeat: 1,
verdict: "inconclusive",
checkNote: "dry-run (no model call)",
finalAgentMessage: "[dry-run]",
turns: 0,
cacheHitRatio: 0,
costUsd: 0,
claudeEquivalentUsd: 0,
harvestedTurns: 0,
totalSubgoals: 0,
totalUncertainties: 0,
totalHypotheses: 0,
totalRejectedPaths: 0,
});
}
}
return { meta: buildMeta(args, tasks.length), results };
}
function filterTasks(filter: string | null): HarvestTask[] {
if (!filter) return TASKS;
const t = TASKS.find((x) => x.id === filter);
if (!t) throw new Error(`unknown task: ${filter}`);
return [t];
}
function buildMeta(args: CliArgs, taskCount: number): HarvestBenchMeta {
return {
date: new Date().toISOString(),
repeatsPerTask: args.repeats,
taskCount,
modesRun: args.modes,
reasonixVersion: "0.2.2",
};
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
if (args.dry) {
const report = runDry(args);
writeReport(report, args.outPath);
return;
}
const client = new DeepSeekClient({ timeoutMs: args.timeoutMs });
const tasks = filterTasks(args.taskFilter);
if (args.transcriptsDir) mkdirSync(args.transcriptsDir, { recursive: true });
const results: HarvestRunResult[] = [];
for (const task of tasks) {
for (let rep = 0; rep < args.repeats; rep++) {
for (const mode of args.modes) {
let stream: WriteStream | null = null;
if (args.transcriptsDir) {
const fname = `${task.id}.${mode}.r${rep + 1}.jsonl`;
stream = openTranscriptFile(join(args.transcriptsDir, fname), {
version: 1,
source: `harvest-bench/${mode}`,
model: modelForMode(mode),
task: task.id,
mode,
repeat: rep + 1,
startedAt: new Date().toISOString(),
});
}
const started = Date.now();
let result: HarvestRunResult;
try {
result = await runOnce(task, mode, rep, client, stream);
} finally {
stream?.end();
}
const elapsed = ((Date.now() - started) / 1000).toFixed(1);
const note = result.checkNote ? ` ${result.checkNote}` : "";
console.log(
`[${task.id}/${mode}/r${rep + 1}] verdict=${result.verdict} cache=${(result.cacheHitRatio * 100).toFixed(1)}% cost=$${result.costUsd.toFixed(6)} harvest=${result.harvestedTurns}:${result.totalSubgoals}s/${result.totalUncertainties}u (${elapsed}s)${note}`,
);
results.push(result);
}
}
}
const report: HarvestBenchReport = { meta: buildMeta(args, tasks.length), results };
writeReport(report, args.outPath);
}
function writeReport(report: HarvestBenchReport, outPath: string | null): void {
const path =
outPath ?? `benchmarks/harvest/results-${new Date().toISOString().replace(/[:.]/g, "-")}.json`;
writeFileSync(path, `${JSON.stringify(report, null, 2)}\n`, "utf8");
console.log(`wrote ${path}`);
}
function isMain(): boolean {
const entry = process.argv[1];
if (!entry) return false;
return import.meta.url === pathToFileURL(entry).href;
}
if (isMain()) {
main().catch((err) => {
console.error(err);
process.exit(1);
});
}
export { main as runHarvestBench };
-143
View File
@@ -1,143 +0,0 @@
/** Seed reasoning tasks for harvest-bench — single-turn Q/A with deterministic checkers. */
import type { HarvestTask } from "./types.js";
const CONCISE_SYSTEM = `You are a precise reasoner. Think carefully, then state your final answer on a clearly-labeled line starting with "Answer:".`;
/** Parse non-negative integers; expands "2-4" → 2,3,4; strips LaTeX decorations first. */
function extractIntegers(text: string): number[] {
// Strip LaTeX delimiters so n_1 / n^2 / \{ ... \} don't confuse us.
const cleaned = text
.replace(/\\[a-zA-Z]+/g, " ") // \frac, \mod etc.
.replace(/[{}\\]/g, " ")
.replace(/[_^]\d+/g, " "); // subscript/superscript numbers
// Expand ranges: "2-4" → "2,3,4" (only for small gaps)
const rangeExpanded = cleaned.replace(/(\d+)\s*[-–]\s*(\d+)/g, (_, a, b) => {
const lo = Number.parseInt(a, 10);
const hi = Number.parseInt(b, 10);
if (!Number.isFinite(lo) || !Number.isFinite(hi) || hi - lo > 50) return `${a} ${b}`;
const out: number[] = [];
for (let i = Math.min(lo, hi); i <= Math.max(lo, hi); i++) out.push(i);
return out.join(" ");
});
const matches = rangeExpanded.match(/-?\d+/g) ?? [];
return matches.map((m) => Number.parseInt(m, 10)).filter((n) => Number.isFinite(n));
}
/** Extract content after the last "Answer:" label (case-insensitive). */
function extractAnswerLine(text: string): string {
const matches = [...text.matchAll(/answer\s*[::]\s*([^\n]+)/gi)];
if (matches.length === 0) return text;
return matches[matches.length - 1]![1]!.trim();
}
/** Positive n ≤ 100 such that n^2 + n + 1 ≡ 0 (mod 7). */
const MOD7_EXPECTED: number[] = (() => {
const out: number[] = [];
for (let n = 1; n <= 100; n++) {
if ((n * n + n + 1) % 7 === 0) out.push(n);
}
return out;
})();
/** Single-integer checker — first plausible int from the last "Answer:" line, exact equality. */
function checkSingleInt(expected: number) {
return (reply: string) => {
const answerLine = extractAnswerLine(reply);
const nums = extractIntegers(answerLine);
if (nums.length === 0) return { verdict: "fail" as const, note: "no number in Answer line" };
const n = nums[0]!;
if (n === expected) return { verdict: "pass" as const };
return { verdict: "fail" as const, note: `got ${n}, expected ${expected}` };
};
}
export const TASKS: HarvestTask[] = [
{
id: "mod7_list",
description:
"Number theory — find all positive n ≤ 100 with n^2+n+1 ≡ 0 (mod 7). 29-element set. Classic R1 scratch-work territory.",
systemPrompt: CONCISE_SYSTEM,
prompt:
'Find all positive integers n with n ≤ 100 such that n^2 + n + 1 is divisible by 7. Briefly justify, then end with the full list on a line starting with "Answer:".',
check: (reply) => {
const answerLine = extractAnswerLine(reply);
const found = new Set(extractIntegers(answerLine).filter((n) => n >= 1 && n <= 100));
const expected = new Set(MOD7_EXPECTED);
if (found.size === 0) {
return { verdict: "fail", note: "no integers extracted from Answer line" };
}
// Exact set equality — both containment directions.
for (const n of expected)
if (!found.has(n)) return { verdict: "fail", note: `missing n=${n}` };
for (const n of found) if (!expected.has(n)) return { verdict: "fail", note: `extra n=${n}` };
return { verdict: "pass" };
},
},
{
id: "flips_until_3heads",
description:
"Probability — expected coin flips until 3 consecutive heads. Answer: 14. Tests whether R1 derives via recurrence or via memorized result.",
systemPrompt: CONCISE_SYSTEM,
prompt:
'A fair coin is flipped repeatedly until you see 3 heads in a row. What is the expected number of total flips? Give a single integer on a line starting with "Answer:".',
check: (reply) => {
const answerLine = extractAnswerLine(reply);
const nums = extractIntegers(answerLine);
if (nums.length === 0) return { verdict: "fail", note: "no number in Answer line" };
// Accept the first sensible number — sometimes agents write "Answer: 14 flips".
const n = nums[0]!;
if (n === 14) return { verdict: "pass" };
return { verdict: "fail", note: `got ${n}, expected 14` };
},
},
{
id: "three_hats",
description:
"Logic — three people wear red/blue hats, at least one red, they're asked in order. First two say no, third says yes. What color? Answer: red (deducible because if third were blue, the first two could see one red + one unknown and wouldn't have said no on their full first round, for most configurations the third can only be certain if red).",
systemPrompt: CONCISE_SYSTEM,
prompt:
'Three people wear hats that are each red or blue. They are told at least one hat is red. Each can see the other two hats but not their own. They are asked in order: "Do you know your hat color?" The first two answer no. The third answers yes. What color is the third person\'s hat? Give a one-word answer on a line starting with "Answer:".',
check: (reply) => {
const answerLine = extractAnswerLine(reply).toLowerCase();
// Accept "red" as a standalone word (not "redirected" etc).
if (/\bred\b/.test(answerLine) && !/\bblue\b/.test(answerLine)) {
return { verdict: "pass" };
}
if (/\bblue\b/.test(answerLine)) return { verdict: "fail", note: "answered blue" };
return { verdict: "fail", note: "no clear color in Answer line" };
},
},
{
id: "pseudoprime_base2",
description:
"Number theory — smallest composite n > 1 such that 2^n ≡ 2 (mod n). This is the smallest Fermat pseudoprime to base 2. Answer: 341 (= 11·31). V3 frequently answers 561 (Carmichael / wrong base-2 property) or 9 (not actually a pseudoprime to base 2, verifying the model isn't computing). R1 usually gets this right.",
systemPrompt: CONCISE_SYSTEM,
prompt:
'Find the smallest composite integer n > 1 such that 2^n is congruent to 2 modulo n (i.e., n is a Fermat pseudoprime to base 2). Briefly justify, then give a single integer on a line starting with "Answer:".',
check: checkSingleInt(341),
},
{
id: "derangements_d7",
description:
"Combinatorics — number of derangements of 7 elements. Answer: 1854 (D_7 = 7! · (1 − 1/1! + 1/2! − 1/3! + … ± 1/7!) = 5040 · 0.367857… = 1854). V3 sometimes approximates via n!/e and rounds wrong, or confuses with D_6=265 or D_8=14833. R1's explicit recurrence D_n = (n-1)(D_{n-1}+D_{n-2}) avoids the mistake.",
systemPrompt: CONCISE_SYSTEM,
prompt:
'How many permutations of {1, 2, 3, 4, 5, 6, 7} have no fixed points? (This is D_7, the derangement number.) Briefly justify, then give a single integer on a line starting with "Answer:".',
check: checkSingleInt(1854),
},
{
id: "euler_quadratic_break",
description:
"Number theory — smallest nonneg integer n where n^2 + n + 41 is NOT prime. Euler's prime-generating polynomial famously produces primes for n = 0..39 and first fails at n = 40 (40²+40+41 = 1681 = 41²). V3 often confuses this with the related n²-n+41 (first fails at 41) or cites the wrong threshold. R1 checks small n systematically.",
systemPrompt: CONCISE_SYSTEM,
prompt:
'Consider the polynomial f(n) = n^2 + n + 41 for n = 0, 1, 2, …. What is the smallest nonneg integer n at which f(n) fails to be prime? Briefly justify (including the value of f(n) at that point), then give just the integer n on a line starting with "Answer:".',
check: checkSingleInt(40),
},
];
-61
View File
@@ -1,61 +0,0 @@
/** Harvest-bench types — single-turn Q/A with deterministic checkers; isolates Pillar 2 the way τ-bench-lite isolates Pillar 1. */
export type HarvestMode =
/** deepseek-chat, no Reasonix tricks. Floor reference for answer quality on reasoning tasks (V3 at its best). */
| "baseline"
/** deepseek-reasoner, no harvest. Isolates "does reasoner help over chat on these problems?" */
| "reasoner"
/** deepseek-reasoner + harvest. Isolates "does the extra V3 harvest call add quality / change behavior?" */
| "reasoner-harvest";
export const ALL_MODES: HarvestMode[] = ["baseline", "reasoner", "reasoner-harvest"];
/** Checker verdict — `inconclusive` reserves room for "right shape, can't verify without running it". */
export type CheckVerdict = "pass" | "fail" | "inconclusive";
export interface HarvestTask {
id: string;
/** One-line human description, not shown to the model. */
description: string;
/** System prompt. Kept minimal so harvest signal can be attributed to the model, not to prompt engineering. */
systemPrompt: string;
/** The single question. */
prompt: string;
/** Pure + deterministic — no LLM calls, no file I/O. Verdict + optional one-line note. */
check: (agentReply: string) => { verdict: CheckVerdict; note?: string };
}
export interface HarvestRunResult {
taskId: string;
mode: HarvestMode;
repeat: number;
verdict: CheckVerdict;
checkNote?: string;
finalAgentMessage: string;
/** Turns the loop completed (usually 1 for a single-shot Q/A, > 1 if tool-calls happen). */
turns: number;
cacheHitRatio: number;
costUsd: number;
claudeEquivalentUsd: number;
/** Harvest-specific — only non-zero on reasoner-harvest mode. */
harvestedTurns: number;
totalSubgoals: number;
totalUncertainties: number;
totalHypotheses: number;
totalRejectedPaths: number;
/** Optional error message if the run crashed (model down, timeout, etc). */
errorMessage?: string;
}
export interface HarvestBenchMeta {
date: string;
repeatsPerTask: number;
taskCount: number;
modesRun: HarvestMode[];
reasonixVersion: string;
}
export interface HarvestBenchReport {
meta: HarvestBenchMeta;
results: HarvestRunResult[];
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+76
View File
@@ -0,0 +1,76 @@
# Real-world cache hit — single user, single day
A real Reasonix user shared their DeepSeek dashboard for **2026-05-01**.
Used with permission, anonymized.
![DeepSeek usage dashboard, 2026-05-01](2026-05-01-deepseek-dashboard.png)
## The numbers
| | Tokens |
|---|---:|
| Input — cache hit | 435,033,856 |
| Input — cache miss | 767,616 |
| Output | 179,763 |
| **Day total** | **435,981,235** |
**Cache hit ratio (input):**
`435,033,856 / (435,033,856 + 767,616)` = **99.82%**
## 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`
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 |
| Output | $0.05 | $0.05 |
| **Total / day** | **$12.34** | **$60.63** |
→ Cache saved this user **$48.29**, or **~80%** 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**.
## "Isn't that just DeepSeek's prefix cache?"
DeepSeek's API ships prefix caching enabled by default; the *cache* is theirs,
the *hit rate* is the client's. Same API, different clients, very different
hit rates:
- DeepSeek's own web chat: 60–80% within a single conversation, drops to 0%
on a new session (system prompt may differ).
- Cherry Studio / Open WebUI / generic OpenAI-shape SDKs: typically 30–60%
on long sessions — history gets reordered, tool specs get re-serialized,
every drift breaks the prefix.
- Cline / Continue and other XML-tool-call clients: lower still — every tool
result inlines into the conversation, shifting bytes the cache keys on.
99.82% is what falls out of these four design choices in Reasonix:
1. **`ImmutablePrefix`** (`src/memory.ts`) — system prompt + tool specs are
frozen at session start. Same byte sequence every turn.
2. **`AppendOnlyLog`** — turns only append. No reorder, no edit-in-place.
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.
DeepSeek gave us cacheable bytes. The four mechanisms above are how we keep
the bytes cacheable.
## Reproduce
The synthetic side of this lives in `benchmarks/tau-bench/` — same task set
run through `CacheFirstLoop` vs a deliberately cache-hostile baseline. The
real-world data above is what the synthetic numbers look like once a user
runs the harness in anger.
Submit your own dashboard screenshot if you want it anonymized and added
here — open an issue.
+139
View File
@@ -0,0 +1,139 @@
# Dashboard ↔ TUI parity
Closing audit of #369. Inventories every slash command and how the
web dashboard handles it.
## Coverage legend
- **panel** — has a dedicated SPA panel or modal beyond just typing the
slash in the chat box.
- **chat-box** — works by typing the slash into the web chat input.
Result text shows in the dashboard scrollback as an info row. No
dedicated UI; the chat box _is_ the UI.
- **tui-only** — keyboard binding or process-controlling action that
has no useful web equivalent. Stays a TUI affordance by design.
## Counts
Roughly **20 commands have a dedicated panel**, **38 work via the chat
box**, and **`/exit` plus 4 raw keyboard shortcuts** stay TUI-only.
Aliases (e.g. `/sessions` and `/resume` share one picker) collapse
into one row.
## Core / observability
| Slash | Purpose | Coverage |
|---|---|---|
| `/help` | command reference | chat-box |
| `/keys` | keyboard shortcuts + prompt prefixes | chat-box |
| `/status` | model + flags + ctx + session | chat-box |
| `/context` | context-window breakdown (stacked bar) | chat-box · `ctxBreakdown` payload |
| `/cost` | last turn / next turn estimate | chat-box · usage card |
| `/stats` | cross-session cost dashboard | **panel** · Usage tab |
| `/think` | last R1 reasoning dump | chat-box |
| `/tool [N]` | dump full output of Nth tool call | chat-box |
| `/clear` | wipe visible scrollback | chat-box |
| `/new` (`/reset`) | wipe context + scrollback | chat-box |
| `/exit` (`/quit`, `/q`) | quit the TUI | **tui-only** |
| `/stop` | abort current model turn | chat-box |
| `/retry` | resend last user message | chat-box |
| `/compact` | fold older turns into summary | chat-box |
| `/update` | show current vs latest version | chat-box |
| `/doctor` | health check card | chat-box · doctor card |
## Model & compute
| Slash | Purpose | Coverage |
|---|---|---|
| `/preset` | model bundle (auto / flash / pro) | **panel** · Settings → Defaults |
| `/effort` | reasoning cap (high / max) | **panel** · Settings → Defaults |
| `/model` | active model | **panel** · Settings → Runtime (D-4 #437) |
| `/models` | list available models | chat-box |
| `/pro` | arm v4-pro for next turn | **panel** · Settings → Compute (D-2 #435) |
| `/budget` | session USD cap | **panel** · Settings → Budget + cockpit tile (D-3 #436) |
| `/loop` | auto-resubmit on interval | **panel** · Settings → Loop (D-5 #438) |
## Memory & project
| Slash | Purpose | Coverage |
|---|---|---|
| `/memory [list / show / forget / clear]` | manage pinned memory | **panel** · Memory tab |
| `/init` | synthesize baseline REASONIX.md | chat-box |
| `/semantic` | semantic-search index status | chat-box |
| `/search-engine` (`/se`) | switch web search backend | chat-box |
| `/language` (`/lang`) | runtime language | **panel** · Settings → Language |
## Sessions
| Slash | Purpose | Coverage |
|---|---|---|
| `/sessions` | list saved sessions | **panel** · SessionPicker modal (C-2 #423) |
| `/resume` | open a session | **panel** · same picker |
| `/rename` | rename current session | chat-box |
| `/forget` | delete current session | chat-box |
| `/plans` | active + archived plans | **panel** · Plans tab |
| `/replay [N]` | read-only plan archive | **panel** · Viewer modal (C-5 #427) |
## MCP
| Slash | Purpose | Coverage |
|---|---|---|
| `/mcp` (list) | bridged servers + tools | **panel** · MCP tab |
| `/mcp browse` | marketplace + install | **panel** · MCP marketplace picker (C-4 #426) |
| `/mcp disable` / `enable` / `reconnect` / `text` | server admin | chat-box |
| `/resource [uri]` | browse / read MCP resources | chat-box |
| `/prompt [name]` | browse / fetch MCP prompts | chat-box |
## Permissions & admin
| Slash | Purpose | Coverage |
|---|---|---|
| `/permissions [list / add / remove / clear]` | shell allowlist | **panel** · Permissions tab |
| `/hooks [reload]` | active hooks | **panel** · Hooks tab |
| `/dashboard [stop]` | embedded dashboard lifecycle | chat-box · *intentional — admin command for the surface you're typing in* |
## Code-mode only
| Slash | Purpose | Coverage |
|---|---|---|
| `/init [force]` | scan + synthesize REASONIX.md | chat-box |
| `/apply [N]` | commit pending edits | chat-box |
| `/discard [N]` | drop pending edits | chat-box |
| `/walk` | step through pending edits | **panel** · edit-review modal already covered web pre-#369 |
| `/undo` | roll back last edit batch | chat-box |
| `/history` | edit batch list | chat-box |
| `/show [id]` | dump stored edit diff | chat-box |
| `/commit "msg"` | git commit | chat-box |
| `/checkpoint [name / list / forget]` | snapshot touched files | chat-box |
| `/restore` | roll back to checkpoint | **panel** · CheckpointPicker modal (C-3 #425) |
| `/plan [on / off]` | read-only plan mode | chat-box |
| `/apply-plan` | force-approve pending plan | chat-box |
| `/mode [review / auto / yolo]` | edit gate | **panel** · Chat header pill |
| `/jobs` | list background jobs | chat-box |
| `/kill <id>` | stop background job | chat-box |
| `/logs <id> [lines]` | tail job output | chat-box |
| `/skill [list / show / new / <name>]` | skill management | **panel** · Skills tab |
## Keyboard / TTY-native
These don't have slashes. They ride alongside the slash surface and
stay TUI-only:
- `Esc` — abort current model turn (web equivalent: Abort button in chat)
- `Shift+Tab` — cycle edit mode (web equivalent: mode pill in chat header)
- `Ctrl-L`, `Ctrl-O`, `space`, `u` — TTY scroll / undo banner / pause hotkeys
## Done
Buckets covered:
- **C** (#416, closed): pickers — `/sessions`, `/restore`, `/mcp browse`, `/replay` + `/walk` (already)
- **D** (#428, closed): settings — `/preset`, `/effort`, `/model`, `/pro`, `/budget`, `/loop`, `/language`
Bucket A (text outputs that stay chat-box) and bucket B (structured
outputs that already have panels) need no further work — the panels
shipped in C/D plus the long-standing Memory / Permissions / Hooks /
Skills / Plans / Usage tabs already cover every command whose output
warranted a dedicated UI.
This file is the source of truth for the audit. Add a row when a
new slash lands.
+754 -16
View File
@@ -85,7 +85,7 @@ a:hover { text-decoration: underline; }
/* ── Doc chrome ─────────────────────────────────────────────────────────── */
.page {
display: grid;
grid-template-columns: 240px minmax(0, 1fr);
grid-template-columns: 260px minmax(0, 1fr);
max-width: 1320px;
margin: 0 auto;
min-height: 100vh;
@@ -94,18 +94,19 @@ a:hover { text-decoration: underline; }
position: sticky; top: 0; align-self: start;
height: 100vh; overflow-y: auto;
border-right: 1px solid var(--bd);
padding: 28px 18px;
padding: 28px 16px;
background: var(--bg);
}
.toc h1 { font-size: 14px; font-weight: 700; margin: 0 0 4px; color: var(--fg-0); letter-spacing: .03em; font-family: var(--font-mono); }
.toc h1 { font-size: 15px; font-weight: 700; margin: 0 0 4px; color: var(--fg-0); letter-spacing: .03em; font-family: var(--font-mono); }
.toc h1 .dot { color: var(--c-brand); margin-right: 8px; }
.toc .sub { font-size: 11px; color: var(--fg-3); margin: 0 0 18px; letter-spacing: .04em; }
.toc-section { font-size: 10px; text-transform: uppercase; letter-spacing: .14em; color: var(--fg-4); margin: 22px 0 6px; font-weight: 700; }
.toc .sub { font-size: 12px; color: var(--fg-3); margin: 0 0 18px; letter-spacing: .04em; }
.toc-section { font-size: 12px; text-transform: uppercase; letter-spacing: .08em; color: var(--fg-4); margin: 22px 0 6px; font-weight: 700; }
.toc-section:first-of-type { margin-top: 0; }
.toc ul { list-style: none; padding: 0; margin: 0; }
.toc li a {
display: block; padding: 3px 8px; margin: 1px 0;
color: var(--fg-2); font-size: 12.5px; border-radius: var(--r);
display: block; padding: 4px 10px; margin: 1px 0;
color: var(--fg-2); font-size: 14px; line-height: 1.4;
border-radius: var(--r); overflow-wrap: anywhere;
}
.toc li a:hover { color: var(--fg-0); background: var(--bg-elev); text-decoration: none; }
@@ -118,7 +119,7 @@ main { padding: 32px 40px 60px 32px; min-width: 0; }
}
.section > h2 .num { color: var(--fg-4); margin-right: 10px; font-weight: 500; }
.section > .lede {
color: var(--fg-2); margin: 0 0 22px; font-size: 13px; max-width: 700px; line-height: 1.6;
color: var(--fg-2); margin: 0 0 22px; font-size: 15px; max-width: 720px; line-height: 1.6;
}
.subsec { margin-bottom: 22px; }
.subsec > h3 {
@@ -126,8 +127,8 @@ main { padding: 32px 40px 60px 32px; min-width: 0; }
margin: 24px 0 4px; letter-spacing: .04em; text-transform: uppercase;
font-family: var(--font-mono);
}
.subsec > h3 .desc { color: var(--fg-3); font-weight: 400; margin-left: 10px; font-size: 12px; text-transform: none; letter-spacing: 0; }
.subsec > p { color: var(--fg-3); font-size: 12.5px; margin: 0 0 12px; max-width: 720px; line-height: 1.6; }
.subsec > h3 .desc { color: var(--fg-3); font-weight: 400; margin-left: 10px; font-size: 13px; text-transform: none; letter-spacing: 0; }
.subsec > p { color: var(--fg-3); font-size: 15px; margin: 0 0 12px; max-width: 720px; line-height: 1.6; }
/* "Mock" — a faux-window frame to display dashboard pieces inside the design doc */
.mock {
@@ -155,11 +156,11 @@ main { padding: 32px 40px 60px 32px; min-width: 0; }
.swatch .chip { width: 22px; height: 22px; border-radius: var(--r); flex-shrink: 0; border: 1px solid rgba(255,255,255,.04); }
.swatch .meta { display: flex; flex-direction: column; gap: 1px; min-width: 0; }
.swatch .name { color: var(--fg-1); font-size: 11.5px; }
.swatch .hex { color: var(--fg-3); font-size: 10.5px; }
.swatch .hex { color: var(--fg-3); font-size: 11.5px; }
.scale-row { display: flex; align-items: baseline; gap: 16px; padding: 6px 0; border-bottom: 1px dashed #181b22; }
.scale-row:last-child { border-bottom: none; }
.scale-row .lbl { font-family: var(--font-mono); font-size: 10.5px; color: var(--fg-3); width: 70px; flex-shrink: 0; }
.scale-row .lbl { font-family: var(--font-mono); font-size: 11.5px; color: var(--fg-3); width: 76px; flex-shrink: 0; }
.scale-row .ex { color: var(--fg-1); }
.glyph-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); gap: 6px; }
@@ -311,12 +312,13 @@ main { padding: 32px 40px 60px 32px; min-width: 0; }
.pill.acc { color: var(--c-accent); background: rgba(210,168,255,.10); }
/* Table */
.tbl { width: 100%; border-collapse: collapse; font-size: 12.5px; }
.tbl { width: 100%; border-collapse: collapse; font-size: 12.5px; table-layout: auto; }
.tbl th, .tbl td { padding: 8px 10px; text-align: left; border-bottom: 1px solid var(--bd); }
.tbl th { font-family: var(--font-mono); font-size: 10.5px; font-weight: 600; color: var(--fg-3); text-transform: uppercase; letter-spacing: .08em; background: var(--bg-elev); }
.tbl th.num, .tbl td.num { font-family: var(--font-mono); text-align: right; font-variant-numeric: tabular-nums; }
.tbl td { color: var(--fg-1); }
.tbl tbody tr:hover { background: var(--bg-hover); }
.tbl td.num { font-family: var(--font-mono); text-align: right; color: var(--fg-0); font-variant-numeric: tabular-nums; }
.tbl td.num { color: var(--fg-0); }
.tbl td.dim { color: var(--fg-3); }
.tbl td.path { font-family: var(--font-mono); font-size: 11.5px; color: var(--fg-2); }
@@ -778,12 +780,12 @@ main { padding: 32px 40px 60px 32px; min-width: 0; }
flex: 1; min-height: 0;
}
.editor-line {
display: grid; grid-template-columns: 44px 1fr;
display: grid; grid-template-columns: 62px 1fr;
padding: 0; white-space: pre;
}
.editor-line:hover { background: rgba(121,192,255,.04); }
.editor-line.cur { background: rgba(121,192,255,.06); }
.editor-line .lineno { color: var(--fg-4); text-align: right; padding-right: 14px; user-select: none; font-variant-numeric: tabular-nums; }
.editor-line .lineno { color: var(--fg-4); text-align: right; padding: 0 10px 0 20px; user-select: none; font-variant-numeric: tabular-nums; }
.editor-line .ln-content { color: var(--fg-1); }
.editor-line .ln-content .kw { color: var(--c-accent); }
.editor-line .ln-content .str { color: var(--c-ok); }
@@ -812,6 +814,9 @@ main { padding: 32px 40px 60px 32px; min-width: 0; }
}
.chip-f:hover { background: var(--bg-hover); color: var(--fg-1); }
.chip-f.active { color: var(--c-brand); border-color: var(--c-brand); background: rgba(121,192,255,.08); }
.chip-f.static { cursor: default; }
.chip-f.static:hover { background: var(--bg-elev); color: var(--fg-2); }
.chip-f.static.active:hover { color: var(--c-brand); background: rgba(121,192,255,.08); }
.chip-f .ct { color: var(--fg-4); font-size: 10px; }
.chip-f.active .ct { color: var(--c-brand); }
.chip-f .x { color: var(--fg-4); padding: 0 2px; }
@@ -2016,6 +2021,155 @@ input:focus, textarea:focus, select:focus { border-color: var(--c-brand); }
max-height: 200px;
}
.modal-picker-search {
width: 100%;
background: var(--bg-elev-2);
border: 1px solid var(--bd);
border-radius: var(--r);
color: var(--fg-1);
padding: 6px 10px;
font-size: 13px;
margin-bottom: 8px;
}
.modal-picker-list {
display: flex;
flex-direction: column;
gap: 2px;
max-height: 320px;
overflow-y: auto;
border: 1px solid var(--bd);
border-radius: var(--r);
background: var(--bg-elev-2);
padding: 4px;
margin-bottom: 8px;
}
.modal-picker-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 4px 8px;
align-items: baseline;
padding: 6px 8px;
background: transparent;
border: 1px solid transparent;
border-radius: var(--r-sm, 4px);
color: var(--fg-1);
text-align: left;
cursor: pointer;
}
.modal-picker-row:hover {
background: var(--bg-elev-3, var(--bg-elev-2));
}
.modal-picker-row.selected {
border-color: var(--accent, #fcd34d);
background: var(--bg-elev-3, var(--bg-elev-2));
}
.modal-picker-title {
grid-column: 1;
font-weight: 500;
}
.modal-picker-badge {
grid-column: 2;
font-size: 11px;
color: var(--fg-2);
padding: 1px 6px;
border-radius: 999px;
background: var(--bg-elev-1, var(--bg-elev-2));
}
.modal-picker-subtitle {
grid-column: 1 / 3;
font-size: 12px;
color: var(--fg-2);
}
.modal-picker-meta {
grid-column: 1 / 3;
font-size: 11px;
color: var(--fg-3, var(--fg-2));
}
.modal-picker-empty {
padding: 16px;
text-align: center;
color: var(--fg-2);
font-size: 12px;
}
.modal-picker-more {
align-self: center;
margin: 0 auto 8px;
font-size: 12px;
}
.modal-picker-form {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: 8px;
}
.modal-picker-form input {
width: 100%;
background: var(--bg-elev-2);
border: 1px solid var(--bd);
border-radius: var(--r);
color: var(--fg-1);
padding: 6px 10px;
font-size: 13px;
}
.modal-viewer-steps {
list-style: none;
padding: 0;
margin: 0 0 8px;
display: flex;
flex-direction: column;
gap: 4px;
}
.modal-viewer-step {
display: grid;
grid-template-columns: 18px 1fr;
gap: 6px;
padding: 4px 8px;
border-radius: var(--r-sm, 4px);
background: var(--bg-elev-2);
align-items: baseline;
}
.modal-viewer-step-mark {
text-align: center;
font-weight: 600;
color: var(--fg-2);
}
.modal-viewer-step-done .modal-viewer-step-mark {
color: #86efac;
}
.modal-viewer-step-title {
color: var(--fg-1);
font-size: 13px;
}
.modal-viewer-step-done .modal-viewer-step-title {
color: var(--fg-2);
}
.modal-viewer-body {
margin-top: 4px;
font-size: 13px;
color: var(--fg-1);
max-height: 360px;
overflow-y: auto;
}
/* Side-by-side diff for the edit-review modal — left is "before" (red
* tint), right is "after" (green tint), context rows render unchanged.
* Lines hljs-highlight per the file's language. */
@@ -2273,3 +2427,587 @@ input:focus, textarea:focus, select:focus { border-color: var(--c-brand); }
color: var(--c-brand);
}
.changes-layout {
display: flex;
flex-direction: row;
height: 100%;
overflow: hidden;
}
.app-body.changes-active {
padding: 0;
overflow: hidden;
}
.changes-panel {
display: flex;
flex-direction: column;
min-width: 200px;
overflow: hidden;
background: var(--bg-elev);
border: 1px solid var(--bd);
border-radius: var(--r);
}
.changes-panel-left {
width: 30%;
}
.changes-panel-center {
flex: 1;
min-width: 0;
}
.changes-panel-right {
width: 30%;
}
.changes-panel-header {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border-bottom: 1px solid var(--bd);
font-family: var(--font-mono);
font-size: 10.5px;
color: var(--fg-3);
text-transform: uppercase;
letter-spacing: .1em;
flex-shrink: 0;
background: var(--bg-elev);
}
.changes-panel-header .glyph {
color: var(--c-brand);
font-size: 12px;
}
.changes-panel-body {
flex: 1;
overflow-y: auto;
min-height: 0;
}
@media (max-width: 899px) {
.changes-layout {
flex-direction: column;
}
.changes-panel {
min-width: 0;
min-height: 180px;
}
.changes-panel-left,
.changes-panel-right {
width: 100%;
max-height: 40vh;
}
.changes-panel-center {
flex: 1;
}
.changes-layout .resize-handle {
display: none;
}
}
/* ── Line Comment System ──────────────────────────────────────────── */
.line-comment-anchor {
width: 16px;
height: 16px;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
pointer-events: none;
cursor: pointer;
transition: opacity 0.15s ease;
flex-shrink: 0;
}
.editor-line:hover .line-comment-anchor.visible {
opacity: 1;
pointer-events: auto;
}
.line-comment-anchor .plus-icon,
.line-comment-anchor .comment-count {
font-family: var(--font-mono);
font-size: 14px;
color: var(--fg-3);
line-height: 1;
}
.line-comment-anchor:hover .plus-icon,
.line-comment-anchor:hover .comment-count {
color: var(--c-brand);
}
.line-comment-anchor .comment-count {
background: rgba(121, 192, 255, 0.12);
border-radius: var(--r);
padding: 0 3px;
font-size: 10px;
color: var(--c-brand);
}
.line-comment-editor {
grid-column: 2;
justify-self: stretch;
min-width: 0;
background: var(--bg-elev);
border: 1px solid var(--bd-strong);
border-radius: 6px;
padding: 10px 12px;
margin: 2px 0 4px 0;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
gap: 8px;
}
.line-comment-bubble {
grid-column: 2;
justify-self: stretch;
min-width: 0;
background: var(--bg-elev);
border: 1px solid var(--bd-strong);
border-radius: 6px;
padding: 10px 12px;
margin: 2px 0 4px 0;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
gap: 8px;
}
.line-comment-label {
font-family: var(--font-mono);
font-size: 10.5px;
color: var(--fg-3);
text-transform: uppercase;
letter-spacing: .08em;
}
.line-comment-textarea {
background: var(--bg-input);
border: 1px solid var(--bd);
border-radius: var(--r);
color: var(--fg-0);
font-family: var(--font-mono);
font-size: 12px;
padding: 8px 10px;
resize: vertical;
min-height: 60px;
outline: none;
line-height: 1.5;
width: 100%;
box-sizing: border-box;
}
.line-comment-textarea:focus {
border-color: var(--c-brand);
}
.line-comment-actions {
display: flex;
gap: 6px;
justify-content: flex-end;
}
.bubble-content {
background: var(--bg-input);
border: 1px solid var(--bd);
border-radius: var(--r);
color: var(--fg-0);
font-family: var(--font-mono);
font-size: 12px;
padding: 8px 10px;
min-height: 36px;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-word;
box-sizing: border-box;
}
.bubble-footer {
display: flex;
align-items: center;
gap: 8px;
font-family: var(--font-mono);
font-size: 10px;
color: var(--fg-3);
}
.bubble-line {
flex: 1;
}
.bubble-actions {
display: flex;
gap: 4px;
}
.bubble-btn {
background: transparent;
border: none;
color: var(--fg-3);
padding: 2px 6px;
font-size: 10px;
cursor: pointer;
border-radius: var(--r);
}
.bubble-btn:hover {
background: var(--bg-hover);
color: var(--fg-0);
}
.bubble-btn.danger:hover {
color: var(--c-err);
}
.comment-card {
display: inline-flex;
align-items: center;
gap: 8px;
background: var(--bg-elev-1);
border: 1px solid var(--bd);
border-radius: 6px;
padding: 6px 10px;
font-family: var(--font-mono);
font-size: 12px;
color: var(--fg-2);
cursor: default;
min-width: 120px;
}
.comment-card-icon {
color: var(--c-brand);
font-size: 12px;
font-weight: bold;
flex-shrink: 0;
}
.comment-card-file {
color: var(--c-brand);
white-space: nowrap;
}
.comment-card-content {
color: var(--fg-1);
font-size: 12px;
line-height: 1.4;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.comment-card-remove {
color: var(--fg-3);
cursor: pointer;
padding: 0 2px;
font-size: 14px;
line-height: 1;
transition: color 0.15s ease;
flex-shrink: 0;
margin-left: auto;
}
.comment-card-remove:hover {
color: var(--c-err);
}
/* ── File Tree Toggle ─────────────────────────────────────────────── */
.file-tree-toggle {
display: flex;
gap: 0;
padding: 6px 8px;
border-bottom: 1px solid var(--bd);
}
.toggle-btn {
flex: 1;
background: transparent;
border: 1px solid var(--bd);
color: var(--fg-3);
padding: 4px 10px;
font-family: var(--font-mono);
font-size: 11px;
cursor: pointer;
text-align: center;
transition: all 0.15s ease;
}
.toggle-btn:first-child {
border-radius: var(--r) 0 0 var(--r);
border-right: none;
}
.toggle-btn:last-child {
border-radius: 0 var(--r) var(--r) 0;
}
.toggle-btn:hover {
background: var(--bg-hover);
color: var(--fg-1);
}
.toggle-btn.active {
background: var(--bg-hover);
color: var(--fg-0);
border-color: var(--fg-4);
}
/* ── Review Tab ───────────────────────────────────────────────────── */
.review-tab {
display: flex;
align-items: center;
gap: 4px;
}
.review-tab .review-icon {
font-size: 12px;
color: var(--c-brand);
}
.review-tab.active .review-icon {
color: var(--c-brand);
}
/* ── Modification Indicator ───────────────────────────────────────── */
.tree-node .mod-indicator {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--c-ok);
flex-shrink: 0;
margin-left: 4px;
}
/* ── Review Diff View ─────────────────────────────────────────────── */
.review-diff-view {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
}
.review-diff-header {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
border-bottom: 1px solid var(--bd);
background: var(--bg-elev);
flex-shrink: 0;
}
.review-diff-title {
font-family: var(--font-mono);
font-size: 11px;
color: var(--fg-2);
text-transform: uppercase;
letter-spacing: .08em;
}
.review-diff-list {
flex: 1;
overflow-y: auto;
padding: 8px;
}
.review-file-item {
margin-bottom: 8px;
border: 1px solid var(--bd);
border-radius: var(--r);
overflow: hidden;
}
.review-file-header {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
background: var(--bg-elev);
cursor: pointer;
user-select: none;
font-family: var(--font-mono);
font-size: 12px;
color: var(--fg-1);
}
.review-file-header:hover {
background: var(--bg-hover);
}
.review-file-header .chev {
color: var(--fg-3);
font-size: 10px;
width: 12px;
}
.review-file-header .filename {
flex: 1;
}
.review-file-header .stat {
font-size: 11px;
color: var(--fg-3);
}
.review-file-header .stat .add {
color: var(--c-ok);
}
.review-file-header .stat .rem {
color: var(--c-err);
}
.review-file-body {
padding: 8px;
background: var(--bg-code);
}
.review-empty {
padding: 32px;
text-align: center;
color: var(--fg-3);
font-family: var(--font-mono);
font-size: 12px;
}
/* ── Split Diff View ──────────────────────────────────────────── */
.split-diff {
font-family: var(--font-mono);
font-size: 12px;
line-height: 1.5;
overflow-x: auto;
}
.diff-hunk-header {
padding: 4px 12px;
background: var(--bg-elev-2);
color: var(--fg-3);
font-size: 11px;
display: flex;
gap: 8px;
border-bottom: 1px solid var(--bd);
}
.diff-hdr-left,
.diff-hdr-right {
flex: 1;
}
.diff-line {
display: flex;
padding: 0 12px;
min-height: 20px;
}
.diff-line.diff-add { background: rgba(126,231,135,.08); }
.diff-line.diff-del { background: rgba(255,139,129,.08); }
.diff-line {
display: flex;
padding-left: 8px;
}
.diff-ln-old,
.diff-ln-new {
display: inline-block;
min-width: 32px;
text-align: right;
color: var(--fg-4);
font-size: 11px;
padding: 0 6px 0 12px;
user-select: none;
flex-shrink: 0;
}
.diff-prefix {
width: 14px;
flex-shrink: 0;
color: var(--fg-3);
}
.diff-content {
flex: 1;
white-space: pre;
}
.diff-add .diff-content { color: var(--c-ok); }
.diff-del .diff-content { color: var(--c-err); }
/* Split rows */
.diff-split-row {
display: flex;
}
.diff-split-cell {
flex: 1;
min-width: 0;
display: flex;
padding: 0 8px;
min-height: 20px;
border-right: 1px solid var(--bd);
overflow: hidden;
}
.diff-split-cell:last-child { border-right: none; }
.diff-split-cell .diff-content {
flex: 1;
white-space: pre;
overflow: hidden;
text-overflow: ellipsis;
}
/* Diff source toggle */
.diff-source-toggle {
display: flex;
gap: 4px;
align-items: center;
}
.diff-source-toggle .toggle-btn {
font-family: var(--font-mono);
font-size: 10.5px;
padding: 2px 8px;
border: 1px solid var(--bd);
border-radius: var(--r);
background: var(--bg-elev);
color: var(--fg-2);
cursor: pointer;
}
.diff-source-toggle .toggle-btn.active {
background: var(--c-brand);
color: var(--bg);
border-color: var(--c-brand);
}
.diff-source-toggle .toggle-btn:hover:not(.active) {
background: var(--bg-hover);
color: var(--fg-0);
}
/* Diff style toggle */
.diff-style-toggle {
display: flex;
gap: 4px;
align-items: center;
}
.diff-style-toggle .toggle-btn {
font-family: var(--font-mono);
font-size: 10.5px;
padding: 2px 8px;
border: 1px solid var(--bd);
border-radius: var(--r);
background: var(--bg-elev);
color: var(--fg-2);
cursor: pointer;
}
.diff-style-toggle .toggle-btn.active {
background: var(--c-brand);
color: var(--bg);
border-color: var(--c-brand);
}
.diff-style-toggle .toggle-btn:hover:not(.active) {
background: var(--bg-hover);
color: var(--fg-0);
}
.diff-empty {
padding: 24px;
text-align: center;
color: var(--fg-3);
font-family: var(--font-mono);
font-size: 12px;
}
+7
View File
@@ -21,6 +21,7 @@ import { SkillsPanel } from "./src/panels/skills";
import { SystemPanel } from "./src/panels/system";
import { ToolsPanel } from "./src/panels/tools";
import { UsagePanel } from "./src/panels/usage";
import { ChangesPanel } from "./src/panels/changes";
const html = htm.bind(h);
@@ -34,6 +35,12 @@ function tabSections() {
{ id: "sessions", name: t("app.tabSessions"), glyph: "›", panel: () => html`<${SessionsPanel} />` },
],
},
{
label: t("app.sectionChanges"),
tabs: [
{ id: "changes", name: t("app.tabChanges"), glyph: "▨", panel: () => html`<${ChangesPanel} />` },
],
},
{
label: t("app.sectionObserve"),
tabs: [
+264 -2
View File
@@ -1,4 +1,5 @@
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";
@@ -104,6 +105,49 @@ interface RevisionSpec {
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;
@@ -257,7 +301,11 @@ export function ToolCard({ msg }: ToolCardProps) {
`;
}
export function ChatMessage({ msg, streaming }: ChatMessageProps) {
// 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") {
@@ -278,7 +326,7 @@ export function ChatMessage({ msg, streaming }: ChatMessageProps) {
</div>
</div>
`;
}
});
//
// Each component renders a card matching the TUI's ModalCard accent
@@ -617,6 +665,220 @@ export function CheckpointModal({ modal, onResolve }: { modal: CheckpointSpec; o
`;
}
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) =>
+193 -20
View File
@@ -17,8 +17,58 @@ export const en = {
tabMemory: "Memory",
tabHooks: "Hooks",
tabSettings: "Settings",
sectionChanges: "Changes",
tabChanges: "Changes",
footer: "127.0.0.1 only · token-gated",
},
changes: {
chatPlaceholder: "Ask about your code...",
chatWelcome: "Changes — ask questions about your project files.",
chatSend: "Send",
viewerPlaceholder: "Select a file to view",
treeEmpty: "(empty)",
tabClose: "Close tab",
newConversation: "New",
clearConversation: "Clear",
newTitle: "/new — wipe conversation context",
clearTitle: "/clear — wipe visible scrollback",
newConfirmBusy: "A turn is in flight. Abort and start a new conversation?",
newConfirm: "Clear current conversation and start fresh?",
newToast: "new conversation",
clearToast: "scrollback cleared",
newFailed: "/new failed: {error}",
clearFailed: "/clear failed: {error}",
chatSendBtn: "Send",
fileTreeTitle: "Files",
codeViewerTitle: "Code Viewer",
chatPanelTitle: "Chat",
loadingFiles: "Loading project files…",
review: "Review",
allFiles: "All Files",
changes: "changes",
commentLabel: "Commenting on line",
commentPlaceholder: "Add a comment…",
commentCancel: "Cancel",
commentSubmit: "Comment",
commentLine: "Line",
commentEdit: "Edit",
commentDelete: "Delete",
diffSourceGit: "Git changes",
diffSourceSession: "Previous session",
diffSourceCheckpoint: "Checkpoint",
checkpointEmpty: "No checkpoints in this workspace yet.",
restoreBtn: "Restore",
restoreConfirm: 'Restore "{name}"? This will overwrite current files.',
deleteBtn: "Delete",
deleteConfirm: 'Delete checkpoint "{name}"? Snapshot will be removed, files stay unchanged.',
createBtn: "Snapshot",
createPlaceholder: "name for snapshot…",
backToList: "back to list",
diffStyleUnified: "Unified",
diffStyleSplit: "Split",
expandAll: "Expand all",
collapseAll: "Collapse all",
},
common: {
loading: "loading…",
loadingFailed: "{name} failed: {error}",
@@ -61,8 +111,36 @@ export const en = {
effortHigh: "high (cheaper / faster)",
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",
sectionBudget: "Budget",
budgetOf: "of",
budgetSetCap: "set a cap",
budgetCustom: "custom",
budgetBumpHint: "bump the cap to keep going",
budgetClear: "Clear cap",
budgetIdleLine: "warns at 80% · refuses past 100%",
budgetWarnLine: "approaching cap — loop will refuse past 100%",
budgetRefusing: "cap exhausted — next turn refused until bumped or cleared",
sectionLoop: "Loop",
loopIdleHint: "Auto-resubmit a prompt on a fixed interval.",
loopCostHint: "Each iteration costs ~{cost} (last turn).",
loopInterval: "interval",
loopCustom: "custom",
loopRangeError: "interval must fall in 5s..6h",
loopPrompt: "prompt",
loopPromptPlaceholder: "e.g. check the deploy status and report any errors",
loopStart: "Start loop",
loopStop: "Stop",
loopRunning: "running",
loopIter: "iter {iter}",
loopFiresIn: "fires in {remaining}",
sectionRuntime: "Runtime",
activeModel: "active model",
modelPricingLine: "${hit} hit · ${miss} miss · ${out} out per 1M tok",
editMode: "edit mode",
editModeNote: "switch from the Chat tab header",
sectionLanguage: "Language",
@@ -89,7 +167,8 @@ export const en = {
clearFailed: "/clear failed: {error}",
eventStreamError: "event stream interrupted — reconnecting…",
semanticBanner: "Semantic search isn't enabled for this project.",
semanticBannerDesc: "Build the index once and the model can find code by meaning (\"where do we handle auth failures?\") instead of grep on exact strings.",
semanticBannerDesc:
'Build the index once and the model can find code by meaning ("where do we handle auth failures?") instead of grep on exact strings.',
semanticBannerBtn: "Build it →",
semanticBannerDismiss: "dismiss (don't show again)",
slashCommands: "slash commands",
@@ -98,9 +177,12 @@ export const en = {
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.",
presetAutoTitle:
"auto — flash baseline; auto-escalates to pro on hard turns (NEEDS_PRO / failure threshold)",
presetFlashTitle:
"flash — always flash; no auto-escalate. /pro still works for one-shot manual",
presetProTitle:
"pro — always pro; ~3× flash cost (5/31 discount). Locks in on hard architecture work.",
editGateTitle: "edit gate — Shift+Tab cycles in TUI",
editReviewTitle: "review — both edits and non-allowlisted shell ask first",
editAutoTitle: "auto — edits auto-apply, shell still asks",
@@ -139,12 +221,14 @@ export const en = {
loading: "loading overview…",
failed: "overview failed: {error}",
standaloneTitle: "Standalone mode",
standaloneDesc: "Read-only disk view. Start /dashboard from inside reasonix code for live session state, MCP, and tools.",
standaloneDesc:
"Read-only disk view. Start /dashboard from inside reasonix code for live session state, MCP, and tools.",
cockpit: "Cockpit",
balance: "balance",
tokens7d: "tokens · 7d",
cacheHit: "cache hit",
toolCalls24h: "tool calls · 24h",
budget: "budget",
currentSession: "current session",
noSession: "No live session — /dashboard from inside reasonix code to attach.",
promptTok: "prompt tok",
@@ -180,12 +264,19 @@ export const en = {
dailyMeta: "cost · cache saved · turns",
noData: "No usage data yet — run a turn in reasonix chat / code / run and refresh.",
windows: "Rolling windows",
colWindow: "window",
colTurns: "turns",
colCacheHit: "cache hit",
colCost: "cost (USD)",
colCacheSaved: "cache saved",
colVsClaude: "vs Claude",
colSaved: "saved",
axisTime: "time",
axisUsd: "USD",
axisTurns: "turns",
seriesCost: "cost",
seriesCacheSaved: "cache saved",
seriesTurns: "turns",
mostUsed: "Most used models",
colModel: "model",
},
@@ -197,7 +288,8 @@ export const en = {
msgs: "msgs",
pickHint: "Pick a session on the left to read its transcript.",
resumeTitle: "Resume in TUI",
resumeDesc: "Mid-session swap requires a restart so the message log can rewind cleanly. Quit your current session, then run:",
resumeDesc:
"Mid-session swap requires a restart so the message log can rewind cleanly. Quit your current session, then run:",
loadingTranscript: "loading transcript…",
emptyTranscript: "empty transcript.",
messages: "{count} message{s}",
@@ -213,29 +305,68 @@ export const en = {
readOnly: "read-only",
write: "write",
flat: "flat",
desc: {
web_search: "Search the public web. Returns ranked results with title, url, and snippet. Call this when the answer depends on current state — events, prices, releases, real-world status.",
web_fetch: "Download a URL and return its visible text content (scripts/styles/nav stripped). Use after web_search when a snippet isn't enough.",
run_command: "Run a shell command in the project root; returns combined stdout+stderr. Allowlisted read-only commands run immediately; mutations are gated by user confirmation.",
run_background: "Spawn a long-running process and detach. Returns a job id for tailing logs, waiting for completion, or killing. Use for dev servers, watchers, and one-shot long jobs.",
job_output: "Read the latest output of a background job. Returns the tail of the buffer and tells you whether the job is still running.",
wait_for_job: "Block server-side until a background job finishes, bounded by timeout. Use instead of polling job_output in a loop.",
stop_job: "Stop a background job. SIGTERM first, SIGKILL after a grace period. Safe to call on an already-exited job.",
list_jobs: "List every background job started this session — running and exited — with id, command, pid, and status.",
remember: "Save a memory for future sessions. Use when the user states a preference, corrects your approach, shares a non-obvious fact, or asks you to remember something.",
forget: "Delete a memory file and remove it from MEMORY.md. Use when the user asks to forget something or a remembered fact is now wrong.",
recall_memory: "Read the full body of a memory file when its one-line summary isn't enough detail.",
read_file: "Read a file under the sandbox root. Supports head/tail/range scoping to save context. Auto-returns a preview for files over 200 lines.",
list_directory: "List entries in a directory. Returns one line per entry, marking directories with a trailing slash.",
directory_tree: "Recursively list entries in a directory as an indented tree. Budget-aware with auto-collapse for large subtrees.",
search_files: "Find files whose NAME matches a substring or regex. Case-insensitive. Skips dependency/build directories by default.",
search_content: "Recursively grep file CONTENTS for a substring or regex. Returns matches in path:line:text format. The right tool for finding references.",
glob: "List files matching a glob pattern, sorted by mtime. Default limit 200, max 1000. Skips node_modules/.git/dist by default.",
get_file_info: "Stat a path under the sandbox root. Returns type, size in bytes, and mtime.",
write_file: "Create or overwrite a file with the given content. Parent directories are created as needed.",
edit_file: "Apply a SEARCH/REPLACE edit to an existing file. The search must match exactly and be unique in the file.",
multi_edit: "Apply N SEARCH/REPLACE edits across one or more files atomically. If any edit fails, no files are written.",
create_directory: "Create a directory (and any missing parents) under the sandbox root.",
move_file: "Rename or move a file or directory under the sandbox root.",
delete_file: "Delete one file under the sandbox root. Refuses directories — use delete_directory for those.",
delete_directory: "Recursively delete a directory under the sandbox root. Pass recursive:false to refuse non-empty directories.",
copy_file: "Copy a file or directory under the sandbox root. Refuses to overwrite an existing destination.",
submit_plan: "Submit one concrete plan for a review gate. Use for multi-file refactors, architecture changes, or anything expensive to undo.",
mark_step_complete: "Mark one step of the approved plan as done. Call exactly once after finishing each step.",
revise_plan: "Surgically replace the remaining steps of an in-flight plan. Done steps are never touched.",
run_skill: "Invoke a playbook from the Skills index. Pass the bare skill name. Subagent-tagged skills spawn an isolated subagent.",
spawn_subagent: "Spawn an isolated subagent for a self-contained subtask. Use for parallel fan-out or when the work needs many file reads.",
todo_write: "In-session task tracker for multi-step work. Replaces the entire list every call. No approval gate or file writes.",
ask_choice: "Present 2-6 alternatives to the user. Use when the user asks for options or you need a preference decision.",
create_skill: "Scaffold a new skill the user can invoke later via /skill. Supports inline and subagent run modes.",
add_mcp_server: "Register a new MCP server in the user's config. Takes effect on the next session. Supports stdio, SSE, and streamable-http.",
},
},
permissions: {
loading: "loading permissions…",
failed: "permissions failed: {error}",
yoloTitle: "YOLO mode",
yoloDesc: "Every shell command auto-runs, allowlist bypassed. Switch back with /mode review in the TUI.",
yoloDesc:
"Every shell command auto-runs, allowlist bypassed. Switch back with /mode review in the TUI.",
project: "project",
builtin: "builtin",
addPrefix: "add a prefix",
addPlaceholder: "e.g. \"npm run build\" or \"deploy.sh\"",
addPlaceholder: 'e.g. "npm run build" or "deploy.sh"',
clearAll: "Clear all",
alreadyIn: "{prefix} already in list",
added: "added: {prefix}",
removed: "removed: {prefix}",
cleared: "cleared {count} entr{y}",
removeConfirm: "Remove \"{prefix}\" from this project's allowlist?",
removeConfirm: 'Remove "{prefix}" from this project\'s allowlist?',
clearConfirm: "Wipe every project allowlist entry? Builtin entries are unaffected.",
projectAllowlist: "Project allowlist · {count}",
nothingStored: "Nothing stored yet for this project.",
colNum: "#",
colPrefix: "prefix",
builtinTitle: "Builtin · {count} · read-only",
standaloneWarning: "Mutations require /dashboard from inside an active reasonix code session — standalone reasonix dashboard can't tell which project's allowlist to edit.",
standaloneWarning:
"Mutations require /dashboard from inside an active reasonix code session — standalone reasonix dashboard can't tell which project's allowlist to edit.",
},
mcp: {
loading: "loading MCP…",
@@ -255,7 +386,8 @@ export const en = {
removeBtn: "Remove",
spec: "spec",
whyUnbridged: "Why unbridged?",
whyUnbridgedDesc: "This spec lives in your config.json but isn't bridged into the live session. MCP servers attach when reasonix code starts; the dashboard alone can't spawn the child process.",
whyUnbridgedDesc:
"This spec lives in your config.json but isn't bridged into the live session. MCP servers attach when reasonix code starts; the dashboard alone can't spawn the child process.",
whyUnbridgedHint: "To activate: restart reasonix code, then refresh this dashboard.",
pickHint: "Pick an MCP server on the left to inspect tools / resources / prompts.",
toolsTitle: "Tools · {count}",
@@ -283,13 +415,17 @@ export const en = {
marketplaceAlready: "already installed",
marketplaceNeedsEnv: "needs env: {names}",
marketplaceSourceTag: "[{source}]",
marketplaceNoInstall: "smithery listing — install metadata not exposed; use `npx -y @smithery/cli install {name}` directly",
marketplaceFetchOnInstall: "Smithery listing — install detail fetched on Install. http servers map to streamable-http remotes; stdio servers run via @smithery/cli.",
marketplaceNoInstall:
"smithery listing — install metadata not exposed; use `npx -y @smithery/cli install {name}` directly",
marketplaceFetchOnInstall:
"Smithery listing — install detail fetched on Install. http servers map to streamable-http remotes; stdio servers run via @smithery/cli.",
marketplaceInstalledBadge: "installed",
marketplaceUninstall: "Uninstall",
marketplaceEnvTitle: "Required environment variables",
marketplaceEnvHint: "Set these in your shell before next `reasonix code` so the bridged server can authenticate.",
marketplaceRestartHint: "Spec written to ~/.reasonix/config.json. Restart `reasonix code` to bridge the server (live hot-reload is on the roadmap).",
marketplaceEnvHint:
"Set these in your shell before next `reasonix code` so the bridged server can authenticate.",
marketplaceRestartHint:
"Spec written to ~/.reasonix/config.json. Restart `reasonix code` to bridge the server (live hot-reload is on the roadmap).",
},
memory: {
loading: "loading memory…",
@@ -332,7 +468,8 @@ export const en = {
runs7d: "runs · 7d",
pickHint: "Pick a skill on the left, or create a new one above.",
readOnlyBuiltin: "read-only · builtin",
builtinDesc: "Built-in skills ship with Reasonix; the model picks them up automatically. To customize, create a project- or global-scoped skill with the same name.",
builtinDesc:
"Built-in skills ship with Reasonix; the model picks them up automatically. To customize, create a project- or global-scoped skill with the same name.",
saved: "saved {scope}/{name}",
deleteConfirm: "Delete skill {scope}/{name}?",
reloadHint: "re-loaded on next /new or session restart",
@@ -375,6 +512,7 @@ export const en = {
filterPlaceholder: "filter plans",
active: "active",
done: "done",
idle: "idle",
steps: "steps",
pickHint: "Pick a plan on the left.",
noTitle: "(no title)",
@@ -388,11 +526,13 @@ export const en = {
ready: "ready",
setupNeeded: "setup needed",
installOllama: "Install Ollama",
installOllamaDesc: "Reasonix doesn't run package managers for you. Install Ollama first, then come back:",
installOllamaDesc:
"Reasonix doesn't run package managers for you. Install Ollama first, then come back:",
macWindows: "macOS / Windows:",
download: "download from ollama.com/download",
linux: "Linux:",
refreshHint: "Refresh after install — this panel will offer to start the daemon and pull {model}.",
refreshHint:
"Refresh after install — this panel will offer to start the daemon and pull {model}.",
daemon: "Daemon",
daemonDesc: "ollama is on your PATH but the HTTP daemon isn't reachable.",
startDaemon: "Start daemon",
@@ -404,16 +544,35 @@ export const en = {
pullModel: "Pull {model}",
indexStatus: "index status",
builtStatus: "● built",
incompatibleStatus: "● incompatible",
chunks: "chunks",
files: "files",
dim: "dim",
size: "size",
lastBuild: "last build",
builtWith: "built with",
currentTarget: "current target",
incompatibleHint: "This on-disk index was built for a different provider or model. Run Rebuild to replace it.",
runIndexHint: "Run an index to enable semantic_search.",
reIndex: "Re-index",
build: "Build",
rebuild: "Rebuild",
stop: "Stop",
provider: "provider",
providerType: "service type",
openaiCompat: "openai-compatible",
apiUrl: "API URL",
apiKey: "API key",
apiKeyStoredNote: "API key is stored in ~/.reasonix/config.json — do not share that file.",
customRequestBody: "custom request body",
invalidCustomRequestBody: "Custom request body must be valid JSON: {error}",
customRequestBodyMustBeObject: "Custom request body must be a JSON object.",
saveBeforeIndex: "Save semantic settings before starting an index.",
extraBody: "extra body",
keepExistingKey: "leave blank to keep existing key",
remoteProvider: "Remote embedding provider",
remoteProviderDesc:
"Configure the full OpenAI-compatible embeddings URL here. Reasonix will send requests exactly to the URL you provide.",
ollama: "ollama",
binary: "binary",
found: "found",
@@ -441,11 +600,14 @@ export const en = {
nothingSkipped: "nothing skipped — all walked files would be indexed.",
firstIncluded: "first {count} included file(s)",
job: "Job",
phaseSetup: "preparing",
phaseScan: "scanning files",
phaseEmbed: "embedding chunks",
phaseWrite: "writing index",
phaseDone: "done",
phaseError: "error",
phaseCancelled: "cancelled",
setupFailed: "setup failed",
stopping: "stopping",
scanned: "scanned {count}",
changed: "changed {count}",
@@ -473,7 +635,7 @@ export const en = {
shellSubtitle: "model wants to run a shell command",
shellBgSubtitle: "long-running — keeps running after approval",
runOnce: "Run once",
alwaysAllow: "Always allow \"{prefix}\"",
alwaysAllow: 'Always allow "{prefix}"',
deny: "Deny",
choiceTitle: "model wants you to pick",
typeOwn: "Type my own answer",
@@ -484,7 +646,8 @@ export const en = {
cancelSummary: "Drop the question. Model will ask what you actually want.",
planTitle: "plan submitted",
planSubtitle: "model proposed a plan; review then pick",
approveInstructions: "Optional last instructions / answers to open questions (Enter to send blank)",
approveInstructions:
"Optional last instructions / answers to open questions (Enter to send blank)",
refinePlaceholder: "What needs to change? Be specific.",
approve: "Approve",
refine: "Refine",
@@ -507,5 +670,15 @@ export const en = {
reject: "Reject",
arguments: "arguments",
revisePlaceholder: "What needs to change before the next step? Leave blank to just continue.",
pickerFilter: "Filter…",
pickerEmpty: "Nothing to show.",
pickerLoadMore: "Load more",
pickerPick: "Open",
pickerInstall: "Install",
pickerUninstall: "Uninstall",
pickerRename: "Rename…",
pickerNew: "New…",
pickerNewPlaceholder: "Name (leave blank for default)",
viewerClose: "Close",
},
};
+167 -11
View File
@@ -17,8 +17,50 @@ export const zhCN = {
tabMemory: "记忆",
tabHooks: "钩子",
tabSettings: "设置",
sectionChanges: "变更",
tabChanges: "变更",
footer: "仅 127.0.0.1 · Token 保护",
},
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: "删除",
reviewEmpty: "暂无可审查的更改",
diffSourceGit: "Git 变更",
diffSourceSession: "上一轮变更",
diffStyleUnified: "统一视图",
diffStyleSplit: "分栏视图",
expandAll: "全部展开",
collapseAll: "全部折叠",
},
common: {
loading: "加载中…",
loadingFailed: "{name}失败:{error}",
@@ -61,14 +103,43 @@ export const zhCN = {
effortHigh: "high(更便宜 / 更快)",
webSearch: "网页搜索",
webSearchNote: "web_fetch + web_search 工具",
sectionCompute: "计算",
proNext: "/pro 单轮",
proArm: "为下一轮装备",
proArmed: "已装备 — 下一轮后自动解除",
proNextNote: "下一轮使用 deepseek-v4-pro,之后自动解除",
sectionBudget: "预算",
budgetOf: "/",
budgetSetCap: "设置上限",
budgetCustom: "自定义",
budgetBumpHint: "提高上限以继续",
budgetClear: "清除上限",
budgetIdleLine: "80% 时提醒 · 100% 后拒绝执行",
budgetWarnLine: "接近上限 — 超过 100% 将拒绝执行",
budgetRefusing: "已超出上限 — 提高或清除后才会继续",
sectionLoop: "循环",
loopIdleHint: "按固定间隔自动重新提交一段提示词。",
loopCostHint: "每次迭代约 {cost}(上一轮成本)。",
loopInterval: "间隔",
loopCustom: "自定义",
loopRangeError: "间隔需在 5s..6h 之间",
loopPrompt: "提示词",
loopPromptPlaceholder: "例如:检查部署状态并汇报任何错误",
loopStart: "启动循环",
loopStop: "停止",
loopRunning: "运行中",
loopIter: "第 {iter} 次",
loopFiresIn: "{remaining} 后触发",
sectionRuntime: "运行时",
activeModel: "当前模型",
modelPricingLine: "${hit} 命中 · ${miss} 未命中 · ${out} 输出 / 100 万 tok",
editMode: "编辑模式",
editModeNote: "在对话标签页头部切换",
sectionLanguage: "语言",
language: "语言",
langEn: "English",
langZhCn: "简体中文",
},
chat: {
modeMirror: "TUI 镜像",
@@ -89,7 +160,8 @@ export const zhCN = {
clearFailed: "/clear 失败:{error}",
eventStreamError: "事件流中断 — 正在重连…",
semanticBanner: "此项目未启用语义搜索。",
semanticBannerDesc: "构建一次索引,模型即可按含义查找代码(“哪里处理认证失败?”),而不仅依赖精确字符串的 grep。",
semanticBannerDesc:
"构建一次索引,模型即可按含义查找代码(“哪里处理认证失败?”),而不仅依赖精确字符串的 grep。",
semanticBannerBtn: "构建 →",
semanticBannerDismiss: "关闭(不再显示)",
slashCommands: "斜杠命令",
@@ -139,12 +211,14 @@ export const zhCN = {
loading: "加载概览…",
failed: "概览失败:{error}",
standaloneTitle: "独立模式",
standaloneDesc: "只读磁盘视图。在 reasonix code 内启动 /dashboard 以获取实时会话状态、MCP 和工具。",
standaloneDesc:
"只读磁盘视图。在 reasonix code 内启动 /dashboard 以获取实时会话状态、MCP 和工具。",
cockpit: "驾驶舱",
balance: "余额",
tokens7d: "tokens · 7 天",
cacheHit: "缓存命中",
toolCalls24h: "工具调用 · 24 小时",
budget: "预算",
currentSession: "当前会话",
noSession: "无活跃会话 — 在 reasonix code 内执行 /dashboard 进行连接。",
promptTok: "提示 tokens",
@@ -180,12 +254,19 @@ export const zhCN = {
dailyMeta: "费用 · 缓存节省 · 轮次",
noData: "暂无用量数据 — 在 reasonix chat / code / run 中执行一轮,然后刷新。",
windows: "滚动窗口",
colWindow: "时间范围",
colTurns: "轮次",
colCacheHit: "缓存命中",
colCost: "费用 (USD)",
colCacheSaved: "缓存节省",
colVsClaude: "对比 Claude",
colSaved: "节省",
axisTime: "时间",
axisUsd: "美元",
axisTurns: "轮次",
seriesCost: "费用",
seriesCacheSaved: "缓存节省",
seriesTurns: "轮次",
mostUsed: "最常用模型",
colModel: "模型",
},
@@ -213,6 +294,43 @@ export const zhCN = {
readOnly: "只读",
write: "写入",
flat: "扁平",
desc: {
web_search: "搜索公共网络。返回带标题、URL 和摘要的排序结果。当答案的正确性依赖于当前状态时调用——事件、价格、发布、现实世界的状态。",
web_fetch: "下载 URL 并返回其可见文本内容(已剥离脚本/样式/导航)。在 web_search 摘要不够时使用。",
run_command: "在项目根目录执行 shell 命令,返回合并的标准输出和标准错误。白名单中的只读命令立即执行;可能修改状态的操作需用户确认。",
run_background: "启动一个长时间运行的进程并分离。返回任务 ID 用于查看日志、等待完成或终止。用于开发服务器、文件监听器和一次性长时间任务。",
job_output: "读取后台任务的最新输出。返回缓冲区末尾内容并告知任务是否仍在运行。",
wait_for_job: "在服务端阻塞直到后台任务完成(有超时限制)。用于替代轮询 job_output。",
stop_job: "停止后台任务。先发送 SIGTERM,宽限期后发送 SIGKILL。可安全调用已退出的任务。",
list_jobs: "列出本次会话启动的所有后台任务——运行中和已退出的——包含 ID、命令、PID 和状态。",
remember: "保存一条记忆供未来会话使用。当用户陈述偏好、纠正你的方法、分享非显而易见的事实或要求你记住某事时使用。",
forget: "删除记忆文件并从 MEMORY.md 中移除。当用户要求忘记某事或之前记住的事实已不再正确时使用。",
recall_memory: "当记忆文件的一行摘要不够详细时,读取其完整内容。",
read_file: "读取沙箱根目录下的文件。支持 head/tail/range 范围读取以节省上下文。超过 200 行的文件自动返回预览。",
list_directory: "列出目录中的条目。每行一个条目,目录以斜杠标记。",
directory_tree: "递归列出目录中的条目,以缩进树形结构显示。对大子目录自动折叠以节省预算。",
search_files: "根据名称匹配子串或正则表达式查找文件。不区分大小写。默认跳过依赖/构建目录。",
search_content: "递归搜索文件内容中的子串或正则表达式。以 path:line:text 格式返回匹配结果。查找引用的正确工具。",
glob: "按 glob 模式列出文件,按修改时间排序。默认限制 200,最大 1000。默认跳过 node_modules/.git/dist。",
get_file_info: "获取沙箱根目录下路径的状态信息。返回类型、字节大小和修改时间。",
write_file: "创建或覆盖文件,内容由参数指定。按需创建父目录。",
edit_file: "对现有文件应用 SEARCH/REPLACE 编辑。搜索必须完全匹配且在文件中唯一。",
multi_edit: "跨一个或多个文件原子性地应用 N 个 SEARCH/REPLACE 编辑。如果任何编辑失败,不写入任何文件。",
create_directory: "在沙箱根目录下创建目录(以及任何缺失的父目录)。",
move_file: "重命名或移动沙箱根目录下的文件或目录。",
delete_file: "删除沙箱根目录下的一个文件。拒绝目录——请使用 delete_directory 删除目录。",
delete_directory: "递归删除沙箱根目录下的目录。传入 recursive:false 可拒绝非空目录。",
copy_file: "复制沙箱根目录下的文件或目录。拒绝覆盖已存在的目标。",
submit_plan: "提交一个具体的计划以供审查审批。用于多文件重构、架构变更或任何撤销代价高昂的操作。",
mark_step_complete: "将已批准计划的一个步骤标记为完成。完成每个步骤后恰好调用一次。",
revise_plan: "外科手术式替换进行中计划的剩余步骤。已完成的步骤永远不会被触及。",
run_skill: "从技能索引中调用一个 playbook。传入裸技能名称。标记为子代理的技能将启动独立的子代理。",
spawn_subagent: "为一个独立子任务启动隔离的子代理。用于并行分发或需要大量文件读取的工作。",
todo_write: "多步工作的会话内任务跟踪器。每次调用替换整个列表。无审批关卡,不写入文件。",
ask_choice: "向用户展示 2-6 个选项。当用户要求选择或需要偏好决策时使用。",
create_skill: "创建一个新技能,用户可通过 /skill 命令调用。支持内联和子代理两种运行模式。",
add_mcp_server: "在用户配置中注册新的 MCP 服务器。下次会话生效。支持 stdio、SSE 和 streamable-http。",
},
},
permissions: {
loading: "加载权限…",
@@ -222,20 +340,21 @@ export const zhCN = {
project: "项目",
builtin: "内置",
addPrefix: "添加前缀",
addPlaceholder: "例如 \"npm run build\" 或 \"deploy.sh\"",
addPlaceholder: '例如 "npm run build" 或 "deploy.sh"',
clearAll: "清除全部",
alreadyIn: "{prefix} 已在列表中",
added: "已添加:{prefix}",
removed: "已移除:{prefix}",
cleared: "已清除 {count} 条",
removeConfirm: "从此项目的允许列表中移除 \"{prefix}\"?",
removeConfirm: '从此项目的允许列表中移除 "{prefix}"?',
clearConfirm: "清除所有项目允许列表条目?内置条目不受影响。",
projectAllowlist: "项目允许列表 · {count}",
nothingStored: "此项目暂无存储的条目。",
colNum: "#",
colPrefix: "前缀",
builtinTitle: "内置 · {count} · 只读",
standaloneWarning: "修改操作需要在活跃的 reasonix code 会话内执行 /dashboard — 独立模式的 reasonix dashboard 无法确定要编辑哪个项目的允许列表。",
standaloneWarning:
"修改操作需要在活跃的 reasonix code 会话内执行 /dashboard — 独立模式的 reasonix dashboard 无法确定要编辑哪个项目的允许列表。",
},
mcp: {
loading: "加载 MCP…",
@@ -255,7 +374,8 @@ export const zhCN = {
removeBtn: "移除",
spec: "规格",
whyUnbridged: "为什么未桥接?",
whyUnbridgedDesc: "此规格存在于您的 config.json 中,但未桥接到实时会话。MCP 服务器在 reasonix code 启动时连接;仪表盘本身无法生成子进程。",
whyUnbridgedDesc:
"此规格存在于您的 config.json 中,但未桥接到实时会话。MCP 服务器在 reasonix code 启动时连接;仪表盘本身无法生成子进程。",
whyUnbridgedHint: "激活方法:重启 reasonix code,然后刷新此仪表盘。",
pickHint: "选择左侧的 MCP 服务器以检查工具 / 资源 / 提示。",
toolsTitle: "工具 · {count}",
@@ -283,13 +403,16 @@ export const zhCN = {
marketplaceAlready: "已安装过",
marketplaceNeedsEnv: "需设置环境变量:{names}",
marketplaceSourceTag: "[{source}]",
marketplaceNoInstall: "Smithery 列表项 — 不暴露安装元数据;请直接 `npx -y @smithery/cli install {name}`",
marketplaceFetchOnInstall: "Smithery 列表 — 安装时再拉详情。HTTP 服务映射为 streamable-http 远端;stdio 服务通过 @smithery/cli 运行。",
marketplaceNoInstall:
"Smithery 列表项 — 不暴露安装元数据;请直接 `npx -y @smithery/cli install {name}`",
marketplaceFetchOnInstall:
"Smithery 列表 — 安装时再拉详情。HTTP 服务映射为 streamable-http 远端;stdio 服务通过 @smithery/cli 运行。",
marketplaceInstalledBadge: "已安装",
marketplaceUninstall: "卸载",
marketplaceEnvTitle: "必需的环境变量",
marketplaceEnvHint: "下次启动 `reasonix code` 之前在 shell 里设好,桥接的服务器才能正常鉴权。",
marketplaceRestartHint: "已写入 ~/.reasonix/config.json。重启 `reasonix code` 后服务器才会真正桥接(热重载在路线图上)。",
marketplaceRestartHint:
"已写入 ~/.reasonix/config.json。重启 `reasonix code` 后服务器才会真正桥接(热重载在路线图上)。",
},
memory: {
loading: "加载记忆…",
@@ -332,7 +455,8 @@ export const zhCN = {
runs7d: "次运行 · 7 天",
pickHint: "选择左侧的技能,或在上方创建新技能。",
readOnlyBuiltin: "只读 · 内置",
builtinDesc: "内置技能随 Reasonix 一起发布;模型会自动识别。如需自定义,请创建同名的项目或全局技能。",
builtinDesc:
"内置技能随 Reasonix 一起发布;模型会自动识别。如需自定义,请创建同名的项目或全局技能。",
saved: "已保存 {scope}/{name}",
deleteConfirm: "删除技能 {scope}/{name}?",
reloadHint: "在下次 /new 或会话重启时重新加载",
@@ -375,6 +499,7 @@ export const zhCN = {
filterPlaceholder: "筛选计划",
active: "进行中",
done: "已完成",
idle: "未开始",
steps: "步骤",
pickHint: "选择左侧的计划。",
noTitle: "(无标题)",
@@ -404,16 +529,34 @@ export const zhCN = {
pullModel: "拉取 {model}",
indexStatus: "索引状态",
builtStatus: "● 已构建",
incompatibleStatus: "● 不兼容",
chunks: "分块",
files: "文件",
dim: "维度",
size: "大小",
lastBuild: "上次构建",
builtWith: "构建来源",
currentTarget: "当前目标",
incompatibleHint: "磁盘上的这个索引是为不同的 provider 或 model 构建的。运行“完全重建”即可替换。",
runIndexHint: "运行索引以启用 semantic_search。",
reIndex: "重建索引",
build: "构建",
rebuild: "完全重建",
stop: "停止",
provider: "提供方",
providerType: "服务类型",
openaiCompat: "OpenAI-Compatible",
apiUrl: "API URL",
apiKey: "API Key",
customRequestBody: "自定义请求体",
invalidCustomRequestBody: "自定义请求体必须是合法 JSON:{error}",
customRequestBodyMustBeObject: "自定义请求体必须是 JSON 对象。",
saveBeforeIndex: "请先保存语义设置,再启动索引。",
extraBody: "扩展请求体",
keepExistingKey: "留空则保留现有 Key",
remoteProvider: "远程向量服务",
remoteProviderDesc:
"在这里配置 OpenAI-Compatible embeddings 的完整 URL。Reasonix 会严格使用你提供的 URL 发起请求。",
ollama: "Ollama",
binary: "二进制",
found: "已找到",
@@ -441,11 +584,14 @@ export const zhCN = {
nothingSkipped: "无跳过 — 所有遍历的文件都将被索引。",
firstIncluded: "前 {count} 个包含的文件",
job: "任务",
phaseSetup: "初始化中",
phaseScan: "扫描文件",
phaseEmbed: "嵌入分块",
phaseWrite: "写入索引",
phaseDone: "完成",
phaseError: "错误",
phaseCancelled: "已停止",
setupFailed: "初始化失败",
stopping: "停止中",
scanned: "已扫描 {count}",
changed: "已变更 {count}",
@@ -473,7 +619,7 @@ export const zhCN = {
shellSubtitle: "模型想要运行一条 Shell 命令",
shellBgSubtitle: "长时间运行 — 批准后继续运行",
runOnce: "运行一次",
alwaysAllow: "始终允许 \"{prefix}\"",
alwaysAllow: '始终允许 "{prefix}"',
deny: "拒绝",
choiceTitle: "模型需要您选择",
typeOwn: "输入自定义回答",
@@ -507,5 +653,15 @@ export const zhCN = {
reject: "拒绝",
arguments: "参数",
revisePlaceholder: "下一步之前需要更改什么?留空则直接继续。",
pickerFilter: "过滤…",
pickerEmpty: "暂无内容。",
pickerLoadMore: "加载更多",
pickerPick: "打开",
pickerInstall: "安装",
pickerUninstall: "卸载",
pickerRename: "重命名…",
pickerNew: "新建…",
pickerNewPlaceholder: "名称(留空使用默认)",
viewerClose: "关闭",
},
};
+45
View File
@@ -0,0 +1,45 @@
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
@@ -0,0 +1,13 @@
/** 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));
}
+3
View File
@@ -1,6 +1,7 @@
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);
@@ -29,10 +30,12 @@ export function reportAppError(error: unknown, source: string, info?: string): v
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");
});
+80
View File
@@ -0,0 +1,80 @@
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;
}
+232
View File
@@ -0,0 +1,232 @@
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 },
];
}
+18
View File
@@ -4,6 +4,24 @@ export function fmtUsd(n: number | null | undefined): string {
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)}%`;
+3 -32
View File
@@ -16,7 +16,6 @@ const TO_BACKEND = new Map(LANG_REGISTRY);
const FROM_BACKEND = new Map(LANG_REGISTRY.map(([d, b]) => [b, d]));
const STORAGE_KEY = "rx.lang";
const EXPLICIT_KEY = "rx.langExplicit";
const listeners: Listener[] = [];
let currentLang: DashboardLang = loadFromStorage() ?? "en";
@@ -30,22 +29,6 @@ function loadFromStorage(): DashboardLang | null {
return null;
}
function isExplicit(): boolean {
try {
return localStorage.getItem(EXPLICIT_KEY) === "1";
} catch {
return false;
}
}
function markExplicit(): void {
try {
localStorage.setItem(EXPLICIT_KEY, "1");
} catch {
/* ignore */
}
}
function toBackendLang(lang: DashboardLang): string {
return TO_BACKEND.get(lang) ?? lang;
}
@@ -54,23 +37,12 @@ function fromBackendLang(raw: string): DashboardLang {
return (FROM_BACKEND.get(raw) as DashboardLang) ?? "en";
}
/** Fetch lang from backend on startup. */
/** Adopt server lang on startup; localStorage is render-cache only, never pushed back. */
export async function initLangFromServer(): Promise<void> {
try {
const stored = loadFromStorage();
const res = await api<{ lang?: string }>("/settings");
const serverLang = res.lang ? fromBackendLang(res.lang) : null;
if (!serverLang || stored === serverLang) return;
if (isExplicit() && stored) {
// User explicitly chose a language — push to server.
api("/settings", { method: "POST", body: { lang: toBackendLang(stored) } })
.catch((err) => console.error("[reasonix dashboard] lang sync:", err));
return;
}
// No explicit choice yet (first visit or cleared storage) — adopt server value.
if (!serverLang || serverLang === currentLang) return;
currentLang = serverLang;
try {
localStorage.setItem(STORAGE_KEY, serverLang);
@@ -79,7 +51,7 @@ export async function initLangFromServer(): Promise<void> {
}
for (const cb of listeners) cb();
} catch {
/* offline — keep localStorage value */
/* offline — keep last-known value rendering */
}
}
@@ -90,7 +62,6 @@ export function getLang(): DashboardLang {
export function setLang(lang: DashboardLang): void {
if (!SUPPORTED.has(lang)) return;
currentLang = lang;
markExplicit();
try {
localStorage.setItem(STORAGE_KEY, lang);
} catch {
+90
View File
@@ -0,0 +1,90 @@
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
@@ -0,0 +1,48 @@
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`;
}
+32
View File
@@ -0,0 +1,32 @@
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 };
}
+15
View File
@@ -0,0 +1,15 @@
/** 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;
}
File diff suppressed because it is too large. Load diff
+129 -50
View File
@@ -1,3 +1,4 @@
import { memo } from "preact/compat";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import {
ChatMessage,
@@ -6,15 +7,17 @@ import {
ChoiceModal,
EditReviewModal,
type OnResolve,
PickerModal,
PlanModal,
RevisionModal,
ShellModal,
ViewerModal,
WorkspaceModal,
parseToolArgs,
} from "../components/chat-internals.js";
import { MODE, TOKEN, api } from "../lib/api.js";
import { appBus, showToast } from "../lib/bus.js";
import { fmtUsd } from "../lib/format.js";
import { fmtCost, fmtUsd } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
@@ -183,8 +186,58 @@ export function ChatPanel() {
};
}, []);
// rAF-coalesce assistant_delta events. A streaming turn fires ~20
// deltas/sec — committing each to React state forces a parent
// re-render per delta, which used to thrash the chat feed. Now the
// accumulated text lives in a ref and we flush at most once per
// frame, capping the streaming-bubble re-render rate at the display
// refresh rate. assistant_final cancels the pending flush.
const streamBufRef = useRef<StreamingState | null>(null);
const streamRafRef = useRef<number | null>(null);
const flushStreaming = useCallback(() => {
streamRafRef.current = null;
if (streamBufRef.current) setStreaming(streamBufRef.current);
}, []);
const cancelStreamingRaf = useCallback(() => {
if (streamRafRef.current !== null) {
cancelAnimationFrame(streamRafRef.current);
streamRafRef.current = null;
}
streamBufRef.current = null;
}, []);
// SSE reconnect drops missed deltas / finals / modals — server only
// snapshots `busy-change` on (re)connect. Pull /messages + /modal to
// recover canonical state, otherwise UI wedges on the last seen state (#521).
const refetchCanonicalState = useCallback(async () => {
try {
const data = await api<MessagesResponse>("/messages");
setMessages(data.messages ?? []);
setBusy(Boolean(data.busy));
cancelStreamingRaf();
setStreaming(null);
setActiveTool(null);
} catch {
/* keep current state — next event or next reconnect will retry */
}
try {
const m = await api<ModalEnvelope>("/modal");
setModal(m.modal ?? null);
} catch {
/* modal endpoint optional in standalone */
}
}, [cancelStreamingRaf]);
useEffect(() => {
const es = new EventSource(`/api/events?token=${TOKEN}`);
let firstOpen = true;
es.onopen = () => {
if (firstOpen) {
firstOpen = false;
return;
}
void refetchCanonicalState();
};
es.onmessage = (ev) => {
let dash;
try {
@@ -202,14 +255,20 @@ export function ChatPanel() {
return;
}
if (dash.kind === "assistant_delta") {
setStreaming((cur) => {
const text = (cur?.text ?? "") + (dash.contentDelta ?? "");
const reasoning = (cur?.reasoning ?? "") + (dash.reasoningDelta ?? "");
return { id: dash.id, text, reasoning };
});
const cur = streamBufRef.current;
const baseId = cur?.id === dash.id ? cur : null;
streamBufRef.current = {
id: dash.id,
text: (baseId?.text ?? "") + (dash.contentDelta ?? ""),
reasoning: (baseId?.reasoning ?? "") + (dash.reasoningDelta ?? ""),
};
if (streamRafRef.current === null) {
streamRafRef.current = requestAnimationFrame(flushStreaming);
}
return;
}
if (dash.kind === "assistant_final") {
cancelStreamingRaf();
setStreaming(null);
setMessages((prev) => [
...prev,
@@ -264,12 +323,16 @@ export function ChatPanel() {
};
es.onerror = () => {
// Auto-reconnect by default; surface a brief banner on persistent
// failure but don't tear down — EventSource retries in the background.
// failure but don't tear down — EventSource retries in the
// background. The next `onopen` will resync canonical state.
setError(t("chat.eventStreamError"));
setTimeout(() => setError(null), 3000);
};
return () => es.close();
}, []);
return () => {
es.close();
cancelStreamingRaf();
};
}, [refetchCanonicalState, cancelStreamingRaf]);
const send = useCallback(async () => {
const text = input.trim();
@@ -473,18 +536,6 @@ export function ChatPanel() {
}, 0);
}, [messages, streaming]);
const allMessages = streaming
? [
...messages,
{
id: streaming.id,
role: "assistant",
text: streaming.text,
reasoning: streaming.reasoning,
},
]
: messages;
const resolveModal = useCallback<OnResolve>(async (kind, choice, text) => {
try {
await api("/modal/resolve", {
@@ -559,7 +610,7 @@ export function ChatPanel() {
<div class="chat-shell">
<div style="display:flex;align-items:center;gap:12px;margin-bottom:10px">
<div class="chips" style="padding:0">
<span class="chip-f active">${MODE === "attached" ? t("chat.modeMirror") : t("chat.modeView")}</span>
<span class="chip-f static active">${MODE === "attached" ? t("chat.modeMirror") : t("chat.modeView")}</span>
</div>
<div class="header-pickers" style="margin-left:auto">
${
@@ -684,29 +735,17 @@ export function ChatPanel() {
? html`<${CheckpointModal} modal=${modal} onResolve=${resolveModal} />`
: modal.kind === "revision"
? html`<${RevisionModal} modal=${modal} onResolve=${resolveModal} />`
: null
: modal.kind === "picker"
? html`<${PickerModal} modal=${modal} onResolve=${resolveModal} />`
: modal.kind === "viewer"
? html`<${ViewerModal} modal=${modal} onResolve=${resolveModal} />`
: null
: null
}
<div class="chat-body">
<div class="chat-main">
<div class="chat-feed" ref=${feedRef}>
${
allMessages.length === 0
? html`<div class="chat-empty">
${t("chat.noConversation")}
</div>`
: allMessages.map(
(m) => html`
<${ChatMessage}
key=${m.id}
msg=${m}
streaming=${streaming && streaming.id === m.id}
/>
`,
)
}
</div>
<${ChatFeed} messages=${messages} streaming=${streaming} innerRef=${feedRef} />
<div class="chat-input-area" style="position:relative">
${
@@ -777,20 +816,60 @@ export function ChatPanel() {
`;
}
interface ChatFeedProps {
messages: ChatMsg[];
streaming: StreamingState | null;
innerRef: { current: HTMLDivElement | null };
}
/** Memoised so keystrokes in ChatPanel don't re-walk the message list. */
const ChatFeed = memo(function ChatFeed({ messages, streaming, innerRef }: ChatFeedProps) {
useLang();
const allMessages = streaming
? [
...messages,
{
id: streaming.id,
role: "assistant" as const,
text: streaming.text,
reasoning: streaming.reasoning,
},
]
: messages;
return html`
<div class="chat-feed" ref=${innerRef}>
${
allMessages.length === 0
? html`<div class="chat-empty">${t("chat.noConversation")}</div>`
: allMessages.map(
(m) => html`
<${ChatMessage}
key=${m.id}
msg=${m}
streaming=${Boolean(streaming && streaming.id === m.id)}
/>
`,
)
}
</div>
`;
});
interface SideRailProps {
stats: ChatStats | null;
budgetUsd: number | null;
activePlan: RailPlan | null;
}
function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
const SideRail = memo(function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
useLang();
if (!stats && !activePlan) return html`<aside class="chat-rail"></aside>`;
const cachePct = stats ? Math.round(stats.cacheHitRatio * 100) : 0;
const cachePct = stats ? stats.cacheHitRatio * 100 : 0;
const cacheTone = cachePct >= 80 ? "ok" : cachePct >= 50 ? "" : "warn";
const showBudget = stats != null && typeof budgetUsd === "number" && budgetUsd > 0;
const budgetPct = showBudget ? Math.min(120, (stats.totalCostUsd / budgetUsd) * 100) : 0;
const budgetTone = budgetPct >= 100 ? "err" : budgetPct >= 80 ? "warn" : "";
const walletCurrency = stats?.balance?.[0]?.currency;
return html`
<aside class="chat-rail">
${activePlan ? html`<${ActivePlanCard} plan=${activePlan} />` : null}
@@ -801,11 +880,11 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
<div class="rh">${t("chat.railSession")}</div>
<div class="rail-kv"><span class="k">${t("chat.railTurns")}</span><span class="v">${stats.turns.toLocaleString()}</span></div>
<div class="rail-kv"><span class="k">${t("chat.railPromptTok")}</span><span class="v">${stats.lastPromptTokens.toLocaleString()}</span></div>
<div class="rail-kv"><span class="k">${t("chat.railCost")}</span><span class="v">${fmtUsd(stats.totalCostUsd)}</span></div>
<div class="rail-kv"><span class="k">${t("chat.railCost")}</span><span class="v">${fmtCost(stats.totalCostUsd, walletCurrency)}</span></div>
<div class="progress-row" style="margin-top:8px">
<span class="lbl">${t("chat.railCacheHit")}</span>
<div class=${`progress ${cacheTone}`}><div class="progress-fill" style=${`width:${cachePct}%`}></div></div>
<span class="v">${cachePct}%</span>
<span class="v">${cachePct.toFixed(1)}%</span>
</div>
</div>
`
@@ -819,7 +898,7 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
<div class="progress-row">
<span class="lbl">${t("chat.railSpend")}</span>
<div class=${`progress ${budgetTone}`}><div class="progress-fill" style=${`width:${Math.min(100, budgetPct)}%`}></div></div>
<span class="v" style=${budgetTone === "err" ? "color:var(--c-err)" : budgetTone === "warn" ? "color:var(--c-warn)" : ""}>${fmtUsd(stats.totalCostUsd)} / ${fmtUsd(budgetUsd)}</span>
<span class="v" style=${budgetTone === "err" ? "color:var(--c-err)" : budgetTone === "warn" ? "color:var(--c-warn)" : ""}>${fmtCost(stats.totalCostUsd, walletCurrency)} / ${fmtCost(budgetUsd, walletCurrency)}</span>
</div>
</div>
`
@@ -827,7 +906,7 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
}
</aside>
`;
}
});
function ActivePlanCard({ plan }: { plan: RailPlan }) {
useLang();
@@ -956,7 +1035,7 @@ interface ChatStatusBarProps {
model: string | null;
}
function ChatStatusBar({ stats, model }: ChatStatusBarProps) {
const ChatStatusBar = memo(function ChatStatusBar({ stats, model }: ChatStatusBarProps) {
useLang();
if (!stats) {
return html`
@@ -989,11 +1068,11 @@ function ChatStatusBar({ stats, model }: ChatStatusBarProps) {
</span>
<span class="status-item">
<span class="status-label">${t("chat.statusTurn")}</span>
<code>${fmtUsd(stats.lastTurnCostUsd)}</code>
<code>${fmtCost(stats.lastTurnCostUsd, balance?.currency)}</code>
</span>
<span class="status-item">
<span class="status-label">${t("chat.statusSession")}</span>
<code>${fmtUsd(stats.totalCostUsd)}</code>
<code>${fmtCost(stats.totalCostUsd, balance?.currency)}</code>
<span class="muted" style="font-size: 10px;">
${t("chat.statusTurns", { count: stats.turns, s: stats.turns === 1 ? "" : "s" })}
</span>
@@ -1010,4 +1089,4 @@ function ChatStatusBar({ stats, model }: ChatStatusBarProps) {
}
</div>
`;
}
});
+17 -4
View File
@@ -68,6 +68,7 @@ export function HooksPanel() {
const [drafts, setDrafts] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(false);
const [info, setInfo] = useState<string | null>(null);
const [eventFilter, setEventFilter] = useState<string>("all");
const load = useCallback(async () => {
try {
@@ -129,19 +130,31 @@ export function HooksPanel() {
data.events.length > 0
? data.events
: Array.from(new Set(matrixRows.flatMap((r) => Object.keys(r.cells))));
const visibleRows =
eventFilter === "all"
? matrixRows
: matrixRows.filter((r) => r.cells[eventFilter]?.on);
const gridCols = `220px repeat(${Math.max(events.length, 1)}, minmax(0, 1fr))`;
return html`
<div style="display:flex;flex-direction:column;gap:6px">
<div class="chips">
<span class="chip-f active">${t("hooks.resolved")} <span class="ct">${data.resolved.length}</span></span>
${data.events.map((ev) => html`<span class="chip-f">${ev}</span>`)}
<span
class=${`chip-f ${eventFilter === "all" ? "active" : ""}`}
onClick=${() => setEventFilter("all")}
>${t("hooks.resolved")} <span class="ct">${data.resolved.length}</span></span>
${data.events.map(
(ev) => html`<span
class=${`chip-f ${eventFilter === ev ? "active" : ""}`}
onClick=${() => setEventFilter(ev)}
>${ev}</span>`,
)}
</div>
${info ? html`<div><span class="pill ok">${info}</span></div>` : null}
${error ? html`<div class="card accent-err">${error}</div>` : null}
${sectionH3(t("hooks.eventMatrix"), t("hooks.matrixSub", { scripts: matrixRows.length, s: matrixRows.length === 1 ? "" : "s", events: events.length }))}${
matrixRows.length === 0
visibleRows.length === 0
? html`<div class="card" style="color:var(--fg-3)">
${t("hooks.noHooks")}
</div>`
@@ -152,7 +165,7 @@ export function HooksPanel() {
<div>${t("hooks.colScript")}</div>
${events.map((ev) => html`<div>${ev}</div>`)}
</div>
${matrixRows.map(
${visibleRows.map(
(r) => html`
<div class="row" style=${`grid-template-columns:${gridCols}`}>
<div class="cell" title=${r.command}>
+31 -4
View File
@@ -1,6 +1,8 @@
import { fmtCompactNum, fmtNum, fmtRelativeTime, fmtUsd } from "../lib/format.js";
import { budgetTone, deriveBudgetState } from "../lib/budget.js";
import { fmtCompactNum, fmtCost, fmtNum, fmtRelativeTime, fmtUsd } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { compareVersions } from "../lib/version.js";
import { t, useLang } from "../i18n/index.js";
interface CockpitKpi {
@@ -65,6 +67,9 @@ interface OverviewData {
toolCount?: number;
cwd?: string;
cockpit?: CockpitData;
budgetUsd?: number | null;
/** Cumulative session spend in USD — set when a session is attached. */
sessionSpendUsd?: number | null;
}
function kpi(label: string, value: unknown, delta?: unknown, deltaTone?: "up" | "down" | "flat") {
@@ -107,6 +112,25 @@ function balanceKpi(c: CockpitData) {
return kpi(t("overview.balance"), `${symbol}${c.balance.total}`, c.balance.currency, "flat");
}
function budgetKpi(o: OverviewData) {
const state = deriveBudgetState(o.budgetUsd, o.cockpit?.currentSession?.totalCostUsd ?? null);
if (state.kind === "off") return null;
const tone = budgetTone(state);
const valueColor =
tone === "err"
? "color:var(--c-err)"
: tone === "warn"
? "color:var(--c-warn)"
: "";
return html`
<div class="kpi cock-w-1">
<div class="label">${t("overview.budget")}</div>
<div class="value" style=${valueColor}>${fmtUsd(state.spent)} / ${fmtUsd(state.cap)}</div>
<div class=${`progress ${tone}`} style="margin-top:4px"><div class="progress-fill" style=${`width:${Math.min(100, state.pct)}%`}></div></div>
</div>
`;
}
function tokens7dKpi(c: CockpitData) {
if (!c.tokens7d) return kpi(t("overview.tokens7d"), "—", t("overview.noUsageYet"), "flat");
const d = deltaPctText(c.tokens7d.deltaPct);
@@ -144,6 +168,7 @@ function currentSessionBlock(c: CockpitData) {
`;
}
const s = c.currentSession;
const currency = c.balance?.currency;
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">${t("overview.currentSession")}</span></div>
@@ -153,7 +178,7 @@ function currentSessionBlock(c: CockpitData) {
<div style="display:grid;grid-template-columns:repeat(3, 1fr);gap:8px;font-family:var(--font-mono);font-size:11px">
<div><span style="color:var(--fg-3)">${t("overview.promptTok")}</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtNum(s.lastPromptTokens)}</div></div>
<div><span style="color:var(--fg-3)">${t("overview.completionTok")}</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtNum(s.completionTokens)}</div></div>
<div><span style="color:var(--fg-3)">${t("overview.cost")}</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtUsd(s.totalCostUsd)}</div></div>
<div><span style="color:var(--fg-3)">${t("overview.cost")}</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtCost(s.totalCostUsd, currency)}</div></div>
</div>
</div>
`;
@@ -185,7 +210,7 @@ function costTrendSpark(c: CockpitData) {
return html`
<div class="chart cock-w-2">
<div class="chart-h"><span class="title">${t("overview.costTrend")}</span></div>
<div class="chart-v">${fmtUsd(avg)}<span class="unit">${t("overview.dayAvg")}</span></div>
<div class="chart-v">${fmtCost(avg, c.balance?.currency)}<span class="unit">${t("overview.dayAvg")}</span></div>
<div class="chart-spark">
<svg viewBox=${`0 0 ${w} ${h}`} preserveAspectRatio="none">
<polyline fill="none" stroke="var(--c-brand)" stroke-width="1.5" points=${points} />
@@ -256,7 +281,8 @@ export function OverviewPanel() {
recentPlans: null,
toolActivity: null,
};
const upToDate = o.latestVersion ? o.latestVersion === o.version : null;
const upToDate =
o.latestVersion && o.version ? compareVersions(o.version, o.latestVersion) >= 0 : null;
const versionDelta =
upToDate === null ? t("overview.checking") : upToDate ? t("overview.latest") : `latest: ${o.latestVersion}`;
const versionTone: "up" | "down" | "flat" = upToDate === false ? "down" : "flat";
@@ -284,6 +310,7 @@ export function OverviewPanel() {
${tokens7dKpi(c)}
${cacheHitKpi(c)}
${toolCallsKpi(c)}
${budgetKpi(o)}
${currentSessionBlock(c)}
${costTrendSpark(c)}
+2 -2
View File
@@ -122,8 +122,8 @@ export function PermissionsPanel() {
}
<div class="chips">
<span class="chip-f active">${t("permissions.project")} <span class="ct">${p.project.length}</span></span>
<span class="chip-f">${t("permissions.builtin")} <span class="ct">${p.builtin.length}</span></span>
<span class="chip-f static active">${t("permissions.project")} <span class="ct">${p.project.length}</span></span>
<span class="chip-f static">${t("permissions.builtin")} <span class="ct">${p.builtin.length}</span></span>
</div>
${
+22 -6
View File
@@ -29,7 +29,7 @@ interface PlansData {
function statusPill(p: ArchivedPlan) {
if (p.completionRatio >= 1) return html`<span class="pill ok">${t("plans.done")}</span>`;
if (p.completionRatio > 0) return html`<span class="pill info">${t("plans.active")}</span>`;
return html`<span class="pill">idle</span>`;
return html`<span class="pill">${t("plans.idle")}</span>`;
}
export function PlansPanel() {
@@ -37,6 +37,7 @@ export function PlansPanel() {
const { data, error, loading } = usePoll<PlansData>("/plans", 8000);
const [openIdx, setOpenIdx] = useState<number | null>(null);
const [filter, setFilter] = useState("");
const [statusFilter, setStatusFilter] = useState<"all" | "active" | "done">("all");
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">${t("plans.loading")}</div>`;
@@ -48,13 +49,19 @@ export function PlansPanel() {
${t("plans.noPlans")}
</div>`;
const statusFiltered =
statusFilter === "all"
? plans
: statusFilter === "active"
? plans.filter((p) => p.completionRatio > 0 && p.completionRatio < 1)
: plans.filter((p) => p.completionRatio >= 1);
const filtered = filter.trim()
? plans.filter(
? statusFiltered.filter(
(p) =>
p.session.toLowerCase().includes(filter.toLowerCase()) ||
(p.summary ?? "").toLowerCase().includes(filter.toLowerCase()),
)
: plans;
: statusFiltered;
const open = openIdx !== null ? plans[openIdx] : null;
@@ -71,12 +78,21 @@ export function PlansPanel() {
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">${t("common.all")} <span class="ct">${plans.length}</span></span>
<span class="chip-f">
<span
class=${`chip-f ${statusFilter === "all" ? "active" : ""}`}
onClick=${() => setStatusFilter("all")}
>${t("common.all")} <span class="ct">${plans.length}</span></span>
<span
class=${`chip-f ${statusFilter === "active" ? "active" : ""}`}
onClick=${() => setStatusFilter("active")}
>
${t("plans.active")}
<span class="ct">${plans.filter((p) => p.completionRatio > 0 && p.completionRatio < 1).length}</span>
</span>
<span class="chip-f">
<span
class=${`chip-f ${statusFilter === "done" ? "active" : ""}`}
onClick=${() => setStatusFilter("done")}
>
${t("plans.done")} <span class="ct">${plans.filter((p) => p.completionRatio >= 1).length}</span>
</span>
</div>
+443 -124
View File
@@ -1,13 +1,50 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { t, useLang } from "../i18n/index.js";
import { api } from "../lib/api.js";
import { fmtBytes, fmtNum, fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface SemanticConfigView {
provider: "ollama" | "openai-compat";
ollama: {
baseUrl: string;
model: string;
};
openaiCompat: {
baseUrl: string;
apiKey: string;
apiKeySet: boolean;
model: string;
extraBody: Record<string, unknown>;
};
}
interface SemanticData {
attached?: boolean;
reason?: string;
root?: string;
provider?: "ollama" | "openai-compat";
providerConfig?: SemanticConfigView;
providerStatus?:
| {
kind: "ollama";
ready: boolean;
baseUrl: string;
binaryFound?: boolean;
daemonRunning?: boolean;
modelPulled?: boolean;
modelName?: string;
installedModels?: string[];
error?: string;
}
| {
kind: "openai-compat";
ready: boolean;
baseUrl: string;
apiKeySet: boolean;
model: string;
extraBodyKeys: string[];
};
index?: IndexInfo;
job?: SemanticJob | null;
pull?: { status: string; startedAt: number; lastLine?: string } | null;
@@ -23,17 +60,25 @@ interface SemanticData {
interface IndexInfo {
exists: boolean;
provider?: "ollama" | "openai-compat";
chunks?: number;
files?: number;
dim?: number;
sizeBytes?: number;
lastBuiltMs?: number;
model?: string;
builtWith?: { provider: "ollama" | "openai-compat"; model: string };
current?: { provider: "ollama" | "openai-compat"; model: string };
compatible?: boolean;
mismatch?: "provider" | "model" | null;
}
interface SemanticJob {
phase: string;
startedAt: number;
finishedAt?: number | null;
cancelledAt?: number | null;
lastPhase?: string | null;
chunksTotal?: number;
chunksDone?: number;
filesScanned?: number;
@@ -50,17 +95,44 @@ interface SemanticJob {
};
}
interface SemanticConfigDraft {
provider: "ollama" | "openai-compat";
ollama: {
baseUrl: string;
model: string;
};
openaiCompat: {
baseUrl: string;
apiKey: string;
model: string;
extraBodyText: string;
apiKeySet: boolean;
};
}
export interface SemanticDraftValidation {
extraBody: Record<string, unknown>;
error: string | null;
}
export function SemanticPanel() {
useLang();
const [data, setData] = useState<SemanticData | null>(null);
const [draft, setDraft] = useState<SemanticConfigDraft | null>(null);
const [draftDirty, setDraftDirty] = useState(false);
const draftDirtyRef = useRef(false);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [info, setInfo] = useState<string | null>(null);
const load = useCallback(async () => {
try {
const r = await api<SemanticData>("/semantic");
setData(r);
const [semantic, config] = await Promise.all([
api<SemanticData>("/semantic"),
api<SemanticConfigView>("/semantic/config"),
]);
setData(semantic);
setDraft((current) => (current && draftDirtyRef.current ? current : toConfigDraft(config)));
} catch (err) {
setError((err as Error).message);
}
@@ -69,7 +141,7 @@ export function SemanticPanel() {
useEffect(() => {
load();
const phase = data?.job?.phase;
const running = phase === "scan" || phase === "embed" || phase === "write";
const running = isActiveSemanticPhase(phase);
const pulling = data?.pull?.status === "pulling";
const ms = running || pulling ? 1200 : 5000;
const id = setInterval(load, ms);
@@ -78,10 +150,18 @@ export function SemanticPanel() {
const start = useCallback(
async (rebuild: boolean) => {
if (!draft) return;
setBusy(true);
setError(null);
setInfo(null);
try {
const validation = validateSemanticDraft(draft);
if (draftDirty) {
throw new Error(t("semantic.saveBeforeIndex"));
}
if (validation.error) {
throw new Error(validation.error);
}
await api("/semantic/start", { method: "POST", body: { rebuild: !!rebuild } });
setInfo(rebuild ? t("semantic.rebuildStarted") : t("semantic.incrementalStarted"));
await load();
@@ -91,7 +171,7 @@ export function SemanticPanel() {
setBusy(false);
}
},
[load],
[draft, draftDirty, load],
);
const stop = useCallback(async () => {
@@ -113,10 +193,11 @@ export function SemanticPanel() {
setError(null);
setInfo(t("semantic.startingDaemon"));
try {
const r = await api<{ ready: boolean }>("/semantic/ollama/start", { method: "POST", body: {} });
setInfo(
r.ready ? t("semantic.daemonUp") : t("semantic.daemonTimeout"),
);
const r = await api<{ ready: boolean }>("/semantic/ollama/start", {
method: "POST",
body: {},
});
setInfo(r.ready ? t("semantic.daemonUp") : t("semantic.daemonTimeout"));
await load();
} catch (err) {
setError((err as Error).message);
@@ -142,10 +223,45 @@ export function SemanticPanel() {
[load],
);
if (!data && !error)
const saveProviderConfig = useCallback(async () => {
if (!draft) return;
setBusy(true);
setError(null);
setInfo(null);
try {
const extraBody = semanticValidation.extraBody;
await api("/semantic/config", {
method: "POST",
body: {
provider: draft.provider,
ollama: {
baseUrl: draft.ollama.baseUrl,
model: draft.ollama.model,
},
openaiCompat: {
baseUrl: draft.openaiCompat.baseUrl,
apiKey: draft.openaiCompat.apiKey,
model: draft.openaiCompat.model,
extraBody,
},
},
});
setDraftDirty(false);
draftDirtyRef.current = false;
setInfo(t("semantic.savedConfig", { count: 1 }));
await load();
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}, [draft, load]);
if (!data && !error) {
return html`<div class="card" style="color:var(--fg-3)">${t("common.loading")}</div>`;
}
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
if (!data || !draft) return null;
if (!data.attached) {
return html`
@@ -158,43 +274,185 @@ export function SemanticPanel() {
const job = data.job;
const phase = job?.phase;
const running = phase === "scan" || phase === "embed" || phase === "write";
const running = isActiveSemanticPhase(phase);
const pull = data.pull;
const pulling = pull?.status === "pulling";
const o = data.ollama ?? {};
const binaryFound = o.binaryFound === true;
const daemonRunning = o.daemonRunning === true;
const modelPulled = o.modelPulled === true;
const modelName = o.modelName ?? "nomic-embed-text";
const installedModels = o.installedModels ?? [];
const ready = binaryFound && daemonRunning && modelPulled;
const provider = data.providerStatus?.kind ?? draft.provider;
const ready = data.providerStatus?.ready === true;
const isOllama = provider === "ollama";
const ollama = data.providerStatus?.kind === "ollama" ? data.providerStatus : null;
const remote = data.providerStatus?.kind === "openai-compat" ? data.providerStatus : null;
const binaryFound = ollama?.binaryFound === true;
const daemonRunning = ollama?.daemonRunning === true;
const modelPulled = ollama?.modelPulled === true;
const modelName = isOllama
? (ollama?.modelName ?? draft.ollama.model ?? "nomic-embed-text")
: draft.openaiCompat.model;
const sectionH3 = (text: string) => html`
<h3 style="margin:18px 0 8px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">${text}</h3>
`;
const idx = data.index;
const indexReady = idx?.exists === true && idx.compatible !== false;
const indexMismatch = idx?.exists === true && idx.compatible === false;
const semanticValidation = validateSemanticDraft(draft);
const semanticDraftBlocked = draftDirty || semanticValidation.error !== null;
return html`
<div style="display:grid;grid-template-columns:minmax(0,1fr) 280px;gap:14px;align-items:start">
<div style="display:flex;flex-direction:column;gap:10px;min-width:0">
<div class="chips">
<span class=${`chip-f ${idx?.exists ? "active" : ""}`}>
${idx?.exists ? t("semantic.indexBuilt") : t("semantic.noIndex")}
<span class=${`chip-f static ${indexReady ? "active" : ""}`}>
${indexReady ? t("semantic.indexBuilt") : t("semantic.noIndex")}
</span>
${
ready
? html`<span class="chip-f" style="border-color:var(--c-ok);color:var(--c-ok)">${t("semantic.ready")}</span>`
: html`<span class="chip-f" style="border-color:var(--c-warn);color:var(--c-warn)">${t("semantic.setupNeeded")}</span>`
? html`<span class="chip-f static" style="border-color:var(--c-ok);color:var(--c-ok)">${t("semantic.ready")}</span>`
: html`<span class="chip-f static" style="border-color:var(--c-warn);color:var(--c-warn)">${t("semantic.setupNeeded")}</span>`
}
</div>
${info ? html`<div><span class="pill info">${info}</span></div>` : null}
${error ? html`<div class="card accent-err">${error}</div>` : null}
${idx?.exists ? html`<${SemanticSearchSection} />` : null}
<div class="card">
<div class="card-h"><span class="title">${t("semantic.provider")}</span></div>
<div class="form-row">
<span class="lbl">${t("semantic.providerType")}</span>
<select
class="input mono"
value=${draft.provider}
onInput=${(e: Event) => {
draftDirtyRef.current = true;
setDraftDirty(true);
setDraft({
...draft,
provider: (e.target as HTMLSelectElement).value as "ollama" | "openai-compat",
});
}}
>
<option value="ollama">Ollama</option>
<option value="openai-compat">OpenAI-Compatible</option>
</select>
</div>
${
draft.provider === "ollama"
? html`
<div class="form-row">
<span class="lbl">${t("semantic.model")}</span>
<input
class="input mono"
type="text"
value=${draft.ollama.model}
onInput=${(e: Event) => {
draftDirtyRef.current = true;
setDraftDirty(true);
setDraft({
...draft,
ollama: { ...draft.ollama, model: (e.target as HTMLInputElement).value },
});
}}
/>
</div>
`
: html`
<div class="form-row">
<span class="lbl">${t("semantic.apiUrl")}</span>
<input
class="input mono"
type="text"
placeholder="https://api.openai.com/v1/embeddings"
value=${draft.openaiCompat.baseUrl}
onInput=${(e: Event) => {
draftDirtyRef.current = true;
setDraftDirty(true);
setDraft({
...draft,
openaiCompat: {
...draft.openaiCompat,
baseUrl: (e.target as HTMLInputElement).value,
},
});
}}
/>
</div>
<div class="form-row">
<span class="lbl">${t("semantic.apiKey")}</span>
<input
class="input mono"
type="password"
placeholder=${draft.openaiCompat.apiKeySet ? t("semantic.keepExistingKey") : "sk-..."}
value=${draft.openaiCompat.apiKey}
onInput=${(e: Event) => {
draftDirtyRef.current = true;
setDraftDirty(true);
setDraft({
...draft,
openaiCompat: {
...draft.openaiCompat,
apiKey: (e.target as HTMLInputElement).value,
},
});
}}
/>
<div style="color:var(--fg-3);font-size:12px">${t("semantic.apiKeyStoredNote")}</div>
</div>
<div class="form-row">
<span class="lbl">${t("semantic.model")}</span>
<input
class="input mono"
type="text"
value=${draft.openaiCompat.model}
onInput=${(e: Event) => {
draftDirtyRef.current = true;
setDraftDirty(true);
setDraft({
...draft,
openaiCompat: {
...draft.openaiCompat,
model: (e.target as HTMLInputElement).value,
},
});
}}
/>
</div>
<details style="margin-top:10px">
<summary style="cursor:pointer;color:var(--fg-2);font-size:12px">${t("semantic.customRequestBody")}</summary>
<div class="form-row" style="margin-top:10px">
<span class="lbl">${t("semantic.customRequestBody")}</span>
<textarea
class="input mono"
rows="6"
value=${draft.openaiCompat.extraBodyText}
onInput=${(e: Event) => {
draftDirtyRef.current = true;
setDraftDirty(true);
setDraft({
...draft,
openaiCompat: {
...draft.openaiCompat,
extraBodyText: (e.target as HTMLTextAreaElement).value,
},
});
}}
></textarea>
</div>
</details>
${
semanticValidation.error
? html`<div style="color:var(--c-err);font-size:12px;margin-top:-2px">${semanticValidation.error}</div>`
: null
}
`
}
<div style="display:flex;gap:6px;margin-top:10px">
<button class="btn primary" disabled=${busy || semanticValidation.error !== null} onClick=${saveProviderConfig}>${t("common.save")}</button>
</div>
</div>
${info ? html`<div><span class="pill info">${info}</span></div>` : null}
${indexReady ? html`<${SemanticSearchSection} />` : null}
${
!binaryFound
isOllama && !binaryFound
? html`
<div class="card">
<div class="card-h"><span class="title">${t("semantic.installOllama")}</span></div>
@@ -211,7 +469,7 @@ export function SemanticPanel() {
: null
}
${
binaryFound && !daemonRunning
isOllama && binaryFound && !daemonRunning
? html`
<div class="card">
<div class="card-h"><span class="title">${t("semantic.daemon")}</span></div>
@@ -227,7 +485,7 @@ export function SemanticPanel() {
: null
}
${
daemonRunning && !modelPulled
isOllama && daemonRunning && !modelPulled
? html`
<div class="card">
<div class="card-h"><span class="title">${t("semantic.model")}</span></div>
@@ -254,6 +512,18 @@ export function SemanticPanel() {
`
: null
}
${
!isOllama
? html`
<div class="card">
<div class="card-h"><span class="title">${t("semantic.remoteProvider")}</span></div>
<div class="card-b" style="font-size:13px;color:var(--fg-2)">
${t("semantic.remoteProviderDesc")}
</div>
</div>
`
: null
}
${
job
@@ -272,7 +542,9 @@ export function SemanticPanel() {
<span class="meta">
${
idx?.exists
? html`<span class="pill ok">${t("semantic.builtStatus")}</span>`
? idx.compatible === false
? html`<span class="pill warn">${t("semantic.incompatibleStatus")}</span>`
: html`<span class="pill ok">${t("semantic.builtStatus")}</span>`
: html`<span class="pill">${t("system.none")}</span>`
}
</span>
@@ -280,44 +552,56 @@ export function SemanticPanel() {
${
idx?.exists
? html`
<div class="rail-kv"><span class="k">${t("semantic.provider")}</span><span class="v">${idx.builtWith?.provider ?? idx.provider ?? provider}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.chunks")}</span><span class="v">${fmtNum(idx.chunks)}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.files")}</span><span class="v">${fmtNum(idx.files)}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.model")}</span><span class="v" style="font-size:11px">${idx.model ?? modelName}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.model")}</span><span class="v" style="font-size:11px">${idx.builtWith?.model ?? idx.model ?? modelName}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.dim")}</span><span class="v">${fmtNum(idx.dim)}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.size")}</span><span class="v">${fmtBytes(idx.sizeBytes)}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.lastBuild")}</span><span class="v">${fmtRelativeTime(idx.lastBuiltMs ?? null)}</span></div>
${
idx.compatible === false
? html`
<div class="rail-kv"><span class="k">${t("semantic.builtWith")}</span><span class="v" style="font-size:11px">${idx.builtWith?.provider} · ${idx.builtWith?.model}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.currentTarget")}</span><span class="v" style="font-size:11px">${idx.current?.provider} · ${idx.current?.model}</span></div>
<div style="color:var(--c-warn);font-size:12px;padding-top:8px">${t("semantic.incompatibleHint")}</div>
`
: null
}
`
: html`
<div style="color:var(--fg-3);font-size:12.5px;padding:6px 0">
${t("semantic.runIndexHint")}
</div>
`
: html`<div style="color:var(--fg-3);font-size:12.5px;padding:6px 0">${t("semantic.runIndexHint")}</div>`
}
<div style="display:flex;gap:6px;margin-top:10px;flex-wrap:wrap">
<button class="primary" disabled=${busy || running || !ready} onClick=${() => start(false)}>${idx?.exists ? t("semantic.reIndex") : t("semantic.build")}</button>
<button class="primary" disabled=${busy || running || !ready || semanticDraftBlocked} onClick=${() => start(false)}>${indexReady ? t("semantic.reIndex") : t("semantic.build")}</button>
${
idx?.exists
? html`<button disabled=${busy || running || !ready} onClick=${() => start(true)}>${t("semantic.rebuild")}</button>`
? html`<button disabled=${busy || running || !ready || semanticDraftBlocked} onClick=${() => start(true)}>${t("semantic.rebuild")}</button>`
: null
}
${
running
? html`<button onClick=${stop} style="border-color:var(--c-err);color:var(--c-err)">${t("semantic.stop")}</button>`
: null
}
${running ? html`<button onClick=${stop} style="border-color:var(--c-err);color:var(--c-err)">${t("semantic.stop")}</button>` : null}
</div>
</div>
<div class="card">
<div class="card-h"><span class="title">${t("semantic.ollama")}</span></div>
<div class="rail-kv">
<span class="k">${t("semantic.binary")}</span>
<span class="v">${binaryFound ? html`<span class="pill ok">${t("semantic.found")}</span>` : html`<span class="pill err">${t("semantic.missing")}</span>`}</span>
</div>
<div class="rail-kv">
<span class="k">${t("semantic.daemonStatus")}</span>
<span class="v">${daemonRunning ? html`<span class="pill ok">${t("semantic.up")}</span>` : html`<span class="pill warn">${t("semantic.down")}</span>`}</span>
</div>
<div class="rail-kv">
<span class="k">${t("semantic.model")}</span>
<span class="v">${modelPulled ? html`<span class="pill ok">${t("semantic.pulled")}</span>` : html`<span class="pill warn">${t("semantic.missing")}</span>`}</span>
</div>
<div class="card-h"><span class="title">${isOllama ? t("semantic.ollama") : t("semantic.openaiCompat")}</span></div>
${
isOllama
? html`
<div class="rail-kv"><span class="k">${t("semantic.binary")}</span><span class="v">${binaryFound ? html`<span class="pill ok">${t("semantic.found")}</span>` : html`<span class="pill err">${t("semantic.missing")}</span>`}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.daemonStatus")}</span><span class="v">${daemonRunning ? html`<span class="pill ok">${t("semantic.up")}</span>` : html`<span class="pill warn">${t("semantic.down")}</span>`}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.model")}</span><span class="v">${modelPulled ? html`<span class="pill ok">${t("semantic.pulled")}</span>` : html`<span class="pill warn">${t("semantic.missing")}</span>`}</span></div>
`
: html`
<div class="rail-kv"><span class="k">${t("semantic.apiUrl")}</span><span class="v" style="font-size:11px;max-width:160px;overflow-wrap:anywhere;word-break:break-word;text-align:right">${remote?.baseUrl ?? draft.openaiCompat.baseUrl}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.apiKey")}</span><span class="v">${remote?.apiKeySet ? html`<span class="pill ok">${t("semantic.found")}</span>` : html`<span class="pill warn">${t("semantic.missing")}</span>`}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.model")}</span><span class="v" style="font-size:11px">${remote?.model ?? draft.openaiCompat.model}</span></div>
<div class="rail-kv"><span class="k">${t("semantic.extraBody")}</span><span class="v">${fmtNum(remote?.extraBodyKeys.length ?? 0)}</span></div>
`
}
</div>
<${SemanticExcludesCard} />
@@ -326,6 +610,46 @@ export function SemanticPanel() {
`;
}
function toConfigDraft(config: SemanticConfigView): SemanticConfigDraft {
return {
provider: config.provider,
ollama: {
baseUrl: config.ollama.baseUrl,
model: config.ollama.model,
},
openaiCompat: {
baseUrl: config.openaiCompat.baseUrl,
apiKey: "",
model: config.openaiCompat.model,
extraBodyText: JSON.stringify(config.openaiCompat.extraBody ?? {}, null, 2),
apiKeySet: config.openaiCompat.apiKeySet,
},
};
}
export function validateSemanticDraft(draft: SemanticConfigDraft): SemanticDraftValidation {
if (draft.provider !== "openai-compat") {
return { extraBody: {}, error: null };
}
const raw = draft.openaiCompat.extraBodyText.trim();
if (!raw) {
return { extraBody: {}, error: null };
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (err) {
return {
extraBody: {},
error: t("semantic.invalidCustomRequestBody", { error: (err as Error).message }),
};
}
if (!isPlainObject(parsed)) {
return { extraBody: {}, error: t("semantic.customRequestBodyMustBeObject") };
}
return { extraBody: parsed, error: null };
}
interface IndexConfig {
excludeDirs?: string[];
excludeFiles?: string[];
@@ -367,6 +691,7 @@ interface SearchHit {
interface SearchResponse {
hits: SearchHit[];
elapsedMs: number;
provider?: string;
model: string;
}
@@ -422,13 +747,15 @@ function SemanticSearchSection() {
hits || busy || error
? html`
<div style="font-family:var(--font-mono);font-size:11px;color:var(--fg-3);margin:8px 0 6px;display:flex;align-items:center;gap:8px">
${busy
? html`<span>${t("semantic.searching")}</span>`
: error
? html`<span style="color:var(--c-err)">${error}</span>`
: hits
? html`<span>${t("semantic.results", { count: hits.length, s: hits.length === 1 ? "" : "s", ms: meta?.elapsedMs ?? 0, model: meta?.model ?? "" })}</span>`
: null}
${
busy
? html`<span>${t("semantic.searching")}</span>`
: error
? html`<span style="color:var(--c-err)">${error}</span>`
: hits
? html`<span>${t("semantic.results", { count: hits.length, s: hits.length === 1 ? "" : "s", ms: meta?.elapsedMs ?? 0, model: meta?.model ?? "" })}</span>`
: null
}
</div>
${
hits && hits.length > 0
@@ -449,8 +776,8 @@ function SemanticSearchSection() {
</div>
`
: hits && hits.length === 0 && !busy
? html`<div class="card" style="color:var(--fg-3);font-size:12px">${t("semantic.noMatches")}</div>`
: null
? html`<div class="card" style="color:var(--fg-3);font-size:12px">${t("semantic.noMatches")}</div>`
: null
}
`
: null
@@ -570,11 +897,7 @@ function SemanticExcludesCard() {
<div class="card-h">
<span class="title">${t("semantic.indexConfig")}</span>
<span class="meta">
<a
class="mono"
style="color:var(--c-brand);text-decoration:none;font-size:11px;cursor:pointer"
onClick=${reset}
>${t("semantic.reset")}</a>
<a class="mono" style="color:var(--c-brand);text-decoration:none;font-size:11px;cursor:pointer" onClick=${reset}>${t("semantic.reset")}</a>
</span>
</div>
${info ? html`<div style="margin-bottom:8px"><span class="pill ok">${info}</span></div>` : null}
@@ -606,11 +929,7 @@ function SemanticExcludesCard() {
placeholder="**/*.test.ts"
/>
<div
class="checkbox-row"
style="margin-top:8px;cursor:pointer"
onClick=${() => setDraft({ ...draft, respectGitignore: !draft.respectGitignore })}
>
<div class="checkbox-row" style="margin-top:8px;cursor:pointer" onClick=${() => setDraft({ ...draft, respectGitignore: !draft.respectGitignore })}>
<span class=${`box ${draft.respectGitignore ? "on" : ""}`}>${draft.respectGitignore ? "✓" : ""}</span>
<span>${t("semantic.respectGitignore")}</span>
</div>
@@ -623,17 +942,14 @@ function SemanticExcludesCard() {
min="1024"
step="1024"
value=${draft.maxFileBytes}
onInput=${(e: Event) =>
setDraft({ ...draft, maxFileBytes: Number((e.target as HTMLInputElement).value) || 0 })}
onInput=${(e: Event) => setDraft({ ...draft, maxFileBytes: Number((e.target as HTMLInputElement).value) || 0 })}
style="font-size:12px"
/>
<span class="help">${t("semantic.skipLarger", { size: (draft.maxFileBytes / 1024 / 1024).toFixed(1) })}</span>
</div>
<div style="display:flex;gap:6px;margin-top:10px">
<button class="btn ghost" style="flex:1" disabled=${busy} onClick=${runPreview}>
<span class="g">⊕</span><span>${t("semantic.preview")}</span>
</button>
<button class="btn ghost" style="flex:1" disabled=${busy} onClick=${runPreview}><span class="g">⊕</span><span>${t("semantic.preview")}</span></button>
<button class="btn primary" style="flex:1" disabled=${busy} onClick=${save}>${t("common.save")}</button>
</div>
@@ -659,26 +975,24 @@ function ExcludesPreview({ preview }: { preview: PreviewData }) {
].filter((k) => (buckets[k] || 0) > 0);
return html`
<div class="excludes-preview">
<div class="summary">
${t("semantic.previewSummary", { included: preview.filesIncluded, skipped: totalSkipped })}
</div>
<div class="summary">${t("semantic.previewSummary", { included: preview.filesIncluded, skipped: totalSkipped })}</div>
${
reasons.length === 0
? html`<div style="color:var(--fg-3)">${t("semantic.nothingSkipped")}</div>`
: reasons.map(
(r) => html`
<details>
<summary><strong>${r}: ${buckets[r]}</strong></summary>
<ul>
${(samples[r] || []).map((p) => html`<li><code>${p}</code></li>`)}
${
(buckets[r] || 0) > (samples[r] || []).length
? html`<li style="color:var(--fg-3)">…${(buckets[r] || 0) - (samples[r] || []).length} more</li>`
: null
}
</ul>
</details>
`,
<details>
<summary><strong>${r}: ${buckets[r]}</strong></summary>
<ul>
${(samples[r] || []).map((p) => html`<li><code>${p}</code></li>`)}
${
(buckets[r] || 0) > (samples[r] || []).length
? html`<li style="color:var(--fg-3)">…${(buckets[r] || 0) - (samples[r] || []).length} more</li>`
: null
}
</ul>
</details>
`,
)
}
${
@@ -723,14 +1037,11 @@ function ChipFormRow({
};
return html`
<div class="form-row">
<span class="lbl">
${label}
${sub ? html`<span style="color:var(--fg-3);font-weight:400;text-transform:none;letter-spacing:0"> · ${sub}</span>` : null}
</span>
<span class="lbl">${label}${sub ? html`<span style="color:var(--fg-3);font-weight:400;text-transform:none;letter-spacing:0"> · ${sub}</span>` : null}</span>
<div style="display:flex;flex-wrap:wrap;gap:4px">
${value.map(
(e) => html`
<span class="chip-f">
<span class="chip-f static">
<span>${e}</span>
<span class="x" style="cursor:pointer" onClick=${() => remove(e)} title="remove">×</span>
</span>
@@ -758,30 +1069,38 @@ function ChipFormRow({
function SemanticJobView({ job, running }: { job: SemanticJob; running: boolean }) {
useLang();
const phaseLabel =
({
scan: t("semantic.phaseScan"),
embed: t("semantic.phaseEmbed"),
write: t("semantic.phaseWrite"),
done: t("semantic.phaseDone"),
error: t("semantic.phaseError"),
} as Record<string, string>)[job.phase] ?? job.phase;
(
{
setup: t("semantic.phaseSetup"),
scan: t("semantic.phaseScan"),
embed: t("semantic.phaseEmbed"),
write: t("semantic.phaseWrite"),
done: t("semantic.phaseDone"),
error: t("semantic.phaseError"),
cancelled: t("semantic.phaseCancelled"),
} as Record<string, string>
)[job.phase] ?? job.phase;
const total = job.chunksTotal ?? 0;
const doneN = job.chunksDone ?? 0;
const ratio = total > 0 ? Math.min(1, doneN / total) : 0;
const elapsed = ((Date.now() - job.startedAt) / 1000).toFixed(1);
const elapsedBase = job.finishedAt ?? Date.now();
const elapsedSeconds = (elapsedBase - job.startedAt) / 1000;
const elapsed = elapsedSeconds < 0.1 ? "<0.1s" : `${elapsedSeconds.toFixed(1)}s`;
const phaseSummary =
job.phase === "error" && job.lastPhase === "setup"
? t("semantic.setupFailed")
: phaseLabel;
return html`
<div class="kv">
<div><span class="kv-key">phase</span>
<span class=${`pill ${job.phase === "error" ? "pill-err" : running ? "pill-active" : "pill-dim"}`}>${phaseLabel}</span>
${job.aborted ? html`<span class="pill warn" style="margin-left: 6px;">${t("semantic.stopping")}</span>` : null}
<span style="color:var(--fg-3);margin-left:8px">${elapsed}s</span>
<span class=${`pill ${job.phase === "error" ? "pill-err" : job.phase === "cancelled" ? "warn" : running ? "pill-active" : "pill-dim"}`}>${phaseSummary}</span>
${job.aborted && running ? html`<span class="pill warn" style="margin-left: 6px;">${t("semantic.stopping")}</span>` : null}
<span style="color:var(--fg-3);margin-left:8px">${elapsed}</span>
</div>
${
job.filesScanned !== null && job.filesScanned !== undefined
? html`<div><span class="kv-key">${t("semantic.files")}</span>${t("semantic.scanned", { count: job.filesScanned })}${
job.filesChanged != null ? ` · ${t("semantic.changed", { count: job.filesChanged })}` : ""
}${job.filesSkipped ? ` · ${t("semantic.skipped", { count: job.filesSkipped })}` : ""}</div>`
? html`<div><span class="kv-key">${t("semantic.files")}</span>${t("semantic.scanned", { count: job.filesScanned })}${job.filesChanged != null ? ` · ${t("semantic.changed", { count: job.filesChanged })}` : ""}${job.filesSkipped ? ` · ${t("semantic.skipped", { count: job.filesSkipped })}` : ""}</div>`
: null
}
${
@@ -796,23 +1115,13 @@ function SemanticJobView({ job, running }: { job: SemanticJob; running: boolean
`
: null
}
${
job.error
? html`<div><span class="kv-key">${t("semantic.phaseError")}</span><span class="err">${job.error}</span></div>`
: null
}
${job.error ? html`<div><span class="kv-key">${t("semantic.phaseError")}</span><span class="err">${job.error}</span></div>` : null}
${
job.result
? html`<div><span class="kv-key">${t("semantic.result")}</span>${t("semantic.added", { count: job.result.chunksAdded })} · ${t("semantic.removed", { count: job.result.chunksRemoved })}${
job.result.chunksSkipped ? ` · ${t("semantic.failed", { count: job.result.chunksSkipped })}` : ""
} · ${(job.result.durationMs / 1000).toFixed(1)}s</div>`
: null
}
${
job.result?.skipBuckets
? html`<${SkipBucketsView} buckets=${job.result.skipBuckets} />`
? html`<div><span class="kv-key">${t("semantic.result")}</span>${t("semantic.added", { count: job.result.chunksAdded })} · ${t("semantic.removed", { count: job.result.chunksRemoved })}${job.result.chunksSkipped ? ` · ${t("semantic.failed", { count: job.result.chunksSkipped })}` : ""} · ${(job.result.durationMs / 1000).toFixed(1)}s</div>`
: null
}
${job.result?.skipBuckets ? html`<${SkipBucketsView} buckets=${job.result.skipBuckets} />` : null}
</div>
`;
}
@@ -836,3 +1145,13 @@ function SkipBucketsView({ buckets }: { buckets: Record<string, number> }) {
.map(([k, label]) => `${label}: ${buckets[k]}`);
return html`<div><span class="kv-key">${t("semantic.skipped")}</span>${t("semantic.skippedFiles", { total, details: parts.join(", ") })}</div>`;
}
function isActiveSemanticPhase(phase: string | undefined): boolean {
return phase === "setup" || phase === "scan" || phase === "embed" || phase === "write";
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
+1 -1
View File
@@ -68,7 +68,7 @@ export function SessionsPanel() {
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">${t("common.all")} <span class="ct">${sessions.length}</span></span>
<span class="chip-f static active">${t("common.all")} <span class="ct">${sessions.length}</span></span>
</div>
<div class="ssl-rows">
${filtered.map(
+487 -2
View File
@@ -1,6 +1,20 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import {
type BudgetState,
QUICK_CAPS_USD,
budgetTone,
bumpSuggestions,
deriveBudgetState,
} from "../lib/budget.js";
import { html } from "../lib/html.js";
import {
INTERVAL_PRESETS_MS,
type IntervalUnit,
type LoopRunStatus,
formatRemaining,
parseCustomInterval,
} from "../lib/loop-control.js";
import { type DashboardLang, getLang, setLang, t, useLang } from "../i18n/index.js";
interface SettingsData {
@@ -11,6 +25,364 @@ interface SettingsData {
search?: boolean;
model?: string;
editMode?: string;
proNext?: boolean;
budgetUsd?: number | null;
/** Cumulative session spend (USD); null when no session is attached. */
sessionSpendUsd?: number | null;
}
function fmtUsd2(n: number): string {
return `$${n.toFixed(n < 1 ? 4 : 2)}`;
}
interface ModelPriceEntry {
inputCacheHit: number;
inputCacheMiss: number;
output: number;
}
interface ModelCatalog {
models: string[] | null;
current: string | null;
pricing: Record<string, ModelPriceEntry>;
}
function formatPricing(p: ModelPriceEntry | undefined): string | null {
if (!p) return null;
return t("settings.modelPricingLine", {
hit: p.inputCacheHit.toFixed(3),
miss: p.inputCacheMiss.toFixed(3),
out: p.output.toFixed(3),
});
}
function ModelRow({
current,
catalog,
saving,
onPick,
}: {
current: string;
catalog: ModelCatalog | null;
saving: boolean;
onPick: (model: string) => void;
}) {
const list = catalog?.models ?? null;
const ready = list && list.length > 0;
if (!ready) {
// Fallback: catalog hasn't loaded (or API failed). Read-only — same as before D-4.
return html`<code class="mono">${current ?? "—"}</code>`;
}
// Ensure the live model is selectable even if the catalog hasn't reported it
// yet (preset overrides, custom IDs).
const options = list.includes(current) ? list : [current, ...list];
const price = catalog?.pricing[current];
return html`
<span style="display:inline-flex;flex-direction:column;gap:4px">
<select
value=${current}
onChange=${(e: Event) => {
const next = (e.target as HTMLSelectElement).value;
if (next && next !== current) onPick(next);
}}
disabled=${saving}
style="font-family:var(--font-mono);min-width:200px"
>
${options.map((m) => html`<option key=${m} value=${m}>${m}</option>`)}
</select>
${
price
? html`<span style="color:var(--fg-3);font-size:11px;font-family:var(--font-mono)">${formatPricing(price)}</span>`
: null
}
</span>
`;
}
function BudgetGauge({ state }: { state: BudgetState }) {
if (state.kind === "off") return null;
const tone = budgetTone(state);
const fill = Math.min(100, state.pct);
const valueColor =
tone === "err"
? "color:var(--c-err)"
: tone === "warn"
? "color:var(--c-warn)"
: "color:var(--fg-1)";
return html`
<div style="display:flex;flex-direction:column;gap:6px">
<div style="display:flex;justify-content:space-between;align-items:baseline;font-size:13px">
<span style=${valueColor}>
<strong style="font-family:var(--font-mono)">${fmtUsd2(state.spent)}</strong>
<span style="color:var(--fg-3)"> ${t("settings.budgetOf")} </span>
<strong style="font-family:var(--font-mono)">${fmtUsd2(state.cap)}</strong>
</span>
<span style=${`font-family:var(--font-mono);font-size:11px;${valueColor}`}>${state.pct.toFixed(1)}%</span>
</div>
<div class=${`progress ${tone}`}><div class="progress-fill" style=${`width:${fill}%`}></div></div>
<span style="color:var(--fg-3);font-size:11px">
${
state.kind === "exhausted"
? t("settings.budgetRefusing")
: state.kind === "warn"
? t("settings.budgetWarnLine")
: t("settings.budgetIdleLine")
}
</span>
</div>
`;
}
interface BudgetSectionProps {
state: BudgetState;
saving: boolean;
onSetCap: (usd: number) => void;
onClear: () => void;
}
function BudgetSection({ state, saving, onSetCap, onClear }: BudgetSectionProps) {
const [custom, setCustom] = useState("");
const submitCustom = () => {
const n = Number.parseFloat(custom);
if (Number.isFinite(n) && n > 0) {
onSetCap(n);
setCustom("");
}
};
const quickButtons = (caps: ReadonlyArray<number>) =>
caps.map(
(c) => html`
<button
key=${c}
class="btn"
style="font-family:var(--font-mono)"
disabled=${saving}
onClick=${() => onSetCap(c)}
>$${c}</button>
`,
);
const customField = html`
<span style="display:inline-flex;align-items:center;gap:4px;margin-left:auto">
<span style="color:var(--fg-3);font-size:11px">${t("settings.budgetCustom")}</span>
<input
type="number"
min="0.01"
step="0.01"
value=${custom}
placeholder="0.00"
onInput=${(e: Event) => setCustom((e.target as HTMLInputElement).value)}
onKeyDown=${(e: KeyboardEvent) => {
if (e.key === "Enter") submitCustom();
}}
style="width:72px;font-family:var(--font-mono)"
disabled=${saving}
/>
<button
class="btn primary"
disabled=${saving || !(Number.parseFloat(custom) > 0)}
onClick=${submitCustom}
>→</button>
</span>
`;
return html`
<div class="card" style="display:flex;flex-direction:column;gap:12px">
<${BudgetGauge} state=${state} />
${
state.kind === "off"
? html`
<div>
<div style="color:var(--fg-3);font-size:11px;margin-bottom:6px">${t("settings.budgetSetCap")}</div>
<div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
${quickButtons(QUICK_CAPS_USD)}
${customField}
</div>
</div>
`
: state.kind === "warn" || state.kind === "exhausted"
? html`
<div>
<div style="color:var(--fg-3);font-size:11px;margin-bottom:6px">${t("settings.budgetBumpHint")}</div>
<div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
${bumpSuggestions(state.cap).map(
(next) => html`
<button
key=${next}
class="btn primary"
style="font-family:var(--font-mono)"
disabled=${saving}
onClick=${() => onSetCap(next)}
>→ $${next % 1 === 0 ? next : next.toFixed(2)}</button>
`,
)}
${customField}
</div>
<div style="margin-top:8px">
<button class="btn" disabled=${saving} onClick=${onClear}>${t("settings.budgetClear")}</button>
</div>
</div>
`
: html`
<div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
${bumpSuggestions(state.cap).map(
(next) => html`
<button
key=${next}
class="btn"
style="font-family:var(--font-mono)"
disabled=${saving}
onClick=${() => onSetCap(next)}
>→ $${next % 1 === 0 ? next : next.toFixed(2)}</button>
`,
)}
${customField}
<button
class="btn"
style="margin-left:8px"
disabled=${saving}
onClick=${onClear}
>${t("settings.budgetClear")}</button>
</div>
`
}
</div>
`;
}
interface LoopSectionProps {
status: LoopRunStatus | null;
/** ms remaining until next fire — ticks down client-side between status polls. */
remainingMs: number;
/** Last-turn cost in USD; used as a hint for "each iteration costs ~". */
avgIterCostUsd: number | null;
busy: boolean;
onStart: (intervalMs: number, prompt: string) => void;
onStop: () => void;
}
function LoopSection({
status,
remainingMs,
avgIterCostUsd,
busy,
onStart,
onStop,
}: LoopSectionProps) {
const [intervalMs, setIntervalMs] = useState<number>(INTERVAL_PRESETS_MS[1]!.ms);
const [prompt, setPrompt] = useState("");
const [customValue, setCustomValue] = useState("");
const [customUnit, setCustomUnit] = useState<IntervalUnit>("m");
if (status) {
return html`
<div class="card" style="display:flex;flex-direction:column;gap:10px">
<div style="display:flex;justify-content:space-between;align-items:baseline">
<span style="color:var(--c-warn);font-family:var(--font-mono);font-size:11px">⟳ ${t("settings.loopRunning")}</span>
<span style="color:var(--fg-3);font-size:11px">
${t("settings.loopIter", { iter: status.iter })} · ${t("settings.loopFiresIn", { remaining: formatRemaining(remainingMs) })}
</span>
</div>
<div style="background:var(--bg-elev-2);border:1px solid var(--bd);border-radius:var(--r);padding:8px 10px;font-family:var(--font-mono);font-size:12px;color:var(--fg-1);white-space:pre-wrap;max-height:120px;overflow-y:auto">${status.prompt}</div>
<div>
<button class="btn danger" disabled=${busy} onClick=${onStop}>${t("settings.loopStop")}</button>
</div>
</div>
`;
}
const customMs = parseCustomInterval(customValue, customUnit);
const canStart = !busy && intervalMs > 0 && prompt.trim().length > 0;
return html`
<div class="card" style="display:flex;flex-direction:column;gap:10px">
<div style="color:var(--fg-3);font-size:11px">
${t("settings.loopIdleHint")}
${
typeof avgIterCostUsd === "number" && avgIterCostUsd > 0
? html` ${t("settings.loopCostHint", { cost: `$${avgIterCostUsd.toFixed(4)}` })}`
: null
}
</div>
<div style="display:flex;flex-direction:column;gap:6px">
<span style="color:var(--fg-3);font-size:11px">${t("settings.loopInterval")}</span>
<div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
${INTERVAL_PRESETS_MS.map(
(p) => html`
<button
key=${p.ms}
class=${`btn ${intervalMs === p.ms && customValue === "" ? "primary" : ""}`}
style="font-family:var(--font-mono)"
disabled=${busy}
onClick=${() => {
setIntervalMs(p.ms);
setCustomValue("");
}}
>${p.label}</button>
`,
)}
<span style="display:inline-flex;align-items:center;gap:4px;margin-left:auto">
<span style="color:var(--fg-3);font-size:11px">${t("settings.loopCustom")}</span>
<input
type="number"
min="1"
step="1"
value=${customValue}
onInput=${(e: Event) => {
const raw = (e.target as HTMLInputElement).value;
setCustomValue(raw);
const ms = parseCustomInterval(raw, customUnit);
if (ms !== null) setIntervalMs(ms);
}}
style="width:64px;font-family:var(--font-mono)"
disabled=${busy}
/>
<select
value=${customUnit}
onChange=${(e: Event) => {
const next = (e.target as HTMLSelectElement).value as IntervalUnit;
setCustomUnit(next);
if (customValue) {
const ms = parseCustomInterval(customValue, next);
if (ms !== null) setIntervalMs(ms);
}
}}
disabled=${busy}
>
<option value="s">s</option>
<option value="m">m</option>
<option value="h">h</option>
</select>
</span>
</div>
${
customValue && customMs === null
? html`<span style="color:var(--c-err);font-size:11px">${t("settings.loopRangeError")}</span>`
: null
}
</div>
<div style="display:flex;flex-direction:column;gap:6px">
<span style="color:var(--fg-3);font-size:11px">${t("settings.loopPrompt")}</span>
<textarea
rows="3"
placeholder=${t("settings.loopPromptPlaceholder")}
value=${prompt}
onInput=${(e: Event) => setPrompt((e.target as HTMLTextAreaElement).value)}
style="width:100%;font-family:var(--font-mono);resize:vertical"
disabled=${busy}
></textarea>
</div>
<div>
<button
class="btn primary"
disabled=${!canStart}
onClick=${() => onStart(intervalMs, prompt.trim())}
>${t("settings.loopStart")}</button>
</div>
</div>
`;
}
export function SettingsPanel() {
@@ -20,6 +392,13 @@ export function SettingsPanel() {
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState<string | null>(null);
const [draft, setDraft] = useState<Partial<SettingsData>>({});
const [catalog, setCatalog] = useState<ModelCatalog | null>(null);
const [loopStatus, setLoopStatus] = useState<LoopRunStatus | null>(null);
const [loopAvgCost, setLoopAvgCost] = useState<number | null>(null);
const [loopBusy, setLoopBusy] = useState(false);
/** Wall-clock time of the last status sync — used to interpolate the countdown. */
const lastStatusSyncRef = useRef<number>(0);
const [now, setNow] = useState<number>(() => Date.now());
const load = useCallback(async () => {
try {
@@ -33,6 +412,73 @@ export function SettingsPanel() {
useEffect(() => {
load();
}, [load]);
useEffect(() => {
api<ModelCatalog>("/models")
.then(setCatalog)
.catch(() => undefined);
}, []);
const refreshLoop = useCallback(async () => {
try {
const r = await api<{ status: LoopRunStatus | null }>("/loop/status");
setLoopStatus(r.status);
lastStatusSyncRef.current = Date.now();
} catch {
/* ignore — status is best-effort */
}
try {
const r = await api<{ stats?: { lastTurnCostUsd?: number } }>("/overview");
setLoopAvgCost(r.stats?.lastTurnCostUsd ?? null);
} catch {
/* ignore */
}
}, []);
useEffect(() => {
let cancelled = false;
refreshLoop();
const id = setInterval(() => {
if (!cancelled) refreshLoop();
}, 5_000);
return () => {
cancelled = true;
clearInterval(id);
};
}, [refreshLoop]);
useEffect(() => {
if (!loopStatus) return;
const id = setInterval(() => setNow(Date.now()), 1_000);
return () => clearInterval(id);
}, [loopStatus]);
const remainingMs = loopStatus
? Math.max(0, loopStatus.nextFireMs - (now - lastStatusSyncRef.current))
: 0;
const startLoop = useCallback(
async (intervalMs: number, prompt: string) => {
setLoopBusy(true);
try {
await api("/loop/start", { method: "POST", body: { intervalMs, prompt } });
await refreshLoop();
} catch (err) {
setError((err as Error).message);
} finally {
setLoopBusy(false);
}
},
[refreshLoop],
);
const stopLoop = useCallback(async () => {
setLoopBusy(true);
try {
await api("/loop/stop", { method: "POST" });
await refreshLoop();
} catch (err) {
setError((err as Error).message);
} finally {
setLoopBusy(false);
}
}, [refreshLoop]);
const save = useCallback(
async (fields: Partial<SettingsData>) => {
@@ -189,11 +635,50 @@ export function SettingsPanel() {
)}
</div>
${sectionH3(t("settings.sectionCompute"))}
<div class="card">
${fieldRow(
t("settings.proNext"),
html`
<button
class=${`btn ${v.proNext ? "primary" : ""}`}
onClick=${() => save({ proNext: !v.proNext })}
disabled=${saving}
>${v.proNext ? t("settings.proArmed") : t("settings.proArm")}</button>
`,
t("settings.proNextNote"),
)}
</div>
${sectionH3(t("settings.sectionBudget"))}
<${BudgetSection}
state=${deriveBudgetState(v.budgetUsd, v.sessionSpendUsd)}
saving=${saving}
onSetCap=${(usd: number) => save({ budgetUsd: usd })}
onClear=${() => save({ budgetUsd: null })}
/>
${sectionH3(t("settings.sectionLoop"))}
<${LoopSection}
status=${loopStatus}
remainingMs=${remainingMs}
avgIterCostUsd=${loopAvgCost}
busy=${loopBusy}
onStart=${startLoop}
onStop=${stopLoop}
/>
${sectionH3(t("settings.sectionRuntime"))}
<div class="card">
${fieldRow(
t("settings.activeModel"),
html`<code class="mono">${v.model ?? "—"}</code>`,
html`<${ModelRow}
current=${v.model ?? "—"}
catalog=${catalog}
saving=${saving}
onPick=${(m: string) => save({ model: m })}
/>`,
t("settings.appliesNextTurn"),
)}
${fieldRow(
t("settings.editMode"),
+21 -6
View File
@@ -29,6 +29,7 @@ export function SkillsPanel() {
const [newName, setNewName] = useState("");
const [newScope, setNewScope] = useState<"global" | "project">("global");
const [filter, setFilter] = useState("");
const [scopeFilter, setScopeFilter] = useState<"all" | Scope>("all");
const load = useCallback(async () => {
try {
@@ -120,13 +121,15 @@ export function SkillsPanel() {
...data.global.map((s) => ({ scope: "global" as Scope, ...s })),
...data.builtin.map((s) => ({ scope: "builtin" as Scope, ...s })),
];
const scopeFiltered =
scopeFilter === "all" ? allWith : allWith.filter((s) => s.scope === scopeFilter);
const filtered = filter.trim()
? allWith.filter(
? scopeFiltered.filter(
(s) =>
s.name.toLowerCase().includes(filter.toLowerCase()) ||
(s.description ?? "").toLowerCase().includes(filter.toLowerCase()),
)
: allWith;
: scopeFiltered;
return html`
<div class="sessions-grid">
@@ -141,10 +144,22 @@ export function SkillsPanel() {
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">${t("common.all")} <span class="ct">${allWith.length}</span></span>
<span class="chip-f">${t("skills.project")} <span class="ct">${data.project.length}</span></span>
<span class="chip-f">${t("skills.global")} <span class="ct">${data.global.length}</span></span>
<span class="chip-f">${t("skills.builtin")} <span class="ct">${data.builtin.length}</span></span>
<span
class=${`chip-f ${scopeFilter === "all" ? "active" : ""}`}
onClick=${() => setScopeFilter("all")}
>${t("common.all")} <span class="ct">${allWith.length}</span></span>
<span
class=${`chip-f ${scopeFilter === "project" ? "active" : ""}`}
onClick=${() => setScopeFilter("project")}
>${t("skills.project")} <span class="ct">${data.project.length}</span></span>
<span
class=${`chip-f ${scopeFilter === "global" ? "active" : ""}`}
onClick=${() => setScopeFilter("global")}
>${t("skills.global")} <span class="ct">${data.global.length}</span></span>
<span
class=${`chip-f ${scopeFilter === "builtin" ? "active" : ""}`}
onClick=${() => setScopeFilter("builtin")}
>${t("skills.builtin")} <span class="ct">${data.builtin.length}</span></span>
</div>
<div style="padding:0 12px 8px;display:flex;gap:6px;flex-wrap:wrap">
+2 -1
View File
@@ -1,6 +1,7 @@
import { fmtBytes, fmtNum } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { compareVersions } from "../lib/version.js";
import { t, useLang } from "../i18n/index.js";
interface HealthData {
@@ -22,7 +23,7 @@ export function SystemPanel() {
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "health", error: error.message })}</div>`;
if (!data) return null;
const h = data;
const upToDate = h.latestVersion ? h.latestVersion === h.version : null;
const upToDate = h.latestVersion ? compareVersions(h.version, h.latestVersion) >= 0 : null;
return html`
<div style="display:flex;flex-direction:column;gap:14px">
+9 -3
View File
@@ -21,6 +21,12 @@ interface ToolsError {
body?: { error?: string };
}
function toolDesc(name: string, fallback: string): string {
const key = `tools.desc.${name}`;
const translated = t(key);
return translated === key ? fallback : translated;
}
export function ToolsPanel() {
useLang();
const { data, error, loading } = usePoll<ToolsData>("/tools", 4000);
@@ -37,8 +43,8 @@ export function ToolsPanel() {
return html`
<div style="display:flex;flex-direction:column;gap:14px">
<div class="chips">
<span class="chip-f active">${t("common.all")} <span class="ct">${d.total}</span></span>
${d.planMode ? html`<span class="chip-f" style="border-color:var(--c-warn);color:var(--c-warn)">${t("tools.planMode")}</span>` : null}
<span class="chip-f static active">${t("common.all")} <span class="ct">${d.total}</span></span>
${d.planMode ? html`<span class="chip-f static" style="border-color:var(--c-warn);color:var(--c-warn)">${t("tools.planMode")}</span>` : null}
</div>
${
@@ -65,7 +71,7 @@ export function ToolsPanel() {
: html`<span class="pill acc">${t("tools.write")}</span>`}
${tool.flattened ? html` <span class="pill">${t("tools.flat")}</span>` : null}
</td>
<td class="dim">${tool.description ?? ""}</td>
<td class="dim">${toolDesc(tool.name, tool.description ?? "")}</td>
</tr>
`,
)}
+21 -15
View File
@@ -36,6 +36,7 @@ interface UsageDay {
function UsageChart({ days }: { days: UsageDay[] }) {
const containerRef = useRef<HTMLDivElement>(null);
const plotRef = useRef<UPlotInstance | null>(null);
useLang();
useEffect(() => {
let cancelled = false;
@@ -64,7 +65,7 @@ function UsageChart({ days }: { days: UsageDay[] }) {
{ stroke: "#94a3b8", grid: { stroke: "rgba(148, 163, 184, 0.08)" } },
{
scale: "y",
label: "USD",
label: t("usage.axisUsd"),
stroke: "#94a3b8",
grid: { stroke: "rgba(148, 163, 184, 0.08)" },
values: (_u: unknown, v: number[]) => v.map((n) => `$${n.toFixed(4)}`),
@@ -72,17 +73,22 @@ function UsageChart({ days }: { days: UsageDay[] }) {
{
scale: "turns",
side: 1,
label: "turns",
label: t("usage.axisTurns"),
stroke: "#94a3b8",
grid: { show: false },
},
],
series: [
{},
{ label: "cost", stroke: "#67e8f9", width: 2, fill: "rgba(103, 232, 249, 0.10)" },
{ label: "cache saved", stroke: "#5eead4", width: 2, dash: [4, 4] },
{ label: t("usage.axisTime") },
{
label: "turns",
label: t("usage.seriesCost"),
stroke: "#67e8f9",
width: 2,
fill: "rgba(103, 232, 249, 0.10)",
},
{ label: t("usage.seriesCacheSaved"), stroke: "#5eead4", width: 2, dash: [4, 4] },
{
label: t("usage.seriesTurns"),
stroke: "#c4b5fd",
scale: "turns",
width: 1.5,
@@ -174,8 +180,8 @@ export function UsagePanel() {
return html`
<div style="display:flex;flex-direction:column;gap:6px">
<div class="chips">
<span class="chip-f active">${t("usage.records", { count: u.recordCount.toLocaleString() })}</span>
<span class="chip-f">${u.logSize}</span>
<span class="chip-f static active">${t("usage.records", { count: u.recordCount.toLocaleString() })}</span>
<span class="chip-f static">${u.logSize}</span>
</div>
${
@@ -203,13 +209,13 @@ export function UsagePanel() {
<table class="tbl">
<thead>
<tr>
<th></th>
<th>${t("usage.colTurns")}</th>
<th>${t("usage.colCacheHit")}</th>
<th>${t("usage.colCost")}</th>
<th>${t("usage.colCacheSaved")}</th>
<th>${t("usage.colVsClaude")}</th>
<th>${t("usage.colSaved")}</th>
<th>${t("usage.colWindow")}</th>
<th class="num">${t("usage.colTurns")}</th>
<th class="num">${t("usage.colCacheHit")}</th>
<th class="num">${t("usage.colCost")}</th>
<th class="num">${t("usage.colCacheSaved")}</th>
<th class="num">${t("usage.colVsClaude")}</th>
<th class="num">${t("usage.colSaved")}</th>
</tr>
</thead>
<tbody>
+187
View File
@@ -0,0 +1,187 @@
# Reasonix Desktop — code signing & notarization
Walkthrough for shipping a signed Reasonix Desktop bundle.
The release workflow at `.github/workflows/release.yml` reads everything
below from repository **Secrets** — nothing in this repo holds keys.
Without these secrets set the workflow still builds, but installers come
out unsigned (Windows shows SmartScreen warnings; macOS marks the app
"damaged" until the user right-clicks → Open).
## Tauri updater signing (all platforms)
Tauri's updater verifies bundle artifacts against a public key embedded
in the app. Generate once and commit the **public** half to
`tauri.conf.json`.
```bash
cd desktop
npx @tauri-apps/cli signer generate -w ~/.tauri/reasonix.key
```
Outputs:
- `~/.tauri/reasonix.key` — the **private** key. Never commit. Add a
passphrase when prompted.
- `~/.tauri/reasonix.key.pub` — paste into `tauri.conf.json` under
`plugins.updater.pubkey`, replacing `REPLACE_ME_RUN_tauri_signer_generate`.
Set repo secrets:
- `TAURI_SIGNING_PRIVATE_KEY` — full contents of `~/.tauri/reasonix.key`
- `TAURI_SIGNING_PRIVATE_KEY_PASSWORD` — the passphrase
The workflow exports both as env vars; `tauri-action` picks them up and
signs the per-platform update bundle (`*.tar.gz.sig`, `*.zip.sig`,
`*.msi.zip.sig`, …) automatically.
## Windows — Authenticode
You need a **code signing certificate** from a CA Microsoft trusts
(DigiCert, Sectigo, SSL.com, …). EV certs avoid SmartScreen reputation
ramp; OV certs work but warn until enough installs build trust.
### One-time: export the cert as PFX
The CA either ships a `.pfx` directly or a `.cer` + private key. If you
get the latter, combine with `openssl`:
```bash
openssl pkcs12 -export \
-inkey reasonix.key \
-in reasonix.cer \
-out reasonix.pfx \
-name "Reasonix Code Signing"
```
Set a strong export password — needed below.
### Wire into the release workflow
Tauri v2 reads three env vars on Windows:
| Secret | What it is |
|---|---|
| `WINDOWS_CERTIFICATE` | base64-encoded contents of `reasonix.pfx` |
| `WINDOWS_CERTIFICATE_PASSWORD` | the PFX export password |
Encode the cert before adding the secret:
```bash
base64 -w0 reasonix.pfx > reasonix.pfx.b64
```
Then add a step to the matrix' Windows job that imports the cert and
points Tauri at it. The simplest approach uses the [Azure trusted
signing action] or the older `@tauri-apps/action`'s built-in
Authenticode path — set the secrets and `tauri-action` will pick them
up via `tauri-plugin-windows-installer`.
For the workflow already in this repo, add to the env block of the
`Build Tauri bundle` step:
```yaml
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
```
`tauri-action` v0 detects these and signs both the `.msi` and the
`.exe` produced by NSIS.
### Verify locally before pushing the tag
```powershell
signtool verify /pa /v Reasonix_0.40.0_x64-setup.exe
```
Output should include `Successfully verified` and the certificate's
common name.
[Azure trusted signing action]: https://github.com/Azure/trusted-signing-action
## macOS — Developer ID + notarization
Two separate signatures are required for a non-warning install:
1. **Code signing** with a Developer ID Application certificate — proves
the bundle came from a paid Apple Developer account.
2. **Notarization** — Apple's automated malware scan, returns a ticket
that gets stapled into the `.dmg` / `.app`.
### One-time: certificate
Enroll in the [Apple Developer Program] ($99/yr). In Xcode → Settings →
Accounts → Manage Certificates, create a `Developer ID Application`
cert. Export from Keychain as a `.p12` with a passphrase.
```bash
base64 -i ReasonixDeveloperID.p12 -o cert.p12.b64
```
### One-time: app-specific password for notarytool
Notarization uses the Apple ID, not the cert. At
<https://appleid.apple.com> → Sign-In and Security → App-Specific
Passwords, generate one labelled "reasonix notarytool". Save it — Apple
only shows it once.
### Repository secrets
| Secret | What it is |
|---|---|
| `APPLE_CERTIFICATE` | base64 of the `.p12` |
| `APPLE_CERTIFICATE_PASSWORD` | the `.p12` passphrase |
| `APPLE_SIGNING_IDENTITY` | the Common Name, e.g. `Developer ID Application: Your Name (TEAMID)` |
| `APPLE_ID` | your Apple ID email |
| `APPLE_PASSWORD` | the app-specific password from the previous step |
| `APPLE_TEAM_ID` | 10-character team identifier, visible in Apple Developer → Membership |
The release workflow already passes all six to `tauri-action`. Once
they're set, builds for both `macos-13` (Intel) and `macos-14` (Apple
Silicon) produce a signed + notarized `.dmg`.
### Verify locally
After downloading the artifact:
```bash
spctl -a -t open --context context:primary-signature -vvv Reasonix_0.40.0_aarch64.dmg
# expected: source=Notarized Developer ID
```
```bash
codesign --verify --deep --strict --verbose=2 /Applications/Reasonix.app
# expected: valid on disk + satisfies its Designated Requirement
```
[Apple Developer Program]: https://developer.apple.com/programs/
## Linux
No signing required — `.deb` and `.AppImage` ship plain. If the project
ever publishes a Flatpak or Snap, the respective store handles signing
on upload.
## Updater pubkey rotation
Rotating the updater key invalidates every previously installed
client's ability to verify updates. Avoid unless the private key
leaked. If it must happen:
1. Generate a new key pair (`tauri signer generate`).
2. Ship one transitional release signed with the **old** key whose
notes tell users to download fresh installers manually.
3. Replace `tauri.conf.json#plugins.updater.pubkey` in the next release.
4. Update `TAURI_SIGNING_PRIVATE_KEY` in repo secrets.
## Troubleshooting
- **"errSecInternalComponent" on macOS runners** — Apple's `notarytool`
needs the keychain unlocked. `tauri-action` handles this when the six
Apple secrets are present; if you've inlined custom steps, add a
keychain-unlock step before signing.
- **"The signature of the application is invalid"** on Windows after
an update — almost always means the updater's `pubkey` in
`tauri.conf.json` doesn't match the private key used by the workflow.
Confirm both halves come from the same `signer generate` run.
- **`xcrun: error: unable to find utility "altool"`** — runner is on
Xcode older than 13. Pin `xcode-select` or upgrade the runner image;
`notarytool` (the replacement) is what Tauri v2 uses.
+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
<defs>
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#8b7cff"/>
<stop offset="100%" stop-color="#5b3df0"/>
</linearGradient>
<linearGradient id="sheen" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.22"/>
<stop offset="38%" stop-color="#ffffff" stop-opacity="0"/>
</linearGradient>
<filter id="innerShadow" x="-10%" y="-10%" width="120%" height="120%">
<feGaussianBlur stdDeviation="6" result="blur"/>
<feOffset dy="-12" result="off"/>
<feComposite in="off" in2="SourceAlpha" operator="arithmetic" k2="-1" k3="1" result="inner"/>
<feFlood flood-color="#1a0e7a" flood-opacity="0.35"/>
<feComposite in2="inner" operator="in"/>
</filter>
</defs>
<rect x="64" y="64" width="896" height="896" rx="220" ry="220" fill="url(#g)"/>
<rect x="64" y="64" width="896" height="896" rx="220" ry="220" fill="url(#sheen)"/>
<g fill="#ffffff" font-family="JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800" text-anchor="middle">
<text x="512" y="700" font-size="640" letter-spacing="-12">R</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Reasonix</title>
<link rel="stylesheet" href="/src/styles.css" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+3516
View File
File diff suppressed because it is too large. Load diff
+38
View File
@@ -0,0 +1,38 @@
{
"name": "reasonix-desktop",
"private": true,
"version": "0.43.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri",
"bundle:node": "node scripts/bundle-node.mjs"
},
"dependencies": {
"@fontsource/ibm-plex-mono": "^5.2.7",
"@fontsource/ibm-plex-sans": "^5.2.8",
"@fontsource/ibm-plex-serif": "^5.2.7",
"@tauri-apps/api": "^2.1.1",
"@tauri-apps/plugin-dialog": "^2.7.1",
"@tauri-apps/plugin-opener": "^2.0.0",
"@tauri-apps/plugin-process": "^2.0.0",
"@tauri-apps/plugin-updater": "^2.0.0",
"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",
"remark-gfm": "^4.0.0"
},
"devDependencies": {
"@tauri-apps/cli": "^2.1.0",
"@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"
}
}
+124
View File
@@ -0,0 +1,124 @@
/**
* Cross-platform Node 22 downloader. Detects host platform + arch and pulls
* the matching official Node distribution from nodejs.org, then extracts the
* node binary into desktop/src-tauri/binaries/. Tauri's per-platform conf
* overlay (tauri.<platform>.conf.json) picks it up at bundle time.
*
* Usage: `npm run bundle:node` from desktop/.
* Re-run when bumping NODE_VERSION. The download is gitignored.
*/
import { execSync } from "node:child_process";
import { chmodSync, createWriteStream, existsSync, mkdirSync, renameSync, rmSync, statSync } from "node:fs";
import https from "node:https";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const NODE_VERSION = "22.13.0";
const here = dirname(fileURLToPath(import.meta.url));
const binDir = join(here, "..", "src-tauri", "binaries");
const PLAT = process.platform;
const ARCH_RAW = process.arch;
const ARCH = ARCH_RAW === "arm64" ? "arm64" : ARCH_RAW === "x64" ? "x64" : null;
if (!ARCH || !["win32", "darwin", "linux"].includes(PLAT)) {
console.error(`Unsupported host: ${PLAT}/${ARCH_RAW}. Supported: win32 / darwin / linux × x64 / arm64.`);
process.exit(1);
}
const isWin = PLAT === "win32";
const triple =
PLAT === "win32" ? `win-${ARCH}` : PLAT === "darwin" ? `darwin-${ARCH}` : `linux-${ARCH}`;
const archiveExt = PLAT === "win32" ? "zip" : PLAT === "darwin" ? "tar.gz" : "tar.xz";
const archiveBase = `node-v${NODE_VERSION}-${triple}`;
const archiveFile = `${archiveBase}.${archiveExt}`;
const url = `https://nodejs.org/dist/v${NODE_VERSION}/${archiveFile}`;
const targetExe = join(binDir, isWin ? "node.exe" : "node");
const archivePath = join(binDir, archiveFile);
const extractDir = join(binDir, "_extract");
if (existsSync(targetExe)) {
const size = statSync(targetExe).size;
if (size > 1024 * 1024) {
console.log(`${targetExe} already present (${(size / 1024 / 1024).toFixed(1)} MB) — delete to refetch`);
process.exit(0);
}
// < 1 MB = placeholder, refetch.
}
mkdirSync(binDir, { recursive: true });
function follow(url, dest, redirects = 5) {
return new Promise((resolve, reject) => {
const req = https.get(url, (res) => {
const status = res.statusCode ?? 0;
if ((status === 301 || status === 302 || status === 307 || status === 308) && res.headers.location && redirects > 0) {
res.resume();
follow(new URL(res.headers.location, url).toString(), dest, redirects - 1).then(resolve, reject);
return;
}
if (status !== 200) {
reject(new Error(`HTTP ${status} fetching ${url}`));
return;
}
const file = createWriteStream(dest);
const total = Number.parseInt(res.headers["content-length"] ?? "0", 10);
let got = 0;
let last = 0;
res.on("data", (chunk) => {
got += chunk.length;
if (total && Date.now() - last > 250) {
process.stdout.write(`\r ${(got / 1024 / 1024).toFixed(1)} / ${(total / 1024 / 1024).toFixed(1)} MB`);
last = Date.now();
}
});
res.pipe(file);
file.on("finish", () => file.close((err) => (err ? reject(err) : resolve())));
file.on("error", reject);
});
req.on("error", reject);
});
}
console.log(`Downloading ${archiveFile} (Node v${NODE_VERSION} ${triple}) ...`);
await follow(url, archivePath);
process.stdout.write("\n");
rmSync(extractDir, { recursive: true, force: true });
mkdirSync(extractDir, { recursive: true });
console.log("Extracting ...");
if (isWin) {
execSync(
`powershell -NoProfile -Command "Expand-Archive -Force -Path '${archivePath}' -DestinationPath '${extractDir}'"`,
{ stdio: "inherit" },
);
} else {
// tar handles both .tar.gz (with -z auto) and .tar.xz (needs xz-utils on host).
execSync(`tar -xf "${archivePath}" -C "${extractDir}"`, { stdio: "inherit" });
}
const inner = isWin
? join(extractDir, archiveBase, "node.exe")
: join(extractDir, archiveBase, "bin", "node");
if (!existsSync(inner)) {
console.error(`Extracted binary not found at expected path: ${inner}`);
process.exit(1);
}
if (existsSync(targetExe)) rmSync(targetExe);
renameSync(inner, targetExe);
if (!isWin) {
try {
chmodSync(targetExe, 0o755);
} catch {
/* ignore */
}
}
rmSync(extractDir, { recursive: true, force: true });
rmSync(archivePath);
const mb = (statSync(targetExe).size / 1024 / 1024).toFixed(1);
console.log(`Done: ${targetExe} (${mb} MB)`);
+5634
View File
File diff suppressed because it is too large. Load diff
+29
View File
@@ -0,0 +1,29 @@
[package]
name = "reasonix-desktop"
version = "0.43.0"
edition = "2021"
publish = false
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = ["devtools"] }
tauri-plugin-updater = "2"
tauri-plugin-process = "2"
tauri-plugin-opener = "2"
tauri-plugin-dialog = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
parking_lot = "0.12"
anyhow = "1"
which = "7"
[features]
custom-protocol = ["tauri/custom-protocol"]
[profile.release]
strip = true
lto = true
codegen-units = 1
panic = "abort"
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build();
}
@@ -0,0 +1,26 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "default app capability",
"windows": ["main", "Reasonix"],
"permissions": [
"core:default",
"core:event:default",
"core:window:default",
"updater:default",
"process:allow-restart",
"dialog:allow-open",
{
"identifier": "opener:allow-open-url",
"allow": [{ "url": "https://*" }, { "url": "http://*" }]
},
{
"identifier": "opener:allow-open-path",
"allow": [{ "path": "**" }]
},
{
"identifier": "opener:allow-reveal-item-in-dir",
"allow": [{ "path": "**" }]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 907 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 964 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#fff</color>
</resources>
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 644 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Loaded 100 of 639 files, more files were not shown because too many files have changed in this diff. Show more