Compare commits

...
242 Commits
Author SHA1 Message Date
reasonix b21a6a0493 chore(release): 0.53.1 2026-05-26 23:15:52 -07:00
reasonix fe1bbb9aa9 chore(release): 0.53.0 2026-05-26 21:55:56 -07:00
YHHandreasonix 1095f5ff52 fix(loop): force-summary uses active model, not hard-coded flash (#1986)
Context-guard and stuck-state recovery were calling
ctx.client.chat({ model: "deepseek-v4-flash" }) regardless of what the
user actually configured. Third-party DeepSeek-compatible endpoints
(mimo, self-hosted, Azure forks) that don't expose flash 400 on every
force-summary, the recovery path crashes, and the session looks like
it lost context — the messages are still there, but the user sees an
error and has no way back without /clear.

Pass this.model through summaryContext() and use it for the summary
call. `thinking: "disabled"` still keeps reasoning tokens off the bill
even when the active model is pro.

Add a regression test that asserts the force-summary path hits the
active model, not flash.

Co-authored-by: reasonix <[email protected]>
2026-05-26 21:52:09 -07:00
Weikeng Chenandreasonix c3e0ccf99c feat(desktop): 余额显示支持多币种(同时展示人民币和美元) (#1930)
* feat(desktop): show all currency balances from user/balance API

DeepSeek's /user/balance endpoint returns a balance_infos array with
separate entries per currency (CNY, USD). The desktop client was only
showing the single largest balance (pickPrimaryBalance), hiding the
other currency.

- Add BalanceInfoItem type and balanceInfos array to BalanceEvent protocol
- Pass all currency balances through emitBalance() in the Node child process
- Store multiple balance infos in the frontend Balance type
- Render all balances as a single segment: \$ X.XX / ¥ YY.YY
- Preserve existing single-balance fallback for backward compatibility

* fixup(desktop): restore click-to-toggle on balance segment

The multi-currency rendering dropped onClick={onToggleCurrency}, breaking
the mouse path to flip the cost segment between CNY/USD. Restore it with
the existing switchCurrency tooltip — the balance now shows both, but
the cost figure still tracks the user's chosen currency.

---------

Co-authored-by: reasonix <[email protected]>
2026-05-26 21:47:26 -07:00
wade1999 16904ce664 feat(qq): default to markdown replies (#1941) 2026-05-26 21:47:06 -07:00
YHHandreasonix 54c3792085 fix(desktop): fire hooks (Pre/PostToolUse, UserPromptSubmit, Stop) per tab (#1984)
Desktop never wired the hook runner — `buildRuntimeFor` constructed
CacheFirstLoop without `hooks`/`hookCwd`, and `runTurn` had no
UserPromptSubmit/Stop dispatch. So hooks defined in
~/.reasonix/settings.json silently no-op'd in the desktop app even
though they fired fine under `reasonix code`.

Load hooks per tab from `tab.rootDir`'s project scope + global,
thread them into the loop (covers Pre/PostToolUse via the loop's own
trigger), fire UserPromptSubmit before `loop.step` and Stop in the
turn-complete tail, and re-load on workspace switch so project hooks
follow the new root. Non-pass outcomes surface via $error; a blocking
UserPromptSubmit aborts the turn before the prompt reaches the model.

Closes #1942

Co-authored-by: reasonix <[email protected]>
2026-05-26 21:45:03 -07:00
YHHandreasonix dac635ed45 fix(desktop): clear pending assistant on error so the spinner stops (#1660) (#1985)
When the SSE stream terminates mid-turn (proxy/LB idle drop, undici
`Error("terminated")`), the loop yields a role:"error" event and
returns. The reducer flips `busy:false` and appends the error card,
but the in-progress assistant message keeps `pending:true` — so the
UI shows a "thinking" spinner above the red error box and looks stuck.
Reported as "对话卡死" in #1660.

Loop has already returned by the time we receive the error, so any
streaming assistant message is no longer streaming. Settle it.

Co-authored-by: reasonix <[email protected]>
2026-05-26 21:16:36 -07:00
YHHandreasonix 691bd03201 fix(config): saveApiKey overrides stale env so UI save takes effect (#1982)
Reported: user installed via npx, ran setup, then switched to the
desktop app. Saving a fresh key from the desktop UI updated
config.json but every request still 401'd with the old key as the
masked tail in the error message.

Root cause: loadEndpoint's fallback (no custom baseUrl on either
side) prefers process.env.DEEPSEEK_API_KEY over cfg.apiKey on the
read path — a 12-factor convention. A stale env (User-level Windows
env var, ~/.env, shell rc) then shadowed the just-saved config
forever inside the running Node sidecar.

Fix: have saveApiKey mirror the new value into process.env so the
explicit UI save wins inside the current process. Read precedence is
unchanged — env still beats config for users who deliberately set
DEEPSEEK_API_KEY to override.

Co-authored-by: reasonix <[email protected]>
2026-05-26 21:04:16 -07:00
YHHandreasonix 4837165227 fix(loop): force-summary uses active model, not hard-coded flash (#1979)
Context-guard and stuck-state recovery were calling
ctx.client.chat({ model: "deepseek-v4-flash" }) regardless of what the
user actually configured. Third-party DeepSeek-compatible endpoints
(mimo, self-hosted, Azure forks) that don't expose flash 400 on every
force-summary, the recovery path crashes, and the session looks like
it lost context — the messages are still there, but the user sees an
error and has no way back without /clear.

Pass this.model through summaryContext() and use it for the summary
call. `thinking: "disabled"` still keeps reasoning tokens off the bill
even when the active model is pro.

Add a regression test that asserts the force-summary path hits the
active model, not flash.

Co-authored-by: reasonix <[email protected]>
2026-05-26 21:03:27 -07:00
YHHandreasonix 49e9d9e04a fix(desktop): wire /skill and /skills slash commands (#1969) (#1978)
Desktop palette had no /skill entry, so typing /skill (which works in
the CLI) showed "no matches". Add /skill + /skills as palette commands
that open Settings → Skills, and handle the same names on submit so
pressing Enter goes there too (mirrors the /search-engine special case).

Co-authored-by: reasonix <[email protected]>
2026-05-26 21:01:36 -07:00
YHHandreasonix ec9788d8ed fix(truncated-result-saver): fall back to ~/.reasonix when rootDir is fs root (#1974)
When launched with cwd=/ (e.g. some daemon/IDE contexts), saveTruncatedResult
joined the project root to .reasonix and tried to mkdir /.reasonix/truncated-results,
which fails with ENOENT and crashes run_skill on oversized results.

Treat fs-root rootDir the same as empty and write under the user's home dir
instead. Closes #1959.

Co-authored-by: reasonix <[email protected]>
2026-05-26 20:51:52 -07:00
YHHandreasonix 58f28d61aa fix(truncate): align slice boundaries to UTF-16 codepoint (#1970) (#1976)
`truncateForModel` and `truncateForModelByTokens` slice on UTF-16 code
units. When the cut lands inside a surrogate pair (emoji, supplementary
CJK) the resulting head ends with a lone high surrogate / tail starts
with a lone low surrogate. The lone-surrogate sanitizer in `client.ts`
catches one downstream layer, but the safer fix is to never produce
the malformed slice in the first place — keeps tool results clean even
on the disk transcript path that bypasses the client sanitizer.

Reported: HTML file full of emoji caused DeepSeek to reject the chat
request with `serde_json: unexpected end of hex escape at line 1
column 38621` once the file content was sliced to fit the result-token
budget.

Co-authored-by: reasonix <[email protected]>
2026-05-26 20:47:17 -07:00
AtmoOmenandreasonix 857951ac83 fix(web_fetch): fallback to DoH when system DNS returns fake internal IPs (#1944)
* fix(web_fetch): fall back to DoH when system DNS returns fake internal IPs

TUN mode proxies (Clash Meta, Sing-box, etc.) use Fake-IP DNS strategy,
returning reserved addresses (e.g. 198.18.0.0/15) for all domain lookups.
The SSRF check in assertPublicHttpUrl treats these as internal hosts and
rejects legitimate public domains like github.com.

Add dohResolve() that queries Cloudflare 1.1.1.1 DNS-over-HTTPS to get
real public IPs. When system DNS returns any internal/reserved address,
fall back to DoH and only reject if the DoH results are also internal.
This preserves SSRF protection while correctly handling DNS pollution
from TUN/mitm proxies.

* test(web_fetch): update SSRF test to account for DoH fallback

The old test asserted that globalThis.fetch was never called when DNS
returned internal addresses. After adding the DoH fallback in the
previous commit, the code now makes a single DoH query to verify.
Update the test to stub fetch with a rejected promise and assert it
calls the correct Cloudflare DoH endpoint.

* fixup(web_fetch): compress dohResolve JSDoc to one line (comment-policy)

---------

Co-authored-by: reasonix <[email protected]>
2026-05-26 20:44:17 -07:00
enderzcx 3f66304eb4 fix(cli): accept models endpoint in doctor (#1972) 2026-05-26 20:33:36 -07:00
enderzcx 7fc3c526f1 fix(desktop): refresh context token meter (#1964) 2026-05-26 20:28:03 -07:00
TaoMu b1ee3ff327 fix: sanitize lone surrogates in chat payloads (#1939) 2026-05-26 20:06:15 -07:00
TaoMu 8ede8830fa fix(desktop): preserve context on abort (#1938) 2026-05-26 20:04:26 -07:00
TaoMu 7e03aca713 Fix generated-script shell cwd guidance (#1937)
* fix: clarify shell cwd guidance for generated scripts

* fix: soften generated script cwd guidance

* test: stabilize regex worker restart check
2026-05-26 20:02:37 -07:00
lightfrontandXingbo Zhao 2f2ddf5d06 fix(desktop): support \[ \] and \( \) math delimiters in markdown (#1923)
* fix(desktop): support \[ \] and \( \) math delimiters in markdown

* fix(desktop): protect \[4pt] LaTeX line-break spacing from math delimiter normalization

---------

Co-authored-by: Xingbo Zhao <[email protected]>
2026-05-26 19:59:14 -07:00
TaoMu 3c08f600a9 fix: keep dashboard New Chat label on one line (#1924)
* fix dashboard new chat button wrapping

* test dashboard new chat localized label

* fix compact sidebar new chat layout
2026-05-26 19:52:15 -07:00
YHHandreasonix bfcf333222 chore(errors): tighten errorDetail propagation (#1965)
Follow-up on #1918 — strip the four loose joints that surfaced in review:

- Replace `(err as any).code` / `(err as any).phase` casts with a small
  `errorMeta(err)` narrowing helper in `loop/errors.ts`. Same payload,
  no escape hatch.
- Extract `is4xxError` alongside `is5xxError` so the loop's "client
  error → not retryable" branch reads like the existing 5xx code path
  instead of an inline regex.
- Decouple `recoverable` from `retryable` in the loop's API-failure
  yield. `recoverable` is the historical "agent can keep going" flag
  (consumed by event listing), `retryable` is the new external retry
  hint; conflating them changed event-listing output silently.
- Carry `name` through `ErrorEvent` + eventize so the ACP dispatcher
  surfaces the real error name instead of `ev.message.split(":")[0]`.

Co-authored-by: reasonix <[email protected]>
2026-05-26 19:52:14 -07:00
YHHandreasonix 82c016b193 fix(tui): break CardStream measure→render→measure loop (#1958)
* fix(tui): break CardStream measure→render→measure loop (#1955)

CardStream measured the inner scroll Box via `useBoxMetrics`, derived
maxScroll from `inner.height - outer.height`, then pinned-mode wrote
that back to scrollRows — which feeds into `marginTop` and items
composition, which feeds back into inner.height. Several edit_file
results streaming in one turn was enough to stack the cascade past
React's nested-update limit (50).

Inner height is already known per-card in the chat-scroll store —
the per-card `useBoxMetrics` in MeasuredCard reports it. Summing the
store gives the same total without ever measuring inner, so scrollRows
can no longer feed back into the value used to compute maxScroll.

- ink-update-depth-repro.test.tsx: pins down the underlying pattern
  (a component that decides its own render from its own useBoxMetrics
  reading trips Max update depth).
- cardstream-architecture.test.tsx: side-by-side pre/post-fix harness
  proving the post-fix path stays linear and converges on the right
  maxScroll.

Closes #1955

* test(tui): assert oscillation by render count, not Max-depth firing

CI hit a flaky failure: Linux + Windows runners didn't trip React's
nested-update guard within 80ms while local Windows did. The guard
firing is timing-dependent (depends on how the event loop happens to
interleave commits and setInterval) — what's deterministic is that the
broken pattern keeps re-measuring forever. Assert that instead: stable
layouts converge in a few renders, the bad pattern compounds without
bound.

* test(tui): loosen oscillation count threshold for slow CI runners

Windows CI cleared 22-26 renders in 80ms versus hundreds locally;
the 10× multiplier kept tripping. Switch to an absolute floor of 15
— still far above the stable-layout converge (≤ 3) and proves the
"doesn't converge" property without coupling to runner speed.

---------

Co-authored-by: reasonix <[email protected]>
2026-05-26 19:45:34 -07:00
paradoxSCH 28990641b1 fix(acp): propagate structured error details through loop, transcript, ACP
When a proxy/LB idle timeout cuts an SSE stream, undici throws "terminated" as a bare string and ACP headless clients lose the context needed to decide whether to retry. Thread structured `errorDetail` ({name, message, code, phase, retryable, recoverable}) through client → loop → kernel events → transcript → ACP so the failure cause survives every hop.

All changes are additive: `LoopEvent.errorDetail`, `TranscriptRecord.errorDetail`, `SessionPromptResult.transcriptPath`, and `SessionUpdate.metadata.error` are all optional, so existing clients that ignore unknown fields keep working.

Closes #1884.
2026-05-26 19:45:11 -07:00
YHHandreasonix 0c837dda91 chore(dashboard): type the new server-snapshot helpers (#1961)
Replace any with named response shapes (ServerSessionsResponse /
ServerOverviewResponse) so mapSessionItem / emitSessionsSnapshot /
emitOverviewSnapshot read off real fields instead of structural any.
Callers still get any from apiFetch — narrowing happens at the boundary.

Co-authored-by: reasonix <[email protected]>
2026-05-26 19:36:45 -07:00
TaoMu 964ee5a0e6 fix dashboard session refresh (#1917) 2026-05-26 19:33:04 -07:00
Hermito Kattandhermitokatt 04694eae65 feat(web): add Brave Search API as web_search backend (#1916)
Add Brave Search (api.search.brave.com) as a new web search engine
alongside bing, searxng, metaso, tavily, perplexity, exa, and ollama.

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

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

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

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

Closes #1763

Co-authored-by: hermitokatt <[email protected]>
2026-05-26 19:25:08 -07:00
YHHandreasonix 65dbd122f6 docs(readme): add AtomGit star badge (#1954)
Co-authored-by: reasonix <[email protected]>
2026-05-26 19:07:04 -07:00
Bernardxu123andBernardxu123 89235a20bb fix(desktop): normalize path separators for Windows file opening (#1914)
* fix(desktop): normalize path separators for Windows file opening

Markdown file references and context panel paths use forward slashes from AI output, causing cmd.exe to fail on Windows. Normalize to backslash when the workspace path indicates Windows.

Closes #1869

* chore: retrigger CI

---------

Co-authored-by: Bernardxu123 <[email protected]>
2026-05-26 19:00:24 -07:00
enderzcx 2ee56515da feat(desktop): expose workspace switcher in sidebar (#1908) 2026-05-26 18:47:23 -07:00
CVEngineerandwufengfan e83a106c64 fix(desktop): allow clearing base URL and editor (#1905)
Co-authored-by: wufengfan <[email protected]>
2026-05-26 18:44:10 -07:00
YHHandreasonix 182d41eb87 refactor(ink): inline ink runtime as workspace package (#1947)
Was a stub `src/vendor/ink/index.d.ts` plus an empty `index.js` (the
real runtime arrived obfuscated, source unreachable). Moving the
source into `packages/ink` as a workspace dep gives consumers real
types and makes the runtime editable in-repo.

API migrations forced by the new stricter types:
- Text/Box `color` is a typed union now (`ansi:<name>` | `#hex` |
  `rgb()` | `ansi256()`); bare ansi names get the `ansi:` prefix
- `dimColor` → `dim`; Text's bold/dim discriminated union relaxed
  so the two can coexist (terminals collapse them anyway)
- `ThemeTokens` fields typed as `Color` so theme-derived values flow
  through helpers / props without manual casts

Markdown OSC 8 hyperlinks switch from `<Transform>` (a shim that
silently ignored the `transform` prop, breaking Ctrl+click hyperlinks)
to `<Link url>`, which uses ink's existing `ink-link` plumbing.

Dropped dead shims: `Transform`, `useAnimation` (zero callers after
the markdown rewrite).

Comment-policy pass on the new package: stripped 638 multi-line
essay block comments to 1-line summaries to match the repo rules.

Co-authored-by: reasonix <[email protected]>
2026-05-26 18:08:51 -07:00
reasonix 25988eb175 fix(desktop): bump app bundle version to 0.52.0 2026-05-26 04:09:20 -07:00
reasonix 171e10f69e chore(dsnix): bump to 0.52.0 + sync lockfile 2026-05-26 03:46:33 -07:00
reasonix cb3e6189d6 chore(release): 0.52.0 2026-05-26 03:39:52 -07:00
enderzcx 651779ae93 feat(web): add Ollama cloud search backend (#1900)
* feat(web): add Ollama cloud search backend

* fix(web): format Ollama web tool test
2026-05-26 03:24:26 -07:00
Tianjiu c634341883 fix(desktop): separate ctx scrollbar from resize handle (#1856)
* fix(desktop): separate ctx scrollbar from resize handle

* fix(desktop): add gap beside context scrollbar

* fix(desktop): push thread scrollbar away from right edge (#1695 #1793)

* fix(desktop): push thread scrollbar away from right edge

* thread scrollbar hover: thumb expands from 4px to 8px on hover

* fix(desktop): un-pin during scrollbar drag to stop rubber-banding
2026-05-26 03:20:02 -07:00
enderzcx 0510873412 fix(desktop): bump app bundle version to 0.51.0 (#1891) 2026-05-26 02:57:36 -07:00
YHHandreasonix f2e0b1f6d8 refactor(desktop): harden clipboard image paste path (#1897)
Three small improvements on top of #1889:

- JS: read the clipboard Blob with file.arrayBuffer() and pass the
  ArrayBuffer straight through invoke(). Drops the FileReader → data URL
  → atob → Uint8Array → number[] chain, which inflated the IPC payload
  by ~5x on every paste.
- Rust: tighten extension validation. sanitize_image_extension now
  requires the post-trim/lowercase value to be 1–8 ASCII alphanumeric
  chars, otherwise falls back to "png". Belts-and-braces vs a renderer
  passing "png/../../escape".
- Rust: spawn a startup thread that removes files older than 24h from
  the pasted-images temp dir so it doesn't grow unbounded between OS
  temp wipes.

Includes Rust unit tests for the extension sanitizer.

Co-authored-by: reasonix <[email protected]>
2026-05-26 02:57:10 -07:00
enderzcx 421fff2263 feat(desktop): import local AI app sessions (#1894) 2026-05-26 02:55:38 -07:00
enderzcx 660dcc662f feat(desktop): paste clipboard images into composer (#1889) 2026-05-26 02:39:00 -07:00
Odisseyandreasonix a44bbae18a i18n: add Russian (ru) language pack (#1879)
* i18n: add Russian (ru) language pack

* fix(i18n): apply biome format, add ru wizard label + slash.language description

- biome format wrapped long ru.ts lines (CI was red on format).
- LANGUAGE_LABELS in Wizard.tsx now includes ru ("Русский"), restoring the Record<LanguageCode, string> exhaustiveness.
- slash.language entry needs an explicit description override since the spread doesn't carry it through TypeScript's narrowing.

---------

Co-authored-by: reasonix <[email protected]>
2026-05-26 02:35:35 -07:00
enderzcx de0d1fb19a fix(client): parse Ollama usage token fields (#1886) 2026-05-26 02:30:21 -07:00
YHHandreasonix 210781f88d refactor(desktop): pull JumpBar dot styling back into a helper (#1892)
Inlining the size/background ternary into JSX made the render branch
hard to read. Move it back into dotProps() — same matrix:
hover/near > active > base, hover transition-delay only when hovered.

Co-authored-by: reasonix <[email protected]>
2026-05-26 02:22:34 -07:00
Hermito Kattandhermitokatt c86383934a fix(i18n): German corrections — capitalization, terminology, and coverage (#1878)
- Capitalize 30 German sentence starts per orthographic rules
  ('noch keine ...' -> 'Noch keine ...', etc.)
- Fix terminology: Systemeingabeaufforderung -> System-Prompt,
  Denkaufwand -> Reasoning-Effort, Veranstaltungstyp -> Ereignistyp,
  Tree-Kill -> Prozessbaum
- Translate ratelimited -> Rate-Limit erreicht across all 6 search engines
- Add missing ui.yoloHint translation (was falling back to English)
- Plural format {e}/{en} -> (e)/(en) for i18n compatibility
- Fix typo: fortgesetzen -> fortgesetzt, awd -> CWD, du -> Du
- Tighten descriptions: zwangsweise/Stelle diesen String vor -> Praefix fuer
- Add German slash-command description coverage test
- Use z.B. consistently instead of z. B.
  (42 insertions, 38 deletions)

Co-authored-by: hermitokatt <[email protected]>
2026-05-26 02:17:20 -07:00
CVEngineerandwufengfan 33d03ef099 feat(desktop): highlight active message bar in JumpBar; follow latest message (#1813)
Co-authored-by: wufengfan <[email protected]>
2026-05-26 02:13:47 -07:00
YHHandreasonix c14d8a3a8a feat(config): accept DEEPSEEK_API_BASE_URL as a base-URL env alias (#1876) (#1887)
Users running an internal Nginx proxy in front of api.deepseek.com pick
the env name from the OPENAI_BASE_URL convention and try
DEEPSEEK_API_BASE_URL. We only read DEEPSEEK_BASE_URL, so the proxy
silently isn't used. Accept the alias (canonical name still wins on
conflict) so the obvious env name works.

Co-authored-by: reasonix <[email protected]>
2026-05-26 01:59:11 -07:00
YHHandreasonix dc1779e8da feat(proxy): accept proxy.url from config.json (#1881)
Desktop and GUI users on Windows often can't reliably set HTTPS_PROXY
for the spawned Reasonix process — env vars set in Clash, system
settings, or PowerShell profiles don't always reach a Tauri-launched
child. The proxy plumbing is in place; only the env-var source path
was wired.

Add cfg.proxy.url as a first-class source: it wins over HTTPS_PROXY /
HTTP_PROXY / ALL_PROXY when set, normalizes bare host:port like the env
path, and tags the install result with source: "config" | "env" so
/doctor can show which one is active.

Closes #1868

Co-authored-by: reasonix <[email protected]>
2026-05-26 01:46:39 -07:00
YHHandreasonix 585a243b0b fix(desktop): unit-suffix CSS vars during drag, use canonical thread-width helper (#1875)
The drag-path direct DOM writes for --thread-max-width and --composer-max-width
were unitless strings, so the consumer max-width var() fell back to its default
for one frame per mousemove until React's render caught up — a visible flicker
that cancels the perf win.

- Suffix both writes with `px`
- Replace the duplicated formula with the existing getThreadMaxWidth helper
- contain-intrinsic-size: 1px 100px → auto 100px, so the browser remembers
  the actual rendered size instead of pinning offscreen messages to 1px wide

Co-authored-by: reasonix <[email protected]>
2026-05-26 01:24:59 -07:00
TaoMu c96a524742 fix(tui): guard ASCII IME enter commits (#1874) 2026-05-26 01:17:56 -07:00
TaoMu 71065f34bd test(jobs): wait for tail output before asserting (#1872) 2026-05-26 01:17:17 -07:00
TaoMu 74e138c472 test(tui): cover prompt incremental repaint (#1873) 2026-05-26 01:13:49 -07:00
YHHandreasonix f226ad2508 fix(dashboard): sync TUI and Web modal state (#1831) (#1866)
The web client was POSTing to /api/modal with {id, response}, but
the server expects /api/modal/resolve with {kind, choice, text?},
so every web confirmation returned 405 and the TUI's pauseGate
stayed open. The reverse direction was broken too: the tauri-bridge
SSE handler ignored modal-down, leaving the web modal up after the
terminal user resolved it.

- bridge confirm/choice/plan/checkpoint/revision RPCs through the
  real /modal/resolve endpoint with the right body shape
- carry "shell" vs "path" on confirm_response so the server can
  route to the matching TUI handler
- emit \$modal_dismissed from modal-down so the web reducer clears
  pending lists when another surface resolves first

Co-authored-by: reasonix <[email protected]>
2026-05-26 01:10:09 -07:00
CVEngineerandwufengfan df0507fbb8 perf(desktop): direct DOM CSS vars during sidebar drag, disable CSS transition, content-visibility for messages (#1812)
* fix(desktop): drag perf — direct DOM + disable CSS transition during drag; fix test types

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

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

---------

Co-authored-by: wufengfan <[email protected]>
2026-05-26 01:05:06 -07:00
YHHandreasonix 85668b0130 fix(desktop): float update banner above the thread (#1865)
The update notice rendered at the top of the thread scroll area, so a
restored session with messages would scroll the banner out of view and
the user had to open a new tab to see it. Lift it out of `thread-inner`
into a fixed-position overlay anchored to the viewport, rendered once at
the App root instead of per tab.

Co-authored-by: reasonix <[email protected]>
2026-05-26 01:02:31 -07:00
Tianjiu 6a2b78f5c0 fix(ui): highlight active plan edit mode (#1863) 2026-05-26 00:49:53 -07:00
YHHandreasonix 31acf1e232 fix(desktop): add search-engine API key UI + intercept slash command (#1867)
The desktop client had no UI for filling in API keys for web search
engines that require them (metaso, tavily, perplexity, exa) or for the
SearXNG endpoint. The `/search-engine` slash command also fell through
to the chat input instead of being handled locally.

- General settings page now renders a credentials row below the engine
  selector that adapts to the chosen engine: a URL input for searxng,
  a password input + signup link + clear button for the API-keyed
  engines. Existing keys show a masked prefix.
- Server-side `settings_save` accepts `webSearchEndpoint`,
  `metasoApiKey`, `tavilyApiKey`, `perplexityApiKey`, `exaApiKey`
  (with `null` to clear); `$settings` reports the masked prefix for
  each so the UI can render a "set" indicator without leaking the key.
- `/search-engine` and `/se` now open the general settings page
  instead of being forwarded as user text.

Closes #1844

Co-authored-by: reasonix <[email protected]>
2026-05-26 00:28:17 -07:00
YHHandreasonix da25e37b1d chore(desktop): split kind/length effects in @ popup, drop redundant guard (#1859)
- Reset activeIdx to 0 on popup.kind switch (slash <-> at) instead of
  clamping into the new popup's range, which left users on an arbitrary
  row after switching.
- Drop the lastActiveRef guard in Popup — useEffect([activeIdx]) already
  reruns only on change.
- Move the conditional class join out of a template literal so the
  non-at branch doesn't leave a trailing space.
- Remove unused EditMode / ReasoningEffort type imports from the test.

Co-authored-by: reasonix <[email protected]>
2026-05-26 00:14:07 -07:00
YHHandreasonix d0643eebb2 chore(i18n): drop zh-CN /qq argsHint, fall back to source (#1862)
Follow-up to #1857. The argsHint values are BNF over English command
keywords (`connect [appId appSecret [sandbox]] | status | disconnect`)
— there's nothing to translate. The merged zh-CN override dropped the
sub-argument structure and inlined an EN+CN gloss (`connect连接`)
that read awkwardly.

Removing the key lets zh-CN fall back to spec.argsHint, so users see
the same syntax as English and don't lose the appId/appSecret hint.

Co-authored-by: reasonix <[email protected]>
2026-05-26 00:13:53 -07:00
YHHandreasonix ab04288066 fix(mcp): drop LSP-only fields from initialize params (#1861)
`rootUri` and `workspaceFolders` are LSP concepts, not part of the MCP
2024-11-05 `initialize` schema. Strict servers (e.g. ida-pro-mcp on the
official Python SDK with pydantic) reject the request with
`Invalid params: unexpected parameters: ['workspaceFolders', 'rootUri']`.

Workspace roots are already exchanged the correct way: the client
advertises the `roots` capability, and the server requests them via
`roots/list` (already wired up).

Co-authored-by: reasonix <[email protected]>
2026-05-26 00:05:38 -07:00
Bernardxu123andBernardxu123 fd32b56535 fix(i18n): /qq command hints now use i18n, argsHint and description localized to Chinese (#1857)
Co-authored-by: Bernardxu123 <[email protected]>
2026-05-26 00:00:26 -07:00
Tianjiu 4163217919 fix(desktop): keep mention popup stable (#1850) 2026-05-25 23:53:01 -07:00
YHHandreasonix cb4b2be38e chore(ui): drop undo-context re-exports through useEditHistory (#1854)
The test was the only consumer routing through useEditHistory.ts —
import undo-context.ts directly. Six re-exports gone, no behavior
change.

Co-authored-by: reasonix <[email protected]>
2026-05-25 23:49:35 -07:00
TaoMu f10267038b fix(tui): preserve undo state in session context (#1810) 2026-05-25 23:22:45 -07:00
YHHandreasonix 6b015c0559 refactor(ink): extract vendored renderer to @esengine/ink + tui polish (#1847)
Stage 1 of #1829: ship the renderer as a separate private package
instead of vendoring at src/ink/. Picks up the tui-polish work that
landed alongside it (visuals, pulse animations, ghosting fix).

## Renderer extraction

- src/ink/ removed; renderer lives in esengine/reasonix-ink (private)
- package.json: ink dep points at @esengine/ink (file: tarball for
  local dev; swap to npm: alias post-publish); react-reconciler and
  yoga-layout added as direct deps so they hoist to a single top-level
  instance (single React dispatcher, single reconciler instance);
  17 transitive runtime deps and 3 @types removed
- tsconfig: ink path-map removed
- vitest.config: ink alias removed
- tests/helpers/ink-stdio.ts: text() uses strip-ansi + restores
  CSI N C cursor-forward back to literal spaces
- tests/helpers/ink-test.ts (new): replaces ink-testing-library;
  lastFrame() joins all chunks instead of returning only the most
  recent write() — required because the diff-based renderer emits
  multi-chunk frames per commit
- 15 test files migrated; 13 obsolete UI snapshot tests removed
  (5 files)

## Visual alignment

- UserCard: single full-row backgroundColor=MESSAGE_BG.user fill
- ApprovalCard: round border with borderLeft/borderRight=false
- PromptInput: round border (top + bottom only) + borderText with
  plan / history / mode / model
- ReasoningCard: italic + dim header; collapsed state appends
  (ctrl-o to expand) hint
- theme/tokens: new MESSAGE_BG section (user/bash/selected) for all
  5 themes
- CardHeader: glyph prop accepts string | ReactElement

## Pulse animation system

- Pulse primitive: generic frame cycler with DIAMOND/SQUARE/
  TRIANGLE/CIRCLE/HEX presets aligned to existing brand glyphs
- Wired into 7 cards + 4 LiveRows components
- ThinkingRow + OngoingToolRow: live elapsed time + output token
  count + t/s rate
- ticker.tsx: useTick / useSlowTick switched from
  useAnimationTimer (keepAlive=false) to useAnimationFrame
  (keepAlive=true) so the shared clock actually starts

## Bug fixes

- PromptInput: removed systemCursorSync — the out-of-band CSI CUP
  write desynced the renderer's screen model under sync-output mode,
  causing residual glyphs starting at the 3rd typed character
- Wizard: TextInput now sourced from ink (drop-in TextInput exposed
  by the package); ink-text-input dep removed

## Tests

279 files, 3722 passed, 11 skipped, 0 failed.

Refs #1829 (Stage 1).

Co-authored-by: reasonix <[email protected]>
2026-05-25 22:42:17 -07:00
reasonix 6c8650d2be fix(desktop): wire memoryDetail/onReadMemory through test fixtures
State requires `memoryDetail` since #1779 added it; test initial-state
builder and ContextPanel render fixture were missing the field. Root
`verify` doesn't run desktop tsc, so this surfaced only in the desktop
release matrix build for desktop-v0.51.0.
2026-05-25 09:42:15 -07:00
reasonix 98dec4a401 chore(dsnix): bump to 0.51.0 + sync lockfile 2026-05-25 09:31:23 -07:00
reasonix 8a56afd571 chore(release): 0.51.0 2026-05-25 09:22:58 -07:00
YHHandreasonix 10dccac9b0 chore(deps): bump ink 7.0.2 -> 7.0.4, drop patch-package machinery (#1791 follow-up) (#1809)
Ink 7.0.3 (Static stale-output fix, useBoxMetrics ref) and 7.0.4
(shared resize listener, useEffectEvent dependency fix) ship upstream
fixes worth picking up. None of them include the overflow-frame
flicker reduction from #1791, so dropping the patch reverts that
optimisation — accepting the regression in exchange for not carrying
a local fork of ink's render path.

- bump `ink` ^7.0.2 -> ^7.0.4 in package.json + lockfile
- delete `patches/ink+7.0.2.patch`
- drop `patch-package` from dependencies (and its transitive tree)
- remove the patch-package execSync from scripts/postinstall.mjs

Co-authored-by: reasonix <[email protected]>
2026-05-25 09:05:28 -07:00
YHHandreasonix 95f5df07e6 fix(tui): demote stuck running plan step on turn end (#1784) (#1806)
advanceActivePlanSteps marks the next non-settled step as `running`
whenever a step completes, but nothing demotes it when the agent stops
calling mark_step_complete mid-plan. The card then displays "step N in
progress" indefinitely even though the turn has ended.

Dispatch a new plan.idle event from the App.tsx turn-end finally; the
reducer maps running→queued on active plans. Multi-turn flows are
unaffected — the next mark_step_complete re-advances the marker via
advanceActivePlanSteps.

Closes #1784

Co-authored-by: reasonix <[email protected]>
2026-05-25 08:51:12 -07:00
YHHandreasonix 25eefbbdec perf(search): bypass regex worker for literal patterns (#1748) (#1804)
`search_content` was dispatching every pattern that parsed as a valid
RegExp — including plain literals like `new ToolRegistry` — to the
worker thread, paying full postMessage round-trip per file. On
multi-file scans this dominates wall time; one report hit the 120s
walk deadline on a query grep finished in 0.72s.

Detect patterns with no regex metacharacters and route them to the
existing main-thread `text.includes` branch. Also short-circuit
files whose buffer doesn't contain the substring so we skip the
line-split for misses.

Local bench (full repo, ~20K walkable files): root no-glob literal
2255 ms → 809 ms (2.8x); src/ *.ts literal 132 ms → 74 ms (1.8x).
Regex patterns still take the worker path; all 3731 tests pass.

Closes #1748

Co-authored-by: reasonix <[email protected]>
2026-05-25 08:50:20 -07:00
TaoMu c53535946a fix(loop): trim long-session retained payloads (#1799)
* fix(loop): prune stale plain reasoning

* fix(loop): trim retained tool-call payloads
2026-05-25 08:49:03 -07:00
YHHandreasonix 3218500736 fix(stdin): refuse ESC-less CSI recovery when followed by typed text (#1771) (#1800)
Typing or pasting tokens like `[DEBUG]` was being parsed as a stripped
left-arrow (`[D`) plus the leftover `EBUG]`. The ConPTY ESC-strip rescue
now only fires when the matched tail ends the chunk or chains into
another control byte; printable letters/digits after the tail mark the
input as user text.

Closes #1771

Co-authored-by: reasonix <[email protected]>
2026-05-25 08:12:18 -07:00
YHHandreasonix 65e833f6e8 fix(tui): hide max effort on non-DeepSeek endpoints (#1798)
#1657 dropped the preset abstraction and exposed reasoning effort
directly, keeping `max` as a DeepSeek-only extension that users opt
into knowing standard OpenAI / vLLM / Azure reject it with 400. The
TUI still advertised `max` everywhere — `/effort` argsHint, slash-arg
picker, ModelPicker effort rows, /effort handler — even when the
active endpoint was a third-party host that can't accept it. Users
on those endpoints saw `max` in every suggestion and reported it as
a preset-era leftover (#1794).

Endpoint-aware filter: when `loop.client.baseUrl` is not api.deepseek.com,
drop `max` from the choices the TUI surfaces:
  - `/effort` argsHint and argCompleter (autocomplete + arg picker)
  - ModelPicker effort rows
  - /effort handler's accept list + status / usage message
  - new `effortUsageNoMax` i18n key (EN / zh-CN / de) so the error
    on bad input doesn't itself name `max` as an option

`max` stays available on DeepSeek endpoints — that's the design from
#1657, just no longer visible where it would 400.

Fixes #1794.

Co-authored-by: reasonix <[email protected]>
2026-05-25 08:10:22 -07:00
Hermito Kattandhermitokatt 4a6be7dc50 fix(i18n): German (de) corrections and completions (#1797)
- /language de: add 'de' to argCompleter and argsHint in commands.ts
- Capitalization: fix ~90 lowercase German sentence starts throughout de.ts
- Backfill: add ~95 new translations for CLI hints, slash command
  descriptions, MCP marketplace text, and UI labels previously falling
  back to English via ...EN spreads
- Native-speaker review: multiple rounds of corrections to word choice,
  terminology consistency, and formatting
- Preserve T1anjiu's existing translations and the ...EN fallback pattern

Co-authored-by: hermitokatt <[email protected]>
2026-05-25 08:08:57 -07:00
YHHandreasonix b224b7bf42 fix(cli): replace BEL with ST on Windows stdout so cmd doesn't beep on every frame (#1795)
Windows cmd.exe rings the system bell when stdout receives a bare BEL
byte (0x07). Third-party libraries (ansi-escapes, terminal-link, ink's
own deps) embed BEL as an OSC sequence terminator — perfectly valid VT
syntax that Windows Terminal, ConEmu, and every *nix terminal handle
silently — but cmd treats the unrecognized OSC start as junk and beeps
on the BEL byte. Visible on #1786 as the system bell ringing on every
assistant response chunk.

Patching every emitter individually doesn't scale (the constants are
scattered across several deps). Instead wrap process.stdout/stderr on
Windows and rewrite `\x07` → `\x1b\` at the boundary. ST and BEL are
both valid OSC terminators per VT 510, so legitimate OSC sequences keep
working (Windows Terminal / ConEmu / conhost-with-VT accept either);
stray BEL outside an OSC turns into ESC backslash which cmd treats as
junk text instead of a bell.

Installed via side-effect import at the very top of src/cli/index.ts,
after node-version-guard and heap-limit-launch (which may re-exec) so
the wrap is in the process that actually runs the CLI.

Fixes #1786.

Co-authored-by: reasonix <[email protected]>
2026-05-25 07:26:59 -07:00
Bernardxu123andBernardxu123 a0a723109a fix(ui): patch Ink to reduce terminal flicker on overflow frames (#1791)
* fix(ui): patch Ink to reduce terminal flicker on overflow frames

* fix: move patch-package to dependencies for global install

---------

Co-authored-by: Bernardxu123 <[email protected]>
2026-05-25 06:51:54 -07:00
Tianjiu c4641ec7f0 fix(desktop): recalc thread width on resize (#1789) 2026-05-25 06:35:07 -07:00
YHHandreasonix ff705c1dc6 fix(dashboard): replay active modal on SSE connect so web confirm gate isn't stuck (#1770) (#1792)
When the assistant triggered a `run_command` shell confirmation in the
web dashboard, the tool card stayed on "running" indefinitely with no
Approve / Deny button. CLI and Tauri desktop worked fine.

Root cause: `modal-up` is broadcast at the moment the gate opens. If the
dashboard tab wasn't already connected to /api/events at that instant,
the event went out to zero subscribers and the dashboard never learned a
modal was up. The SSE handler already snapshotted `busy-change` for this
exact "client connects mid-state" reason; `getActiveModal` existed on
DashboardContext for the same purpose ("Snapshot of any modal currently
up (for SSE clients that connect mid-modal)") but was never wired into
the SSE stream.

Send the modal snapshot alongside `busy-change` on every new SSE
connection. Verified the new regression test fails on main (the read
times out at 5s — no modal-up ever arrives) and passes with the snapshot.

Fixes #1770.

Co-authored-by: reasonix <[email protected]>
2026-05-25 06:34:08 -07:00
ForeverYoungPp a65f1062fc fix: normalizeSemanticEmbeddingUserConfig drops timeoutMs field (#1788) 2026-05-25 06:33:33 -07:00
arata 48cc3f4cb2 fix(docs): polish docs responsive spacing (#1785)
Remove the duplicated Download item from the top nav while keeping the desktop download CTA, and add priority-based nav tiers so lower-value anchor links progressively disappear at narrower widths.

Tighten layout details across the landing page: prevent nav/version/language text wrapping, clean up hero metric alignment, and normalize spacing in feature cards, roadmap columns, and config bullet rows.
2026-05-25 06:32:09 -07:00
YHHandreasonix d85f9387a6 fix(dashboard): expose new memory browser to web mode (followup to #1766) (#1779)
PR #1766 reshaped MemoryEntryInfo to include `kind`/`path`/`type` and
added a `memory_read` RPC for the detail view, but only wired the
Tauri-desktop emit path. The web dashboard still mapped the old
response shape via #1775's loader, so:
  - frontend uses `m.path` as React key + onClick arg → undefined keys,
    duplicate-key warnings
  - clicking a memory row dispatches `memory_read` with undefined path →
    bridge default case warns, nothing happens

Plug the gap:
  - new GET /api/memory/entries → MemoryEntryInfo[] via the shared
    collectMemoryEntriesForWorkspace, identical to desktop's $memory shape
  - new GET /api/memory/read?path=... → MemoryEntryDetail via
    readMemoryEntryDetail
  - bridge: loadAndEmitMemory hits /memory/entries and emits entries
    verbatim; new memory_read RPC handler fetches /memory/read and emits
    $memory_detail

Co-authored-by: reasonix <[email protected]>
2026-05-25 04:33:17 -07:00
TaoMu 5165a54658 fix(tui): coalesce prompt cursor sync (#1768) 2026-05-25 04:28:16 -07:00
Tianjiu 582b440967 feat(i18n): add German (de) language support (#1773)
* fix(desktop): keep ctx resize handle off scrollbar

* feat(i18n): add German locale support

* feat(i18n): complete German translation for all three UI layers

Translate every untranslated key in src/i18n/de.ts (CLI/TUI),
dashboard/src/i18n/de.ts (web dashboard), and desktop/src/i18n/de.ts
(desktop app) — ~3,200 new lines of native German strings.

Covers all sections: common, cli/commands, ui, slash (all 42
commands), wizard, planFlow, errors, handlers, statusBar, editMode,
composer, path/shell/edit confirm, pickers, webErrors (all search
engines), marketplace, cards, labels, skills help, shortcuts, and
every other i18n namespace.

Terminology is consistent across all three layers. Translations
follow German typographic conventions (guillemets for quotation,
correct apostrophes, natural compound nouns).
2026-05-25 04:20:20 -07:00
TaoMu 3d9a0de38b fix: restore scroll and memory visibility (#1766) 2026-05-25 04:18:31 -07:00
YHHandreasonix b9ecc4efe0 fix(config): EXDEV fallback for atomic write on OneDrive / NTFS reparse points (#1778)
writeConfig and rewriteSession used renameSync for the final atomic swap.
On Windows, when ~/.reasonix sits inside a OneDrive-managed folder or
crosses a junction / reparse-point boundary, rename refuses with EXDEV
(-4037) even though the tmp file and destination are siblings. The CLI
then crashed on every launch trying to mint the dashboard token (#1738).

Extract a shared atomicWriteSync helper that catches EXDEV from rename
and falls back to copyFileSync + unlink. Atomicity is lost on that path
(no other safe option on Windows), but a working write beats the
launch-blocking error.

Fixes #1738.

Co-authored-by: reasonix <[email protected]>
2026-05-25 04:08:07 -07:00
YHHandreasonix 95913f1cf6 fix(dashboard): bootstrap mcp/skills/memory panels in web mode (#1775)
The CLI-hosted web dashboard's `serverInit()` only fetched settings,
sessions, and overview on mount — it never called `/api/mcp`,
`/api/skills`, or `/api/memory`. The reducer waits for `$mcp_specs`,
`$skills`, `$memory` events that the bridge had no path to emit, so
those three panels rendered empty and stayed empty until the user
triggered settings_save or restarted. Desktop (Tauri) shipped a
matching emit triple in desktop.ts on tab open — web mode regressed
on the equivalent.

Add three loaders that GET the REST endpoints and map their response
shape onto the dashboard event shape (`McpSpecInfo` / `SkillInfo` /
`MemoryEntryInfo`), fire them from `serverInit()`, and wire the
`mcp_specs_get` / `skills_get` / `memory_get` RPC commands so the
panels' refresh buttons also work. `mcp_specs_add` / `_remove` now
also re-emit the live list after the POST.

Fixes #1715.

Co-authored-by: reasonix <[email protected]>
2026-05-25 03:50:17 -07:00
YHHandreasonix 7df5d8b58e fix(loop): drain steer queue on /new + /cwd so prior intent doesn't leak (#1774)
clearLog() and switchWorkspace() left _steerQueue untouched. If the user
had typed a steer mid-turn in the prior session and the queue still held
text at the time of /new, the very next step() would pop it, wrap it in
the steer scaffolding, and ship it to DeepSeek as a user message — the
first prompt after /new would silently carry a fragment of the previous
conversation's intent.

Fixes #1707.

Co-authored-by: reasonix <[email protected]>
2026-05-25 03:44:36 -07:00
Bernardxu123andBernardxu123 1d6a30d11b fix(desktop): fix right panel scrollbar not draggable (#1765)
The scrollbar in the context panel was being overlapped by the resize
handle when the window was resized to trigger responsive breakpoints.

- Added padding-right: 20px to .ctx-body to create space for scrollbar
- Increased scrollbar width from 4px to 8px for better usability

Fixes #1695

Co-authored-by: Bernardxu123 <[email protected]>
2026-05-25 03:03:22 -07:00
Tianjiu 603600bf02 fix(desktop): verify bundled node TCC inheritance (#1749) 2026-05-25 03:00:59 -07:00
YHHandreasonix e6a175e138 perf(ui): index-backed mutateCard + O(n) plan.drop + elide cursor (#1769)
Three hot-path fixes in the cards reducer measured to cut per-event
cost dramatically on long sessions:

- mutateCard now does a Map<CardId, number> lookup instead of a full
  state.cards.findIndex scan. Each streaming/reasoning/tool chunk used
  to walk the whole transcript; on a 2000-card session that cost
  ~12.7ms per 1000 chunks, now ~1.7ms (86% faster).
- plan.drop replaces a .map() containing a .slice(i+1).some() with a
  single backward scan to find the last active plan, then one in-place
  patch. 1000-card session: ~65ms -> ~0.34ms per drop (99.5% faster).
- elideOldCardContent now starts from a persistent elideCursor that
  advances past stubbed and immutable-kind cards, so repeated appends
  no longer re-scan all prior elision-zone cards. 500 appends on a
  1000-card session: ~3.1ms -> ~1.6ms (48% faster).

The cardIndex map is mutated in place on append; structural changes
(session.fork, session.reset) rebuild it. tools/bench-reducer-hotpath.mjs
keeps the inlined old vs new comparison as a regression check.

All 3694 existing reducer / memory-budget / hydrate tests pass.

Co-authored-by: reasonix <[email protected]>
2026-05-25 02:55:13 -07:00
TaoMu bb9415a457 fix(tui): avoid Apple Terminal mouse reset crash (#1764) 2026-05-25 02:39:43 -07:00
TaoMu 5f661b932a Show desktop startup failures (#1759) 2026-05-25 02:30:31 -07:00
TaoMu bfef3c3e73 Guard CLI startup on unsupported Node (#1757) 2026-05-25 02:30:03 -07:00
Bernardxu123andBernardxu123 eb065799c7 fix(tui): sync system cursor for IME candidate window alignment (#1754)
* fix(tui): sync system cursor for IME candidate window alignment

* fix: satisfy biome exhaustive-deps lint rule

---------

Co-authored-by: Bernardxu123 <[email protected]>
2026-05-25 02:27:12 -07:00
Ethanandannon dba8a49e88 feat(ui): configurable cost display currency with click-to-toggle (#1710)
* feat(ui): configurable cost display currency with click-to-toggle

Add a costCurrency config option and a clickable status bar that
lets users toggle between USD and CNY display on the fly.

- costCurrency config field seeds the display preference on startup
- costDisplayCurrency state field drives reactive re-rendering
- mouse click on bottom status bar toggles USD/CNY instantly
- Wallet balance always stays in its own currency unaffected
- Module-level fallback ensures formatCost works without state
- All existing tests pass unchanged

* feat(ui): toast notification on cost-currency toggle

When clicking the status bar to swap display currency, a brief
toast confirms the change: 'Costs: $USD' or 'Costs: ¥CNY'.

* feat(ui): reactive UsageCard follows live cost currency toggle

* feat(ui): visual click hint on cost pill

Replace the generic '▸' arrow with '↻' (cycle arrow) on the
turn-cost pill to hint the display currency is clickable/togglable.

* style: trim comments to comply with comment policy

* refactor(ui): drop click-to-toggle, keep config-only cost currency

Per PR review feedback:
- Remove click-to-toggle interaction (hit-area too broad)
- Remove toast notification on toggle
- Remove module-level _defaultCostCurrency global (redundant with session state)
- Revert ↻ → ▸ glyph
- Keep costCurrency config field + costDisplayCurrency state plumbing
- Keep reactive UsageCard via useAgentState
- Keep precedence chain costDisplayCurrency ?? balanceCurrency in callers

---------

Co-authored-by: annon <[email protected]>
2026-05-25 02:23:04 -07:00
YHHandreasonix a683234090 perf(ui): progressive Static mount — session restore 4.5s → 430ms first paint (#1761)
Session restore on a 1000-turn workspace was committing every card to
ink's <Static> in one synchronous render — measured 4.5s of frozen
terminal. The cards array can't shrink (Static is append-only by
design), but it can grow incrementally.

useProgressiveBacklog snapshots the initial cards.length on first
non-empty render, releases the first INITIAL_BATCH (30) immediately,
then drains the rest in PROGRESSIVE_BATCH-sized chunks via setImmediate.
Each batch yields back to the event loop between renders so keystroke
input stays responsive during the catch-up.

Cards added AFTER the snapshot bypass the gate — new live turns
(streaming responses, mid-turn tool output) appear instantly even when
the historical backlog is still draining.

Cards added DURING the drain (rare — user typing during restore) are
deferred until the snapshot drains. This trades a small UX hiccup
(brief delay before a new card appears) for Static's append-only
contract — out-of-order commits would re-render history in the wrong
chronological order.

Measured (probe-render-large-session.mts, heavy 1KB card bodies):

  backlog | before    | after     | speedup
  --------+-----------+-----------+--------
    100   |   738 ms  |   399 ms  |  1.9x
    250   |  1440 ms  |   419 ms  |  3.4x
    500   |  2520 ms  |   411 ms  |  6.1x
   1000   |  4520 ms  |   429 ms  | 10.5x

First paint is now ~constant regardless of backlog size. Total mount
time is unchanged (the rest still has to render), but the user sees
the most-recent context immediately and can type while the rest
catches up.

Tests cover three invariants:
- small backlog (<= INITIAL_BATCH) releases everything immediately
- large backlog releases initial batch first, drains the rest in
  batches across setImmediate ticks
- chronological order is preserved across the drain (no card index
  reorder when more batches release)

Co-authored-by: reasonix <[email protected]>
2026-05-25 02:20:46 -07:00
TaoMu 0fe5041ccd fix(ui): reduce Windows terminal repaint cadence (#1750) 2026-05-25 02:00:16 -07:00
douglarek b5096d1278 feat(memory): support CLAUDE.md and ~/.claude/CLAUDE.md for Claude Code migration (#1694)
Add CLAUDE.md and .claude/CLAUDE.md to the project memory file search order (after REASONIX.md, before AGENTS.md) and read ~/.claude/CLAUDE.md as a global memory source alongside ~/.reasonix/REASONIX.md.

Changes:
- src/memory/project.ts: PROJECT_MEMORY_FILES now includes .claude/CLAUDE.md and CLAUDE.md
- src/memory/user.ts: add readGlobalClaudeMemory() and applyGlobalClaudeMemory() for ~/.claude/CLAUDE.md
- src/memory/user.ts: wire applyGlobalClaudeMemory into applyMemoryStack
- tests/project-memory.test.ts: add tests for CLAUDE.md priority and fallback
2026-05-25 01:57:13 -07:00
dacec354 618ed36b2a feat: preserve full tool results when truncated (#1615) (#1703)
* feat: preserve full tool results when truncated (#1615)

When a tool result exceeds the per-call token cap, auto-save the full
content to .reasonix/truncated-results/ and embed the file path in the
truncation marker so the model can read_file the complete result.

Changes:
- src/tools/truncated-result-saver.ts — new file: save + cleanup + skip
- src/mcp/registry.ts — truncateForModel/truncateForModelByTokens gain
  optional extraNote param appended to marker when truncated
- src/tools.ts — ToolDefinition.skipTruncationSave; dispatch save logic
- src/loop.ts — pass hookCwd as rootDir to dispatch
- src/tools/filesystem.ts — skipTruncationSave on read-only fs tools
- .gitignore — ignore .reasonix/truncated-results/
- tests/truncated-result-saver.test.ts — coverage for all paths

* fix: fix truncated-result-saver for CI + review — double .reasonix, Windows paths, comment policy, cleanup wiring, drop RFC doc

- Fix double .reasonix in fallback path (TRUNCATED_DIR had prefix, storageDir added it again)
- Normalize returned paths to forward slashes for cross-platform consistency
- Shrink multi-line block comments to one line (comment policy violation)
- Export storageDir for test consumption
- Align test file-creation patterns with project conventions (mkdtempSync, HOME redirect, top-level imports)
- Strengthen cleanupOldResults assertions to actually verify file removal
- Call cleanupOldResults(rootDir) at start of saveTruncatedResult so old files don't accumulate
- Drop .reasonix/rfc-1615.md — design docs don't belong in source tree
2026-05-25 01:54:02 -07:00
YHHandreasonix 3781904b11 test(edit-blocks): skip symlink-preservation test when symlink syscall fails (#1753)
Windows hosts without Developer Mode (or non-elevated shells) can't
create symlinks via fs.symlinkSync — the call throws EPERM. The new
symlink-preservation test added in b40a569 didn't guard for this and
failed for any contributor running `npm test` on a default Windows
setup.

Match the pattern already used in tests/at-mentions.test.ts: probe
symlinkSync once, set symlinksWorked = false on throw, return early
so the test passes vacuously on hosts that lack the capability.

Co-authored-by: reasonix <[email protected]>
2026-05-25 01:50:47 -07:00
YHHandreasonix aa539fdd55 chore(ui): render-trace readStats API + large-session probe with real numbers (#1751)
Extend src/cli/ui/render-trace.ts:
- readRenderTraceStats(): snapshot the counters directly instead of
  scraping stderr. Lets probes report numbers in their own format and
  decide when to read.
- resetRenderTraceStats(): clear between scenarios.

scripts/probe-render-large-session.mts runs two scenarios:
- (a) Mount of N cards via ink-testing-library — proxies session-restore
  paint cost. Real Ink reconciliation + yoga layout.
- (b) K parent-state ticks via react-test-renderer (which fires effects;
  ink-testing-library does not) — measures whether memo'd children
  actually skip work when an unrelated parent state changes.

Numbers from this probe answer the App.tsx-split debate:

  cards | (a) mount  | per-card  | (b) StaticCardStream re-renders / 200 ticks
  ------+------------+-----------+--------------------------------------------
   100  |   738 ms   | 7.38 ms   |     1
   250  |  1441 ms   | 5.76 ms   |     1
   500  |  2521 ms   | 5.04 ms   |     1
  1000  |  4517 ms   | 4.52 ms   |     1

Memo holds — parent re-rendering 200x cascades to ZERO StaticCardStream
re-renders. The "log append re-renders the whole App" hypothesis is
disproved. The real perceived cost is the ~5 ms/card initial-paint
hit on session restore (4.5 s freeze for a 1000-turn resume), which an
App.tsx structural split would not fix — that's a Static-priming /
progressive-render problem, not a memo problem.

react-test-renderer added to devDependencies for the probe (ink-testing-
library doesn't fire useEffect, so it can't be used to count renders).

Co-authored-by: reasonix <[email protected]>
2026-05-25 01:34:46 -07:00
YHHandreasonix e826984619 chore(ui): add per-component render trace gated by REASONIX_TRACE_RENDERS (#1747)
Before further App.tsx-shaped optimization (the "split into InputArea /
MessageList / Sidebar" advice), wire in cheap measurement so we cut
where the cost actually is, not where intuition points.

src/cli/ui/render-trace.ts
- useRenderTrace(name): noop when the flag is off (hooks still called
  unconditionally for rules-of-hooks compliance). When on, records
  count + avg/max ms per name and prints a one-line summary per second
  per traced component to stderr.

Wired into the four components most likely to dominate:
- AppInner — confirms whether App is actually re-rendering per keystroke
- ComposerArea — the input region; expected to re-render on every char
- StaticCardStream — the message list; should stay flat once history is
  in <Static>
- LiveActivityArea — the activity row; expected to tick on busy state

Usage:
  REASONIX_TRACE_RENDERS=1 reasonix code
  # then type — see lines like:
  # [render-trace] AppInner             42 renders · 7.0/s · avg 0.84ms · max 3.2ms
  # [render-trace] ComposerArea         42 renders · 7.0/s · avg 0.43ms · max 1.8ms

The existing memo boundaries (ComposerArea, StaticCardStream,
LiveActivityArea, CardRenderer all React.memo'd) make the obvious
optimization moves already in place. This lets a future PR target the
component whose number is actually too high, rather than splitting
App.tsx on principle and hoping.

Co-authored-by: reasonix <[email protected]>
2026-05-25 01:16:20 -07:00
YHHandreasonix 558d471113 refactor(core): extract LruCache + TtlLruCache + lazy(), replace ad-hoc duplicates (#1746)
Five hot-path call sites had grown the same patterns inline — Map +
delete-on-hit + size-cap eviction (tokenizer BPE + content caches),
and `await import()` scattered through tool handler bodies. Collapse
into three primitives.

src/core/lru.ts
- LruCache<K,V>: insertion-ordered Map with promote-on-hit + oldest-out.
- TtlLruCache<K,V>: LruCache wrapping {value, expiresAt}; stale read
  is a miss. One place owns the eviction rules.

src/core/lazy.ts
- lazy<T>(loader): memoize the loader's promise. First call starts the
  work, every later call returns the same pending/resolved promise.
  Failures stay sticky — the caller sees the same error on retry.

Call-site simplification

- src/tokenizer.ts — bpeCache + contentTokenCache: 14-line ad-hoc LRU
  → `cache.get/set`. Also exposes `warmupTokenizer()` so callers don't
  have to know how to trigger the gunzip + Map build.
- src/gitignore.ts — adds 5s TTL cache around loadGitignoreAt /
  loadGitignoreAtSync. Per-keystroke @-pickers walk every ancestor
  .gitignore; cached lookups inside the same tick are now free.
- src/at-mentions.ts — listDirectory result cached with 5s TTL, 64-entry
  cap. Same-tick keystroke bursts collapse to one readdir.
- src/tools/code-query.ts — `await import()` inside the fn bodies
  replaced with module-level `lazy(() => import(...))` factories.
  Lazy intent is declared at top of file; the handler body just awaits.
  Sessions that never call code_query no longer pay the multi-MB
  web-tree-sitter Emscripten runtime.
- src/code-query/grammar-map.ts (new) — extension→language detection
  as pure data, no web-tree-sitter dependency. parser.ts re-exports for
  back-compat.
- src/cli/ui/App.tsx — `setTimeout(warmupTokenizer, 0)` after first
  paint, amortizing the ~100ms / 35MB cold load while the user reads
  the banner.

Tests: tests/lru.test.ts (10 cases covering LRU promotion, eviction,
clear, TTL fresh/stale/refresh) and tests/lazy.test.ts (single-load,
identity, sticky rejection). All 3653 existing tests still pass.

Co-authored-by: reasonix <[email protected]>
2026-05-25 00:58:50 -07:00
Bernardxu123andBernardxu123 38d88abcc0 fix(tui): show plan mode [PLAN]/[计划] badge in input bar footer (#1742)
* feat(acp): support REASONIX_ACP_SYSTEM_APPEND env var for system prompt injection

* fix(tui): show plan mode badge in input bar footer

The ModeStatusBar component was imported but never rendered after the
ComposerArea extraction (#565 Phase 2), making plan mode invisible to
users running editMode=yolo + plan=on.

Fix: render the plan mode indicator as a localized [PLAN]/[计划] badge
directly inside the input bar's footer, to the right of the mode label.
No extra row, no layout shift — uses the existing i18n key
statsPanel.modePlan for automatic Chinese/English display.

Closes #1502

---------

Co-authored-by: Bernardxu123 <[email protected]>
2026-05-25 00:34:09 -07:00
Kagura 8a7c83435e fix(tui): implement forward-delete for Delete key (#1735)
The Delete key was treated identically to Backspace (both deleted the
character before the cursor). Split the handling so Delete removes the
character at the cursor position (forward-delete) while Backspace
continues to remove the character before the cursor.

Fixes #1728
2026-05-25 00:29:39 -07:00
YHHandreasonix 81249ec581 perf(markdown): memoize CodeBlock syntax highlight (#1743)
cli-highlight's tokenization ran on every CodeBlock render — multi-block
assistant replies were re-highlighting on every parent re-render
(slow-tick during streaming, theme change, terminal resize). Wrap the
highlight + entity decode in useMemo keyed on the token text and lang
so it only fires when the block content actually changes.

Settled cards already render via Static and skip re-render entirely;
this matters for the live streaming card where the parent re-renders
on every chunk while the code block content is stable.

Co-authored-by: reasonix <[email protected]>
2026-05-25 00:22:39 -07:00
YHHandreasonix d6aeafa984 perf(tokenizer): cache BPE + per-content bounded counts, fast-path truncate (#1741)
Three changes that together cut per-turn CPU ~57% and steady-state RSS
~22% in the 200-turn fakeFetch probe (rss=256MB→181MB at log.len=800).

- bpeEncode: in-place splice instead of slice/spread rebuild on every
  merge, plus 8K-entry LRU cache. Repetitive tool output (padded
  payloads, identifiers in code) re-encodes the same byte-level chunks
  thousands of times per session; the cache caps that at ~400KB.

- estimateConversationTokens: drop the full formatDeepSeekPrompt
  rebuild + single bounded tokenize. Sum per-message bounded counts
  with a fixed template overhead, gated by a content-string-keyed
  4K-entry LRU. Same entry tokenizes once over its lifetime instead of
  once per turn. The estimate drives fold thresholds (50%/75% of ctx)
  where ±5% slop is harmless.

- truncateForModelByTokens: sample-based fast path. For inputs in the
  [maxTokens, maxTokens*4] range the old code unconditionally tokenized
  the full string (37% total CPU on the 200-turn probe). Now we use a
  2KB-sample estimate with a 1.15x safety margin; only borderline cases
  fall through to a precise tokenize.

Regression origin: #1642/#1646 collapsed the conditional preflight into
an unconditional estimateTurnStart that runs every turn, surfacing the
underlying tokenizer cost. The tokenizer itself has always been a
pure-TS BPE port without caching — fine when called rarely, expensive
when called on every turn against growing logs.

Also adds three probes that reproduce + measure:
- scripts/probe-mem-leak.mts — drives CacheFirstLoop through N turns
  with fakeFetch, samples RSS/heap/log
- scripts/probe-jobs-leak.mts — confirms JobRegistry's MAX_COMPLETED_JOBS
  cap actually evicts
- scripts/analyze-cpuprofile.mjs — flat self/total roll-up for any
  .cpuprofile produced by --cpu-prof or `reasonix code --profile`

Co-authored-by: reasonix <[email protected]>
2026-05-25 00:11:38 -07:00
TaoMu 1768cf4d58 fix(desktop): contain long mcp specs (#1736) 2026-05-24 23:32:08 -07:00
CVEngineerandwufengfan 5290275857 feat(desktop): add JumpBar message navigation dock (#1729)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 23:26:16 -07:00
TaoMu f00f238b66 fix(desktop): sync slash setting commands (#1724) 2026-05-24 23:23:13 -07:00
Bernardxu123andBernardxu123 395ffdb6d5 feat(acp): support REASONIX_ACP_SYSTEM_APPEND env var for system prompt injection (#1737)
Co-authored-by: Bernardxu123 <[email protected]>
2026-05-24 23:18:29 -07:00
YHHandreasonix 3a05934db0 refactor(loop): extract stream aggregator + chunked dispatch from step() (#1739)
step() was a ~560-line method doing model streaming, repair, context
decisions, and tool dispatch in one body. Pull two independent pieces
into their own files so future edits to either don't risk the other.

- src/loop/streaming.ts — async generator that owns the chunk loop,
  toolCallDelta buffering, and readiness counting. Caller uses yield*
  to splice events and capture {content, reasoning, toolCalls, usage}.
- src/loop/dispatch.ts — chunked parallel dispatch with per-call
  inflight tracking, tool_start/tool yields, and rate-limit warning.
  Env reads (REASONIX_TOOL_DISPATCH, REASONIX_PARALLEL_MAX) move with
  the dispatch logic.

loop.ts: 1174 -> 1022 lines. Public API of CacheFirstLoop unchanged.
Full test suite green (3625 / 12 skipped).

Co-authored-by: reasonix <[email protected]>
2026-05-24 23:00:08 -07:00
CVEngineer 6b5bf7ac2f feat(desktop): add JumpBar message navigation dock (#1725)
Floating right-edge dock that surfaces the last 10 user messages as
horizontal bars: hover to magnify + preview text, click to scroll the
thread to that turn. Bar widths step 32 / 20 / 14 / 12 px around the
hover point with staggered cubic-bezier transitions for the wave feel.

Adds data-turn on each user message in the thread so JumpBar can
querySelector the scroll target.

Thanks @CVEngineer66 for the original idea and the polished landing.
2026-05-24 20:58:49 -07:00
TaoMu 5467670146 fix(tui): drop ESC-stripped legacy X10 mouse reports (#1723)
#1637 handled the canonical ESC [ M ... legacy mouse form, but Windows
ConPTY can strip the leading ESC, leaving a bare [M... that fell back to
the printable-text path. A burst of these (e.g. holding the mouse over
the terminal) would keep growing composer state — residual of #1598.

Add tryEscapelessLegacyMouse() parallel to the existing escapeless SGR
mouse path: recognize [M + 3 payload bytes as a fixed 5-byte packet,
consume it, surface no input event. Wire it into both the main parse
loop and the printable-run terminator so a stray [M mid-typing breaks
the run instead of swallowing the report into text.

Tests cover: single packet dropped, 1000-packet flood produces no
events, printable text either side of a report stays intact.

Trade-off: literal user input of "[M" followed by exactly 3 chars is
also swallowed — but [M is not a realistic typing pattern and the
flood-protection win is worth it.

Thanks @GTC2080 for tracking down the residual case.
2026-05-24 20:25:03 -07:00
YoungDan-hero b40a5692ec fix(code): make edit-block writes crash-safe via atomic rename (#1721)
applyEditBlock previously truncated the target file in-place before
writing the new bytes. A crash between truncate and writeAll could leave
the file empty, partially rewritten, or NUL-padded — high blast radius
since model-generated edits all flow through this path.

Switch to the standard atomic-replace pattern:
1. Resolve realpath so edits through a symlink modify the referent.
2. Write the new bytes to a sibling .tmp file with wx (exclusive create).
3. chmod to preserve the original mode under umask.
4. fsync the temp fd, close, then rename onto the target.
5. Best-effort fsync the parent directory.
6. On any error, unlink the temp file so we don't leak .tmp clutter.

Also fixes a latent short-write bug in the previous loop: `if (n <= 0)
break;` would silently truncate on a partial write. The new writeAllSync
throws instead.

One semantic change worth noting: atomic-rename breaks hardlinks. The
edited path now points at the new file while any other hardlink to the
old inode is left pointing at the pre-edit content. Industry-standard
tradeoff (same as the editor in your shell does), but a behavior change
versus the old in-place truncate.

New test covers the symlink-preservation case (edit through link →
link still exists → referent file has new content).

Thanks @YoungDan-hero for the careful patch.
2026-05-24 20:20:20 -07:00
FriendsHL 7d49171a28 docs: sync ARCHITECTURE.md and benchmark pricing to match code (#1720)
Three stale-doc fixes:

- ARCHITECTURE.md §4.3 — replace removed /pro single-turn arming with the
  current /model flash|pro + settings.json model selection. Note the
  removal in 0.50.0 (#1657, #1630).
- ARCHITECTURE.md §4.4 — replace the never-existed FAILURE_ESCALATION_THRESHOLD
  counter with the actual <<<NEEDS_PRO>>> model self-report mechanism. No
  failure-counter; purely LLM-initiated, no-op on pro tier.
- benchmarks/real-world-cache/README.md — fix 10× pricing error in
  v4-flash cache-hit ($0.028 → $0.0028) and entirely wrong v4-pro pricing
  ($0.139/1.667/3.333 → $0.003625/0.435/0.87). Recalculated cost tables;
  headline 99.82% hit ratio unchanged, savings now correctly show ~97.7%
  (flash) / ~98.9% (pro).

Thanks @FriendsHL for catching this — the benchmark pricing in particular
is the public cache-first defense link, the old numbers would have been
embarrassing.
2026-05-24 20:00:13 -07:00
bluedevil947 e4259d3543 fix(index): skip .devenv and .direnv in glob, search, and directory_tree (#1706)
.devenv/ and .direnv/ in Nix/devenv-based projects hold cargo registries,
uv caches, and Nix store symlinks — easily 1.5 GB and tens of thousands of
files. A bare glob("**/package.json") would stat every entry under those
trees before matching. Add them to DEFAULT_INDEX_EXCLUDES.dirs alongside
node_modules / .git / target / etc; include_deps:true still lets users
opt in.

Thanks @bluedevil947 for the patch.
2026-05-24 19:19:51 -07:00
paradoxSCH 5af0f1661f fix(plan): archive completed plans instead of letting them persist (#1700)
On session resume, if a stored plan has every step completed, archive it
and skip restoration so users don't see a stale "resumed plan" card on
every open. Same archive-instead-of-persist behavior triggers mid-session
when the final step completes.

Thanks @paradoxSCH for the patch + tests.

Closes #1355
2026-05-24 19:00:06 -07:00
YHHandreasonix 0df09f32cb fix(loop): don't show DeepSeek-specific 5xx hints when host is not DeepSeek (#1716)
A user on a corporate intranet running a local model saw "DeepSeek 服务不可用 …
查看状态页 https://status.deepseek.com" after their local model returned a 500.
Three hardcoded assumptions stacked up: the client error prefix is always
"DeepSeek N:", is5xxError matched it regardless of provider, and the probe
hit /user/balance (a DS-only endpoint that 404s on ollama/vLLM/etc.), so the
unreachable branch fired and pointed users at DeepSeek's status page for an
outage that didn't exist.

Allow-list api.deepseek.com explicitly. For any other host, skip the
/user/balance probe and use provider-neutral wording that surfaces the
configured host instead of "DeepSeek".

Co-authored-by: reasonix <[email protected]>
2026-05-24 18:56:20 -07:00
YHHandreasonix 56f3ffe968 fix(desktop): self-heal stale model id + expose plan as 4th editMode (#1699)
* fix(api): self-heal stale model id in settings GET

#1663 added `loadModel()` which maps unsupported model ids (e.g. v3
`deepseek-chat` / `deepseek-reasoner` left over in a user's config)
to `DEFAULT_MODEL` when no custom endpoint is set. The CLI uses it,
but the dashboard/desktop `/settings` GET endpoint still returned the
raw `cfg.model`, so users upgrading from a pre-v4 config saw their
desktop landing on the stale id and the model picker rendering it as
"custom" — looks like the app forgot which model it's on.

Route the GET through `loadModel(ctx.configPath)` so the same
self-heal applies on the wire. Custom-baseUrl users still keep their
custom ids unchanged (`loadModel` trusts non-empty `baseUrl`).

* feat(plan): expose plan as a 4th editMode in API + desktop + dashboard UIs

#1681 wired `editMode === "plan"` into the ToolRegistry dispatch gate
so plan mode is now a persisted state, not a slash-only toggle. The
desktop and dashboard surfaces never grew a control to set it though —
the settings API + edit-mode API still rejected "plan" with a 400, the
composer's ModeSwitch hardcoded review/auto/yolo, and the settings
page tri-state only listed the same three. Net: plan mode was
reachable from the CLI's `/plan` slash and direct config edits, but
not from either GUI surface.

Admit "plan" in both validation sets (`src/server/api/settings.ts`,
`src/server/api/edit-mode.ts`) and the `/mode` slash completer
(`src/cli/ui/slash/commands.ts`). Add a "plan" entry to MODE_INFO in
both composers with `I.list` and a planHint string. Add "plan" to the
settings page button maps. Extend the local `EditMode` string unions
in `desktop/src/{protocol,App,ui/composer}.tsx` and the dashboard
equivalents so TS accepts it everywhere.

i18n: add `editMode.plan` + `editMode.planHint` (and `planDesc` on
desktop) in both en + zh-CN for each surface.

---------

Co-authored-by: reasonix <[email protected]>
2026-05-24 08:33:35 -07:00
TaoMu 38e6d2cf8c fix(desktop): restore aborted prompt drafts (#1693) 2026-05-24 08:30:00 -07:00
TaoMu d2f62d4561 fix(tui): drop stale copy startup hint (#1692) 2026-05-24 08:28:12 -07:00
CVEngineerandwufengfan 03fb6582ed feat(desktop): show collapsible file-change summary after each assistant turn (#1691)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 08:19:38 -07:00
reasonix 5e757bd372 chore(dsnix): bump to 0.50.1 + sync lockfile 2026-05-24 07:39:33 -07:00
reasonix 2e7bdec3a8 fix(install): use execSync, not execFileSync, in postinstall
Node 18+ refuses to execFile `npm.cmd` directly on Windows
(CVE-2024-27980 mitigation), throwing `spawnSync npm.cmd EINVAL`.
Failed every Windows CI matrix entry on main after 0.50.1.

`execSync` routes through cmd.exe / sh, matching what the original
inline `&&`-chained postinstall did before #1584's regression.

End-user installs of [email protected].1 are unaffected: postinstall
short-circuits via the `dashboard/package.json` existence check before
reaching the broken execFile call. Only repo checkouts at tag v0.50.1
hit the bug, which is dev-side only.
2026-05-24 07:33:07 -07:00
reasonix 05b47947a1 fix(install): postinstall no-ops outside a git checkout (0.50.1)
#1584 wired `npm --prefix dashboard ci && npm --prefix desktop ci` into
root `postinstall` to fix CI's missing workspace deps. But the
published tarball ships only build artifacts under `dashboard/`
(index.html, app.css, dist/) and no `desktop/` at all, so end-user
`npx [email protected].0 code` failed during the dashboard `npm ci` and
the bin never ran — the only visible output was npm's cleanup
warnings on the half-extracted tree.

Move the workspace install into `scripts/postinstall.mjs`, which
exits 0 when `dashboard/package.json` is absent (i.e. when running
from the tarball, not the repo). Ship the script via `files:`.

Deprecate 0.50.0 on npm so existing installers see the warning.
2026-05-24 07:25:20 -07:00
reasonix 4188ddf007 chore(dsnix): bump to 0.50.0 + sync lockfile 2026-05-24 07:08:48 -07:00
reasonix be60c9539e fix(release): build before test in prepublishOnly so dashboard smoke tests find dist/
Dashboard smoke tests added in #1418 read `dashboard/dist/app.js` and
`app.css` at filesystem level. They pass under `npm run verify` (which
builds first) but fail under `npm publish`, whose `prepublishOnly` ran
in `lint → typecheck → test → build` order — tests fire before the
artifacts they need exist.

Reorder to `lint → typecheck → build → test` so the publish-time gate
matches the verify-time gate. Caught when the v0.50.0 publish-npm.yml
run failed before reaching `npm publish`.
2026-05-24 07:01:55 -07:00
reasonix 28d95059c7 chore(release): 0.50.0 — CLI-hosted dashboard for desktop, presets removed, persisted usage stats, plan dispatch gate
Headline themes:
- Desktop: bundle the CLI-hosted React dashboard, retire Tauri+Preact duplicate (#1418)
- Config: drop preset abstraction; flash/pro are direct model selections (#1657, #1630)
- Stats: persist cumulative usage to session meta + auto-restore on startup (#1667, #1680, #1643, #1628)
- Plans: editMode="plan" enforced at the ToolRegistry dispatch gate (#1681); step advance fix (#1629)
- Context: fold once at turn start, drop pre-flight + byte-ceiling (#1642, #1646); collapsible compacted card (#1649)
- Subagents: per-skill flash/pro override + Settings UI (#1632)
- Desktop polish: sidebar drag-resize (#1688), responsive collapse (#1585), copy/edit overlay + msg-history nav (#1645), Esc closes modal not turn (#1685), QQ tab isolation (#1672), DiffCard for edits (#1662), theme-aware highlighting (#1655), system events toggle (#1654/#1650), macOS TCC inheritance (#1614), dashboard.enabled (#1612)
- Dashboard polish: persistent session URL (#1586, #1589, #1599), theme-aware highlighting (#1664), IME confirm-enter guard (#1689), code-fence lang fix (#1677), vendor chunk split (#1587), markdown table h-scroll (#1562)
- TUI: Alt+S input stash/recall; static history isolated from input rerenders (#1635); legacy mouse drop (#1637, #1648); multi-edit gated in review (#1647)
- Diff: SplitDiff column border holds under CJK (#1686)
- MCP: workspace roots passed to servers (#1625); codeCommand honors mcpServers (#1603)
- Config plumbing: (baseUrl, apiKey) resolved as a tuple (#1658); stale model id self-heal (#1663)

See CHANGELOG for the full list.
2026-05-24 06:55:16 -07:00
TaoMu 217a9d1804 fix(dashboard): ignore IME confirm enter (#1689) 2026-05-24 06:34:51 -07:00
TaoMu 0c0e800520 fix(desktop): discard explicitly aborted turns (#1687) 2026-05-24 06:29:56 -07:00
CVEngineerandwufengfan be4e619dd3 feat(desktop): draggable sidebar resize + responsive conversation panel width (#1688)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 06:16:39 -07:00
66c5b5107e fix(diff): SplitDiff renders CJK without misaligning the column border (#1686)
Two bugs in the same `Cell` body (#1671):

- truncation used `raw.length > inner`, which undercounts wide chars —
  a CJK row that was visually too wide for the column slipped past the
  check and overflowed into the gutter
- padding used `padEnd(inner)`, which counts string length not cells —
  short CJK content got padded as if each wide char were 1 cell, so the
  background-color stripe ran past the column edge

Repo already has a cell-aware clipper (`clipToCells`) for the cut and
a private `padToCells` in `markdown.tsx` for the pad. Promote
`padToCells` to `text-width.ts` so SplitDiff can use both — collapses
the original four lines (slice + ternary + padEnd + ascii comment) to
a single `padToCells(clipToCells(raw, inner), inner)` and drops the
duplicate definition from `markdown.tsx`.

Supersedes #1683, which fixed the detection half but left the slice +
padEnd in place — for CJK content the truncated string ended up wider
than `inner` and short rows still over-padded.

Co-authored-by: reasonix <[email protected]>
Co-authored-by: Bernardxu123 <[email protected]>
2026-05-24 05:55:14 -07:00
YHHandreasonix bf18fd648b fix(dashboard): mirror code fence lang detection fix from #1661 (#1677)
#1661 fixed the lang-detection bug for desktop only. Dashboard's pre
handler has the same `c.type === "code"` check that fails when
react-markdown's component override replaces `code` — the element's
type is the override function, not the string "code". For dashboard
this didn't just mislabel the language; the fallback returned a vanilla
`<pre>` and skipped CodeBlock entirely, so syntax highlighting and the
copy button were missing for every fenced code block.

Extracted the lang lookup into `extractFencedLang` in both files so it
can be unit-tested without rendering CodeView (prism-react-renderer
pulls in each package's own React copy under vitest, which breaks
full-render tests across desktop/dashboard).

Co-authored-by: reasonix <[email protected]>
2026-05-24 05:44:29 -07:00
YHHandreasonix 3555d36b57 chore(ui): drop redundant overflow-wrap from inherited descendants (#1675)
overflow-wrap is an inherited property; .msg-text already declares it,
so the duplicate declarations on .msg-text .markdown and .msg-text p
are noise. The combined `.msg-text X, .markdown X` selectors keep their
declarations because the standalone .markdown case (cards) has no
ancestor setting overflow-wrap.

Co-authored-by: reasonix <[email protected]>
2026-05-24 05:26:32 -07:00
wade1999 a6c2fb6115 fix(desktop): isolate QQ turn routing by tab (#1672) 2026-05-24 05:15:39 -07:00
4ecfd877fc fix(desktop): Esc closes the open modal instead of aborting the model (#1685)
Two related papercuts in the desktop client:

1. Esc during streaming with a modal (settings / about / jobs popover /
   workdir popover) open used to fire `abort()` and leave the modal
   sitting on screen. Now the global Esc handler bails out when any of
   those flags is set; settings/about modals each install their own
   `keydown` listener that calls `onClose()`. JobsPop and WorkdirPop
   already had their own handlers, so this just rounds out the set.

2. Clicking (or Enter-ing) the already-active session in the sidebar
   used to round-trip a session_load and clear live in-turn state
   (issue #1653). Skip when `s.name === activeName`.

Co-authored-by: reasonix <[email protected]>
Co-authored-by: CVEngineer <[email protected]>
2026-05-24 05:13:14 -07:00
4068b9d3b5 feat(plan): wire editMode="plan" into the ToolRegistry dispatch gate (#1681)
`ToolRegistry.setPlanMode(true)` (src/tools.ts:86) already blocks every
non-readonly tool at dispatch — but the only path that ever turned it
on was the `/plan` slash command. Persisted `editMode = "plan"` (set via
config edit or a settings UI that surfaces it) was previously inert:
the registry's `_planMode` stayed false across boots, so the model
could still call `write_file` etc.

Extend `EditMode` to include "plan", and have `buildCodeToolset` mirror
the loaded mode into the registry on construction. Desktop host calls
the new `applyPlanMode` helper in three places: on `emitSettings`, on
every `buildRuntimeFor`, and inside the `settings_save` handler when
the user toggles edit mode — so live changes take effect without a
rebuild. CLI's `/plan` slash continues to work as the direct toggle.

This is the minimal foundation needed before a settings UI in desktop
or dashboard can offer "plan" as a 4th edit-mode option.

Co-authored-by: reasonix <[email protected]>
Co-authored-by: T1anjiu <[email protected]>
2026-05-24 04:33:32 -07:00
YHHandreasonix f297fe0a26 fix(stats): carry totalCompletionTokens across resumes (#1667 follow-up) (#1680)
#1667 added totalCompletionTokens to SessionMeta and wrote it after every
turn via patchSessionMeta, but the carryover plumbing in SessionStats
was incomplete:

- seedCarryover didn't read meta.totalCompletionTokens
- SessionStats had no _carryoverCompletion field
- the write call summed only this.turns (no carryover), and trimOldTurns
  dropped completion tokens into the void

Net effect: on every resume, the first turn's patchSessionMeta call
overwrote the previously-saved totalCompletionTokens with just the new
turn's tally — counter reset to ~0 across restarts. (Cost / cache hit /
miss don't have this problem because they each have proper carryover
plumbing.)

Currently zero user-visible impact since no UI reads the field yet, but
the data was already flowing through UsageStats in both dashboard and
desktop, so the next surface that exposes it would inherit the bug.

Fix mirrors the cacheHit/Miss pattern: new _carryoverCompletion field
seeded from meta, a cumulativeCompletionTokens getter, trimOldTurns
folds completion tokens into carryover like the other counters, and
loop.ts switches the write to use the new getter.

Co-authored-by: reasonix <[email protected]>
2026-05-24 04:11:08 -07:00
CVEngineerandwufengfan 56a3efd93e fix(cli,desktop): persist cumulative usage stats to session meta + auto-restore on startup (#1667)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 04:03:45 -07:00
YHHandreasonix 1c3cfba15b chore(theme): finish theme rename follow-up after #1666 (#1678)
#1666 renamed/dropped themes (tokyo-night → midnight, removed
default/github-dark/github-light, added deep-blue) but missed three
surfaces:

- `/theme` slash command's `argsHint` and `argCompleter` still advertised
  the removed names and were missing `midnight` / `deep-blue`
- i18n `themeCaption` dicts in EN.ts and zh-CN.ts still held the removed
  entries and had no labels for the new themes, so the picker would
  render the literal i18n key (e.g. `wizard.themeCaption.midnight`)
  next to the new theme names

Drop the stale entries from both locales, add captions for `midnight`
and `deep-blue`, and trim the slash command lists to the actual theme
set. The "default" caption is gone because the theme itself was removed.

Co-authored-by: reasonix <[email protected]>
2026-05-24 03:57:14 -07:00
Bernardxu123andBernardxu123 860ae56633 fix(ui): optimize prompt input styling with theme simplification and history indicator (#1666)
- Simplify themes from 7 to 5 (dark, light, midnight, deep-blue, high-contrast)
- Add new deep-blue theme with #0153e5 brand color
- Rename tokyo-night to midnight (remove geographic name)
- Fix input text color to follow theme changes (add FG.body)
- Add history mode indicator (↑ history) when viewing past inputs
- Optimize bgInput color values for better contrast

Closes #1665

Co-authored-by: Bernardxu123 <[email protected]>
2026-05-24 03:52:43 -07:00
CVEngineerandwufengfan 326e657bf9 feat(dashboard): code block syntax highlighting follows light/dark theme (#1664)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 03:45:03 -07:00
CVEngineerandwufengfan 36228c72a8 feat(desktop): render edit_file/multi_edit results as DiffCard (#1662)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 03:30:31 -07:00
YHHandreasonix 8686c91b45 fix(dashboard): tool cards no longer stuck spinning forever (#1676)
`loopEventToDashboard` was generating dashboard event ids as
`${assistantId}-${role}-${Date.now()}` for both tool_start and tool
events. Different role string and different timestamp → completely
different ids. The SSE bridge passes that id through as the segment
callId, and the dashboard reducer keys segments by it — so tool.result
never matched the segment created by tool.intent, segment.result
stayed undefined, and the card sat in `running` state forever
(its only "done" trigger is `result !== undefined`).

LoopEvent already carries a stable `callId` for this exact purpose
(see `src/loop/types.ts:40-41`: "UI uses this as the card id"). Use
it for both tool_start and tool so they share an id and the reducer
can pair them.

Regression-tested in `tests/loop-to-dashboard.test.ts`.

Co-authored-by: reasonix <[email protected]>
2026-05-24 03:26:31 -07:00
CVEngineerandwufengfan 7219a20cb7 fix(desktop): code block lang detection + overlay header + icon-only copy button (#1661)
Co-authored-by: wufengfan <[email protected]>
2026-05-24 03:25:47 -07:00
YHHandreasonix 340760feb1 fix(dashboard): composer queue-count label was passing wrong var name (#1674)
The composer's "N queued" label called `t("composer.queueCount", { n })`
but the i18n templates use `{count}` — variable mismatch left the
placeholder un-interpolated, so the UI rendered the literal string
`{count} 个排队` whenever a message was queued while busy.

Co-authored-by: reasonix <[email protected]>
2026-05-24 03:16:26 -07:00
Yvoneandkoge_yvone 1dc54dfc78 fix: 修复长路径撑开聊天气泡 (#1590)
Co-authored-by: koge_yvone <[email protected]>
2026-05-24 03:15:03 -07:00
YHHandreasonix 2a45ac45af fix(dashboard): don't synthesize $turn_complete from per-iter assistant_final (#1673)
The SSE bridge was reading the loop's `assistant_final` event as a
turn-end signal and synthesizing `$turn_complete`, but loop emits
`assistant_final` after EVERY model iteration — including mid-turn
iterations whose response carries tool_calls. So once the model said
"I'll run the test", busy flipped to false and the composer swapped
the stop button for send while npm test was still spawning.

The bridge also reset `sseTurnStarted` on that same event, which then
suppressed the real turn-end synthesis when `busy-change` (busy=false)
arrived later from the CLI's `handleSubmit` finally block. Drop both
the synthesized event and the flag reset; `busy-change` is the
authoritative turn-end signal and already drives `$turn_complete`
correctly via the case below it.

Co-authored-by: reasonix <[email protected]>
2026-05-24 03:04:36 -07:00
YHHandreasonix 4610d54743 fix(model): self-heal stale model id on load; drop v3 ids from picker fallbacks (#1663)
A stale `deepseek-chat` / `deepseek-reasoner` (or any other id no longer
accepted by api.deepseek.com) persisted in config.json bricked the next
launch with "Bad request (DeepSeek 400): supported API model names are
deepseek-v4-pro or deepseek-v4-flash, but you passed …". The picker
fallback list (used when the live catalog fetch fails) still surfaced
the v3 ids as selectable, so users could land there without ever
hand-editing config.

loadModel now keeps the persisted id only when (a) the user has a
custom baseUrl set — in which case we trust their model namespace —
or (b) the id is in the supported v4 allowlist. Otherwise it returns
DEFAULT_MODEL, and the next /model or picker write replaces the stale
config value.

Also drops the v3 ids from all six picker / settings fallback lists
(CLI, QQ, desktop composer + settings, dashboard composer + settings).

Co-authored-by: reasonix <[email protected]>
2026-05-23 23:24:01 -07:00
YHHandreasonix f11e2188b9 chore(loop): drop redundant abort warning, keep only synthetic final (#1659)
The "aborted at iter N" warning duplicated the synthetic assistant_final
that follows it; only the iter number was unique, and that's debug noise.
Removed the warning yield + the i18n string in both locales, and updated
the three loop tests that asserted on it.

Co-authored-by: reasonix <[email protected]>
2026-05-23 23:13:45 -07:00
YHH d2b5d0542e fix(config): resolve (baseUrl, apiKey) as a tuple, not two independent fields (#1658)
When a user set a custom baseUrl + apiKey in config.json (e.g. routing
DeepSeek through new-api) but also had a stale env DEEPSEEK_API_KEY
left over from a default-endpoint setup, the resolver pulled baseUrl
from one source and apiKey from the other. The request hit the proxy
URL with the wrong token and the API returned auth errors with no
obvious cause.

Reported in #1631, root-caused but unfixed in #1577.

New loadEndpoint() resolves (baseUrl, apiKey) atomically: whichever
source defines baseUrl owns apiKey too. 12-factor env > config is
preserved for the default-endpoint apiKey case. New bridgeEndpointEnv()
mirrors the resolved tuple into process.env so subprocess constructions
and lazy DeepSeekClient instances see the matched pair. Every
DeepSeekClient construction site now passes both apiKey and baseUrl
explicitly via loadEndpoint().

Closes #1631
2026-05-23 23:05:10 -07:00
YHHandreasonix 88fc19d962 refactor(config): drop preset abstraction, expose model + effort directly (#1657)
Presets bundled (model, reasoning_effort, thinking) under names like
flash/pro/auto. The bundling forced "max" as the cap and silently broke
OpenAI-compatible endpoints that only accept the standard literal set
(vLLM rejects "max" with a 400 — saw it in the wild against a
self-hosted DeepSeek-V4-Pro).

Direct controls instead:

- ReasoningEffort widens to low | medium | high | max
- Default cap is now "high" — the value every OpenAI-compatible
  endpoint accepts; users opt into "max" knowing it's DeepSeek-only
- Dashboard + desktop settings: model picker + effort buttons,
  both apply live through the existing settings bridge
- CLI: /model and /effort slash commands; ModelPicker shows EFFORT
  and MODELS sections with full enumeration
- Config: preset field removed, model field persisted directly

Co-authored-by: reasonix <[email protected]>
2026-05-23 22:37:02 -07:00
YHHandreasonix 8aba0e2c78 chore(cli): drop dead i18n helper + variable from #1617 (#1656)
Two small tidies left over from the edit-approval i18n PR:

- `entryStatusLabel(status)` was added to edit-history.ts but never
  imported anywhere. The status-label i18n keys it wrapped are still
  resolved inline by useEditHistory.ts (the only real consumer), so
  the helper is pure dead code. Drop it, drop the now-unused `t`
  import.

- `const status = t("app.editHistoryStatusApplied")` in useCodeMode's
  discard path was unused. Even if it had been used, "applied" is
  semantically wrong inside discard — the surrounding tail is built
  from `discardedCount` and `nothingWritten` already.

Co-authored-by: reasonix <[email protected]>
2026-05-23 22:19:09 -07:00
Fengfan Wu 267c4901dc feat(desktop): code block syntax highlighting follows light/dark theme (#1655)
Add a LIGHT_THEME (GitHub-style palette) alongside the existing
DARK_THEME and a usePrismTheme() hook that watches `<html data-theme>`
via MutationObserver, so code blocks switch highlight colors when the
app theme toggles. Without this, light mode rendered code in pale
dark-mode greys that were nearly invisible on the white background.

The MutationObserver only fires on data-theme changes (attributeFilter)
and skips no-op state writes via a prevRef, so the cost per toggle is a
single re-render.

Dashboard has the same hardcoded theme bug (dashboard/src/CodeView.tsx)
— good follow-up candidate.
2026-05-23 22:17:50 -07:00
YHH bac58aedd0 feat(ui): desktop system events + show/hide toggle (#1654)
Follow-up to #1650. Completes the system-event surfacing work:

1. Desktop bridge — the kernel WarningEvent (added in #1650) already
   flowed through eventize → desktop sidecar → webview as a Tauri
   event, but desktop's protocol type and App reducer didn't know
   about it. Add WarningEvent to desktop/src/protocol.ts (matches
   dashboard shape), grow ChatMessage with a "warning" kind, reducer
   gated on severity === "high", thread renderer adds the
   .sys-event-row inline divider (same styling as dashboard).

2. Settings toggle — new config field thread.showSystemEvents
   (default true) with load/saveShowSystemEvents helpers in
   src/config.ts. Desktop sidecar pushes it in $settings and handles
   it in settings_save. Both SPAs grow Settings/SettingsEvent/
   SettingsPatch, reducer stores it, warning render gates on
   settings.showSystemEvents !== false. Settings panel adds a
   seg-ctrl row in the Behavior section, en + zh-CN strings.

Default remains "shown" — severity filter (high-only) already caps
visible events to ~1-3 per session, so this is a preference, not a
noise mitigation.
2026-05-23 22:13:58 -07:00
YHHandreasonix bf77bba995 chore(desktop): extract useAutoCollapse hook, tidy sidebar logic (#1652)
Follow-up to #1585. The responsive sidebar logic was split across six
refs (autoSideCollapsedRef / autoCtxCollapsedRef / suppressSide... /
suppressCtx... / sideCollapsedRef / ctxCollapsedRef) and a 70-line
useEffect that did everything inline. Each panel's "is this collapsed
because the user asked, or because the layout forced it" state was
encoded across two of those refs; the resize logic had to spell out
all 6 stage-transition combinations by hand.

Extracted the per-panel collapse into useAutoCollapse(persistKey):

  - collapsed: the boolean for CSS
  - toggle:    user-driven flip; persists to localStorage
  - requireCollapsed:  layout asks for collapsed — claims as auto if
                       the panel wasn't already collapsed
  - releaseCollapsed:  layout asks for expanded — restores only if WE
                       collapsed it (manual collapses stay)

The resize effect drops to one branch per stage:

  WIDE    → release both
  COMPACT → require ctx (only when entering from wider — coming from
            narrow we preserve a user's manual ctx-open); release side
  NARROW  → require both

Also: fixed the one-line CSS indent slip on .app[data-side-collapsed].

Behavior is unchanged — same five stage-transition outcomes that #1585
hand-coded, just expressed declaratively.

Co-authored-by: reasonix <[email protected]>
2026-05-23 22:07:49 -07:00
Evan-Pycraft 341dc83f3c feat(i18n): localize edit approval/discard messages and events errors with zh-CN (#1617) 2026-05-23 22:06:26 -07:00
Tianjiu e02d0984c3 fix(desktop): add responsive sidebar collapse (#1585)
* fix(desktop): add responsive sidebar collapse

* fix(desktop): preserve composer menus in responsive layout
2026-05-23 21:54:34 -07:00
YHHandreasonix 5a9a5db4e7 feat(dashboard): surface system events as quiet inline dividers, drop chatty ones (#1650)
Layer 1 follow-up to #1649 (CompactionCard). Before this, every loop
warning fell through eventize.classifyWarning's default branch and
became an "error" event — Dashboard rendered compaction notices and
storm-stuck interrupts as alarming red error cards. Chatty warnings
(per-iter repeat-tool nudges, storm-suppressed counters) flooded the
thread.

- Add EventSeverity ("low" | "high") to LoopEvent. Tag the two known
  chatty sites in loop.ts (repeatToolCallWarning, stormSuppressed
  counter) as "low"; everything else is "high" by default — safer for
  new emit sites added later.
- Add a typed WarningEvent to the kernel + dashboard protocol.
  Eventize.classifyWarning now: drops low-severity entirely, emits a
  proper warning event (not an error) for high-severity. Existing
  policy.escalated / policy.budget classification still wins for those
  patterns.
- Dashboard SPA: add warning kind to ChatMessage, reducer case in
  applyIncoming (filters anything not "high"), render as a quiet
  inline divider (.sys-event-row) — single line, dim, ~0.7 opacity,
  flanked by hairline rules. Visually weak so several can stack
  through a long session without crowding the conversation.

Tests: low-severity warnings dropped, high-severity emit typed warning
(not error), unmarked warnings default to high.

Follow-ups not in this PR:
- Desktop bridge equivalent (Tauri IPC + Tauri-side event types).
- Settings toggle to fully hide system events for users who want a
  cleaner thread.

Co-authored-by: reasonix <[email protected]>
2026-05-23 21:52:17 -07:00
YHHandreasonix f78beded5c chore(desktop): #1645 follow-ups + isolate flaky server-dashboard test (#1651)
* chore(desktop): tidy follow-ups from #1645

Three small cleanups landed alongside the desktop UX bundle:

- composer: extract `recordSendAndReset` so the history-push + browse-
  index reset logic is one helper, not duplicated between the Enter key
  path and the send-button onClick.
- composer: drop the duplicate IME-quirk comment at the use site; the
  ref declaration block at the top of the component already documents
  the macOS Chinese IME ordering quirk.
- App: hoist the inline `onEdit` arrow into a useCallback so UserMsg's
  memo isn't busted by a fresh function identity on every render of the
  message list.

* test(server-dashboard): isolate from real \$HOME/.reasonix

The v0.13 panels suite uses mkdtempSync for cfgPath and usagePath but
the handlers it exercises (/api/health, listSessions) still call
homedir() under the hood. On a dev machine with thousands of session
jsonl files in ~/.reasonix/sessions the readdir + per-file statSync
walk blows past the 5 s default test timeout, even though the same
test runs in ms on a clean CI box.

Redirect HOME and USERPROFILE inside the suite's beforeEach so the
walks land in the suite's already-empty temp dir, and restore the
originals in afterEach. No production-code change — the handlers'
homedir() coupling is a separate cleanup.

Whole file now runs in 1.7 s.

---------

Co-authored-by: reasonix <[email protected]>
2026-05-23 21:48:52 -07:00
Fengfan Wuandwufengfan e170db3ec2 feat(desktop): copy/edit overlay, msg history nav, IME guard, card collapse (#1645)
* feat(desktop): copy/edit overlay, msg history nav, IME guard, card collapse

* fix(desktop): guard history nav behind cursor position; keep reasoning open while streaming

---------

Co-authored-by: wufengfan <[email protected]>
2026-05-23 21:21:21 -07:00
TaoMu 5116d11198 test(tui): cover legacy mouse report flood (#1648) 2026-05-23 21:17:11 -07:00
YHH 106255be72 feat(ui): render compacted history as a collapsible card on all three surfaces (#1649)
After auto-compaction, the synthesized recap was being stored as a
plain assistant message with a HISTORY_FOLD_MARKER prefix. None of the
three surfaces special-cased it — TUI hydrated it as a regular streaming
card on resume; Desktop and Dashboard rendered it inline through
AssistantText. Users had no way to tell compaction had happened or
distinguish the recap from a real model reply.

- Single-source the marker + helpers in @reasonix/core-utils/compaction
  (COMPACTION_SUMMARY_MARKER, isCompactionSummary, stripCompactionMarker).
  Re-export the constant from src/context-manager.ts so existing
  HISTORY_FOLD_MARKER imports keep resolving.
- TUI: new kind: "compaction" in state/cards.ts, renderer in
  cards/CompactionCard.tsx, hydrate.ts emits it instead of a streaming
  card when the marker is present.
- Desktop / Dashboard: CompactionCard component in ui/cards.tsx,
  intercepted in the assistant-segment renderer in ui/thread.tsx.
  Default-collapsed, archive icon, header shows char count, body renders
  the recap markdown.
- Wire vite + tsconfig aliases for the sub-import path so browser bundles
  don't pull in Node-only siblings (tildeify) via the barrel.

Tests: marker detection edge cases in core-utils, hydrate emits
compaction card for the marker, full verify (262 files / 3595 tests).

Follow-up: surface the loop "warning" event ("folded N messages → M")
as a visible row on Desktop / Dashboard (currently flows through
protocol, no ChatMessage reducer).
2026-05-23 21:05:14 -07:00
TaoMu c848df3fa3 fix(tui): gate multi-edit in review mode (#1647)
Route multi_edit through the same review gate that edit_file and
write_file already use, so the model can't mutate files in review mode
without surfacing pending edits to the user. Extract the gate logic from
App.tsx into edit-tool-gate.ts (pure, unit-tested) and add
setEditModeLive that updates the ref, React state, and disk in one
atomic callback — fixes the stale-ref window where an in-flight tool
call could see the old mode immediately after the user toggled it.

Closes #1639
2026-05-23 20:25:51 -07:00
YHH 421e412658 refactor(context-manager): drop preflight, fold once at turn start (#1646)
Follow-up to #1642. After landing the fold-first preflight, the next
question was whether preflight needs to exist at all — and on a 1M-context
provider it doesn't: post-response decideAfterUsage already folds at
75%, upstream tool-result caps prevent single-message blowups, and the
byte ceiling the preflight was originally guarding against is gone.
Converge on the Claude-Code-style single compaction path: one fold check
per turn, at turn start.

- Delete decidePreflight, mechanicalTruncate, related constants, the
  PreflightDecision interface, and the per-iter preflight block in step().
- Add a single turn-start check after the user message is appended:
  if local request estimate > TURN_START_FOLD_THRESHOLD (90%), fold once
  before the iter loop.
- No mechanical fallback. If fold can't shrink the log, the request goes
  out and DeepSeek's error surfaces to the user — honest beats silent
  re-compaction with worse semantics.
- Drop preflight i18n keys + delete tests/preflight.test.ts.

Net -393 lines. E2E (live DeepSeek) green across baseline, high-ratio
terminal turn, and turn-start fold scenarios.
2026-05-23 20:23:37 -07:00
TaoMu b3e868135d fix(desktop): surface file paths and completion feedback (#1644)
Show the full tracked path for files in the desktop context panel, plus
per-file open/copy actions. Open honors `settings.editor` when set, else
falls back to the system default opener. Add an in-window completion
toast when a long task (>= COMPLETION_NOTIFY_MIN_MS) finishes while the
window is focused; unfocused windows continue to use the existing native
desktop notification path.

Closes #1638
2026-05-23 20:16:24 -07:00
YHHandreasonix 6ca6219513 fix(desktop): show current context size, not cumulative cache totals (#1643)
The right-side context meter summed cacheHitTokens and cacheMissTokens,
which are session-wide running totals. After ~20 cached turns of a
50k-token context, the cumulative cacheHit alone reaches 1M+ and the
panel renders "1,500,000 / 1,000,000" with the bar pegged at 100%.

What the meter is supposed to show is the *current* context size — i.e.
prompt_tokens of the most recent API call. That value is already
captured per-turn as lastCallCacheHit / lastCallCacheMiss; switch the
meter to use those. Cumulative totals are still used elsewhere (status
bar / settings) for the cache-hit-rate display, where summing is the
right semantic.

Also mirror the reset into lastCall* on the $ctx_breakdown event so
/compact takes effect immediately instead of waiting for the next
model.final to overwrite a stale pre-compact value.

Co-authored-by: reasonix <[email protected]>
2026-05-23 19:51:03 -07:00
YHH 3c8cc8c477 refactor(context-manager): preflight folds first, drop obsolete byte ceiling (#1642)
Live probe shows DeepSeek's gateway accepts at least 8MB request bodies —
the empirical ~880KB ceiling MAX_BODY_BYTES guarded against no longer
exists. Remove the byte path from decidePreflight + mechanicalTruncate
and converge on a single fold-first pipeline: preflight tries semantic
fold first, mechanical truncate is last-resort only when fold cannot
summarize.

fold() per-message token estimate now counts tool_calls JSON so heavy
args can't slip past the tail-budget check. New requireTailBoundary
option (preflight-only) prevents fold from wiping an active tool turn.
Preflight sets _foldedThisTurn to block decideAfterUsage from re-folding.
2026-05-23 19:49:36 -07:00
TaoMu bfb6d8e289 fix(ui): preserve code operators in code blocks (#1640)
Disable font ligatures and contextual alternates for markdown code blocks
in both dashboard and desktop, so operator sequences like `->` `=>` `!=`
render as separate glyphs instead of shaped ligatures.

Closes #1636
2026-05-23 19:44:20 -07:00
YHHandreasonix a00ea34411 fix(desktop): block right-click context menu (#1641)
Right-clicking in the WebView2 surface showed the browser's default
menu, where "Reload" wipes the in-memory session and leaves a blank
white screen. Block the contextmenu event at app startup. F5/Ctrl+R
are already trapped earlier in the same file.

Co-authored-by: reasonix <[email protected]>
2026-05-23 19:42:57 -07:00
TaoMu c5debed4da fix(tui): drop legacy mouse reports (#1637) 2026-05-23 19:03:37 -07:00
TaoMu 31998dfe93 fix(tui): isolate static history from input rerenders (#1635) 2026-05-23 19:00:19 -07:00
ForeverYoungPp 3d150437a2 fix(api): normalize preset in settings/overview endpoints to prevent badge crash (#1633) 2026-05-23 18:58:29 -07:00
YHHandreasonix 7d817f8a8e feat(subagents): per-skill flash/pro override + Settings UI (#1632)
* feat(subagents): per-skill flash/pro override + Settings UI

Subagent skills (`/explore`, `/research`, `/review`, `/security-review`
out of the box, plus any user-authored `runAs: subagent` skill) had only
one knob for picking the spawn model: a `model:` line in the .md
frontmatter. That meant users couldn't tune the four built-ins without
shadowing them by copying the bodies into a custom file, and the desktop
/ web settings had no surface for it at all.

Adds a per-skill `flash | pro` selector:
- `config.json` gets `subagentModels?: Record<skillName, "flash" | "pro">`
  with `load`/`save` helpers that filter to valid values
- `SkillStore` accepts `subagentModels` in its constructor and applies
  the override only to `runAs: subagent` entries (inline skills with
  the same name are untouched, frontmatter `model:` is overridden
  when an entry exists)
- `registerSkillTools` plumbs it through; `buildCodeToolset` reads
  `loadSubagentModels()` so the runtime path picks up the live value
- desktop `settings_save` accepts the field, persists via
  `saveSubagentModels`, re-emits the skill list so the UI's
  inline-rendered model badge stays in sync
- dashboard `POST /api/settings` validates the same shape, GET surfaces
  the current map, `appliesAt.subagentModels` = "next-skill-run"
- both desktop and dashboard Settings → Skills page render a
  `<select flash | pro>` per subagent skill — inline skills get no
  selector

`flash`/`pro` map to `deepseek-v4-flash`/`deepseek-v4-pro` inside
`SkillStore` so the config stays human-readable across model id swaps.

Tests:
- config: round-trip, filter unknown values, clear-all removes field
- SkillStore: override applies to builtins, doesn't touch inline `test`,
  override beats frontmatter `model:` when both set, frontmatter still
  wins absent override

* fix(settings): reject prototype-pollution keys in subagentModels POST

CodeQL js/remote-property-injection — `__proto__` / `constructor` /
`prototype` in a POST /api/settings body would land as own properties
on the sanitized map and persist into config.json.

* fix(settings): null-prototype map for CodeQL sanitizer recognition

The previous fix's explicit string blocklist wasn't recognized by
CodeQL's js/remote-property-injection rule as a barrier. Object.create(null)
is the canonical sanitizer — keeps the explicit blocklist so dangerous
keys still get dropped before persistence.

* fix(settings): use Map+Object.fromEntries for CodeQL sanitizer

CodeQL js/remote-property-injection didn't accept the explicit blocklist
or Object.create(null) as a barrier. Map.set bypasses the writeAccess
sink CodeQL tracks, and Object.fromEntries constructs via
[[CreateDataProperty]] which the rule trusts.

---------

Co-authored-by: reasonix <[email protected]>
2026-05-23 09:53:56 -07:00
Bernardxu123andBernardxu123 f12e10db62 fix(memory): cap SessionStats turns at 200 with cost carryover (#1628)
Per-turn stats array grows indefinitely — iterated on every
summary() call. Over long sessions this causes both memory growth
and O(n) cost on each summary.

Add MAX_TURNS=200 cap: when the array exceeds this, oldest turns
are dropped and their costs/cache tokens folded into carryover
fields. Session totals remain accurate (totalCost, cacheHitRatio)
while the array stays bounded.

The cap is generous — 200 turns covers a full day of active use.
The carryover aggregation means resuming a session after trim still
reports correct cumulative totals.

Co-authored-by: Bernardxu123 <[email protected]>
2026-05-23 09:53:34 -07:00
TaoMu 12a9a518ef fix(ui): advance active plan steps (#1629) 2026-05-23 08:24:46 -07:00
TaoMu 84952744f8 fix(mcp): pass workspace roots to servers (#1625) 2026-05-23 08:18:18 -07:00
TaoMu f38100ed44 fix(ui): replace repeated live hints (#1624) 2026-05-23 08:15:57 -07:00
YHHandreasonix 161d6ec78f feat(presets): drop auto + /pro — flash/pro are the only knobs now (#1630)
Auto-escalation (flash → pro via the `<<<NEEDS_PRO>>>` marker) and the
one-shot `/pro` arming were both surfaces that could spend money behind
the user's back: a turn that ran on flash could silently re-bill on pro,
and `/pro` plus an idle session compounded the same risk. Both are gone.

PresetName is now exactly `"flash" | "pro"`. Old configs holding
`auto` / `smart` / `fast` / `max` keep loading: `loadPreset` and the
loose-input `resolvePreset` / `canonicalPresetName` silently coerce
anything that isn't `flash`/`pro` to `flash`. No legacy migration
notice — the user just gets the new safe default.

Surface dropped:
- `CacheFirstLoopOptions.autoEscalate`, `loop.autoEscalate`, the
  streaming-time NEEDS_PRO buffer/flush, the post-call NEEDS_PRO retry,
  `src/loop/escalation.ts`, the `loop.flashEscalation` i18n string.
- `loop.armProForNextTurn`, `loop.disarmPro`, `loop.proArmed`,
  `loop.escalatedThisTurn`, `loop.currentCallModel`, the `_escalateThisTurn`
  / `_proArmedForNextTurn` state, the `loop.proArmed` warning yield.
- `/pro` slash command + handler + i18n.
- Dashboard `proNext` field on `POST /api/settings` + ctx.setProNextLive
  + the proNext / proArm / proArmed / proNextNote i18n bundle.
- StatsPanel's pro pill (escalated / proArmed props + rendering).
- ModelPicker's `currentAutoEscalate` prop and detect.
- usePresetMode's proArmed / turnOnPro state.
- ResolvedDefaults.autoEscalate, handleWarningEvent's setTurnOnPro hook,
  AppProps.autoEscalate / ChatOptions.autoEscalate.
- "auto" preset card in both desktop and dashboard Settings → Models.

Tests updated:
- tests/presets.test.ts: legacy + unknown values coerce to flash.
- tests/resolve.test.ts: legacy auto/smart/fast/max coerce silently.
- tests/slash.test.ts: `/preset auto` returns usage; `/preset flash` /
  `/preset pro` keep working; arg-picker enum is `["flash", "pro"]`.
- tests/loop.test.ts: NEEDS_PRO describe block and the proArm/disarm
  tests are gone with the features.
- tests/server-dashboard.test.ts: proNext field is gone from the live
  callback test.
- tests/preset-effort-isolation.test.ts: only flash/pro iterated.
- tests/ui-slash-suggestions.test.tsx: advanced-group count 11 → 10.

Verify: tsc clean (root + dashboard), biome clean (only pre-existing
welcome-banner warning), 3576 tests pass.

Net -669 lines.

Co-authored-by: reasonix <[email protected]>
2026-05-23 07:45:09 -07:00
YHHandreasonix dc1acf7526 fix(theme): composer + user card bg use theme tokens, not hardcoded #1e1e1e (#1623)
iTerm2 light theme + reasonix theme `github-light` still rendered the
composer dock as a black band (#1607). The composer and the user-message
card both hardcoded `#1e1e1e` for their bg and `#0153e5` for the brand
accent — the proxy-tokens system (`SURFACE.bgInput`, `TONE.brand`) was
bypassed entirely, so theme switches did nothing to either surface.

What looked in the screenshots like "the status bar is also black" is
actually `PromptInput`'s inline mode/model row, which lives *inside* the
dark Box. The real `<StatusRow>` rendered below it with no bg and stayed
themed correctly all along.

Replaces four hardcoded literals with their theme tokens:
- composer left accent stripe        #0153e5 → TONE.brand
- composer body bg                   #1e1e1e → SURFACE.bgInput
- composer inline mode label color   #0153e5 → TONE.brand
- user message card bg               #1e1e1e → SURFACE.bgInput

All six themes already define matching `bgInput` values, so dark themes
get the same near-black they had before and light themes (`light`,
`github-light`) get the near-white they were missing.

EditConfirm + SplitDiff still tint diff lines with hardcoded dark
red/green and will need new `diffAddedBg`/`diffRemovedBg` tokens for
light-theme parity — separate PR.

Closes #1607

Co-authored-by: reasonix <[email protected]>
2026-05-23 07:14:49 -07:00
TaoMu f459dbf268 test(lifecycle): cover npm package aliases (#1621) 2026-05-23 05:47:35 -07:00
Bernardxu123andCI Fix 9372b3a316 fix(memory): JobRegistry self-cleanup for completed jobs (#1620)
- Auto-evict oldest completed jobs when count exceeds MAX_COMPLETED_JOBS (20)
- Cleanup runs on job completion (settleClosed) and list() calls
- No time throttle — gate on count only, O(jobs.size) is trivial at N=20
- Initialize lastCleanupAt to 0 so first call always runs (fixes dead zone)

Fixes #1571 (JobRegistry portion)

Co-authored-by: CI Fix <[email protected]>
2026-05-23 05:44:18 -07:00
YHHandreasonix b16f614368 fix(settings): restore search-engine switcher in dashboard + desktop (#1618)
The dashboard's <select> for switching web search backends shipped in
#1558 against the old Preact panel; the React port (#1418) dropped it
silently and the i18n strings have been dead code since. The desktop
settings panel never had it. Both surfaces now expose the same dropdown
under General → Behavior, alongside reasoning effort / edit mode /
budget — six engines (bing, searxng, metaso, tavily, perplexity, exa)
matching the `/search-engine` slash.

- protocol: `webSearchEngine` on SettingsEvent + SettingsPatch in both
  desktop and dashboard mirrors
- backend: `src/cli/commands/desktop.ts` settings_save persists the
  field via writeConfig; emitSettings reads it back via webSearchEngine()
- dashboard bridge: emitServerSettings forwards the field from
  `GET /api/settings` (server side was already wired by #1558)
- desktop i18n: copies the six already-translated strings that were
  living only in the dashboard bundle

API keys for metaso / tavily / perplexity / exa still go through the
slash command (or config.json) — UI-side key entry can come later if
demand shows up.

Co-authored-by: reasonix <[email protected]>
2026-05-23 05:39:34 -07:00
YHHandreasonix 9e541658c8 fix(desktop): macOS bundled node inherits parent TCC grants (#1614)
Place `node` next to a `com.apple.security.inherit` entitlement so the
child Node process inherits the .app's Documents / Desktop / Downloads
TCC grants instead of re-prompting on every spawn.

- entitlements/main.plist applied via bundle.macOS.entitlements; Tauri's
  --deep codesign propagates inherit to Contents/Resources/node when
  Developer ID is configured
- bundle-node.mjs adds an ad-hoc codesign with the helper plist so the
  inherit entitlement still attaches on unsigned local / CI builds where
  --deep never runs

Closes #1611

Co-authored-by: reasonix <[email protected]>
2026-05-23 04:57:30 -07:00
douglarek 7d90606f8e feat(config): add dashboard.enabled setting to suppress auto-start (#1612)
* feat(config): add dashboard.enabled setting to suppress auto-start

Add a `dashboard.enabled` boolean config field (default true) so users
can permanently disable the embedded dashboard without passing
--no-dashboard on every launch. The CLI flag still overrides the config
(--no-dashboard wins over enabled: true).

* test(config): cover loadDashboardEnabled defaults, explicit values, and noConfig
2026-05-23 04:55:41 -07:00
Bernardxu123andCI Fix f67fcd261f fix(desktop): prevent stale events from corrupting UI after session switch (#1582)
* fix(desktop): prevent stale events from corrupting UI after session switch (#1217)

When a session switch happens while a turn is running, the old turn's
cleanup code may still emit events (, , etc.)
that arrive after the new session is active, causing UI lag and state
corruption.

Add a switching flag to the Tab interface:
- Set tab.switching = true before aborting in session_load/new_chat
- In runTurn's finally block, check tab.switching to suppress stale events
- Reset tab.switching = false after processing

This prevents the old turn from emitting events that would interfere
with the new session's state.

Fixes #1217

* fix(desktop): only set switching flag when aborter is live (#1217)

The previous implementation set tab.switching=true unconditionally in
session_load/new_chat handlers. When no turn was in flight (the common
case), the flag stayed true and suppressed events for the first turn
in the new session.

Fix: only set switching=true when tab.aborter exists (live turn).

---------

Co-authored-by: CI Fix <[email protected]>
2026-05-23 04:49:10 -07:00
dacec354 a6afeabd05 feat(tui): add Alt+S input stash/recall hotkey
Empty input + stash exists → recall into input, clear stash.
Empty input + no stash → "Nothing to stash" hint.
Non-empty input + stash exists → true exchange.
Non-empty input + no stash → stash input, clear buffer.

Gated behind busy + modal guard. No dead i18n keys.
2026-05-23 04:47:23 -07:00
Irene Luoandllr-selfgit 96c91279a8 fix(tui): surface failed shell command output (#1608)
Co-authored-by: llr-selfgit <[email protected]>
2026-05-23 03:37:26 -07:00
Bernardxu123andCI Fix 3daafde4a7 fix(mcp): use normalizeMcpConfig in codeCommand to support mcpServers (#1568) (#1603)
codeCommand was directly reading readConfig().mcp which only handles
the legacy string array format. When users configured mcpServers
(the object format) without the mcp array, MCP servers would not start.

Fixed by using normalizeMcpConfig() which processes both mcp and
mcpServers formats, then converts back to string array via specToRaw().

Fixes #1568

Co-authored-by: CI Fix <[email protected]>
2026-05-23 03:27:03 -07:00
Tianjiu 019a852be5 fix(desktop): preserve compact composer default (#1594)
* fix(desktop): preserve compact composer default

* fix(desktop): widen chat when rails collapse
2026-05-23 03:23:56 -07:00
Tianjiu d1ca21f545 fix(ui): preserve user message newlines (#1588) 2026-05-23 03:11:57 -07:00
TaoMu 018aa2e76e test(lifecycle): cover deterministic policy corpus (#1574) 2026-05-23 02:12:19 -07:00
YHHandreasonix ff4032c7db feat(dashboard): cross-session stability, persistent URL, polish pass (#1599)
* fix(dashboard): scope session list to current workspace + fix new-chat flow

Two related sidebar bugs:

1. The session list was unfiltered — users with thousands of subagent
   transcripts (`subagent-sub-*.jsonl`) and cross-workspace sessions
   in `~/.reasonix/sessions/` saw 10 000+ entries. The CLI's session
   picker already uses `listSessionsForWorkspace(currentRootDir)`;
   the dashboard's GET /api/sessions handler now does the same when
   `ctx.getCurrentCwd()` is wired. Also surface `meta.summary` in the
   listing so the bridge stops falling back to bare session names.

2. Clicking "new chat" pushed an error card into the transcript via
   `$session_empty` ("loaded with no messages") and never updated
   state.currentSession, which left #1586's URL mirror pointing at
   the old session. The new endpoint echoes the freshly-minted
   session name, and the bridge fires a real `$session_loaded` with
   empty messages so the reducer resets cleanly and the URL flips.

Sessions-ops test grows by two cases covering each behaviour.

* feat(dashboard): cross-session stability, persistent URL, polish pass

Squash-merges a chain of fixes prompted by post-#1418 user feedback on
the live web dashboard. The unifying themes: nothing should change
when you don't expect it to (token, port, URL, SSE stream), and
everything should give visible feedback when you do change it.

Server
- POST /api/sessions/new now echoes the new session name so the bridge
  can update state.currentSession without diffing the list.
- parseTranscript surfaces reasoning_content, tool_calls, and tool
  results (by tool_call_id) so historical replays show what the model
  actually did, not just the raw text turns.
- serveAsset injects ?token=... into CSS url() font references in
  addition to the existing JS-import rewrite — the previous gap 401'd
  every Geist / KaTeX font fetch.
- New /api/browse?path= lists immediate subdirectories (Windows drive
  letters included on first call) so the web runtime can ship a real
  directory picker.
- startDashboardServer exposes updateContext(ctx) — the handle now
  outlives a chat.tsx-driven App remount, and the new App rewires its
  loop/refs in place instead of forcing a port rebind that the OS
  hadn't released yet (EADDRINUSE -> ephemeral fallback -> new URL).
- Dashboard token + actual bound port are persisted to config.json on
  first run via ensureDashboardToken / saveDashboardPort, with an
  EADDRINUSE fallback to ephemeral. /dashboard reset-token rotates
  the token and restarts the server.

CLI
- listSessions workspace filter now reaches the dashboard's GET
  /api/sessions, cutting sidebar entries from "every subagent
  transcript on disk" (10 000+ for active users) down to the current
  workspace's chats.
- getDashboardUrl appends &session=<name> so the printed URL points
  at the attached session and survives copy/paste.

Dashboard UI
- Persistent module-level dashboardHandle + eventSubscribers Set so
  React App remounts (session swap) don't tear the server down and
  don't drop SSE subscribers on the floor — fixed the "send a message
  after switching, web stays silent" desync.
- session_load bridge handler emits $session_loaded with the new
  name and full segments (text + reasoning + tool calls stitched to
  results), instead of pushing an error card via $session_empty.
- Thread renders use index-based React keys for AssistantMsg —
  replayed transcripts arrive with turn=0 for every assistant row,
  so the turn-keyed list was collapsing every assistant message into
  one stale slot on every session switch.
- Sidebar gets a per-row loading spinner; thread shows a centered
  overlay during the swap so big sessions don't look dead.
- CSS containment on .session-item, .msg, and .thread; dropped a
  needless backdrop-filter on the loading overlay. Together these cut
  the Paint/Layout/pointerover budget noticeably on long transcripts.
- New WorkdirInputModal backed by /api/browse — the web build
  previously stub'd openDialog to "" so clicking Browse did nothing.
- Removed the "+ new tab" affordance from the tab bar (web has no
  multi-tab story).
- URL session mirror from #1586 reverted to read-on-mount only so
  clicking a session doesn't churn the address bar.

i18n
- statusbar.themeStyle{Graphite,Sandstone,Porcelain,Midnight}
- settings.themeStyle* + Desc, settings.page* Label + Desc for all 8
  pages, sidebarPanel.loading, workdir.{cancel,go,goTip,loading,
  emptyDir,openHere,pathPlaceholder}, handlers.dashboard.tokenReset*
  (en and zh-CN where relevant).

Tests
- tests/dashboard-token-persistence.test.ts (9 cases) for
  ensureDashboardToken / saveDashboardPort / clearDashboardToken.
- dashboard-sessions-ops gains coverage for the workspace filter
  and the new POST /sessions/new name echo.
- dashboard-smoke verifies CSS font url() token injection in
  addition to the existing JS chunk-import rewrite.

---------

Co-authored-by: reasonix <[email protected]>
2026-05-23 01:00:28 -07:00
YHHandreasonix 4689ea42e8 fix(dashboard): include current session in CLI-printed URL (#1589)
After #1586 the browser URL stays in sync with the active session,
but the URL the CLI prints on startup and via /dashboard still only
carried `?token=`. Copying it never restored the right session.

Append `&session=<name>` in `getDashboardUrl()` and use it for the
auto-start log line and openUrl call too, so the URL you see, copy,
or click always points back at the session the CLI is attached to.

Co-authored-by: reasonix <[email protected]>
2026-05-22 21:19:45 -07:00
YHHandreasonix cb0851c4cc perf(dashboard): split heavy vendor libs into separate chunks (#1587)
Builds went from a 943 KB monolithic `app.js` to a 224 KB entry plus
five lazy-cacheable vendor chunks (react, markdown, katex, prism,
icons). Total bytes are unchanged but the browser can fetch chunks
in parallel and reuse them across deploys when only app code moves.

Browsers strip query strings when resolving relative ESM imports, so
chunk-to-chunk references like `from "./vendor-react.js"` would 401
against the token-gated /assets/* route. `serveAsset` now rewrites
every relative `.js` import to carry the live token before sending
the body — same shape as the existing index.html templating, just
applied to JS bodies.

Before:  app.js               942.61 kB │ gzip: 292.58 kB
After:   app.js               223.76 kB │ gzip:  74.75 kB
         vendor-react.js      192.84 kB │ gzip:  60.17 kB
         vendor-katex.js      258.26 kB │ gzip:  77.53 kB
         vendor-markdown.js   171.91 kB │ gzip:  52.18 kB
         vendor-prism.js       86.04 kB │ gzip:  26.77 kB
         vendor-icons.js        8.07 kB │ gzip:   1.98 kB

Co-authored-by: reasonix <[email protected]>
2026-05-22 21:10:42 -07:00
YHHandreasonix 790949c8f1 feat(dashboard): persist active session in URL for shareable / refresh-safe links (#1586)
Until now the dashboard URL only carried the auth token, so a copied
link always landed on whichever session the CLI happened to be
attached to — refreshing a tab or pasting the URL elsewhere never
restored the session the user was actually viewing.

Mirror state.currentSession to a `?session=NAME` query param via
`history.replaceState` (no back-button noise) and, on the active
tab's first ready+sessions tick, read the same param back and
auto-dispatch session_load if the named session exists. Unknown
session names clear the param instead of erroring.

Both effects are gated on the tab being active, so multi-tab tabs
don't fight over the URL.

Co-authored-by: reasonix <[email protected]>
2026-05-22 20:52:19 -07:00
Tianjiu 595a83ee74 fix(ui): add horizontal scroll for markdown tables (#1562) 2026-05-22 20:17:39 -07:00
YHHandreasonix 6e8cad791e chore(install): include desktop deps in root postinstall (#1584)
CI's `npm ci` at the root only triggers `npm --prefix dashboard ci`,
leaving `desktop/node_modules` empty. Vitest scans `desktop/src/**`
for tests, so the first desktop test that imports a transitive dep
(e.g. `react-markdown` via `Markdown.tsx`) fails to resolve in CI
even though it passes locally for anyone who's ever run
`npm install` inside `desktop/`.

Unblocks #1562.

Co-authored-by: reasonix <[email protected]>
2026-05-22 19:46:57 -07:00
462b79b15e feat: port desktop dashboard from Tauri+Preact to CLI-hosted React Web app (#1418)
* feat: port desktop dashboard from Tauri+Preact to CLI-hosted React Web app

Migrate the desktop Tauri + React UI to a CLI-hosted Web dashboard,
replacing the legacy Preact UI and laying groundwork for mobile compatibility.

- Independent Vite + React 19 dashboard build chain (dashboard/)
- Mock/Server dual-mode bridge layer (tauri-bridge.ts)
- REST API routing alignment (sessions, settings, submit, abort)
- editMode support (review/auto/yolo) with runtime setEditMode
- User message deduplication in busy state (App.tsx:546-549)
- assistant_final event carries usage + costUsd fields
- Binary asset serving fix (woff/woff2/ttf/png as Buffer, not UTF-8)
- Smoke tests (10 cases) + editMode regression tests
- Build chain: npm run build now runs dashboard build first
- Removed 38 legacy Preact files + 8 obsolete tests

- SSE reconnection: fixed 3s retry, no exponential backoff or max attempts
- settings_save: does not merge overview for complete  broadcast
- session_load: still uses POST /api/sessions/load, not switch + GET
- app.js bundle size ~900KB (code-splitting deferred)
- Mobile layout optimization (deferred until desktop Web is stable)

- npm run build: pass
- npm run typecheck: pass
- npm run lint: pass
- npm run test: pass (229 files / 3271 tests)

* fix(ci): run build before test so smoke tests find dashboard artifacts

* cleanup: remove updater mechanism from web dashboard (CLI manages updates)

Web version doesn't need Tauri's @tauri-apps/plugin-updater since
updates are handled by CLI (npm). Removed:
- Imports and usage from App.tsx (pendingUpdate state, UpdateBanner component, check() call)
- about.tsx update checking UI (CheckStatus component, checkForUpdates)
- tauri-bridge.ts mock exports (Update type, check function)
- tsconfig.json and vite.config.ts path/resolve aliases

* fix: add /dashboard copy subcommand to copy URL to clipboard

Users could not copy the dashboard URL because /copy mode only captures
conversation cards, not the WelcomeBanner which displays the URL.
This caused repeated failed attempts (infinite loop).

Add /dashboard copy as a quick way to yank the live dashboard URL to
the clipboard via OSC 52.

Fixes #1450

* fix(ci): restructure settings.ts to fix biome parse errors

Move orphaned code (GET response body, declarations, helper function)
back into proper positions within the module. The merge left code
scattered at module level causing 41 biome lint errors.

- Move handleSettings function and its complete GET/POST handlers
  into correct position after declarations
- Move VALID_WEB_SEARCH_ENGINES, VALID_EDIT_MODES, void saveEditMode,
  and debugLogPresetWriteFromDashboard before the main function
- Restore complete GET response with session, model, proNext, budgetUsd,
  skillPaths, appliesAt fields

* fix(i18n): add missing translation keys for dashboard components

Add 200+ missing i18n keys to en.ts and zh-CN.ts for new React
dashboard components (cards, composer, contextPanel, sidebar,
statusbar, thread, etc.). Also fix settings.ts structural issues.

* fix(ci): add postinstall to install dashboard deps automatically

npm ci in CI only installs root dependencies. Add postinstall script
that runs npm ci --prefix dashboard to ensure dashboard deps
(prism-react-renderer, lucide-react, etc.) are available for
typecheck and build steps.

* fix(tui): surface failure signals in collapsed run_command cards (#1496)

When a command exits non-zero, the collapsed card now:
- Shows error-relevant lines (error/fail/exception/assertion patterns)
  mixed with tail lines instead of only the last N lines
- Displays exit code in the truncated hint: 'N lines hidden · exit 1'
- Uses 'Ctrl+R to expand' instead of confusing 'use /tool to read full'

Smart truncation for failed commands:
- Scan output for error-pattern lines (error, fail, fatal, exception, etc.)
- Include those lines + context + tail in visible output
- Add separators for hidden gaps between error regions

* Revert "fix(tui): surface failure signals in collapsed run_command cards (#1496)"

This reverts commit 3d71f613a2.

---------

Co-authored-by: Reasonix Dev <[email protected]>
Co-authored-by: CI Fix <[email protected]>
2026-05-22 19:36:08 -07:00
YHHandreasonix fe141e069d fix(presets): drop stale "5/31 discount" framing in pro cost copy (#1583)
The 75%-off promo became the permanent rate on 2026-05-31, so the
parenthetical caveat is now misleading — readers think pro is on a
limited-time sale that will expire. Pricing math is unchanged
(stats.ts already uses the 1/4-of-original rate).

Closes #1559

Co-authored-by: reasonix <[email protected]>
2026-05-22 19:27:48 -07:00
YHHandreasonix cf148a1285 chore(dsnix): bump to 0.49.0 + sync lockfile (#1570)
Co-authored-by: reasonix <[email protected]>
2026-05-22 10:23:35 -07:00
YHHandreasonix 6ea352fdd8 chore(changelog): document #1563 + #1565 under 0.49.0 (#1569)
read-before-edit gate (#1563) and cache-aligned fold summary (#1565)
landed after the release commit was written. Document them in the
0.49.0 entry before tagging so the published CHANGELOG matches what
ships.

Co-authored-by: reasonix <[email protected]>
2026-05-22 10:11:59 -07:00
YHHandreasonix 544714b2ba fix(context): align fold summary prefix with main agent for cache reuse (#1565)
* chore(release): 0.49.0 — static-history TUI, queued steers, Bing default, lifecycle plans

Headline themes:
- TUI: Static-history renderer is the only path; virtual-viewport layers removed (#1529 stages 1-4)
- Chat: queued mid-turn steer handling so input mid-render doesn't drop or fight the live frame (#1501)
- Web search: default switches to Bing; dashboard engine switcher; Mojeek dropped (#1558)
- Plans: lifecycle evidence summaries surface why a plan is ready to accept (#1500)
- Desktop: native OS notifications for approvals + completion (#1519)
- i18n: CLI command output (/mcp /sessions /prune /theme) + approval-prompt labels translated (#1524, #1560)
- Security: SSRF block in web_fetch (#1544), edit-snapshot path containment (#1454), shell redirect sandbox (#1457), Task integrity guardrail (#1516)
- Tools: per-turn dispatch-rate limit (#1356); run_command discourages shell-based edits (#1514)
- Client: DeepSeek 429 → concurrency-limit hint (#1526); timeoutMs honored with AbortSignal (#1535); --no-proxy opt-out for direct route (#1507)
- Files: read/edit/restore preserves source encoding (GB18030 / UTF-8 BOM) (#1518)
- Context: pinned constraints survive folds + full tail capture (#1515, #1552)
- Refactor: lifecycle risk policy extracted into its own module (#1557)

See CHANGELOG for the full list.

* fix(context): align fold summary prefix with main agent for cache reuse

The summarizer call was sending a bespoke "You compress conversation
history" system prompt and no tools, guaranteeing a 0% cache hit
against the main agent's just-cached prefix. Reshape the request so
system + tools + head bytes mirror the live agent's last call — the
only novel bytes are the trailing summarize instruction.

Skill-pin handling now collects bodies read-only instead of stubbing
mid-head, so the cache prefix stays unbroken. The summarize
instruction names pinned skills so the model knows not to paraphrase
their bodies (which we append verbatim regardless).

Measured on a real session at 48.7K prompt tokens:
  OLD shape: 0.0% cache hit  → $0.145 per fold
  NEW shape: 99.6% cache hit → $0.015 per fold
  saving: 89.6% per fold

* tools: add fold-cache shape + live benchmarks

bench-fold-cache-shape.mjs replays real session jsonls, simulates
OLD vs NEW summary-call shapes at the fold point, and reports
byte-level shared-prefix with the main agent's preceding request.
Pure local — no API required.

bench-fold-cache-live.mjs sends one priming + two summary calls to
DeepSeek and reports prompt_cache_hit_tokens / cost for each shape.
Used to confirm the shape change actually translates to API-side
cache hits.

---------

Co-authored-by: reasonix <[email protected]>
2026-05-22 09:20:25 -07:00
YHHandreasonix 7ae935335e feat(edit): enforce read-before-edit at the dispatch gate (#1563)
Soft prompt hint ("read_file first so SEARCH matches byte-for-byte")
was easy for the model to skip — the failure mode is a tool round
spent on "search text not found", a guess at the bytes, and a retry.
Each round is a cache-miss tail and an obviously-not-grounded edit
that erodes trust.

New ReadTracker lives on CacheFirstLoop and threads through
ToolCallContext. read_file marks the absolute path on any successful
load (full, range, head, tail, outline); write_file marks too — the
model knows what it just wrote. edit_file / multi_edit consult the
tracker before applying and refuse unread targets with a message
that names the path and tells the model to call read_file first.
multi_edit refuses the whole batch if any target is unread, so a
partial-knowledge cross-file refactor can't half-apply.

ContextManager fires a new onLogRewrite callback from fold and
mechanicalTruncate; the loop wires it to ReadTracker.reset() because
once the byte-level history is folded away the model's "I saw it"
claim no longer holds. The tracker is in-memory only, so session
resume also starts empty — the model must re-read before editing
after a restart.

tools.ts's repeat-rejection detector recognizes the "read_file first"
gate so a 2nd identical unread edit gets the sharper "do not retry
identical args — call read_file on the target path first" hint
instead of the same refusal echoed back.

Path normalization lower-cases on win32 so case variants of the same
file resolve to one tracker entry.

11 new tests in tests/read-before-edit-gate.test.ts cover: refusal,
post-read success, write_file-counts-as-read, partial-read accepted,
multi_edit all-or-nothing, repeat-rejection sharpening, reset
semantics, and backwards compat when no tracker is injected.

Co-authored-by: reasonix <[email protected]>
2026-05-22 08:36:09 -07:00
YHHandreasonix 77a7cd9c61 fix(approval-prompts): translate Shell/Path confirm title and action labels (#1560) (#1561)
`toApprovalPrompt` in core-utils mints English labels so the ACP surface
(no i18n layer) can render immediately — but the CLI surface was rendering
those English strings verbatim, leaving "Run command" / "Run once" /
"Always allow — …" / "Deny" on screen even when the locale was zh-CN.

ShellConfirm and PathConfirm now override `prompt.title` and each
`action.label` with locally-translated strings keyed off `action.id` and
`prompt.data` (so we can still tell foreground vs background and read vs
write apart, even after the unified `prompt.kind` collapses each pair).

New i18n keys in both EN.ts and zh-CN.ts:

- `shellConfirm.promptTitleRunCommand` / `promptTitleRunBackground`
- `shellConfirm.actionRunOnce` / `actionAlwaysAllow` (with `{prefix}`) / `actionDeny`
- `pathConfirm.promptTitleRead` / `promptTitleWrite`
- `pathConfirm.actionAllowRead` / `actionAllowWrite` / `actionAlwaysAllow` / `actionDeny`

Test plan:
- `tests/shell-confirm-render.test.tsx` gains a `setLanguageRuntime("zh-CN")`
  case that asserts 运行命令 / 运行一次 / 始终允许 / 拒绝 render and the
  English labels do NOT survive.
- `npm run verify` passes (3554 tests).

Closes #1560

Co-authored-by: reasonix <[email protected]>
2026-05-22 08:26:21 -07:00
TaoMu 615cc81fce refactor(lifecycle): extract risk policy (#1557) 2026-05-22 08:07:14 -07:00
YHHandreasonix 65c0d641ef feat(web-search): default to Bing, drop Mojeek, dashboard engine switcher (#1558)
* feat(web-search): default to Bing (cn.bing.com), drop Mojeek, dashboard switcher

Mojeek's IP-geolocation reputation system 403s most CN-residential
clients on the very first request, leaving the default `web_search`
tool unusable for the bulk of this project's users. cn.bing.com serves
clean HTML from CN without a proxy, returns real URLs (not the
`/ck/a?u=a1<base64>` click-tracking wrappers the international `www.bing.com`
uses), and has no per-IP daily quota. Live probes across three queries
× two endpoints returned 200 with zero anti-bot markers.

- New `searchBing` + `parseBingResults` scrapes `<li class="b_algo">`
  blocks (h2 a[href] + div.b_caption p) from cn.bing.com.
- `webSearch` dispatcher's fallback is now Bing; `webSearchEngine()`
  loader returns "bing" for unset / unknown / legacy "mojeek" values.
- Legacy migration is read-only — we don't rewrite the user's
  config.json. `/search-engine mojeek` is no longer in the slash
  validation set, so users who explicitly retry the dead name see an
  immediate "invalid engine" reject instead of a silent revert loop
  on the next launch.
- Dashboard settings panel gets a Search Engine `<select>` with the
  six valid backends; POST /api/settings validates the new
  `webSearchEngine` field, persists to config, and includes it in the
  GET response + `appliesAt` hints.
- searchMojeek/parseMojeekResults/MOJEEK_ENDPOINT removed; i18n
  webErrors.mojeek* renamed to bing*; public-API surface swaps
  parseMojeekResults for parseBingResults.

Tests:
- parseBingResults: real cn.bing.com HTML fixture, empty input, h2-less
  block skip
- webSearch dispatcher hits cn.bing.com with browser UA
- webSearchEngine config loader: enum round-trip, default = bing, legacy
  "mojeek" value reads back as bing

* fix(web-search): switch parseBingResults to DOM walk to silence ReDoS scanner

CodeQL flagged three polynomial-backtracking patterns in the regex-based
parser. node-html-parser is already in the file (used by
parseSearxngHtmlResults); using its selector API eliminates the
backtracking class entirely without changing parse semantics.

---------

Co-authored-by: reasonix <[email protected]>
2026-05-22 07:57:50 -07:00
YHHandreasonix 4e136aad4e fix(config): atomic write + restore preset-write diagnostic trace (#1555)
Users still report `preset` flipping back to its prior value after a
relaunch, even with the BOM-cascade root cause (#1431) fixed. Two
follow-on changes to close the gap:

1. `writeConfig` now writes to a sibling `${path}.${pid}.tmp` and
   `renameSync` into place. The previous `writeFileSync` is not atomic
   on Windows — a concurrent reader during the write window can see a
   truncated file, `readConfig` falls through to `{}`, and the next
   read-modify-write saves an empty baseline that loses every other
   field. The temp + rename pattern guarantees readers see either the
   old file or the new one, never an in-flight blob.

2. Restore the `REASONIX_DEBUG_PRESET` env-gated trace retired in
   #1431. Logs every `savePreset()` call, every `writeConfig()` call,
   and the dashboard PATCH bypass — each with a short stack — so the
   `tools/debug-preset-launcher.ps1` script can pinpoint who flipped
   the preset when it does. Zero cost when the env var is unset.

Co-authored-by: reasonix <[email protected]>
2026-05-22 07:16:53 -07:00
YHHandreasonix 4de6321b10 fix(client): wire timeoutMs to fetch when caller passes a signal (#1535) (#1553)
`opts.signal ?? ctrl.signal` orphaned the timer's controller whenever the
loop forwarded its `_turnAbort.signal` — i.e. every real call. A genuinely
stalled SSE body (TCP open, no `[DONE]`, no close) then sat on
`reader.read()` forever and the TUI hung in "…waiting for response…"
until the user restarted it, even though the server-side request had
already completed.

Combine both signals with `AbortSignal.any` and have the timer abort with
a reason so the loop's error path surfaces "timed out after Xms" instead
of a silent stall.

Closes #1535

Co-authored-by: reasonix <[email protected]>
2026-05-22 06:54:42 -07:00
wby 152477205f fix(tui): restrict @mention file search to current directory prefix (#1548)
For example: just in this repo
- before:
  1. input @benchmarks/compression-eval/.git
  2. press tab
  3. reasonix would show @.gitignore
  (if just input @benchmarks/compression-eval/ and press tab, then would get benchmarks/compression-eval/.gitignore correctly)
- after: same step1 and step2, in step3 reasonix would show @benchmarks/compression-eval/.gitignore
2026-05-22 06:40:27 -07:00
paradoxSCH 6ac18cfbce fix(code-system): add Task integrity guardrail preventing objective simplification (#1516)
Pure prompt-engineering tweak — addresses #1495. In long sessions the model has been rationalizing scope cuts to itself ("save tokens", "be efficient") and silently narrowing the user's task instead of asking. Adds a "Task integrity — non-negotiable" paragraph to the code-mode system prompt:

> The user's original objective and ALL constraints (especially "do NOT do X", "avoid Y", "never Z") remain in force for the entire session. You may NOT unilaterally simplify, narrow, or change the objective to save tokens, time, or steps. If you believe the objective needs adjustment, ask the user — do NOT decide on your own.

Inserted before `__ESCALATION_CONTRACT__`, after the format-rules section. About 50 tokens, in the static prefix so it caches with the rest. Additive — the existing cost-aware escalation contract is unchanged.

Refs #1495.
2026-05-22 06:31:53 -07:00
YHH fc85376c3f chore(context): capture all pinned-constraint blocks in fold tail (#1552)
Small follow-up to #1515.

`extractPinnedConstraints` used `.match()` without the `g` flag, which only returns the first capture. The system prompt can carry multiple blocks under the same prefix:

- `# User memory — global` and `# User memory — this project` both exist when a user has both (`src/memory/user.ts` emits them as separate sections).
- Multiple `# Project memory (filename)` sections can show up when a project carries per-subdir memory.

Single-match meant the second one was silently dropped from the fold-tail constraint reinforcement.

Combined the three prefixes into one regex and switched to `matchAll` so every pinned block makes it into the fold summary.
2026-05-22 06:29:49 -07:00
paradoxSCH 736deb1321 fix(context): preserve memory constraints across context folds (#1515)
Two fixes around context-fold memory preservation, plus a behavior-stability harness to regression-test them.

**`context-manager.ts`** — fold now reinforces pinned constraints after the summary:

- New `extractPinnedConstraints()` pulls the `# HIGH PRIORITY constraints`, `# User memory`, and `# Project memory` blocks out of the live system prompt and appends them verbatim under a `[PINNED CONSTRAINTS — preserved verbatim]` tail on the synthetic fold summary message. The system prompt always survives the fold (only history is compressed), but in long sessions the model's attention drifts away from instructions at the top; restating them near the current context window mitigates the "lost in the middle" effect.
- Summarizer system prompt now explicitly tells the model to preserve "do not" / "never" / "avoid" instructions when compressing — independent improvement, useful regardless of whether the new constraint tail fires.

**`loop.ts`** — wires `getSystemPrompt: () => this.prefix.system` into `ContextManagerDeps` so the fold can read the current system prompt.

**`benchmarks/behavior-stability/`** — small evals scaffold (harness / runner / report / types + one scenario). The `constraint-persistence` scenario stuffs the log with 40 synthetic turns, triggers a fold with a tiny `keepRecentTokens` budget, and asserts all four pinned constraints (2× HIGH PRIORITY, 1× User memory, 1× Project memory) survive in the folded summary. Local: `npx tsx benchmarks/behavior-stability/runner.ts --local` — 1/1 passing.

Refs #1462.
2026-05-22 06:22:09 -07:00
paradoxSCH fa5f3a01c6 fix(tools): discourage shell-based file edits in run_command description (#1514)
Pure prompt-engineering tweak. Issue #1372 reports the model reaching for `echo`/`cp`/`sed` through `run_command` to edit files, which trips the confirmation gate and ignores the dedicated `write_file` / `edit_file` / `multi_edit` / `copy_file` / `move_file` / `delete_file` tools that already have validation + rollback.

Prepends a negative-constraint paragraph to the `run_command` tool description telling the model not to use shell utilities for file operations and pointing at the right alternatives. About 50 tokens, included in the static tool spec so it caches with the rest of the prefix.

No behavior or schema change — just text the model sees every turn `run_command` is in scope.
2026-05-22 06:14:58 -07:00
TaoMu b5a2175c6e test(lifecycle): rename lifecycle harness fixtures (#1532)
Tiny follow-up to #1499. The harness helper used to register only mutation tools (`delete_file`, `move_file`, etc), but #1499 extended it to register `read_file` too so the cancel/stop-recovery tests could verify read-only operations still work. The old name `registerMutationTools` doesn't fit anymore — renaming to `registerLifecycleToolFixtures`.

Test-only, behavior-neutral.

Refs #1285. Follow-up to #1499.
2026-05-22 05:59:42 -07:00
Shaun Xiao c7368be722 feat(chat): queued mid-turn steer handling (#1501)
Lets users type into the composer while a turn is busy and have those messages queued as mid-turn steers — they're appended as user-role guidance at the next loop iteration boundary, never interrupting the in-flight request.

**Loop side (`src/loop.ts`)**

- `_steer: string | null` → `_steerQueue: string[]`. `steer(text)` pushes; `steer(null)` clears.
- At the iteration boundary, shift one off the queue, wrap with `MID_TURN_STEER_WRAPPER` ("Do not treat this as a new task; use it only as additional guidance for the current task after completing the current step.") and `appendAndPersist` it as a `user` message before the next `buildMessages()`.
- `steerConsumed` now means "queue empty after consume" — the UI gate against double-submit.
- All abort / budget / 5xx / context-guard / final-done paths clear the queue so steers can't survive past the turn that owned them.
- When a model response has no tool calls but a steer is queued, the loop now `continue`s instead of returning `done` — so the queued steer drives one more iteration.

**TUI side (`App.tsx`, `PromptInput.tsx`, `ComposerArea.tsx`)**

- New `isBusyPromptCommand(text)` rejects slash / `!`-bang / `#`-memory while busy; ordinary text is accepted as steer.
- `submitPrompt` (dashboard ctx) and the busy keystroke branch both gate on it.
- `PromptInput` separates `inputFrozen` (`disabled && !steerBusy`) from `inputActive` (`!disabled || steerBusy`); placeholder, accent color, and cursor track that. New hint row: `⏎ send — injected mid-turn · esc to stop`.

**Dashboard side (`chat.ts`, `changes.ts`)**

- Both ChatInputs drop `disabled={busy}` on textarea + submit button; placeholder switches to `chat.placeholderSteerBusy`; popover dismisses when busy.
- `loop-to-dashboard` maps `steer` events to `user` messages so the consumed steer shows up in the dashboard transcript.

**i18n** — EN + zh-CN: `placeholderSteerBusy`, `steerHint`, `steerInjected`, `steerCommandRejected`, `steerPlaceholder`, `steerHint`.

**Tests** — 3 new `tests/loop.test.ts` cases:
- steer is persisted wrapped (not raw)
- multiple steers queue + FIFO consume
- `steerConsumed` flips back to `false` on a fresh steer
2026-05-22 05:47:04 -07:00
TaoMu 6ca3c94d21 test(lifecycle): cover stop and cancel recovery (#1499)
Adds e2e coverage for two strict-lifecycle recovery paths that weren't pinned down:

1. **User cancels a proposed plan** — after `submit_plan` returns `plan cancelled: ...`, snapshot resets (`planSteps=[]`, `completedStepIds=[]`, `mutatedSinceLastStep=false`); a fresh user prompt flips state back to `armed`; read-only tools work; a follow-up mutation is still rejected with `nextAction: "submit_plan"`.
2. **Checkpoint stop** — same assertions on the post-stop fresh prompt.

To make these tests possible the harness also picks up:
- `QueueGate` now handles the `cancel` verdict on `plan_proposed` (calls `lifecycle.cancel()`).
- Registers a `read_file` tool with `readOnly: true` so the test can prove the read path still works after recovery.

Tests-only — no runtime, prompt, or tool-schema changes.

Refs #1285.
2026-05-22 05:40:35 -07:00
Bernardxu123 900c68d638 fix(tui): remove misleading ^O expand from paste sentinel label; update shortcut panel descriptions (#1517)
Drops the misleading `^O expand` action hint from the paste-sentinel chip and tightens the Ctrl+O / Ctrl+P shortcut-panel labels.

`Ctrl+O` only toggles the streaming-reply expand view; it does nothing during input, and certainly nothing for pastes. Showing `^O expand` next to a paste chip is a false promise — issue #1493's reporter pressed it and (correctly) got no response. The chip now reads `📋 pasted ... · ⌫ remove`, which is the actual interaction it offers.

While in the strings file, the shortcut descriptions are sharpened:
- `descCtrlO`: "Expand stream" → "Expand reply (streaming only)" (EN) / "展开流式输出" → "展开回复(仅流式输出期间)" (zh-CN) — clarifies the streaming-only scope.
- `descCtrlP`: "Toggle shortcut panel" → "Show/hide shortcuts" / "打开/关闭快捷键面板" → "显示/隐藏快捷键" — shorter, same meaning.

Issue #1493 also reports a separate Shift+Enter bug; that's out of scope for this PR.

Refs #1493.
2026-05-22 05:36:33 -07:00
wade1999 7eecebe3ea feat(desktop): add approval and completion notifications (#1519)
Adds OS-level notifications to the Tauri desktop app so a user away from the window finds out when:

- a new approval request appears (shell command / path access / choice / plan / checkpoint / revision)
- a long-running turn finishes (only after at least 15 s of busy → idle, to skip quick replies)

Design:

- Pure `deriveDesktopNotifications(...)` derives the list from previous-vs-current snapshots; no Tauri calls inside, so the unit tests run without a window.
- `dispatchDesktopNotifications(...)` takes injected deps (`isFocused` / `isPermissionGranted` / `requestPermission` / `sendNotification`) so the App.tsx wiring is the only place that talks to the Tauri plugin. Focus check is repeated at dispatch time as a second guard.
- Notification permission is requested at most once per session; a denial sticks.
- All copy goes through `t()` against the active desktop UI language; both EN and zh-CN added.

Wiring lives in `TabRuntime` via a `useEffect` over the pending-state slices + busy flag.

`tauri-plugin-notification` is added on both the JS and Rust sides (`Cargo.toml` + `capabilities/default.json`). A vitest alias maps the plugin to a mock so the desktop test suite stays hermetic.
2026-05-22 05:32:19 -07:00
YHH b43dd4bb91 chore(changes): gate @mention popover on MODE === "attached" (#1549)
Follow-up to #1546: gate the new `@mention` popover behind `MODE === "attached"`, matching the existing pattern in `chat.ts`.

Without this guard, standalone dashboard clients call `/files` on every `@` keystroke and get a 503 (`"@-mention picker requires a code-mode session"`) back — the popover never opens but each `@` still costs a round-trip. The `MODE` import added in #1546 becomes load-bearing here.
2026-05-22 05:08:48 -07:00
ForeverYoungPp ca68ba07f9 fix(changes): add @mention file picker popover to ChatPane (#1546)
Brings the `@`-mention file picker to the dashboard's Changes / ChatPane, mirroring what's already in `chat.ts`:

- `PopoverKind` extended with `"mention"`.
- `updatePopover` detects the trailing `@prefix` token and posts to `/files` for matching paths.
- `applyPopover` replaces the `@prefix` token in place (not the whole input) so the user keeps anything they typed before it.
- Popover header / row icon switch between `/` and `@` based on `popoverKind`.

The `chat.projectFiles` i18n key already exists in EN + zh-CN — no new strings.
2026-05-22 04:40:26 -07:00
Tianjiu f0f1ac60a5 fix(web): block SSRF in web_fetch (#1544)
Closes a real SSRF hole in `web_fetch`. Previously the tool accepted any `http(s)` URL and auto-followed redirects, so the model could:

- hit `127.0.0.1` / `::1` directly,
- reach private / link-local / metadata ranges,
- or be redirected from a public host into an internal one mid-chain.

Defense-in-depth in `src/tools/web.ts`:

- Scheme allowlist (`http:` / `https:` only).
- IP-literal check rejecting RFC 1918 + loopback + link-local + CGN (100.64/10) + TEST-NET-1/2/3 + multicast + reserved + benchmarking (198.18/15).
- IPv6 check covering `::`, `::1`, ULA (`fc00::/7`), link-local (`fe80::/10`), multicast (`ff00::/8`), and `::ffff:` IPv4-mapped (recursing into the v4 check).
- For hostnames, `dns.lookup(host, { all: true })` and reject if **any** resolved address is internal — defends against half-public/half-private multi-A records.
- Manual redirect handling with re-validation on every hop + a 5-redirect cap.
- Timeout / response-size limits untouched.

Tests cover loopback literal, hostname resolving to an internal IP, and a public→internal redirect.
2026-05-22 04:35:12 -07:00
Evan-Pycraft 72f2478f35 feat(i18n): localize CLI command output strings (MCP, sessions, prune, theme) (#1524)
Localizes the remaining hardcoded CLI output strings — `reasonix mcp list / search / install` flow, `sessions` listing, `prune-sessions`, and the `/theme` slash handler — so zh-CN users see translated text instead of mixed EN/CN output.

31 new keys across `sessions` / `mcpCli` / `app` namespaces with full EN ↔ zh-CN parity. Mechanical migration — `t()` calls replace each string with the same parameters; no behavior change.

Verified clean rebase on top of the stage-1-through-4 refactor (#1530 / #1534 / #1536 / #1537) plus the path-approval bridge (#1540): typecheck + lint + 3528 tests all pass.
2026-05-22 02:34:42 -07:00
YHH 57a3624d13 fix(web): bridge path-access approval modal to the dashboard (#1538)
When the model asked for file access outside the sandbox, the TUI opened `PathConfirm` but the web dashboard stayed blank — the loop hung waiting for a decision the web user couldn't make. Same shape as #832 (plan-checkpoint). This PR bridges the path-approval gate end-to-end.

- `ActiveModal` gains a `path` variant (path / intent / toolName / sandboxRoot / allowPrefix).
- `DashboardContext.resolvePathConfirm` mirrors `resolveShellConfirm`.
- `App.tsx` broadcasts `modal-up` / `modal-down` for `pendingPath`, surfaces it in `getActiveModal` (mid-modal reconnect repaints correctly), wires `resolvePathConfirm` to `handlePathConfirmRef`.
- `/api/modal/resolve` accepts `kind: "path"` with `run_once` / `always_allow` / `deny`.
- New `PathModal` Preact component renders with sandbox / allow-prefix rows and three resolution buttons. EN + zh-CN strings added.

Audited every loop-blocking gate while in there — after this lands all of run_command / path_access / plan / plan_checkpoint / plan_revision / choice / edit_review have a TUI ↔ web bridge. Slash-command pickers (ModelPicker / ThemePicker / EditPicker / WorkspacePicker) are still TUI-only but don't block the loop, so out of scope here.

Closes #1538.
2026-05-22 02:28:40 -07:00
YHH cd8def12b6 refactor(tui): drop the byte-virtual frame layer (stage 4 of #1529)
Final stage of #1529. The Frame algebra (`vstack`, `hstack`, `slice`, `overlay`, `viewport`, `bottom`, `fitWidth`, etc.) and its ANSI rasterizer existed so a full-screen persistent frame could be composed cell-by-cell. With Static-anchored history and Ink-native rendering, none of that is exercised — `frame-render.tsx` was the only caller of the Frame layer, and it itself had zero callers.

**Deleted:** `src/frame/{frame,ansi,types,index}.ts`, `src/cli/ui/frame-render.tsx`, `tests/frame.test.ts`.

**Migrated:** `src/frame/width.ts` → `src/cli/ui/text-width.ts`. These are text-cell utilities (`stringWidth` passthrough to the `string-width` lib, grapheme-safe `clipToCells` / `wrapToCells` / `graphemes` / `graphemeWidth`) that card renderers and markdown still need — they're not "frame" anything. Implementation is unchanged. 6 src callers and 2 tests updated. New `tests/text-width.test.ts` rescues the width-relevant edge-case coverage that lived in the deleted `frame.test.ts` (CJK, Hiragana / Katakana / Hangul, emoji, ZWJ clusters, combining marks, control chars, mixed scripts) and adds cases for `clipToCells` / `wrapToCells`.

Net: 907 deletions, 9 insertions across 16 files (plus the new 60-line `text-width.ts` and 100-line test file as untracked-then-added).

Closes #1529. Cumulative across stages 1–4: ≈ -2620 lines.
2026-05-22 02:10:48 -07:00
YHH b465b73178 refactor(tui): drop viewport-budget row allocator (stage 3 of #1529)
Stage 3 of #1529. The vertical row allocator existed so a full-screen persistent frame could parcel rows between zones (modal, status, input, stream, safety). With Static-anchored history the persistent frame sizes to content and the zones don't compete; there's nothing left to allocate.

**Deleted:** `src/cli/ui/layout/viewport-budget.tsx` (reducer + allocator + `ViewportBudgetProvider` + `useReserveRows` + `useTotalRows`) and its tests.

**Trimmed:** `App.tsx` drops the `<ViewportBudgetProvider>` wrapper (and the indentation it imposed). `StreamingCard`, `PromptInput`, `ChoiceConfirm`, `PathConfirm`, `ShellConfirm`, `PlanCheckpointConfirm` were all side-effect-only callers — removed. `EditConfirm` and `PlanConfirm` were the only consumers that read the allocator's return value; both swap `useTotalRows()` for `useStdout().stdout?.rows` and inline the max into a direct expression. `tests/plan-confirm.test.tsx` renders without the provider wrapper now.

**Kept:** `src/cli/ui/prompt-viewport.ts` — composer-internal input-cell math (CJK width, paste sentinels, single-row slicing). The stage 3 plan said "drop viewport-budget / prompt-viewport, after confirming the composer no longer depends on them"; the composer still depends on prompt-viewport, so it stays.

Net: 727 deletions, 433 insertions across 12 files (most of the App.tsx insertion count is biome re-indenting the subtree that lost its wrapper).
2026-05-22 01:50:23 -07:00
YHH 8a8d7655e6 refactor(tui): make Static the only history renderer; drop virtual-viewport machinery (stage 2 of #1529)
Stage 2 of #1529. `StaticCardStream` landed behind a flag in Stage 1 and held up under real use; this stage promotes it to the only path and deletes the machinery whose entire job was fighting the terminal for scrollback.

**Deleted:** `CardStream` (virtual viewport + height measurement + monotonic-shrink lock + scroll indicator), `chat-scroll-store` + `chat-scroll-provider`, `copy-mode/` (vim/tmux selection mode + OSC 52 snapshot), `InputAreaWithHistoryHint` (unused dead leaf), 5 obsolete tests, the `/copy` slash command + `openCopyMode` slash result + the qq-channel terminal-only notice + the `copyMode` i18n block.

**Trimmed:** `App.tsx` -114 net (drops `STATIC_HISTORY` flag, `HistoryTypingCapture`, `ChatScrollProvider` wrapper, `useChatScroll*` subscriptions, `pendingCopyMode`, the PgUp/PgDn/End/wheel/arrow keystroke handler, the conditional outer Box height); `ComposerArea` no longer wraps the input area in the "scrolled-up history hint" branch; `PromptInput` drops the absolute IME cursor write (its math required the persistent UI at terminal bottom and the Static frame floats); `mouse-mode` defaults to `off` everywhere with the env-var override kept as an escape hatch.

Net: 1545 deletions, 48 insertions across 26 files.
2026-05-22 01:36:21 -07:00
YHH bb76851f95 feat(tui): static-history path behind REASONIX_STATIC_HISTORY (stage 1 of #1529)
Stage 1 of #1529. Adds a Static-based history renderer behind `REASONIX_STATIC_HISTORY=1` so we can validate it in parallel before later stages delete the virtual-viewport CardStream + chat-scroll-store + copy-mode entirely.

- New `StaticCardStream` partitions cards at the first unsettled entry: settled prefix goes through Ink `<Static>` (terminal owns scrollback), live tail renders dynamically.
- Outer Box drops `height={stdout.rows}` under the flag so the persistent frame doesn't push Static commits straight into off-screen scrollback.
- Mouse mode resolves to a known wheel-passthrough state under the flag, and emits disable sequences for `?1000 / ?1002 / ?1003 / ?1006 / ?1007 / ?1015` on every "off" enable so stale capture from a crashed prior session can't keep eating wheel events.
- `PromptInput`'s absolute IME cursor positioning is skipped under the flag — its `\x1b[row;colH` math assumed the persistent UI sits at the terminal bottom; with the floating Static frame the absolute write desynced Ink's cursor tracking and ghosted previous frames.

Off by default; nothing changes for users who don't opt in.
2026-05-22 01:12:45 -07:00
Bernardxu123 78e7327ead fix(tui): Ctrl+Enter inserts newline and update shortcut panel (#1513)
Ctrl+Enter now inserts a newline instead of submitting, matching the behavior of Shift+Enter and Alt+Enter.

Changes:
- multiline-keys.ts: add key.ctrl to newline condition
- PromptInput.tsx: HintRow shows ^J as alt newline shortcut
- ShortcutsHelpModal.tsx: add Ctrl+Enter and Ctrl+J entries
- i18n: add descCtrlEnter / descCtrlJ translations

Refs #1493
2026-05-21 23:37:26 -07:00
YHHandreasonix c9f8bc1507 fix(client): translate DeepSeek 429 into a concurrency-limit hint (#1526)
DeepSeek's actual rate limit is concurrency-based, not RPM (500 for
v4-pro, 2500 for v4-flash, account-wide across API keys). When the
account exceeds it the server returns HTTP 429, which currently
surfaces as a raw `DeepSeek 429: {...body}` string — fine for a
maintainer to read, useless for a user trying to figure out why.

Add a friendly message that names the actual cap, identifies the
likely cause (another reasonix process on the same key, or a
parallel subagent fan-out that overshot), and points at the
remediation (wait + retry, reduce parallelism, or request expansion).
Same shape as the existing 401/402/422/400 cases.

Also clarify the `rateLimit.rpm` config docstring: it's a client-side
self-throttle for politeness on shared infra, not a DeepSeek-enforced
limit. DeepSeek has never had a published RPM cap.

Closes #1522

Co-authored-by: reasonix <[email protected]>
2026-05-21 23:30:32 -07:00
YHHandreasonix 1024a0cc44 fix(edit): preserve file encoding on read/edit/restore (GB18030, UTF-8 BOM) (#1518)
* fix(edit): preserve file encoding on read/edit/restore (GB18030, UTF-8 BOM)

read_file / edit_file / multi_edit / applyEditBlock all hard-coded
UTF-8 in readFileSync + writeFileSync. On Chinese Windows hosts most
project files are GB18030; lossy UTF-8 decode mangled the bytes so
the model's SEARCH text never byte-matched, edit_file silently
failed, and the model fell back to PowerShell + git-replay (token-
expensive and lossy for any user manual edits in between).

The shell stdout path already handled this via smartDecodeOutput's
UTF-8-fatal → GB18030 fallback. Same pattern, applied to the
filesystem path, plus encode-back via iconv-lite so the file stays
in its original encoding. UTF-8 BOM round-trips too. Snapshot
records prevEncoding so restoreSnapshots writes back correctly.

Closes #1445

* fix(edit): make GB18030 fallback platform-independent

CI ubuntu build flagged the previous platform gate — GB18030 files
are portable, Linux developers can have CN-Windows-origin files in
their projects. The gate was a copy of smartDecodeOutput's
cmd.exe-specific behavior that doesn't apply to file-on-disk
encoding detection.

---------

Co-authored-by: reasonix <[email protected]>
2026-05-21 22:36:06 -07:00
YHHandreasonix 002a97fe91 feat(tui): add mouseWheelRows config knob for per-terminal scroll tuning (#1511)
Mouse wheel sensitivity is terminal-dependent — most emit 2-5 SGR
mouse reports per physical notch (#1419 settled SCROLL_WHEEL_ROWS=1
to keep that case bearable), but some emit one report per notch and
the resulting 1-row-per-notch scroll feels broken (#1494).

A constant-bump fix would regress the over-sensitive class. Add
`mouseWheelRows?: number` (clamped to [1,10]) so affected users can
tune without compromising the default that #1419 validated.

Closes #1494

Co-authored-by: reasonix <[email protected]>
2026-05-21 20:59:14 -07:00
YHHandreasonix 45f9a65fd4 fix(proxy): allow opting out of the DeepSeek direct-route default (#1507)
`DEFAULT_NO_PROXY` hardcoded `api.deepseek.com` / `*.deepseek.com` so
the dispatcher always routed them through `undici.Agent()` direct,
bypassing HTTPS_PROXY. Corporate firewalls that block direct egress
therefore broke `reasonix doctor`'s api-reach check with a
ConnectTimeoutError, with no way for the user to override.

Split the defaults: loopback stays mandatory, DeepSeek becomes opt-out
via `proxy.bypassDeepSeekDirect: false` (config) or
`REASONIX_PROXY_DEEPSEEK_DIRECT=0` (env). Default behaviour preserves
the clash/v2ray US-exit-IP 403 fix that put the bypass there.

Closes #1497

Co-authored-by: reasonix <[email protected]>
2026-05-21 20:14:46 -07:00
TaoMu 3cc72075f2 feat(plans): surface lifecycle evidence summaries (#1500) 2026-05-21 19:38:30 -07:00
TaoMu d807c1f9b8 test(lifecycle): cover failed verification revise flow (#1498) 2026-05-21 19:27:10 -07:00
YoungDan-hero acb1dca762 fix: constrain shell redirects to sandbox boundaries (#1457)
Validate redirect targets before execution to block sandbox escapes, symlink traversal, and sensitive redirect paths. Preserve PauseGate test stub typing and support case-insensitive Windows environment variables in executable resolution.
2026-05-21 19:11:08 -07:00
YoungDan-hero e5bb6b4a24 fix: prevent edit snapshots from reading outside workspace (#1454)
* fix: resolve root-relative edit block paths

* fix: prevent edit snapshots from reading outside workspace
2026-05-21 18:59:52 -07:00
Irene Luoandllr-selfgit 4e8a49408e feat(tools): limit tool dispatch rate (#1356)
Co-authored-by: llr-selfgit <[email protected]>
2026-05-21 18:45:35 -07:00
reasonix 245e13b245 fix(desktop): tsc errors blocking desktop bundle build
- App.tsx $session_empty branch was missing `id` on the error card so
  TS rejected the literal against ChatMessage's required-id variant.
- App.test.ts stub state still used the pre-#1487 UsageStats shape
  (`tokens.{input,output,...}`); update to the current flat shape so
  the test compiles.

Caught by the desktop-v* release workflow — root verify doesn't run
desktop tsc, so these regressed silently after #1487.
2026-05-21 06:36:05 -07:00
reasonix be414940cb fix(desktop): drop workspace:* protocol for core-utils — desktop isn't a workspace member
`npm ci` inside desktop/ failed with EUNSUPPORTEDPROTOCOL because desktop/
is not listed under root workspaces, so the `workspace:*` spec added in
#1443 had no resolver. Replace with `file:../packages/core-utils`,
which is what the desktop install actually wants (source-only package,
type-only import in desktop sources).
2026-05-21 06:25:41 -07:00
reasonix b6492b2677 chore(dsnix): bump to 0.48.1 + sync lockfile 2026-05-21 06:20:55 -07:00
641 changed files with 71256 additions and 20009 deletions

No files matched your search

+1
View File
@@ -1,4 +1,5 @@
DEEPSEEK_API_KEY=sk-your-key-here
DEEPSEEK_BASE_URL=https://api.deepseek.com
# DEEPSEEK_API_BASE_URL is accepted as an alias of DEEPSEEK_BASE_URL.
REASONIX_LOG_LEVEL=INFO
REASONIX_TRANSCRIPT_DIR=./transcripts
+3 -3
View File
@@ -33,6 +33,9 @@ jobs:
- name: Typecheck
run: npm run typecheck
- name: Build (tsup + dashboard)
run: npm run build
- name: Test (vitest + coverage)
run: npm run test:coverage
@@ -40,9 +43,6 @@ jobs:
if: always()
run: node scripts/coverage-summary.mjs
- name: Build (tsup)
run: npm run build
# Smoke-test the bench harnesses themselves. --dry skips all LLM
# calls, so this catches wiring regressions (task factories, CLI
# parsing, file IO, checker determinism) without needing a
+11
View File
@@ -104,6 +104,7 @@ jobs:
echo "node archs: $archs"
echo "$archs" | grep -q "arm64"
echo "$archs" | grep -q "x86_64"
codesign -d --entitlements :- src-tauri/binaries/node 2>&1 | grep -q "com.apple.security.inherit"
- name: Build & verify desktop frontend
working-directory: desktop
@@ -172,3 +173,13 @@ jobs:
releaseDraft: true
prerelease: false
args: --target ${{ matrix.target.tauri }}
- name: Verify app Node inherits TCC grants (macOS)
if: startsWith(matrix.target.os, 'macos-')
working-directory: desktop
shell: bash
run: |
node_bin=$(find src-tauri/target -path '*/release/bundle/macos/*.app/Contents/Resources/node' -type f | head -n 1)
test -n "$node_bin"
codesign -vvv --strict "$node_bin"
codesign -d --entitlements :- "$node_bin" 2>&1 | grep -q "com.apple.security.inherit"
+3
View File
@@ -31,6 +31,7 @@ sessions/
.reasonix/semantic/
.reasonix/sessions/
.reasonix/semantic-skip
.reasonix/truncated-results/
# Scratch entry regenerated each time scripts/bundle-codemirror.mjs runs.
scripts/.cm-entry.mjs
# Personal bun lockfile — project uses npm officially.
@@ -48,3 +49,5 @@ desktop/src-tauri/binaries/
# Design mock-up reference (local, not part of repo)
.design-ref/
*.cpuprofile
.probe-snapshots/
+476
View File
@@ -3,6 +3,482 @@
All notable changes to Reasonix. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.53.1] — 2026-05-27
**Install fix — `npx reasonix` no longer crashes on `EUNSUPPORTEDPROTOCOL`.**
The 0.52.0 refactor that inlined Ink as a workspace package (#1947)
left `"ink": "workspace:*"` in runtime `dependencies`. tsup already
bundles ink into `dist/`, so the runtime never resolves it — but npm
on consumer machines parses the declaration and rejects the
unresolvable `workspace:` protocol. Removed from runtime deps; the
bundled ink in `dist/` is the implementation. 0.53.0 is deprecated
on npm.
## [0.53.0] — 2026-05-27
**Force-summary respects the active model.** Context-guard and stuck-state
recovery were calling `client.chat({ model: "deepseek-v4-flash" })`
regardless of the user's configured model (#1979). Third-party
DeepSeek-compatible endpoints (mimo, self-hosted, Azure forks) that
don't expose flash returned 400 on every recovery — the session looked
like it lost context (the messages were still there) and the user had
no way back without `/clear`. Force-summary now uses `this.model` with
`thinking: "disabled"` to keep reasoning tokens off the bill even when
the active model is pro.
**Web search — Brave backend.** `web_search` now supports the Brave
Search API as an alternative backend (#1916), alongside the existing
Bing / Tavily / Ollama-cloud paths. Configurable per-instance.
**Desktop — workspace switcher.** Sidebar exposes a workspace
switcher (#1908) so multiple project roots can be juggled without
restarting the app. Bundled-app version surfacing for desktop is
unified through the same sync pipeline as the CLI.
**Desktop — fixes.**
- Per-tab hook firing for Pre/PostToolUse, UserPromptSubmit, Stop
(#1984) — hooks were leaking across tabs in multi-session windows
- Clear the pending assistant on error so the spinner stops (#1985,
fixes #1660)
- `/skill` and `/skills` slash commands wired through (#1978, fixes
#1969)
- Context token meter refreshes after each turn (#1964)
- Preserve session context across abort (#1938)
- `\[ \]` and `\( \)` math delimiters now render in markdown (#1923)
- Windows file opening normalizes path separators (#1914)
- Settings allow clearing base URL and editor fields (#1905)
**Dashboard / web.**
- Dashboard session refresh no longer skips updates (#1917)
- "New Chat" label stays on one line (#1924)
- Server-snapshot helpers fully typed (#1961)
**Config / auth.** `saveApiKey` now overrides a stale `DEEPSEEK_API_KEY`
env var so the UI save takes effect immediately (#1982) — previously
the env shadow won and the user had to relaunch.
**QQ adapter.** `/qq` defaults to markdown replies (#1941); the
previous plain-text default lost code blocks and lists.
**Networking / fetch.** `web_fetch` falls back to DNS-over-HTTPS when
the system resolver returns RFC1918 / link-local addresses (#1944) —
some captive portals and split-horizon DNS configs hand back fake
internal IPs and the fetch then connects to the wrong host. CLI
`doctor` accepts a custom `/models` endpoint instead of hard-coding
DeepSeek's (#1972).
**Truncation / encoding.**
- Slice boundaries align to UTF-16 codepoints so multi-code-unit
characters can't be split mid-surrogate (#1976, includes #1970)
- Truncated-result-saver falls back to `~/.reasonix` when `rootDir`
resolves to the filesystem root (#1974)
- Lone surrogates are sanitized in chat payloads before serialization
(#1939)
**TUI — CardStream measure loop.** Break the
measure→render→measure feedback loop that could pin CPU on resize
(#1958).
**Errors / ACP.** Structured `errorDetail` propagates through loop,
transcript, and ACP wire format (#1965 + follow-up) so external
clients see the same fault classification the CLI does.
**Internals.** Inline the ink runtime as a workspace package (#1947) —
last step of the `@esengine/ink` in-tree work started in 0.52.0.
**Misc.**
- Generated-script shell `cwd` guidance fixed (#1937)
- AtomGit star badge in README (#1954)
## [0.52.0] — 2026-05-26
**Ink renderer in-tree as `@esengine/ink`.** The vendored Ink fork now
lives as a workspace package (#1847), unblocking TUI-specific
renderer tweaks (focus, IME, Static append) without forking upstream.
TUI polish lands on top: guard ASCII IME enter commits so JP/CN IME
atomic commits don't double-submit (#1874), preserve undo state across
session context switches (#1810), incremental repaint coverage
(#1873).
**Desktop — clipboard image paste.** Paste screenshots / copied images
directly into the composer (#1889); paste path hardened against
oversized + non-image clipboard payloads (#1897). Sessions exported by
other local AI apps can be imported into Reasonix (#1894).
**Desktop — JumpBar polish + drag perf.** JumpBar now highlights the
active message bar and follows the latest one as the thread grows
(#1813); dot styling pulled into a shared helper (#1892). Sidebar drag
writes CSS vars directly to the DOM with `content-visibility` on
messages (#1812) and unit-suffixes the vars to dodge a Chromium
recompute storm (#1875).
**Desktop — smaller fixes.**
- Search-engine API key UI + slash command interception (#1867)
- Mention `@` popup stays stable while filtering (#1850); split
kind/length effects in the popup (#1859)
- Update banner floats above the thread instead of pushing layout
(#1865)
- `memoryDetail` / `onReadMemory` wired through test fixtures so the
desktop memory browser is exercisable in unit tests
**Config — base URL + proxy.** `DEEPSEEK_API_BASE_URL` accepted as an
env alias to the existing base-url override (#1876, #1887), and
`proxy.url` is now a first-class field in `config.json` (#1881). MCP
`initialize` no longer leaks LSP-only fields that some servers reject
(#1861).
**Providers.** Ollama usage parsing tolerates the field-name variants
recent Ollama versions emit (#1886).
**i18n.**
- Russian (`ru`) language pack added (#1879)
- German corrections — capitalization, terminology, coverage (#1878)
- `/qq` command hints + argsHint localized; English fallback for
zh-CN (#1857, #1862)
**Dashboard / UI.**
- Sync TUI and Web modal state so confirm gate doesn't desync between
surfaces (#1831, #1866)
- Highlight active plan edit mode (#1863)
- `useEditHistory` no longer re-exports undo-context through itself
(#1854)
## [0.51.0] — 2026-05-25
**First paint — session restore 4.5s → 430ms.** Progressive `<Static>`
mount streams scrollback in chunks instead of mounting the full history
synchronously (#1761). Combined with index-backed `mutateCard` + O(n)
`plan.drop` + cursor elide (#1769) and the bump to `[email protected]` (which
ships the flicker fix we'd been carrying as a patch — patch-package
machinery is gone, #1809), large session restores no longer block the
event loop on startup.
**Perf — tokenizer + markdown + search.** BPE tokenizer caches its
table + bounds per-content counts with a fast-path truncate (#1741),
so long sessions don't re-tokenize the world on every turn. CodeBlock
syntax highlight is memoized (#1743). Literal-pattern search bypasses
the regex worker entirely (#1748). Windows terminal repaint cadence is
throttled (#1750) and a BEL → ST swap on Windows stdout stops `cmd.exe`
from beeping on every render frame (#1795).
**Cross-platform robustness.**
- `EXDEV` fallback for atomic config writes on OneDrive / NTFS reparse
points (#1778) — config saves no longer fail on Windows + cloud-sync
- Apple Terminal mouse-reset crash guarded (#1764); legacy X10 mouse
reports without ESC are dropped (#1723); `ESC`-less CSI recovery is
refused when followed by typed text (#1771)
- CLI startup gates on unsupported Node versions with a clear error
instead of crashing in the middle of bootstrap (#1757)
- Desktop bundled Node inherits parent TCC grants on macOS (#1749) so
file / microphone permission prompts attach to the app, not the helper
- Crash-safe atomic rename for edit-block writes (#1721); completed
plans archive instead of persisting across sessions (#1700)
- `.devenv` and `.direnv` are skipped by glob / search / directory_tree (#1706)
**Memory — CLAUDE.md import for Claude Code migration.** Loading
`CLAUDE.md` and `~/.claude/CLAUDE.md` alongside the existing
`REASONIX.md` (#1694) lets Claude Code users carry their project /
user memory directly into Reasonix without rewriting it.
**i18n — German.** Full German (`de`) locale added (#1773) with a
follow-up correction pass (#1797).
**Desktop polish.**
- JumpBar message navigation dock (#1725, #1729)
- File-change summary card after each assistant turn (#1691)
- Self-heal stale model id; expose plan as 4th editMode (#1699)
- Restore aborted prompt drafts on relaunch (#1693)
- Recalc thread width on resize (#1789); right panel scrollbar
draggable (#1765); contain long MCP spec strings (#1736)
- Sync slash setting commands across surfaces (#1724)
- Surface desktop startup failures instead of silent exit (#1759)
**TUI polish.**
- Plan-mode `[PLAN]` / `[计划]` badge in input bar (#1742)
- Forward-delete for `Delete` key (#1735)
- IME candidate window cursor alignment (#1754)
- Coalesce prompt cursor sync to reduce flicker (#1768)
- Demote stuck `running` plan step on turn end (#1784)
- Hide `max` effort on non-DeepSeek endpoints (#1798)
- Drop stale "press Cmd-C to copy" startup hint (#1692)
**Dashboard / web mode.**
- Bootstrap mcp / skills / memory panels in web mode (#1775)
- Expose new memory browser to web (#1779)
- Replay active modal on SSE connect so confirm gate isn't stuck (#1770)
- Restore scroll and memory visibility (#1766)
- Docs responsive spacing polish (#1785)
**Smaller fixes.**
- Preserve full tool results when truncated (#1615)
- Trim long-session retained payloads to bound memory growth (#1799)
- Drain steer queue on `/new` + `/cwd` so prior intent doesn't leak (#1774)
- Suppress DeepSeek-specific 5xx hints when host isn't DeepSeek (#1716)
- `normalizeSemanticEmbeddingUserConfig` preserves `timeoutMs` (#1788)
- `REASONIX_ACP_SYSTEM_APPEND` env var for system-prompt injection (#1737)
- Configurable cost-display currency with click-to-toggle (#1710)
**Refactors / internals.**
- Extract `LruCache` + `TtlLruCache` + `lazy()` helpers from ad-hoc
duplicates (#1746)
- Split stream aggregator + chunked dispatch out of `step()` (#1739)
- Per-component render trace gated by `REASONIX_TRACE_RENDERS` (#1747);
`readStats` API on render trace + real-numbers large-session probe (#1751)
## [0.50.1] — 2026-05-24
**Install fix — `postinstall` no longer crashes on `npx`.** The
`postinstall` hook added in 0.50.0 (#1584) ran `npm ci` inside
`dashboard/` and `desktop/` to set up the dev workspace, but those
directories aren't shipped in the published tarball. Result: `npx
reasonix@0.50.0 code` failed during install with a `dashboard/package.json
not found` error and the CLI never started. `postinstall` now delegates
to `scripts/postinstall.mjs`, which exits 0 when `dashboard/package.json`
is missing (i.e. anywhere except a git checkout). 0.50.0 is deprecated
on npm.
## [0.50.0] — 2026-05-24
**Desktop dashboard — unified on the CLI-hosted React surface.** The
old Tauri+Preact dashboard inside the desktop bundle is gone (#1418).
Desktop now embeds the same CLI-hosted dashboard the browser surface
already uses, so there's one React app rendering chat across all
three surfaces (CLI, browser, desktop) instead of two divergent
implementations drifting apart. Cuts the duplicate rendering paths
that caused tool cards, code blocks, and compacted history to look
subtly different depending on where you opened the same session.
**Presets — flash/pro are the only knobs now.** The preset abstraction
is removed (#1657, #1630): config now exposes `model` + `effort`
directly instead of indirecting through `preset: auto | flash | pro`.
The `/pro` switch is dropped too — flash and pro remain as direct
model selections. Per-skill flash/pro override lands with a Settings
UI (#1632) so subagents can opt into a heavier model without
reconfiguring the parent.
**Cumulative usage stats — persisted + auto-restored.** Session token
totals and accumulated cost now write to the session meta on each
turn and reload on startup (#1667, #1680 follow-up). Cost telemetry
survives a CLI restart or desktop relaunch instead of resetting to
zero, and the context-size readout shows the current window, not the
all-time cumulative cache count (#1643). `SessionStats` caps at 200
turns with cost carryover so long-lived sessions don't unbound (#1628).
**Plans — `editMode="plan"` enforced at the dispatch gate.** Plan
mode now blocks write tools at the `ToolRegistry` dispatch layer
(#1681), not as a per-tool soft check. Plan steps also advance
correctly when intermediate actions are skipped (#1629), so the
"current step" indicator no longer stalls on a step the model already
completed.
**Context — fold once at turn start.** The pre-flight fold pass is
gone — context folding now happens once at the start of each turn
instead of being threaded through mid-turn checks (#1642, #1646). The
obsolete byte-ceiling check is dropped too. Compacted history renders
as a single collapsible card on all three surfaces (#1649), so the
fold is visible without dominating the scrollback.
**Desktop polish.**
- Draggable sidebar resize + responsive conversation panel width (#1688)
- Responsive sidebar collapse on narrow windows (#1585)
- Copy/edit overlay, message-history navigation, IME guard, card collapse (#1645)
- `Esc` closes the open modal instead of aborting the model turn (#1685)
- QQ turn routing isolated by tab so cross-tab messages don't bleed (#1672)
- Discard explicitly aborted turns instead of replaying them on resume (#1687)
- Render `edit_file` / `multi_edit` results as DiffCard, matching CLI (#1662)
- Code-block syntax highlighting follows light/dark theme (#1655)
- System events surface as a show/hide toggle (#1654, #1650)
- File paths + completion feedback surface in tool results (#1644)
- Block right-click context menu in release builds (#1641)
- Preserve code operators when rendering inline code (#1640)
- Compact composer default preserved across relaunches (#1594)
- Stale events no longer corrupt UI after a session switch (#1582)
- macOS bundled Node inherits parent TCC grants so file/microphone
permission prompts attach to the desktop app, not the helper (#1614)
- New `dashboard.enabled` config to suppress auto-start when the
dashboard isn't wanted (#1612)
- Localize edit approval/discard messages + event errors with zh-CN (#1617)
**Dashboard polish.**
- Persistent active-session URL — shareable + refresh-safe (#1586,
#1589, #1599)
- Code-block syntax highlighting follows light/dark theme (#1664)
- IME confirm-enter no longer submits mid-composition (#1689)
- Code-fence language detection fix mirrored from desktop (#1677, #1661)
- Heavy vendor libs split into separate chunks for faster cold load (#1587)
- Tool cards no longer stuck spinning when the turn ends without an
explicit completion event (#1676)
- Markdown tables get a horizontal scrollbar instead of overflowing
the chat column (#1562)
- Search-engine switcher restored in dashboard + desktop settings (#1618)
- Composer queue-count label was reading the wrong variable name (#1674)
- Long file paths stop stretching the chat bubble width (#1590)
- Don't synthesize `$turn_complete` from per-iter `assistant_final` —
let the real completion event fire (#1673)
**TUI.**
- New `Alt+S` hotkey stashes the current input buffer and recalls it
later, like a one-slot clipboard for the composer
- Static history is isolated from input re-renders, so typing during
a model turn doesn't repaint the whole scrollback (#1635)
- Legacy mouse reports (X10) are dropped so terminals that emit them
by default no longer flood the input stream (#1637, #1648)
- `multi_edit` is gated in review mode to match the single-edit
approval flow (#1647)
- Shell command failure output is surfaced to the user instead of
silently truncated (#1608)
**Diff rendering — CJK column-border alignment.** `SplitDiff` no
longer misaligns the column border when CJK characters appear in
either side of the diff (#1686). The width math now accounts for
double-width graphemes when laying out the gutter.
**Subagents — per-skill model override.** Each named skill
(`/explore`, `/research`, `/review`, `/security-review`) can now
override flash/pro independently (#1632), with a Settings UI to
manage the overrides. Defaults flow from the parent session.
**MCP.**
- Workspace roots are passed to MCP servers on connect (#1625), so
servers that scope by root see the right project
- `codeCommand` honors the full `normalizeMcpConfig` pipeline including
inline `mcpServers` blocks (#1603, follow-up to #1568)
**Config.**
- `(baseUrl, apiKey)` is resolved as a tuple instead of two
independent fields (#1658), so a partial override on one no longer
silently falls through to the env value of the other
- Stale model IDs self-heal on load; v3 IDs are dropped from the
picker fallback list (#1663)
- Theme rename follow-up from #1666 closes out the prompt-input + user
card token migration (#1678, #1666, #1623)
**Memory.** `JobRegistry` self-cleans entries for completed jobs
(#1620), so long sessions don't accumulate dead job records that
never release their references.
**Other.**
- `chore(loop)` drop redundant abort warning, keep only the synthetic
final event (#1659)
- `chore(theme)` finish theme rename follow-up after #1666 (#1678)
- `chore(ui)` drop redundant `overflow-wrap` from inherited
descendants (#1675)
- `fix(presets)` drop stale "5/31 discount" framing in pro cost copy
(#1583)
- `chore(install)` include desktop deps in root postinstall (#1584)
- `test(lifecycle)` cover deterministic policy corpus + npm package
aliases (#1574, #1621)
## [0.49.0] — 2026-05-22
**TUI — Static-history renderer.** The history pane is now rendered
exclusively through Ink's `<Static>` (#1529, stages 1–4). The previous
virtual-viewport machinery — viewport-budget row allocator, byte-virtual
frame layer, manual scroll math — is gone. Net: less code on the hot
path, no more "frame drift" on very long sessions, and the rewrite stays
Ink-native instead of fighting it. Behind `REASONIX_STATIC_HISTORY` at
stage 1, default-on by stage 2, scaffolding removed by stage 4.
**Chat — queued mid-turn steers.** Typing while the model is mid-turn
no longer fights the live render or drops the keystroke. New input
queues, surfaces a small "queued" hint, and feeds into the next user
turn cleanly (#1501). Pairs with the static-history switch so the
queued line stays visible across re-renders.
**Web search — Bing default, dashboard engine switcher.** Default web
backend switches from Mojeek to Bing (#1558); the dashboard gains a
visible engine switcher so you can flip between configured backends
without editing config. Mojeek is dropped from the bundled set entirely
in this release.
**Plans — lifecycle evidence summaries.** Plan acceptance now surfaces
the evidence captured at each lifecycle step (#1500), so the "why this
plan is ready to accept" question has a structured answer instead of
implicit trust. Builds on the strict-lifecycle observability that
landed in 0.48.1.
**Desktop — approval + completion notifications.** Native OS
notifications for approval prompts and turn-complete events (#1519),
so a long-running turn can land in the background and still surface.
Uses `tauri-plugin-notification`.
**i18n — CLI command output.** `/mcp`, `/sessions`, `/prune`, `/theme`
output is now translated (#1524), closing the remaining English-only
gap in CLI command surfaces. Approval-prompt confirm titles and action
labels also get zh-CN (#1560/#1561).
**Security.**
- `web_fetch` now blocks SSRF — private/loopback/link-local targets are
rejected at the boundary (#1544)
- Edit snapshots can no longer read outside the workspace (#1454)
- Shell redirects (`>`, `>>`, `<`) are constrained to the sandbox
boundary (#1457)
- New Task integrity guardrail catches objective simplification — i.e.
the model trying to redefine a hard requirement away (#1516)
**Tools.** `run_command` description now actively discourages
shell-based file edits in favor of the structured `edit` tool (#1514).
A per-turn dispatch-rate limit lands for tool calls (#1356), keeping
runaway loops from burning a quota slice in one turn.
**TUI polish.**
- `Ctrl+Enter` now inserts a newline (#1513) — matching how every
modern composer treats the modifier
- `mouseWheelRows` config knob tunes scroll velocity per terminal
(#1511) so trackpad vs. wheel mouse don't fight the default
- `@mention` file search is restricted to the current directory prefix
(#1548) so the picker doesn't dump the whole repo
- Paste-sentinel label no longer claims `^O` expands the paste — the
shortcut never existed (#1517)
**Context.** Pinned-constraint blocks are now preserved across context
folds (#1515) and the fold tail captures all of them, not just the last
(#1552). Memory constraints survive the fold instead of silently
dropping out under pressure.
**Client.**
- DeepSeek 429s are translated into an actionable "concurrency limit
hit" hint instead of a raw HTTP error (#1526)
- `timeoutMs` is now wired to `fetch` when the caller passes an
`AbortSignal` (#1535) — previously the timeout was silently ignored
- `--no-proxy` / `REASONIX_NO_PROXY` opt-out is honored for the
DeepSeek direct-route default (#1507)
**Files.** Read/edit/restore now preserve the source file's encoding
(GB18030, UTF-8 BOM, etc.) instead of normalizing to UTF-8 on write
(#1518). Important for CJK Windows projects.
**Web/Dashboard.**
- Path-access approval modal is bridged to the dashboard (#1538) so
the browser surface can resolve the same prompts as CLI/Desktop
- `@mention` file picker popover lands in the dashboard ChatPane
(#1546), gated on attached mode (#1549)
**Config.** Atomic config writes restore the preset-write diagnostic
trace (#1555), so when a preset write goes wrong you can actually see
why.
**Refactor.** `lifecycle` extracts a standalone risk policy module
(#1557), shrinking the orchestrator and unblocking risk policy reuse
from non-lifecycle callers.
**Edit safety.** `read-before-edit` is now enforced at the dispatch
gate, not as a per-tool check (#1563) — `edit` / `multi_edit` refuse
to fire on a file the model hasn't read this session, closing the
race where a SEARCH block could match stale bytes after an external
write.
**Cache.** Fold-summary requests now reuse the live agent's system
prompt + tool list as their prefix, so the cached bytes the main
agent just paid for carry over to the summary call (#1565). Measured
on a 48.7K-token fold: 0% → 99.6% cache hit, ~89% input cost
reduction per fold.
**Other:**
- `fix(desktop)` drop `workspace:*` protocol for core-utils — desktop
isn't a workspace member
- `fix(desktop)` tsc errors blocking desktop bundle build
## [0.48.1] — 2026-05-21
**`dsnix` — short alias.** A new `dsnix` shim package lands alongside
+1
View File
@@ -25,6 +25,7 @@
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg?style=flat-square&color=3fb950&labelColor=161b22&label=downloads" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg?style=flat-square&color=5fa04e&labelColor=161b22&logo=nodedotjs&logoColor=white" alt="node"/></a>
<a href="https://github.com/esengine/reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/reasonix.svg?style=flat-square&color=dbab09&labelColor=161b22&logo=github&logoColor=white" alt="GitHub stars"/></a>
<a href="https://atomgit.com/esengine/DeepSeek-Reasonix"><img src="https://atomgit.com/esengine/DeepSeek-Reasonix/star/badge.svg" alt="AtomGit stars"/></a>
<a href="https://github.com/esengine/reasonix/graphs/contributors"><img src="https://img.shields.io/github/contributors/esengine/reasonix.svg?style=flat-square&color=bc8cff&labelColor=161b22&logo=github&logoColor=white" alt="contributors"/></a>
<a href="https://github.com/esengine/reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/reasonix.svg?style=flat-square&color=58a6ff&labelColor=161b22&logo=github&logoColor=white" alt="Discussions"/></a>
<a href="https://discord.gg/XF78rEME2D"><img src="https://img.shields.io/badge/discord-join-5865F2.svg?style=flat-square&labelColor=161b22&logo=discord&logoColor=white" alt="Discord"/></a>
+1
View File
@@ -25,6 +25,7 @@
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg?style=flat-square&color=3fb950&labelColor=161b22&label=downloads" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg?style=flat-square&color=5fa04e&labelColor=161b22&logo=nodedotjs&logoColor=white" alt="node"/></a>
<a href="https://github.com/esengine/reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/reasonix.svg?style=flat-square&color=dbab09&labelColor=161b22&logo=github&logoColor=white" alt="GitHub stars"/></a>
<a href="https://atomgit.com/esengine/DeepSeek-Reasonix"><img src="https://atomgit.com/esengine/DeepSeek-Reasonix/star/badge.svg" alt="AtomGit stars"/></a>
<a href="https://github.com/esengine/reasonix/graphs/contributors"><img src="https://img.shields.io/github/contributors/esengine/reasonix.svg?style=flat-square&color=bc8cff&labelColor=161b22&logo=github&logoColor=white" alt="contributors"/></a>
<a href="https://github.com/esengine/reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/reasonix.svg?style=flat-square&color=58a6ff&labelColor=161b22&logo=github&logoColor=white" alt="Discussions"/></a>
<a href="https://discord.gg/XF78rEME2D"><img src="https://img.shields.io/badge/discord-join-5865F2.svg?style=flat-square&labelColor=161b22&logo=discord&logoColor=white" alt="Discord"/></a>
+39
View File
@@ -0,0 +1,39 @@
/** Evaluation harness — runs scenarios and collects results. */
import type { EvalReport, EvalResult, EvalScenario } from "./types.js";
export async function runScenarios(
scenarios: EvalScenario[],
opts: {
onResult?: (r: EvalResult) => void;
} = {},
): Promise<EvalReport> {
const results: EvalResult[] = [];
for (const sc of scenarios) {
const t0 = Date.now();
let result: EvalResult;
try {
result = await sc.run();
result.durationMs = Date.now() - t0;
} catch (err) {
result = {
scenarioId: sc.id,
pass: false,
durationMs: Date.now() - t0,
details: `UNEXPECTED ERROR: ${(err as Error).message}`,
};
}
results.push(result);
opts.onResult?.(result);
}
// Dynamic import avoids bundling VERSION into the harness module.
const { VERSION } = await import("../../src/version.js");
return {
meta: {
date: new Date().toISOString(),
reasonixVersion: VERSION,
},
results,
};
}
+81
View File
@@ -0,0 +1,81 @@
/** Render behavior-stability results.json → markdown report. */
import { readFileSync, writeFileSync } from "node:fs";
import { pathToFileURL } from "node:url";
import type { EvalReport } from "./types.js";
interface CliArgs {
input: string;
outPath: string;
}
function parseArgs(argv: string[]): CliArgs {
const out: CliArgs = { input: "", outPath: "benchmarks/behavior-stability/report.md" };
const positional: string[] = [];
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "--out") out.outPath = argv[++i] ?? out.outPath;
else if (a && !a.startsWith("--")) positional.push(a);
}
out.input = positional[0] ?? "";
if (!out.input) {
throw new Error(
"usage: npx tsx benchmarks/behavior-stability/report.ts <results.json> [--out report.md]",
);
}
return out;
}
function renderHeader(report: EvalReport): string {
return `# Reasonix Behavior-Stability Evaluation
**Date:** ${report.meta.date}
**Version:** ${report.meta.reasonixVersion}
`;
}
function renderSummary(report: EvalReport): string {
const passed = report.results.filter((r) => r.pass).length;
const total = report.results.length;
const pct = total > 0 ? ((passed / total) * 100).toFixed(0) : "0";
const rows = report.results.map((r) => {
const icon = r.pass ? "✅" : "❌";
return `| ${icon} | \`${r.scenarioId}\` | ${r.durationMs}ms | ${r.details} |`;
});
return `## Summary
**${passed}/${total} passed (${pct}%)**
| status | scenario | time | details |
|---|---:|---:|:---|
${rows.join("\n")}
`;
}
function render(report: EvalReport): string {
return [renderHeader(report), renderSummary(report)].join("\n\n");
}
function isMain(): boolean {
const entry = process.argv[1];
if (!entry) return false;
return import.meta.url === pathToFileURL(entry).href;
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
const raw = readFileSync(args.input, "utf8");
const report = JSON.parse(raw) as EvalReport;
const md = render(report);
writeFileSync(args.outPath, md, "utf8");
console.log(`Wrote ${args.outPath} (${report.results.length} results)`);
}
if (isMain()) {
main().catch((err) => {
console.error(err);
process.exit(1);
});
}
+87
View File
@@ -0,0 +1,87 @@
/** CLI runner for behavior-stability evaluation. */
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
import { loadDotenv } from "../../src/index.js";
import { ALL_SCENARIOS, API_SCENARIOS, LOCAL_SCENARIOS } from "./scenarios.js";
import { runScenarios } from "./harness.js";
import type { EvalScenario } from "./types.js";
loadDotenv();
interface CliArgs {
local: boolean;
api: boolean;
outPath: string | null;
}
function parseArgs(argv: string[]): CliArgs {
const out: CliArgs = { local: false, api: false, outPath: null };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "--local") out.local = true;
else if (a === "--api") out.api = true;
else if (a === "--out") out.outPath = argv[++i] ?? null;
}
// Default to local-only when neither flag is provided.
if (!out.local && !out.api) out.local = true;
return out;
}
function pickScenarios(args: CliArgs): EvalScenario[] {
const scenarios: EvalScenario[] = [];
if (args.local) scenarios.push(...LOCAL_SCENARIOS);
if (args.api) scenarios.push(...API_SCENARIOS);
return scenarios;
}
function isMain(): boolean {
const entry = process.argv[1];
if (!entry) return false;
return import.meta.url === pathToFileURL(entry).href;
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
const scenarios = pickScenarios(args);
if (scenarios.length === 0) {
console.log("No scenarios selected. Use --local, --api, or both.");
process.exit(0);
}
const categories = new Set(scenarios.map((s) => s.category));
console.log(`Running ${scenarios.length} scenario(s) [${[...categories].join(", ")}] …\n`);
const report = await runScenarios(scenarios, {
onResult: (r) => {
const icon = r.pass ? "✅" : "❌";
console.log(`${icon} ${r.scenarioId} (${r.durationMs}ms)`);
console.log(` ${r.details}\n`);
},
});
const passed = report.results.filter((r) => r.pass).length;
const total = report.results.length;
console.log(`────────────────────────────────────────`);
console.log(`Results: ${passed}/${total} passed`);
console.log(`Version: ${report.meta.reasonixVersion}`);
console.log(`Date: ${report.meta.date}`);
if (args.outPath) {
const dir = dirname(args.outPath);
if (dir !== ".") mkdirSync(dir, { recursive: true });
writeFileSync(args.outPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
console.log(`Wrote ${args.outPath}`);
}
if (passed < total) process.exit(1);
}
if (isMain()) {
main().catch((err) => {
console.error(err);
process.exit(1);
});
}
+147
View File
@@ -0,0 +1,147 @@
/** Behavior-stability scenario for PR #1462 — constraint persistence across context folds. */
import { AppendOnlyLog, SessionStats } from "../../src/index.js";
import { ContextManager } from "../../src/context-manager.js";
import { Usage } from "../../src/client.js";
import type { EvalResult, EvalScenario } from "./types.js";
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
function withTiming(fn: () => Promise<EvalResult>): Promise<EvalResult> {
const t0 = Date.now();
return fn().then((r) => ({ ...r, durationMs: Date.now() - t0 }));
}
function pass(id: string, details: string): EvalResult {
return { scenarioId: id, pass: true, durationMs: 0, details };
}
function fail(id: string, details: string): EvalResult {
return { scenarioId: id, pass: false, durationMs: 0, details };
}
/* ------------------------------------------------------------------ */
/* Mock client — returns a fixed summary for fold testing */
/* ------------------------------------------------------------------ */
class MockDeepSeekClient {
private _replyContent: string;
constructor(replyContent: string) {
this._replyContent = replyContent;
}
async chat(): Promise<{
content: string;
reasoningContent: string;
usage: Usage;
}> {
return {
content: this._replyContent,
reasoningContent: "",
usage: new Usage(100, 50, 150, 0, 100),
};
}
}
/* ------------------------------------------------------------------ */
/* #1462 — Constraint persistence across folds (local) */
/* ------------------------------------------------------------------ */
const constraintPersistence: EvalScenario = {
id: "constraint-persistence",
name: "Context fold preserves pinned constraints from system prompt",
category: "context",
requiresApi: false,
run: () =>
withTiming(async () => {
const systemPrompt = `You are a coding assistant.
# HIGH PRIORITY constraints
- DO NOT use npm install without asking.
- Never delete files without confirmation.
# User memory
The user prefers TypeScript over JavaScript.
# Project memory
This project uses pnpm instead of npm.`;
const log = new AppendOnlyLog();
// Fill log with synthetic long history to trigger a fold boundary > 0.
for (let i = 0; i < 40; i++) {
log.append({
role: "user",
content: `Turn ${i}: Please review the codebase and tell me what you found.`,
});
log.append({
role: "assistant",
content: `Turn ${i} summary: I reviewed the codebase and found several issues including unused imports, missing type annotations, and inconsistent formatting.`,
});
}
const client = new MockDeepSeekClient("Summary of all prior turns.");
const stats = new SessionStats();
const ctx = new ContextManager({
client: client as any,
log,
stats,
sessionName: null,
getAbortSignal: () => new AbortController().signal,
getCurrentTurn: () => 1,
getSystemPrompt: () => systemPrompt,
});
// Use a tiny tail budget so almost everything becomes head and gets summarized.
const result = await ctx.fold("deepseek-v4-flash", { keepRecentTokens: 200 });
if (!result.folded) {
return fail(
"constraint-persistence",
`Fold did not happen (before=${result.beforeMessages}, after=${result.afterMessages}).`,
);
}
const foldedSystem = log.toMessages()[0];
if (foldedSystem?.role !== "assistant") {
return fail(
"constraint-persistence",
`Expected first folded message to be assistant summary, got ${foldedSystem?.role}.`,
);
}
const content = foldedSystem.content as string;
const checks = [
{ text: "DO NOT use npm install without asking", label: "HIGH PRIORITY constraint" },
{ text: "Never delete files without confirmation", label: "HIGH PRIORITY constraint 2" },
{ text: "TypeScript over JavaScript", label: "User memory" },
{ text: "pnpm instead of npm", label: "Project memory" },
];
const missing = checks.filter((c) => !content.includes(c.text));
if (missing.length > 0) {
return fail(
"constraint-persistence",
`Folded summary missing ${missing.length} constraint(s): ${missing.map((m) => m.label).join(", ")}.`,
);
}
return pass(
"constraint-persistence",
`Fold reduced ${result.beforeMessages} → ${result.afterMessages} messages and preserved all ${checks.length} pinned constraints.`,
);
}),
};
/* ------------------------------------------------------------------ */
/* Exports */
/* ------------------------------------------------------------------ */
export const LOCAL_SCENARIOS: EvalScenario[] = [constraintPersistence];
export const API_SCENARIOS: EvalScenario[] = [];
export const ALL_SCENARIOS: EvalScenario[] = [...LOCAL_SCENARIOS, ...API_SCENARIOS];
+26
View File
@@ -0,0 +1,26 @@
/** Behavior-stability evaluation types — lightweight, local-first regression suite. */
export interface EvalScenario {
id: string;
name: string;
category: "shell" | "context" | "integrity";
/** True when the scenario calls the live LLM API (costs money). */
requiresApi: boolean;
run: () => Promise<EvalResult>;
}
export interface EvalResult {
scenarioId: string;
pass: boolean;
durationMs: number;
details: string;
}
export interface EvalReport {
meta: {
date: string;
reasonixVersion: string;
model?: string;
};
results: EvalResult[];
}
+8 -8
View File
@@ -20,22 +20,22 @@ Used with permission, anonymized.
## Cost — using the prices Reasonix bills against (`src/telemetry/stats.ts`)
USD per 1M tokens — `inputCacheHit / inputCacheMiss / output`:
- `deepseek-v4-flash` — `0.028 / 0.139 / 0.278`
- `deepseek-v4-pro` — `0.139 / 1.667 / 3.333`
- `deepseek-v4-flash` — `0.0028 / 0.14 / 0.28`
- `deepseek-v4-pro` — `0.003625 / 0.435 / 0.87`
Assuming **v4-flash** (the project default):
| | This user (99.82% hit) | Same workload, **0% cache** |
|---|---:|---:|
| Cache-hit input | $12.18 | — |
| Cache-miss input | $0.11 | $60.58 |
| Cache-hit input | $1.22 | — |
| Cache-miss input | $0.11 | $61.01 |
| Output | $0.05 | $0.05 |
| **Total / day** | **$12.34** | **$60.63** |
| **Total / day** | **$1.38** | **$61.06** |
→ Cache saved this user **$48.29**, or **~80%** off the un-cached baseline, on a single day.
→ Cache saved this user **$59.68**, or **~97.7%** off the un-cached baseline, on a single day.
On **v4-pro** (5× the prefix-cache discount) the same workload would cost
**~$62.35** vs **~$727.08** without cache — a **~91% saving**.
On **v4-pro** (6.25% of uncached input cost) the same workload would cost
**~$2.07** vs **~$189.73** without cache — a **~98.9%** saving.
## "Isn't that just DeepSeek's prefix cache?"
+8 -1
View File
@@ -24,6 +24,13 @@
}
},
"files": {
"ignore": ["dist", "node_modules", "coverage", "*.d.ts", "dashboard/codemirror.js"]
"ignore": [
"dist",
"node_modules",
"coverage",
"*.d.ts",
"dashboard/codemirror.js",
"packages/ink/**"
]
}
}
+4 -3
View File
@@ -2,13 +2,14 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-capable" content="yes" />
<title>Reasonix</title>
<meta name="reasonix-token" content="__REASONIX_TOKEN__" />
<meta name="reasonix-mode" content="__REASONIX_MODE__" />
<!-- Production: served by CLI server; Vite dev: transformed by vite.config.ts -->
<link rel="stylesheet" href="/assets/app.css?token=__REASONIX_TOKEN__" />
<link rel="stylesheet" href="/assets/vendor-uplot.css?token=__REASONIX_TOKEN__" />
<link rel="stylesheet" href="/assets/vendor-hljs.css?token=__REASONIX_TOKEN__" />
</head>
<body>
<div id="root">
+3601
View File
File diff suppressed because it is too large. Load diff
+34
View File
@@ -0,0 +1,34 @@
{
"name": "reasonix-dashboard-v2",
"private": true,
"version": "0.47.2",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"@fontsource/geist": "^5.2.8",
"@fontsource/geist-mono": "^5.2.7",
"@fontsource/inter": "^5.2.8",
"katex": "^0.16.21",
"lucide-react": "^0.469.0",
"prism-react-renderer": "^2.4.1",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-markdown": "^9.0.1",
"react-virtuoso": "^4.12.5",
"rehype-katex": "^7.0.1",
"remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.0",
"remark-math": "^6.0.0"
},
"devDependencies": {
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.6.3",
"vite": "^5.4.10"
}
}
File diff suppressed because it is too large. Load diff
+163
View File
@@ -0,0 +1,163 @@
import { Highlight, type PrismTheme } from "prism-react-renderer";
import { useEffect, useRef, useState } from "react";
const DARK_THEME: PrismTheme = {
plain: { color: "#dde1ea", backgroundColor: "transparent" },
styles: [
{ types: ["comment", "prolog", "doctype", "cdata"], style: { color: "#6d6e80", fontStyle: "italic" } },
{ types: ["punctuation"], style: { color: "#a8a9b8" } },
{ types: ["property", "tag", "boolean", "number", "constant", "symbol", "deleted"], style: { color: "#fbbf24" } },
{ types: ["selector", "attr-name", "string", "char", "builtin", "inserted"], style: { color: "#86dcb1" } },
{ types: ["operator", "entity", "url"], style: { color: "#84b9e8" } },
{ types: ["atrule", "attr-value", "keyword"], style: { color: "#b4a8f0" } },
{ types: ["function", "class-name", "maybe-class-name"], style: { color: "#84b9e8", fontWeight: "500" } },
{ types: ["regex", "important", "variable"], style: { color: "#f0c062" } },
{ types: ["important", "bold"], style: { fontWeight: "bold" } },
{ types: ["italic"], style: { fontStyle: "italic" } },
],
};
const LIGHT_THEME: PrismTheme = {
plain: { color: "#24292e", backgroundColor: "transparent" },
styles: [
{ types: ["comment", "prolog", "doctype", "cdata"], style: { color: "#6a737d", fontStyle: "italic" } },
{ types: ["punctuation"], style: { color: "#24292e" } },
{ types: ["property", "tag", "boolean", "number", "constant", "symbol", "deleted"], style: { color: "#d73a49" } },
{ types: ["selector", "attr-name", "string", "char", "builtin", "inserted"], style: { color: "#032f62" } },
{ types: ["operator", "entity", "url"], style: { color: "#d73a49" } },
{ types: ["atrule", "attr-value", "keyword"], style: { color: "#d73a49" } },
{ types: ["function", "class-name", "maybe-class-name"], style: { color: "#6f42c1", fontWeight: "500" } },
{ types: ["regex", "important", "variable"], style: { color: "#e36209" } },
{ types: ["important", "bold"], style: { fontWeight: "bold" } },
{ types: ["italic"], style: { fontStyle: "italic" } },
],
};
function usePrismTheme(): PrismTheme {
const [theme, setTheme] = useState<"dark" | "light">(() =>
document.documentElement.dataset.theme === "light" ? "light" : "dark",
);
const prevRef = useRef(theme);
useEffect(() => {
const el = document.documentElement;
const cb = () => {
const t = el.dataset.theme === "light" ? "light" : "dark";
if (t !== prevRef.current) {
prevRef.current = t;
setTheme(t);
}
};
const mo = new MutationObserver(cb);
mo.observe(el, { attributes: true, attributeFilter: ["data-theme"] });
return () => mo.disconnect();
}, []);
return theme === "dark" ? DARK_THEME : LIGHT_THEME;
}
export const PRISM_THEME = DARK_THEME;
const EXTS: Record<string, string> = {
ts: "typescript", tsx: "tsx", mts: "typescript", cts: "typescript",
js: "javascript", jsx: "jsx", mjs: "javascript", cjs: "javascript",
py: "python", pyi: "python",
rs: "rust",
go: "go",
json: "json", jsonc: "json",
md: "markdown", mdx: "markdown",
css: "css", scss: "scss", less: "less",
html: "markup", htm: "markup", xml: "markup", svg: "markup",
yaml: "yaml", yml: "yaml",
toml: "toml",
sh: "bash", bash: "bash", zsh: "bash", fish: "bash",
sql: "sql",
rb: "ruby",
java: "java", kt: "kotlin",
swift: "swift",
c: "c", h: "c",
cpp: "cpp", cc: "cpp", cxx: "cpp", hpp: "cpp", hxx: "cpp",
cs: "csharp",
php: "php",
lua: "lua",
dart: "dart",
ex: "elixir", exs: "elixir",
erl: "erlang",
hs: "haskell",
clj: "clojure", cljs: "clojure",
zig: "zig",
vue: "markup",
svelte: "markup",
graphql: "graphql", gql: "graphql",
proto: "protobuf",
dockerfile: "docker",
};
export function langFromPath(path: string | null | undefined): string | null {
if (!path) return null;
const base = path.split(/[\\/]/).pop() ?? "";
if (base.toLowerCase() === "dockerfile") return "docker";
if (base.toLowerCase() === "makefile") return "makefile";
const m = /\.([a-z0-9]+)$/i.exec(base);
if (!m) return null;
return EXTS[m[1].toLowerCase()] ?? null;
}
export function CodeView({
text,
lang,
startLine = 1,
showLineNumbers = true,
}: {
text: string;
lang: string;
startLine?: number;
showLineNumbers?: boolean;
}) {
const theme = usePrismTheme();
return (
<Highlight theme={theme} code={text} language={lang}>
{({ className, tokens, getLineProps, getTokenProps }) => (
<pre className={`codeview ${className}`}>
{tokens.map((line, i) => (
<div key={i} {...getLineProps({ line })} className="codeview-line">
{showLineNumbers && (
<span className="codeview-line-num">{i + startLine}</span>
)}
<span className="codeview-line-content">
{line.map((token, k) => (
<span key={k} {...getTokenProps({ token })} />
))}
</span>
</div>
))}
</pre>
)}
</Highlight>
);
}
export function CollapsibleCode({
text,
lang,
startLine = 1,
maxLines = 20,
}: {
text: string;
lang: string;
startLine?: number;
maxLines?: number;
}) {
const [open, setOpen] = useState(false);
const lines = text.split("\n");
const tooLong = lines.length > maxLines;
const shown = open || !tooLong ? text : lines.slice(0, maxLines).join("\n");
return (
<>
<CodeView text={shown} lang={lang} startLine={startLine} />
{tooLong && (
<button type="button" className="tool-more" onClick={() => setOpen((v) => !v)}>
{open ? "less" : `+ ${lines.length - maxLines} more lines`}
</button>
)}
</>
);
}
+345
View File
@@ -0,0 +1,345 @@
import {
ClipboardCopy,
Download,
FilePlus,
FocusIcon,
FolderOpen,
Info,
Plus,
Search,
Settings,
SquareX,
StopCircle,
Trash2,
} from "lucide-react";
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { t, useLang } from "./i18n";
import { Shortcut, type ShortcutKey } from "./ui/shortcut";
export type CommandGroup = "nav" | "action" | "workspace" | "settings";
export type Command = {
id: string;
label: string;
hint?: string;
icon: ReactNode;
shortcut?: ShortcutKey[];
group: CommandGroup;
run: () => void;
};
export function useCommandPalette(active: boolean = true) {
const [open, setOpen] = useState(false);
useEffect(() => {
// Skip in background tabs — each TabRuntime calls this hook, so without the gate Cmd+K toggles every tab's palette at once.
if (!active) return;
const onKey = (e: KeyboardEvent) => {
const mod = e.ctrlKey || e.metaKey;
if (mod && (e.key === "k" || e.key === "K")) {
e.preventDefault();
setOpen((v) => !v);
} else if (e.key === "Escape") {
setOpen(false);
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [active]);
return { open, setOpen };
}
export type CommandHandlers = {
newChat: () => void;
clearChat: () => void;
focusComposer: () => void;
openSettings: () => void;
about: () => void;
abort: () => void;
copyLast: () => void;
conversationCopy: () => void;
exportMarkdown: () => void;
pickWorkspace: () => void;
newTab: () => void;
closeTab: () => void;
busy: boolean;
canCloseTab: boolean;
hasMessages: boolean;
};
export function buildCommands(handlers: CommandHandlers): Command[] {
const list: Command[] = [
{
id: "new-chat",
group: "nav",
label: t("palette.newChat"),
hint: t("palette.newChatHint"),
icon: <FilePlus size={13} />,
shortcut: ["mod", "N"],
run: handlers.newChat,
},
{
id: "new-tab",
group: "nav",
label: t("palette.newTab"),
hint: t("palette.newTabHint"),
icon: <Plus size={13} />,
shortcut: ["mod", "T"],
run: handlers.newTab,
},
];
if (handlers.canCloseTab) {
list.push({
id: "close-tab",
group: "nav",
label: t("palette.closeTab"),
hint: t("palette.closeTabHint"),
icon: <SquareX size={13} />,
shortcut: ["mod", "W"],
run: handlers.closeTab,
});
}
list.push({
id: "focus-composer",
group: "nav",
label: t("palette.focusComposer"),
icon: <FocusIcon size={13} />,
shortcut: ["mod", "L"],
run: handlers.focusComposer,
});
if (handlers.busy) {
list.push({
id: "abort",
group: "action",
label: t("palette.abort"),
hint: t("palette.abortHint"),
icon: <StopCircle size={13} />,
shortcut: ["esc"],
run: handlers.abort,
});
}
if (handlers.hasMessages) {
list.push({
id: "copy-last",
group: "action",
label: t("palette.copyLast"),
hint: t("palette.copyLastHint"),
icon: <ClipboardCopy size={13} />,
run: handlers.copyLast,
});
list.push({
id: "copy-conv",
group: "action",
label: t("palette.copyConv"),
hint: t("palette.copyConvHint"),
icon: <ClipboardCopy size={13} />,
run: handlers.conversationCopy,
});
list.push({
id: "export-md",
group: "action",
label: t("palette.exportMd"),
hint: t("palette.exportMdHint"),
icon: <Download size={13} />,
run: handlers.exportMarkdown,
});
list.push({
id: "clear-chat",
group: "action",
label: t("palette.clearChat"),
hint: t("palette.clearChatHint"),
icon: <Trash2 size={13} />,
run: handlers.clearChat,
});
}
list.push({
id: "pick-workspace",
group: "workspace",
label: t("palette.pickWorkspace"),
hint: t("palette.pickWorkspaceHint"),
icon: <FolderOpen size={13} />,
run: handlers.pickWorkspace,
});
list.push({
id: "settings",
group: "settings",
label: t("palette.settings"),
hint: t("palette.settingsHint"),
icon: <Settings size={13} />,
run: handlers.openSettings,
});
list.push({
id: "about",
group: "settings",
label: t("palette.about"),
icon: <Info size={13} />,
run: handlers.about,
});
return list;
}
const GROUP_ORDER: CommandGroup[] = ["nav", "action", "workspace", "settings"];
function groupLabel(g: CommandGroup): string {
switch (g) {
case "nav": return t("palette.groupNav");
case "action": return t("palette.groupAction");
case "workspace": return t("palette.groupWorkspace");
case "settings": return t("palette.groupSettings");
}
}
export function CommandPalette({
open,
onClose,
commands,
}: {
open: boolean;
onClose: () => void;
commands: Command[];
}) {
useLang();
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return commands;
return commands.filter((c) =>
[c.label, c.hint].filter(Boolean).join(" ").toLowerCase().includes(q),
);
}, [query, commands]);
useEffect(() => {
if (open) {
setQuery("");
setActive(0);
requestAnimationFrame(() => inputRef.current?.focus());
}
}, [open]);
useEffect(() => {
setActive((a) => Math.min(a, Math.max(0, filtered.length - 1)));
}, [filtered.length]);
useEffect(() => {
const el = listRef.current?.querySelector<HTMLElement>(`[data-idx="${active}"]`);
el?.scrollIntoView({ block: "nearest" });
}, [active]);
const grouped = useMemo(() => {
const byGroup = new Map<CommandGroup, Command[]>();
for (const c of filtered) {
const arr = byGroup.get(c.group) ?? [];
arr.push(c);
byGroup.set(c.group, arr);
}
return GROUP_ORDER
.map((g) => ({ group: g, items: byGroup.get(g) ?? [] }))
.filter((s) => s.items.length > 0);
}, [filtered]);
if (!open) return null;
const run = (cmd: Command) => {
cmd.run();
onClose();
};
return (
<div className="cmdk-mask" onMouseDown={onClose}>
<div className="cmdk" onMouseDown={(e) => e.stopPropagation()}>
<div className="cmdk-head">
<Search size={14} />
<input
ref={inputRef}
placeholder={t("palette.searchPlaceholder")}
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setActive((a) => Math.min(a + 1, filtered.length - 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((a) => Math.max(a - 1, 0));
} else if (e.key === "Enter") {
e.preventDefault();
const cmd = filtered[active];
if (cmd) run(cmd);
}
}}
/>
<span className="hint">
<Shortcut keys={["esc"]} />
</span>
</div>
<div className="cmdk-body" ref={listRef}>
{filtered.length === 0 ? (
<div className="cmdk-empty">{t("palette.empty")}</div>
) : null}
{grouped.map((section) => (
<div className="cmdk-group" key={section.group}>
<div className="cmdk-gh">{groupLabel(section.group)}</div>
{section.items.map((c) => {
const i = filtered.indexOf(c);
return (
<div
key={c.id}
data-idx={i}
className="cmdk-row"
data-active={i === active}
onMouseEnter={() => setActive(i)}
onClick={() => run(c)}
>
<span className="ic">{c.icon}</span>
<span className="l">{c.label}</span>
<span className="g">{groupLabel(c.group)}</span>
{c.shortcut ? (
<span className="kb">
<Shortcut keys={c.shortcut} />
</span>
) : (
<span className="kb-empty" />
)}
</div>
);
})}
</div>
))}
</div>
<div className="cmdk-foot">
<span>
<Shortcut keys={["updown"]} />
{t("palette.footMove")}
</span>
<span>
<Shortcut keys={["enter"]} />
{t("palette.footRun")}
</span>
<span>
<Shortcut keys={["esc"]} />
{t("palette.footClose")}
</span>
<span style={{ marginLeft: "auto", color: "var(--muted)" }}>
{filtered.length} {t("palette.countSuffix")}
</span>
</div>
</div>
</div>
);
}
export function Toast({ message }: { message: { msg: string; yolo?: boolean } | null }) {
if (!message) return null;
if (message.yolo) {
return (
<div className="toast toast-yolo">
<span className="toast-yolo-badge">YOLO</span>
{message.msg}
</div>
);
}
return <div className="toast">{message.msg}</div>;
}
+271
View File
@@ -0,0 +1,271 @@
import { invoke } from "@tauri-apps/api/core";
import { openPath, openUrl } from "@tauri-apps/plugin-opener";
import { Check, Copy, ExternalLink, FileText } from "lucide-react";
import {
Children,
cloneElement,
createContext,
isValidElement,
memo,
type ReactNode,
useContext,
useState,
} from "react";
import ReactMarkdown from "react-markdown";
import rehypeKatex from "rehype-katex";
import remarkBreaks from "remark-breaks";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import { CodeView } from "./CodeView";
import { t, useLang } from "./i18n";
async function openWithEditor(
editor: string | undefined,
abs: string,
line?: number,
): Promise<void> {
if (editor && editor.trim()) {
await invoke("open_in_editor", { command: editor, path: abs, line: line ?? null });
return;
}
await openPath(abs);
}
type WorkspaceCtx = { dir?: string; editor?: string };
const WorkspaceContext = createContext<WorkspaceCtx>({});
export const WorkspaceProvider = WorkspaceContext.Provider;
function resolveAgainstWorkspace(rel: string, ws: string | undefined): string {
if (!ws) return rel;
if (/^[a-zA-Z]:[\\/]/.test(rel) || rel.startsWith("/")) return rel;
const sep = ws.includes("\\") ? "\\" : "/";
const trimmed = ws.replace(/[\\/]$/, "");
return `${trimmed}${sep}${rel.replace(/^\.[\\/]/, "")}`;
}
const KNOWN_EXTS =
"ts|tsx|mts|cts|js|jsx|mjs|cjs|py|pyi|rs|go|json|jsonc|md|mdx|css|scss|less|html|htm|xml|svg|yaml|yml|toml|sh|bash|zsh|fish|sql|rb|java|kt|swift|c|cpp|cc|cxx|h|hpp|hxx|cs|php|lua|dart|ex|exs|erl|hs|clj|cljs|zig|vue|svelte|graphql|gql|proto";
// No lookbehind here — Tauri's WKWebView on macOS Monterey (Safari < 16.4)
// can't parse `(?<=...)` and the whole bundle fails to load with an
// "invalid group specifier name" error. Capture the leading char as
// group 1 instead and let splitFilePaths skip past it. Issue #1209.
const FILE_PATH_RE = new RegExp(
`(^|[\\s\`'"(\\[])((?:[\\w.-]+\\/)+[\\w.-]+\\.(?:${KNOWN_EXTS}))(?::(\\d+(?:-\\d+)?))?(?=[\\s.,;!?\\]\\)'"\`]|$)`,
"g",
);
function FilePill({ path, line }: { path: string; line?: string }) {
useLang();
const ctx = useContext(WorkspaceContext);
const [done, setDone] = useState<"open" | "copy" | null>(null);
const display = line ? `${path}:${line}` : path;
const openInEditor = async () => {
try {
const abs = resolveAgainstWorkspace(path, ctx.dir);
const lineNum = line ? Number.parseInt(line.split("-")[0] ?? line, 10) : undefined;
await openWithEditor(ctx.editor, abs, Number.isFinite(lineNum) ? lineNum : undefined);
setDone("open");
setTimeout(() => setDone(null), 1200);
} catch {
try {
await navigator.clipboard.writeText(display);
setDone("copy");
setTimeout(() => setDone(null), 1200);
} catch {
/* ignore */
}
}
};
const copyOnly = async (e: React.MouseEvent) => {
e.stopPropagation();
try {
await navigator.clipboard.writeText(display);
setDone("copy");
setTimeout(() => setDone(null), 1200);
} catch {
/* ignore */
}
};
return (
<span
className={`file-pill ${done ? "done" : ""}`}
role="button"
tabIndex={0}
onClick={openInEditor}
onContextMenu={(e) => {
e.preventDefault();
void copyOnly(e);
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
void openInEditor();
}
}}
title={t("markdown.filePillTitle")}
>
<FileText size={10} className="file-pill-icon" />
<span className="file-pill-path">{path}</span>
{line && <span className="file-pill-line">:{line}</span>}
{done && <Check size={10} className="file-pill-check" />}
</span>
);
}
function splitFilePaths(text: string): ReactNode[] | string {
FILE_PATH_RE.lastIndex = 0;
const out: ReactNode[] = [];
let last = 0;
let m: RegExpExecArray | null = FILE_PATH_RE.exec(text);
while (m !== null) {
const prefix = m[1] ?? "";
const path = m[2]!;
const line = m[3];
const pillStart = m.index + prefix.length;
if (pillStart > last) out.push(text.slice(last, pillStart));
out.push(<FilePill key={`fp-${pillStart}`} path={path} line={line} />);
last = pillStart + path.length + (line ? line.length + 1 : 0);
m = FILE_PATH_RE.exec(text);
}
if (out.length === 0) return text;
if (last < text.length) out.push(text.slice(last));
return out;
}
type AnyProps = { children?: ReactNode } & Record<string, unknown>;
function withFilePills(children: ReactNode): ReactNode {
return Children.map(children, (child) => {
if (typeof child === "string") return splitFilePaths(child);
if (isValidElement(child)) {
const props = child.props as AnyProps;
if (props.children !== undefined) {
return cloneElement(child, undefined, withFilePills(props.children));
}
}
return child;
});
}
export const Markdown = memo(function Markdown({ source }: { source: string }) {
return (
<div className="markdown">
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkBreaks, remarkMath]}
rehypePlugins={[[rehypeKatex, { throwOnError: false }]]}
components={{
pre: ({ children }) => {
// react-markdown v9 nests children unpredictably — flatten all text.
const rawText = flattenChildText(children).trimEnd();
return <CodeBlock lang={extractFencedLang(children)} text={rawText} />;
},
code: ({ className, children }) => <code className={className}>{children}</code>,
a: ({ href, children }) => <SafeLink href={href}>{children}</SafeLink>,
p: ({ children }) => <p>{withFilePills(children)}</p>,
li: ({ children }) => <li>{withFilePills(children)}</li>,
td: ({ children }) => <td>{withFilePills(children)}</td>,
}}
>
{source}
</ReactMarkdown>
</div>
);
});
function SafeLink({ href, children }: { href?: string; children: ReactNode }) {
useLang();
const ctx = useContext(WorkspaceContext);
const [done, setDone] = useState(false);
const isExternal = !!href && /^https?:\/\//i.test(href);
const onClick = async (e: React.MouseEvent) => {
e.preventDefault();
if (!href) return;
if (isExternal) {
try {
await openUrl(href);
} catch {
window.open(href, "_blank", "noopener,noreferrer");
}
return;
}
try {
const stripped = href.replace(/^file:\/\//, "");
const abs = resolveAgainstWorkspace(stripped, ctx.dir);
await openWithEditor(ctx.editor, abs);
} catch {
try {
await navigator.clipboard.writeText(href);
setDone(true);
setTimeout(() => setDone(false), 1200);
} catch {
/* ignore */
}
}
};
return (
<a
href={href ?? "#"}
onClick={onClick}
className={`md-link ${isExternal ? "external" : "local"} ${done ? "done" : ""}`}
title={
isExternal
? t("markdown.externalLinkTitle", { href: href ?? "" })
: t("markdown.localLinkTitle", { href: href ?? "" })
}
>
{children}
{isExternal ? (
<ExternalLink size={10} className="md-link-icon" />
) : done ? (
<Check size={10} className="md-link-icon" />
) : null}
</a>
);
}
export function extractFencedLang(children: ReactNode): string {
for (const kid of Children.toArray(children)) {
if (isValidElement(kid)) {
const cls = (kid.props as Record<string, unknown>).className;
if (typeof cls === "string") {
const m = cls.match(/language-([\w-]+)/);
if (m) return m[1]!;
}
}
}
return "text";
}
function flattenChildText(node: ReactNode): string {
if (typeof node === "string" || typeof node === "number") return String(node);
if (Array.isArray(node)) return node.map(flattenChildText).join("");
if (isValidElement(node))
return flattenChildText((node.props as { children?: ReactNode }).children);
return "";
}
function CodeBlock({ lang, text }: { lang: string; text: string }): ReactNode {
useLang();
const [copied, setCopied] = useState(false);
const onCopy = async () => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 1400);
} catch {
/* ignore */
}
};
return (
<div className="codeblock">
<div className="codeblock-head">
<span className="codeblock-lang">{lang}</span>
<button type="button" className={`copy-btn ${copied ? "done" : ""}`} onClick={onCopy}>
{copied ? <Check size={11} /> : <Copy size={11} />}
{copied ? t("markdown.copied") : t("markdown.copy")}
</button>
</div>
<CodeView text={text} lang={lang} />
</div>
);
}
-912
View File
@@ -1,912 +0,0 @@
import { marked } from "marked";
import { memo } from "preact/compat";
import { useState } from "preact/hooks";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
import {
escapeHtml,
hlLine,
langFromPath,
renderHighlightedBlock,
renderMarkdownToString,
renderSearchReplace,
} from "../lib/markdown.js";
export type ChatRole = "user" | "assistant" | "tool" | "info" | "warning" | "error";
export interface ChatMsg {
id: string;
role: ChatRole;
text?: string;
reasoning?: string;
toolName?: string;
toolArgs?: string;
}
const ROLE_GLYPH: Record<ChatRole, string> = {
user: "◇",
assistant: "◆",
tool: "▣",
info: "·",
warning: "▲",
error: "✦",
};
export type OnResolve = (kind: string, ...args: unknown[]) => void;
interface ToolCardProps {
msg: ChatMsg;
}
interface ChatMessageProps {
msg: ChatMsg;
streaming?: boolean;
}
interface ModalCardProps {
accent: string;
icon: string;
title: string;
subtitle?: string;
children?: unknown;
}
interface ShellModalSpec {
command: string;
allowPrefix?: string;
shellKind?: string;
}
interface ChoiceOption {
id: string;
title: string;
summary?: string;
}
interface ChoiceModalSpec {
question: string;
options: ChoiceOption[];
allowCustom?: boolean;
}
interface PlanModalSpec {
body?: string;
}
interface EditReviewSpec {
search?: string;
replace?: string;
path?: string;
remaining: number;
total: number;
}
interface WorkspaceSpec {
path: string;
}
interface CheckpointSpec {
stepId: string;
title?: string;
completed?: number;
total?: number;
}
interface RevisionStep {
id: string;
title: string;
action: string;
risk?: "low" | "med" | "high";
}
interface RevisionSpec {
summary?: string;
reason: string;
remainingSteps: RevisionStep[];
}
export type PickerActionName =
| "pick"
| "delete"
| "rename"
| "new"
| "install"
| "uninstall"
| "load-more"
| "refine"
| "cancel";
export interface PickerItemSpec {
id: string;
title: string;
subtitle?: string;
badge?: string;
meta?: string;
}
export interface PickerModalSpec {
pickerKind: string;
title: string;
query?: string;
items: PickerItemSpec[];
actions: PickerActionName[];
hasMore?: boolean;
hint?: string;
}
export interface ViewerStep {
id: string;
title: string;
status: "done" | "queued";
}
export interface ViewerModalSpec {
viewerKind: string;
title: string;
body?: string;
steps?: ViewerStep[];
meta?: string;
}
interface DiffEntry {
kind: "context" | "ins" | "del";
text: string;
}
interface DiffPair {
left: string | null;
right: string | null;
kind: "context" | "change" | "ins" | "del";
}
export function renderMessageBody(text: string | null | undefined) {
if (!text) return null;
return html`<div class="md" dangerouslySetInnerHTML=${{ __html: renderMarkdownToString(text) }}></div>`;
}
export function parseToolArgs(raw: string | null | undefined): Record<string, unknown> | null {
if (!raw) return null;
try {
return JSON.parse(raw);
} catch {
return null;
}
}
export function ToolCard({ msg }: ToolCardProps) {
useLang();
const args = parseToolArgs(msg.toolArgs);
const name = msg.toolName ?? "tool";
// Reasonix's filesystem tools emit the path in args.path; MCP-bridged
// ones may differ but most expose a `path` field too. Normalize.
const path = (args?.path ?? args?.file_path ?? args?.filename) as string | undefined;
// edit_file (Reasonix) — search/replace pair → diff view.
if (
(name === "edit_file" || name.endsWith("_edit_file")) &&
args &&
typeof args.search === "string" &&
typeof args.replace === "string"
) {
const diffHtml = renderSearchReplace(
args.search as string,
args.replace as string,
path ?? "",
);
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">✎</span>
<span class="tool-card-name">edit_file</span>
${path ? html`<code class="tool-card-path">${path}</code>` : null}
</div>
<div dangerouslySetInnerHTML=${{ __html: diffHtml }}></div>
${msg.text ? html`<div class="tool-card-result">${msg.text}</div>` : null}
</div>
`;
}
// write_file — show new content as a code block with path-derived lang.
if (
(name === "write_file" || name.endsWith("_write_file")) &&
args &&
typeof args.content === "string"
) {
const lang = langFromPath(path);
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">+</span>
<span class="tool-card-name">write_file</span>
${path ? html`<code class="tool-card-path">${path}</code>` : null}
${lang ? html`<span class="pill">${lang}</span>` : null}
</div>
<div dangerouslySetInnerHTML=${{ __html: renderHighlightedBlock(args.content as string, lang) }}></div>
${msg.text ? html`<div class="tool-card-result">${msg.text}</div>` : null}
</div>
`;
}
// read_file / list_files — content lands in msg.text.
if (name === "read_file" || name.endsWith("_read_file") || name === "filesystem_read_file") {
const lang = langFromPath(path);
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">▤</span>
<span class="tool-card-name">read_file</span>
${path ? html`<code class="tool-card-path">${path}</code>` : null}
${lang ? html`<span class="pill">${lang}</span>` : null}
</div>
<div dangerouslySetInnerHTML=${{ __html: renderHighlightedBlock(msg.text ?? "", lang) }}></div>
</div>
`;
}
// run_command / run_background — terminal-style.
if (name === "run_command" || name === "run_background") {
const cmd = args?.command;
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">⚡</span>
<span class="tool-card-name">${name === "run_background" ? "run_background" : "run_command"}</span>
</div>
${
cmd
? html`<pre class="tool-card-cmd"><span class="tool-card-prompt">$</span> <code>${cmd}</code></pre>`
: null
}
${msg.text ? html`<pre class="tool-card-output">${msg.text}</pre>` : null}
</div>
`;
}
// list_files / file_exists / delete_file — show args + result inline.
if (
name === "list_files" ||
name === "file_exists" ||
name === "delete_file" ||
name === "create_directory" ||
name === "delete_directory" ||
name.endsWith("_list_files")
) {
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">▣</span>
<span class="tool-card-name">${name}</span>
${path ? html`<code class="tool-card-path">${path}</code>` : null}
</div>
<pre class="tool-card-output">${msg.text}</pre>
</div>
`;
}
// Default — keep the legacy compact box but add an args preview when
// present so MCP-bridged tools still surface something readable.
return html`
<div class="tool-card">
<div class="tool-card-head">
<span class="tool-card-icon">▣</span>
<span class="tool-card-name">${name}</span>
</div>
${
args
? html`<details class="tool-card-args"><summary>${t("modal.arguments")}</summary><pre>${escapeHtml(JSON.stringify(args, null, 2))}</pre></details>`
: null
}
<pre class="tool-card-output">${msg.text}</pre>
</div>
`;
}
// memo() short-circuits re-renders when shallow props are unchanged.
// Historical messages keep stable msg references across deltas, so the
// O(N) marked.parse + hljs work that used to fire per assistant_delta
// now only runs on truly new messages and the live streaming bubble.
export const ChatMessage = memo(function ChatMessage({ msg, streaming }: ChatMessageProps) {
const role = msg.role;
const glyph = ROLE_GLYPH[role as ChatRole] ?? "·";
if (role === "tool") {
return html`
<div class="chat-msg tool">
<div class="glyph">${glyph}</div>
<${ToolCard} msg=${msg} />
</div>
`;
}
return html`
<div class="chat-msg ${role}">
<div class="glyph">${glyph}</div>
<div class="body">
${msg.reasoning ? html`<div class="reasoning">${msg.reasoning}</div>` : null}
${renderMessageBody(msg.text)}
${streaming ? html`<span class="chat-streaming-cursor"></span>` : null}
</div>
</div>
`;
});
//
// Each component renders a card matching the TUI's ModalCard accent
// palette: red for shell (run-now), magenta for choice (branching),
// cyan for plan (decision), green for edits. onResolve pushes to the
// server; the SSE channel will echo back a modal-down that clears the
// local state — both surfaces stay in lockstep without polling.
export function ModalCard({ accent, icon, title, subtitle, children }: ModalCardProps) {
return html`
<div class="modal-card" style=${`border-left-color: ${accent};`}>
<div class="modal-card-head">
<span class="modal-card-icon" style=${`color: ${accent};`}>${icon}</span>
<div>
<div class="modal-card-title">${title}</div>
${subtitle ? html`<div class="modal-card-subtitle">${subtitle}</div>` : null}
</div>
</div>
${children}
</div>
`;
}
export function ShellModal({ modal, onResolve }: { modal: ShellModalSpec; onResolve: OnResolve }) {
useLang();
const isBg = modal.shellKind === "run_background";
return html`
<${ModalCard}
accent="#f87171"
icon=${isBg ? "⏱" : "⚡"}
title=${isBg ? t("modal.shellBgTitle") : t("modal.shellTitle")}
subtitle=${
isBg ? t("modal.shellBgSubtitle") : t("modal.shellSubtitle")
}
>
<div class="modal-cmd"><span class="modal-cmd-prompt">$</span> <code>${modal.command}</code></div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("shell", "run_once")}>${t("modal.runOnce")}</button>
<button onClick=${() => onResolve("shell", "always_allow")}>${t("modal.alwaysAllow", { prefix: modal.allowPrefix ?? "" })}</button>
<button class="danger" onClick=${() => onResolve("shell", "deny")}>${t("modal.deny")}</button>
</div>
<//>
`;
}
export function ChoiceModal({ modal, onResolve }: { modal: ChoiceModalSpec; onResolve: OnResolve }) {
useLang();
const [custom, setCustom] = useState("");
const [showCustom, setShowCustom] = useState(false);
return html`
<${ModalCard} accent="#f0abfc" icon="🔀" title=${t("modal.choiceTitle")} subtitle=${modal.question}>
${modal.options.map(
(opt: ChoiceOption) => html`
<button
key=${opt.id}
class="modal-choice-row"
onClick=${() => onResolve("choice", { kind: "pick", optionId: opt.id })}
>
<span class="modal-choice-id">${opt.id}</span>
<span class="modal-choice-title">${opt.title}</span>
${opt.summary ? html`<span class="modal-choice-summary">${opt.summary}</span>` : null}
</button>
`,
)}
${
modal.allowCustom
? showCustom
? html`
<div class="modal-custom">
<textarea
placeholder=${t("modal.typePlaceholder")}
rows="2"
value=${custom}
onInput=${(e: Event) => setCustom((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("choice", { kind: "custom", text: custom })} disabled=${!custom.trim()}>${t("modal.send")}</button>
<button onClick=${() => {
setShowCustom(false);
setCustom("");
}}>${t("common.back")}</button>
</div>
</div>
`
: html`
<button class="modal-choice-row" onClick=${() => setShowCustom(true)}>
<span class="modal-choice-id">·</span>
<span class="modal-choice-title">${t("modal.typeOwn")}</span>
<span class="modal-choice-summary">${t("modal.typeOwnSummary")}</span>
</button>
`
: null
}
<button class="modal-choice-row modal-choice-cancel" onClick=${() => onResolve("choice", { kind: "cancel" })}>
<span class="modal-choice-id">×</span>
<span class="modal-choice-title">${t("modal.cancel")}</span>
<span class="modal-choice-summary">${t("modal.cancelSummary")}</span>
</button>
<//>
`;
}
export function PlanModal({ modal, onResolve }: { modal: PlanModalSpec; onResolve: OnResolve }) {
useLang();
const [feedback, setFeedback] = useState("");
const [stage, setStage] = useState<"approve" | "refine" | null>(null);
const send = () => onResolve("plan", stage, feedback);
return html`
<${ModalCard} accent="#67e8f9" icon="◆" title=${t("modal.planTitle")} subtitle=${t("modal.planSubtitle")}>
<div class="md modal-plan-body" dangerouslySetInnerHTML=${{ __html: marked.parse(modal.body || "") }}></div>
${
stage
? html`
<textarea
placeholder=${
stage === "approve"
? t("modal.approveInstructions")
: t("modal.refinePlaceholder")
}
rows="3"
value=${feedback}
onInput=${(e: Event) => setFeedback((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${send}>${stage === "approve" ? t("modal.approve") : t("modal.sendRefinement")}</button>
<button onClick=${() => {
setStage(null);
setFeedback("");
}}>${t("common.back")}</button>
</div>
`
: html`
<div class="modal-actions">
<button class="primary" onClick=${() => setStage("approve")}>${t("modal.approve")}</button>
<button onClick=${() => setStage("refine")}>${t("modal.refine")}</button>
<button class="danger" onClick=${() => onResolve("plan", "cancel")}>${t("modal.cancel")}</button>
</div>
`
}
<//>
`;
}
// Line-level LCS diff. Returns an ordered list of rows; "context" rows
// appear on both sides, "del" only on the left (red), "ins" only on the
// right (green). Adjacent del/ins are paired into one row downstream so
// the change reads "old → new" left-to-right like a git side-by-side.
function lineDiff(aLines: string[], bLines: string[]): DiffEntry[] {
const m = aLines.length;
const n = bLines.length;
const dp: number[][] = Array.from({ length: m + 1 }, () => new Array<number>(n + 1).fill(0));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (aLines[i - 1] === bLines[j - 1]) dp[i]![j] = dp[i - 1]![j - 1]! + 1;
else dp[i]![j] = Math.max(dp[i - 1]![j]!, dp[i]![j - 1]!);
}
}
const out: DiffEntry[] = [];
let i = m;
let j = n;
while (i > 0 || j > 0) {
if (i > 0 && j > 0 && aLines[i - 1] === bLines[j - 1]) {
out.push({ kind: "context", text: aLines[i - 1]! });
i--;
j--;
} else if (j > 0 && (i === 0 || dp[i]![j - 1]! >= dp[i - 1]![j]!)) {
out.push({ kind: "ins", text: bLines[j - 1]! });
j--;
} else {
out.push({ kind: "del", text: aLines[i - 1]! });
i--;
}
}
return out.reverse();
}
// Pair del/ins runs into side-by-side rows. A run of consecutive dels
// followed by a run of inss collapses into rows of (del[k], ins[k]) so
// the modified line lines up across the gutter; surplus on either side
// produces rows with the opposite cell empty.
function pairDiffRows(diff: DiffEntry[]): DiffPair[] {
const rows: DiffPair[] = [];
let k = 0;
while (k < diff.length) {
const entry = diff[k]!;
if (entry.kind === "context") {
rows.push({ left: entry.text, right: entry.text, kind: "context" });
k++;
continue;
}
const dels: string[] = [];
const inss: string[] = [];
while (k < diff.length && diff[k]!.kind === "del") {
dels.push(diff[k]!.text);
k++;
}
while (k < diff.length && diff[k]!.kind === "ins") {
inss.push(diff[k]!.text);
k++;
}
const pairs = Math.max(dels.length, inss.length);
for (let p = 0; p < pairs; p++) {
const dp = dels[p];
const ip = inss[p];
rows.push({
left: dp ?? null,
right: ip ?? null,
kind: dp != null && ip != null ? "change" : dp != null ? "del" : "ins",
});
}
}
return rows;
}
export function EditReviewModal({ modal, onResolve }: { modal: EditReviewSpec; onResolve: OnResolve }) {
useLang();
const search = modal.search ?? "";
const replace = modal.replace ?? "";
const lang = langFromPath(modal.path);
const aLines = search.split("\n");
const bLines = replace.split("\n");
const rows = pairDiffRows(lineDiff(aLines, bLines));
return html`
<${ModalCard}
accent="#86efac"
icon="◆"
title=${t("modal.editTitle")}
subtitle=${t("modal.editSubtitle", { path: modal.path ?? "", remaining: modal.remaining, total: modal.total })}
>
<div class="edit-diff-wrap">
<div class="edit-diff-head">
<div class="edit-diff-side edit-diff-side-old">
<span class="edit-diff-marker">−</span> ${t("modal.before")}
</div>
<div class="edit-diff-side edit-diff-side-new">
<span class="edit-diff-marker">+</span> ${t("modal.after")}
</div>
</div>
<div class="edit-diff-body">
${rows.map(
(row, i) => html`
<div key=${i} class=${`edit-diff-row edit-diff-row-${row.kind}`}>
<div class="edit-diff-cell edit-diff-cell-old">
${
row.left != null
? html`<span
class="edit-diff-line"
dangerouslySetInnerHTML=${{ __html: hlLine(row.left, lang) || "&nbsp;" }}
></span>`
: html`<span class="edit-diff-empty">&nbsp;</span>`
}
</div>
<div class="edit-diff-cell edit-diff-cell-new">
${
row.right != null
? html`<span
class="edit-diff-line"
dangerouslySetInnerHTML=${{ __html: hlLine(row.right, lang) || "&nbsp;" }}
></span>`
: html`<span class="edit-diff-empty">&nbsp;</span>`
}
</div>
</div>
`,
)}
</div>
</div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("edit-review", "apply")}>${t("chat.confirmBtn")}</button>
<button onClick=${() => onResolve("edit-review", "reject")}>${t("chat.rejectBtn")}</button>
<button onClick=${() => onResolve("edit-review", "apply-rest-of-turn")}>${t("chat.applyRestBtn")}</button>
<button onClick=${() => onResolve("edit-review", "flip-to-auto")}>${t("chat.flipAutoBtn")}</button>
</div>
<//>
`;
}
export function WorkspaceModal({ modal, onResolve }: { modal: WorkspaceSpec; onResolve: OnResolve }) {
useLang();
return html`
<${ModalCard}
accent="#fbbf24"
icon="◇"
title=${t("modal.workspaceTitle")}
subtitle=${t("modal.workspaceSubtitle")}
>
<div class="modal-cmd"><span class="modal-cmd-prompt">→</span> <code>${modal.path}</code></div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("workspace", "switch")}>${t("modal.switchBtn")}</button>
<button class="danger" onClick=${() => onResolve("workspace", "deny")}>${t("modal.denyBtn")}</button>
</div>
<//>
`;
}
export function CheckpointModal({ modal, onResolve }: { modal: CheckpointSpec; onResolve: OnResolve }) {
useLang();
const [reviseText, setReviseText] = useState("");
const [staged, setStaged] = useState(false);
const label = modal.title ? `${modal.stepId} · ${modal.title}` : modal.stepId;
const counter = (modal.total ?? 0) > 0 ? ` (${modal.completed}/${modal.total})` : "";
return html`
<${ModalCard}
accent="#a5f3fc"
icon="✓"
title=${t("modal.stepComplete", { counter })}
subtitle=${label}
>
${
staged
? html`
<textarea
placeholder=${t("modal.revisePlaceholder")}
rows="3"
value=${reviseText}
onInput=${(e: Event) => setReviseText((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("checkpoint", "revise", reviseText)}>${t("modal.sendRevision")}</button>
<button onClick=${() => {
setStaged(false);
setReviseText("");
}}>${t("common.back")}</button>
</div>
`
: html`
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("checkpoint", "continue")}>${t("modal.continueBtn")}</button>
<button onClick=${() => setStaged(true)}>${t("modal.reviseBtn")}</button>
<button class="danger" onClick=${() => onResolve("checkpoint", "stop")}>${t("modal.stopBtn")}</button>
</div>
`
}
<//>
`;
}
export function PickerModal({
modal,
onResolve,
}: {
modal: PickerModalSpec;
onResolve: OnResolve;
}) {
useLang();
const [selectedId, setSelectedId] = useState<string | null>(modal.items[0]?.id ?? null);
const [query, setQuery] = useState(modal.query ?? "");
const [renameTarget, setRenameTarget] = useState<string | null>(null);
const [renameText, setRenameText] = useState("");
const [showNew, setShowNew] = useState(false);
const [newText, setNewText] = useState("");
const has = (a: PickerActionName) => modal.actions.includes(a);
const selected = modal.items.find((i) => i.id === selectedId) ?? null;
const submitRefine = (next: string) => {
setQuery(next);
if (has("refine")) onResolve("picker", { action: "refine", query: next });
};
const startRename = (id: string) => {
const item = modal.items.find((i) => i.id === id);
if (!item) return;
setRenameTarget(id);
setRenameText(item.title);
};
const sendRename = () => {
if (!renameTarget || !renameText.trim()) return;
onResolve("picker", { action: "rename", id: renameTarget, text: renameText });
setRenameTarget(null);
setRenameText("");
};
const sendNew = () => {
onResolve("picker", newText.trim() ? { action: "new", text: newText } : { action: "new" });
setShowNew(false);
setNewText("");
};
return html`
<${ModalCard}
accent="#fcd34d"
icon="≡"
title=${modal.title}
subtitle=${modal.hint}
>
${
has("refine")
? html`<input
class="modal-picker-search"
type="search"
placeholder=${t("modal.pickerFilter")}
value=${query}
onInput=${(e: Event) => submitRefine((e.target as HTMLInputElement).value)}
/>`
: null
}
<div class="modal-picker-list">
${
modal.items.length === 0
? html`<div class="modal-picker-empty">${t("modal.pickerEmpty")}</div>`
: modal.items.map(
(it) => html`
<button
key=${it.id}
class=${`modal-picker-row${it.id === selectedId ? " selected" : ""}`}
onClick=${() => setSelectedId(it.id)}
onDblClick=${() => has("pick") && onResolve("picker", { action: "pick", id: it.id })}
>
<span class="modal-picker-title">${it.title}</span>
${it.badge ? html`<span class="modal-picker-badge">${it.badge}</span>` : null}
${it.subtitle ? html`<span class="modal-picker-subtitle">${it.subtitle}</span>` : null}
${it.meta ? html`<span class="modal-picker-meta">${it.meta}</span>` : null}
</button>
`,
)
}
</div>
${
modal.hasMore && has("load-more")
? html`<button
class="modal-picker-more"
onClick=${() => onResolve("picker", { action: "load-more" })}
>${t("modal.pickerLoadMore")}</button>`
: null
}
${
renameTarget
? html`
<div class="modal-picker-form">
<input
type="text"
value=${renameText}
onInput=${(e: Event) => setRenameText((e.target as HTMLInputElement).value)}
/>
<div class="modal-actions">
<button class="primary" onClick=${sendRename} disabled=${!renameText.trim()}>${t("common.save")}</button>
<button onClick=${() => setRenameTarget(null)}>${t("common.back")}</button>
</div>
</div>
`
: showNew
? html`
<div class="modal-picker-form">
<input
type="text"
placeholder=${t("modal.pickerNewPlaceholder")}
value=${newText}
onInput=${(e: Event) => setNewText((e.target as HTMLInputElement).value)}
/>
<div class="modal-actions">
<button class="primary" onClick=${sendNew}>${t("common.add")}</button>
<button onClick=${() => setShowNew(false)}>${t("common.back")}</button>
</div>
</div>
`
: html`
<div class="modal-actions">
${
has("pick") && selected
? html`<button
class="primary"
onClick=${() => onResolve("picker", { action: "pick", id: selected.id })}
>${t("modal.pickerPick")}</button>`
: null
}
${
has("install") && selected
? html`<button
class="primary"
onClick=${() => onResolve("picker", { action: "install", id: selected.id })}
>${t("modal.pickerInstall")}</button>`
: null
}
${
has("uninstall") && selected
? html`<button
onClick=${() => onResolve("picker", { action: "uninstall", id: selected.id })}
>${t("modal.pickerUninstall")}</button>`
: null
}
${
has("rename") && selected
? html`<button onClick=${() => startRename(selected.id)}>${t("modal.pickerRename")}</button>`
: null
}
${
has("delete") && selected
? html`<button
class="danger"
onClick=${() => onResolve("picker", { action: "delete", id: selected.id })}
>${t("common.delete")}</button>`
: null
}
${
has("new")
? html`<button onClick=${() => setShowNew(true)}>${t("modal.pickerNew")}</button>`
: null
}
<button onClick=${() => onResolve("picker", { action: "cancel" })}>${t("modal.cancel")}</button>
</div>
`
}
<//>
`;
}
export function ViewerModal({
modal,
onResolve,
}: {
modal: ViewerModalSpec;
onResolve: OnResolve;
}) {
useLang();
return html`
<${ModalCard}
accent="#67e8f9"
icon="◇"
title=${modal.title}
subtitle=${modal.meta}
>
${
modal.steps && modal.steps.length > 0
? html`
<ol class="modal-viewer-steps">
${modal.steps.map(
(s: ViewerStep) => html`
<li key=${s.id} class=${`modal-viewer-step modal-viewer-step-${s.status}`}>
<span class="modal-viewer-step-mark">${s.status === "done" ? "✓" : "·"}</span>
<span class="modal-viewer-step-title">${s.title}</span>
</li>
`,
)}
</ol>
`
: null
}
${
modal.body
? html`<div class="md modal-viewer-body" dangerouslySetInnerHTML=${{ __html: marked.parse(modal.body) }}></div>`
: null
}
<div class="modal-actions">
<button onClick=${() => onResolve("viewer", { action: "close" })}>${t("modal.viewerClose")}</button>
</div>
<//>
`;
}
export function RevisionModal({ modal, onResolve }: { modal: RevisionSpec; onResolve: OnResolve }) {
useLang();
const riskColor = (r: string | undefined) =>
r === "high" ? "#f87171" : r === "med" ? "#fbbf24" : r === "low" ? "#86efac" : "#9ca3af";
return html`
<${ModalCard}
accent="#c4b5fd"
icon="✎"
title=${t("modal.revisionTitle")}
subtitle=${modal.summary || modal.reason}
>
<div class="modal-revise-reason">${modal.reason}</div>
<ol class="modal-revise-steps">
${modal.remainingSteps.map(
(s: RevisionStep) => html`
<li key=${s.id}>
<span class="modal-revise-dot" style=${`background:${riskColor(s.risk)}`}></span>
<span class="modal-revise-id">${s.id}</span>
<span class="modal-revise-title">${s.title}</span>
<span class="modal-revise-action">${s.action}</span>
</li>
`,
)}
</ol>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("revision", "accept")}>${t("modal.accept")}</button>
<button class="danger" onClick=${() => onResolve("revision", "reject")}>${t("modal.reject")}</button>
</div>
<//>
`;
}
File diff suppressed because it is too large. Load diff
+583 -20
View File
@@ -23,6 +23,111 @@ export const en = {
themeToggle: "Toggle theme",
themeLight: "Light",
themeDark: "Dark",
skill: {
scope: {
builtin: "Built-in",
global: "Global",
project: "Project",
},
runAs: {
subagent: "Subagent",
inline: "Inline",
},
generic: "Skill",
},
exportReasoningSummary: "Reasoning Summary",
exportToolLabel: "Tool Calls",
exportUserLabel: "User Messages",
empty: {
currentWorkspace: "Current workspace",
selectWorkspace: "Select a workspace to get started",
suggestion0: "Start a new conversation",
suggestion1: "Open settings",
suggestion2: "View overview",
suggestion3: "Browse sessions",
welcome: "Welcome to Reasonix",
},
errorLabel: "Error",
connecting: "Connecting…",
session: {
format: "Session",
new: "New Session",
},
setup: {
choose: "Choose a workspace",
description: "Select a workspace to start working",
notSelected: "No workspace selected",
saveAndStart: "Save & Start",
welcome: "Welcome",
workspace: "Workspace",
},
tab: {
newTab: "+ New Tab",
newTabTitle: "Open a new tab",
},
titlebar: {
clearChat: "Clear Chat",
close: "Close",
commandPalette: "Command Palette",
contextPanel: "Context Panel",
copyMd: "Copy as Markdown",
exportMd: "Export as Markdown",
maximize: "Maximize",
minimize: "Minimize",
more: "More",
restore: "Restore",
settings: "Settings",
sidebar: "Sidebar",
windowControls: "Window Controls",
},
toast: {
cleared: "Chat cleared",
copied: "Copied to clipboard",
copiedMd: "Copied as Markdown",
emptySession: "No messages to export",
exportDialogTitle: "Export Chat",
exportedMd: "Exported as Markdown",
exportFailed: "Export failed",
langSwitched: "Language switched",
modelSwitched: "Model → {model}",
effortSwitched: "Effort → {effort}",
modeSwitched: "Mode switched",
newSession: "New session created",
},
yolo: {
toast: "YOLO mode enabled",
},
cmd: {
abort: "Abort",
btw: "BTW",
clearChat: "Clear Chat",
compact: "Compact",
copyLast: "Copy Last",
exportMd: "Export as Markdown",
feedback: "Feedback",
help: "Help",
newSession: "New Session",
retry: "Retry",
switchModel: "Switch Model",
toggleCurrency: "Toggle Currency",
toggleLang: "Toggle Language",
toggleTheme: "Toggle Theme",
},
header: {
abort: "Abort",
clickToSelect: "Click to select",
copy: "Copy",
copyMd: "Copy as Markdown",
export: "Export",
exportMd: "Export as Markdown",
newChat: "New Chat",
noWorkspace: "No workspace",
running: "Running…",
},
jumpToBottom: "Jump to bottom",
langEN: "English",
langZH: "中文",
splashSubtitle: "AI-powered coding assistant",
},
changes: {
chatPlaceholder: "Ask about your code...",
@@ -101,29 +206,44 @@ export const en = {
saved: "saved: {fields}",
sectionApi: "DeepSeek API",
apiKey: "API key",
apiKeyNotSet: "Not set",
apiKeySave: "Save key",
apiKeySet: "Set",
apiSection: "API Configuration",
notSet: "(not set)",
replace: "replace",
pasteKey: "paste a fresh sk-… token",
saveKey: "Save key",
baseUrl: "base url",
baseUrlPlaceholder: "https://api.deepseek.com (default)",
baseUrlHint: "Base URL for API requests",
sectionDefaults: "Defaults",
preset: "preset",
presetAuto: "auto — flash → pro on hard turns",
presetFlash: "flash — always flash, no auto-escalate",
presetPro: "pro — always pro",
effortSection: "Reasoning effort",
modelCustom: "Custom model id",
modelCustomHint: "Any OpenAI-compatible id your endpoint serves (vLLM, Ollama, Together, …).",
modelCustomActive: "Currently running on a custom id: {model}",
appliesNextTurn: "applies next turn",
effort: "effort",
effortMax: "max (default — best)",
effortHigh: "high (cheaper / faster)",
effortMax: "max (DeepSeek extension — rejected by stock OpenAI / vLLM)",
effortHigh: "high (safe default — vLLM / Azure compatible)",
effortMedium: "medium",
effortLow: "low (fastest)",
webSearch: "web search",
webSearchNote: "web_fetch + web_search tools",
sectionCompute: "Compute",
proNext: "/pro one-shot",
proArm: "Arm for next turn",
proArmed: "Armed — disarms after next turn",
proNextNote: "next turn runs on deepseek-v4-pro, then auto-disarms",
webSearchEngine: "search engine",
webSearchEngineBing: "bing — default, works from CN without proxy",
webSearchEngineSearxng: "searxng — self-hosted (set endpoint via /se searxng <url>)",
webSearchEngineMetaso: "metaso — 100/day free (CN-friendly, free key at metaso.cn)",
webSearchEngineTavily: "tavily — 1000/mo free (set TAVILY_API_KEY)",
webSearchEnginePerplexity: "perplexity — AI-native (set PERPLEXITY_API_KEY)",
webSearchEngineExa: "exa — AI-native 1000/mo free (set EXA_API_KEY)",
webSearchEngineBrave: "brave — independent index, 2000/mo free (set BRAVE_SEARCH_API_KEY)",
webSearchEngineOllama: "ollama — Ollama cloud web search (set OLLAMA_API_KEY)",
webSearchEngineNote: "applies to the next web_search call",
sectionBudget: "Budget",
budget: "Budget",
budgetHint: "Set spending limits",
budgetPlaceholder: "Enter budget amount",
budgetOf: "of",
budgetSetCap: "set a cap",
budgetCustom: "custom",
@@ -149,21 +269,145 @@ export const en = {
skillPaths: "skill paths",
skillPathsPlaceholder: "/path/to/skills-a, /path/to/skills-b",
skillPathsNote: "comma-separated · next /new or new session",
skillsEmpty: "No skills loaded",
skillsLoaded: "Skills loaded",
subagentModelFlash: "flash",
subagentModelPro: "pro",
subagentModelHint: "Model used when this skill spawns its isolated subagent",
sectionRuntime: "Runtime",
activeModel: "active model",
model: "Model",
modelFlashDesc: "Flash — always flash",
modelProDesc: "Pro — always pro",
modelPricingLine: "${hit} hit · ${miss} miss · ${out} out per 1M tok",
editMode: "edit mode",
editModeNote: "switch from the Chat tab header",
editModeHint: "Configure edit mode",
showSystemEvents: "system events",
showSystemEventsHint: "Show quiet inline notices for context compaction, abort, rate-limit.",
shown: "shown",
hidden: "hidden",
sectionLanguage: "Language",
language: "language",
languageHint: "Switch language",
langEn: "English",
langZhCn: "简体中文",
appMode: "App mode",
appearanceSection: "Appearance",
behaviorSection: "Behavior",
ruleAutoApprovalHint: "Configure auto-approval rules",
ruleAutoApprovalSection: "Auto-approval Rules",
theme: "Theme",
themeDark: "Dark",
themeHint: "Switch between light and dark themes",
themeLight: "Light",
themeStyle: "Theme style",
themeStyleHint: "Choose theme style",
themeStyleGraphite: "Graphite",
themeStyleGraphiteDesc: "Cool dark neutrals — best for long sessions.",
themeStyleSandstone: "Sandstone",
themeStyleSandstoneDesc: "Warm light tones — easy on bright rooms.",
themeStylePorcelain: "Porcelain",
themeStylePorcelainDesc: "Clean light with extra contrast.",
themeStyleMidnight: "Midnight",
themeStyleMidnightDesc: "Deep dark with cooler highlights.",
pageGeneralLabel: "General",
pageGeneralDesc: "Theme, fonts, language and workspace.",
pageModelsLabel: "Models",
pageModelsDesc: "Default model and reasoning effort.",
pageMcpLabel: "MCP servers",
pageMcpDesc: "Connect external tool servers.",
pageSkillsLabel: "Skills",
pageSkillsDesc: "User-defined skills you can run with /skill.",
pageMemoryLabel: "Memory",
pageMemoryDesc: "Long-lived notes carried across sessions.",
pageRulesLabel: "Rules",
pageRulesDesc: "Auto-approval rules for shell + path access.",
pageBillingLabel: "Billing",
pageBillingDesc: "API key, balance and per-session budget.",
pageShortcutsLabel: "Shortcuts",
pageShortcutsDesc: "Keyboard shortcuts reference.",
fontFamily: "Font family",
fontFamilyHint: "Choose font family",
fontFamilySans: "Sans-serif",
fontFamilySerif: "Serif",
fontFamilySystem: "System",
fontScale: "Font scale",
fontScaleHint: "Adjust font size",
fontScaleLarge: "Large",
fontScaleMedium: "Medium",
fontScaleSmall: "Small",
currentWorkspace: "Current workspace",
defaultModelCurrent: "Current model",
editor: "Editor",
editorHint: "Configure editor preferences",
maxOutput: "Max output",
reasoningEffort: "Reasoning effort",
reasoningEffortHint: "Adjust reasoning depth",
sessionCost: "Session cost",
balanceAvailable: "Available",
balanceLabel: "Balance",
balanceLow: "Low balance",
cacheHitRate: "Cache hit rate",
ctxWindow: "Context window",
notSelected: "Not selected",
parseError: "Parse error",
workspaceChange: "Change",
workspaceSection: "Workspace",
mcpAdd: "Add",
mcpAddSection: "Add MCP Server",
mcpBridged: "Bridged",
mcpConfigured: "Configured",
mcpEmpty: "No MCP servers",
mcpNotBridged: "Not bridged",
mcpRemove: "Remove",
mcpSpecFormat: "JSON format",
mcpSpecLabel: "Server spec",
memoryDesc: "Configure memory settings",
memorySection: "Memory",
shortcutAbort: "Abort",
shortcutCloseTab: "Close Tab",
shortcutCommandPalette: "Command Palette",
shortcutFocusComposer: "Focus Composer",
shortcutNewChat: "New Chat",
shortcutNewTab: "New Tab",
shortcutSettings: "Settings",
shortcutSwitchTab: "Switch Tab",
qqAccessAllowlist: "Allowlist",
qqAccessOpen: "Open",
qqAccessOwner: "Owner",
qqAccessOwnerWithAllowlist: "Owner + Allowlist",
qqAccessRuntime: "Runtime",
qqAppId: "App ID",
qqApplyAction: "Apply",
qqApplyLabel: "Apply",
qqAppSecret: "App Secret",
qqBack: "Back",
qqConfigure: "Configure",
qqConfigureHint: "Set up QQ integration",
qqConfigureTitle: "QQ Configuration",
qqConnected: "Connected",
qqConnecting: "Connecting…",
qqDisconnected: "Disconnected",
qqEnvironment: "Environment",
qqFailed: "Failed",
qqProduction: "Production",
qqSandbox: "Sandbox",
qqSave: "Save",
qqSaveAndConnect: "Save & Connect",
qqSection: "QQ Integration",
qqSummaryAppId: "App ID",
qqSummaryDetail: "Details",
qqSummaryMissing: "Not configured",
qqTitle: "QQ Bot",
},
chat: {
modeMirror: "TUI mirror",
modeView: "session view",
placeholder: "Type a prompt — Enter sends, Shift+Enter for a newline · / @ for pickers",
placeholderBusy: "wait for the current turn to finish…",
placeholderSteerBusy: "type to steer — commands and pickers are disabled while busy",
steerHint: "message steers the current turn (added as instruction)",
send: "Send",
new: "New",
clear: "Clear",
@@ -185,15 +429,10 @@ export const en = {
slashCommands: "slash commands",
projectFiles: "project files",
effortTitle: "reasoning_effort — applies next turn",
effortMaxTitle: "max (default — best quality)",
effortHighTitle: "high (cheaper / faster)",
presetTitle: "preset — model commitment",
presetAutoTitle:
"auto — flash baseline; auto-escalates to pro on hard turns (NEEDS_PRO / failure threshold)",
presetFlashTitle:
"flash — always flash; no auto-escalate. /pro still works for one-shot manual",
presetProTitle:
"pro — always pro; ~3× flash cost (5/31 discount). Locks in on hard architecture work.",
effortMaxTitle: "max (DeepSeek extension)",
effortHighTitle: "high (safe default — vLLM / Azure compatible)",
effortMediumTitle: "medium",
effortLowTitle: "low (fastest)",
editGateTitle: "edit gate — Shift+Tab cycles in TUI",
editReviewTitle: "review — both edits and non-allowlisted shell ask first",
editAutoTitle: "auto — edits auto-apply, shell still asks",
@@ -694,6 +933,12 @@ export const en = {
shellBgTitle: "background process",
shellSubtitle: "model wants to run a shell command",
shellBgSubtitle: "long-running — keeps running after approval",
pathTitle: "file outside sandbox",
pathSubtitle: "{intent} via {tool}",
pathRead: "read",
pathWrite: "write",
pathSandboxLabel: "sandbox",
pathAllowPrefixLabel: "allow prefix",
runOnce: "Run once",
alwaysAllow: 'Always allow "{prefix}"',
deny: "Deny",
@@ -758,4 +1003,322 @@ export const en = {
hoursAgo: "{n}h ago",
daysAgo: "{n}d ago",
},
cards: {
applied: "Applied",
cacheHit: "Cache hit",
checkpointRewind: "Checkpoint Rewind",
cost: "Cost",
diffApply: "Apply",
diffApplyChanges: "Apply Changes",
diffAwaiting: "Awaiting review",
diffDiscard: "Discard",
done: "Done",
elapsed: "Elapsed",
error: "Error",
errorName: "Error",
failed: "Failed",
hits: "Hits",
memoryCountSuffix: "memories",
memoryName: "Memory",
output: "Output",
planDefaultTitle: "Plan",
prompt: "Prompt",
compactionMeta: "{chars} chars",
compactionName: "Compacted history",
reasoningComplete: "Reasoning complete",
reasoningName: "Reasoning",
result: "Result",
running: "Running",
searchName: "Search",
shellAlwaysAllow: "Always Allow",
shellAwaiting: "Awaiting approval",
shellExecuteHint: "Execute this command?",
shellReject: "Reject",
shellRun: "Run",
shellRunning: "Running",
streaming: "Streaming",
subagentDone: "Subagent done",
subagentDoneProgress: "Subagent done ({pct}%)",
subagentFailed: "Subagent failed",
subagentRunning: "Subagent running",
},
planBadge: {
blocked: "Blocked",
done: "Done",
failed: "Failed",
pending: "Pending",
running: "Running",
},
composer: {
atHeader: "Mention files",
close: "Close",
commandPalette: "Command Palette",
commands: "Commands",
commandsLabel: "Commands",
confirm: "Confirm",
imageFilterName: "Images",
insertFile: "Insert File",
insertImage: "Insert Image",
interrupt: "Interrupt",
mentionFiles: "Mention Files",
mentionLabel: "Mention",
newline: "New Line",
noMatches: "No matches",
placeholder: "Type a prompt…",
queue: "Queue",
queueCount: "{count} queued",
select: "Select",
send: "Send",
slashHeader: "Slash Commands",
switchModel: "Switch Model",
switchEffort: "Switch Reasoning Effort",
workspaceRoot: "Workspace Root",
},
contextPanel: {
allow: "Allow",
ask: "Ask",
autoApproveTitle: "Auto-approve",
cacheKey: "Cache",
contextTokens: "Context tokens",
fileInContext: "In context",
fileModified: "Modified",
filesCount: "{count} files",
filesTab: "Files",
filesTitle: "Files",
freeKey: "Free",
itemCount: "{count} items",
mcpConfigured: "Configured",
mcpConnecting: "Connecting…",
mcpDisabled: "Disabled",
mcpEmpty: "No MCP servers",
mcpFailed: "Failed",
mcpReady: "Ready",
mcpReadyAll: "All ready",
mcpReadySome: "Some ready",
mcpTitle: "MCP",
mcpTools: "Tools",
memoryTab: "Memory",
memoryTitle: "Memory",
noFilesMsg: "No files in context",
noMemoriesMsg: "No memories",
reservedKey: "Reserved",
ruleReadOnly: "Read-only",
ruleReview: "Review",
ruleShellAllowlist: "Shell allowlist",
rulesTab: "Rules",
ruleWritesAsk: "Writes ask",
ruleYolo: "YOLO",
scopeGlobal: "Global",
scopeProject: "Project",
toolsTab: "Tools",
usedKey: "Used",
},
dragDrop: {
overlay: "Drop files here",
},
extraCards: {
approve: "Approve",
balance: "Balance",
cache: "Cache",
cacheHit: "Cache hit",
contextWindow: "Context window",
doctorTitle: "Diagnostics",
output: "Output",
prompt: "Prompt",
reasoning: "Reasoning",
reject: "Reject",
sessionCost: "Session cost",
sessionUsage: "Session usage",
topToolsUsage: "Top tools",
unknownKind: "Unknown",
memoryUser: "User",
memoryFeedback: "Feedback",
memoryProject: "Project",
memoryReference: "Reference",
},
jobs: {
empty: "No background jobs",
exited: "Exited",
kbClose: "Close",
kbToggle: "Toggle",
running: "Running",
stop: "Stop",
stopAll: "Stop All",
stopAllTip: "Stop all jobs",
stopOne: "Stop",
title: "Background Jobs",
},
live: {
deliveredWaiting: "Waiting for next message",
reasoning: "Reasoning",
running: "Running",
secondsAgo: "{n}s ago",
you: "You",
},
markdown: {
copied: "Copied!",
copy: "Copy",
externalLinkTitle: "Open in new tab",
filePillTitle: "Open file",
localLinkTitle: "Open link",
},
palette: {
abort: "Abort",
abortHint: "Abort current request",
about: "About",
clearChat: "Clear Chat",
clearChatHint: "Clear conversation",
closeTab: "Close Tab",
closeTabHint: "Close current tab",
copyConv: "Copy Conversation",
copyConvHint: "Copy conversation as Markdown",
copyLast: "Copy Last Response",
copyLastHint: "Copy last assistant message",
countSuffix: "items",
empty: "No matching commands",
exportMd: "Export as Markdown",
exportMdHint: "Export chat as Markdown file",
focusComposer: "Focus Composer",
footClose: "Close",
footMove: "Move",
footRun: "Run",
groupAction: "Actions",
groupNav: "Navigation",
groupSettings: "Settings",
groupWorkspace: "Workspace",
newChat: "New Chat",
newChatHint: "Start a new conversation",
newTab: "New Tab",
newTabHint: "Open a new tab",
pickWorkspace: "Switch Workspace",
pickWorkspaceHint: "Change workspace",
searchPlaceholder: "Search commands…",
settings: "Settings",
settingsHint: "Open settings",
},
panel: {
renderError: "Panel crashed",
},
sidebarPanel: {
approvalRules: "Approval Rules",
cancel: "Cancel",
commandPalette: "Command Palette",
daysAgo: "{n}d ago",
delete: "Delete",
deleteSession: "Delete Session",
hoursAgo: "{n}h ago",
justNow: "Just now",
loading: "Loading…",
messageCount: "{count} messages",
minutesAgo: "{n}m ago",
newChat: "New Chat",
noMatches: "No matches",
noSessions: "No sessions",
recent: "Recent",
searchSessions: "Search sessions…",
sessionTitle: "Sessions",
settings: "Settings",
weeksAgo: "{n}w ago",
},
statusbar: {
balance: "Balance",
busy: "Busy",
cache: "Cache",
cacheHit: "Cache hit",
jobs: "Jobs",
jobsTip: "Background jobs",
offline: "Offline",
online: "Online",
switchCurrency: "Switch currency",
switchTheme: "Switch theme",
switchWorkspace: "Switch workspace",
themeDark: "Dark",
themeLight: "Light",
themeStyleGraphite: "Graphite",
themeStyleSandstone: "Sandstone",
themeStylePorcelain: "Porcelain",
themeStyleMidnight: "Midnight",
thisTurn: "This turn",
tokens: "Tokens",
},
thread: {
activePlan: "Active plan",
allowRead: "Allow read",
allowWrite: "Allow write",
alwaysAllow: "Always allow",
alwaysAllowPrefix: "Always allow {prefix}",
approve: "Approve",
approveRewrite: "Approve rewrite",
cancel: "Cancel",
checkpointKind: "Checkpoint",
checkpointSub: "Save current state",
checkpointTitle: "Create checkpoint",
collapse: "Collapse",
continue: "Continue",
copyMessage: "Copy message",
copyResponse: "Copy response",
execute: "Execute",
keepOriginal: "Keep original",
keepSteps: "Keep steps",
optionCount: "{count} options",
pathAccessKind: "Path access",
planConfirmationKind: "Plan approval",
planRevisionKind: "Plan revision",
planRunning: "Plan in progress",
planStepCount: "Step {done}/{total}",
readPathOutsideSandbox: "Read path outside sandbox",
refine: "Refine",
reject: "Reject",
revise: "Revise",
revisionMeta: "Revision",
rewritePlan: "Rewrite plan",
risk: "Risk assessment",
riskMedium: "Medium risk",
runBackgroundCommand: "Run in background",
runCommand: "Run command",
shellConfirmationKind: "Shell confirmation",
startPlan: "Start plan",
stop: "Stop",
subagent: "Subagent",
userChoiceKind: "User choice",
writePathOutsideSandbox: "Write path outside sandbox",
you: "You",
},
workdir: {
browse: "Browse…",
cancel: "Cancel",
empty: "No workspaces",
emptyDir: "No subdirectories.",
go: "Go",
goTip: "Navigate to this path",
loading: "Loading…",
openHere: "Open this folder",
pathPlaceholder: "Absolute path…",
promptWeb: "Enter the absolute path of the workspace to open:",
searchPlaceholder: "Search workspaces…",
title: "Workspace",
},
about: {
close: "Close",
repo: "Repository",
sidebarLabel: "About",
tagline: "AI-powered coding assistant",
version: "Version",
},
effort: {
lowDesc: "fastest — minimal reasoning",
mediumDesc: "balanced",
highDesc: "default — safe for vLLM / Azure",
maxDesc: "DeepSeek extension; rejected by stock OpenAI / vLLM",
},
editMode: {
plan: "Plan",
planHint: "read-only · all write tools refuse to dispatch",
review: "Review",
reviewHint: "both edits and non-allowlisted shell ask first",
auto: "Auto",
autoHint: "edits auto-apply, shell still asks",
yolo: "YOLO",
yoloHint: "edits AND shell auto-run, allowlist bypassed",
},
};
+105 -6
View File
@@ -1,8 +1,107 @@
import { createT } from "../lib/i18n.js";
import { en } from "./en.js";
import { zhCN } from "./zh-CN.js";
import { useEffect, useState } from "react";
import { de } from "./de";
import { en } from "./en";
import { zhCN } from "./zh-CN";
export { getLang, initLangFromServer, setLang, useLang, onLangChange } from "../lib/i18n.js";
export type { DashboardLang } from "../lib/i18n.js";
export type Lang = "en" | "zh-CN" | "de";
export const t = createT({ en, "zh-CN": zhCN });
const SUPPORTED_LANGS: readonly Lang[] = ["en", "zh-CN", "de"];
const SUPPORTED: ReadonlySet<Lang> = new Set<Lang>(SUPPORTED_LANGS);
const LANG_LABELS: Record<Lang, string> = { en: "English", "zh-CN": "简体中文", de: "Deutsch" };
const STORAGE_KEY = "reasonix.lang";
type Listener = () => void;
const listeners: Listener[] = [];
function detectDefault(): Lang {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored && SUPPORTED.has(stored as Lang)) return stored as Lang;
} catch {
/* private mode */
}
const nav = typeof navigator !== "undefined" ? navigator.language : "";
const lower = nav.toLowerCase();
if (lower.startsWith("zh")) return "zh-CN";
if (lower.startsWith("de")) return "de";
return "en";
}
let currentLang: Lang = detectDefault();
function syncHtmlLang(lang: Lang): void {
if (typeof document === "undefined") return;
try {
document.documentElement.lang = lang;
} catch {
/* document not ready */
}
}
syncHtmlLang(currentLang);
export function getLang(): Lang {
return currentLang;
}
export function getSupportedLangs(): readonly Lang[] {
return SUPPORTED_LANGS;
}
export function getLangLabel(lang: Lang): string {
return LANG_LABELS[lang];
}
export function setLang(lang: Lang): void {
if (!SUPPORTED.has(lang) || lang === currentLang) return;
currentLang = lang;
try {
localStorage.setItem(STORAGE_KEY, lang);
} catch {
/* ignore */
}
syncHtmlLang(lang);
for (const cb of listeners) cb();
}
export function useLang(): Lang {
const [, setTick] = useState(0);
useEffect(() => {
const cb = () => setTick((n) => n + 1);
listeners.push(cb);
return () => {
const idx = listeners.indexOf(cb);
if (idx >= 0) listeners.splice(idx, 1);
};
}, []);
return currentLang;
}
const dicts = { en, "zh-CN": zhCN, de } as const;
type Dict = typeof en;
type Path<T, K extends keyof T = keyof T> = K extends string
? T[K] extends Record<string, unknown>
? `${K}.${Path<T[K]>}`
: K
: never;
export type TKey = Path<Dict>;
function resolve(dict: Dict, key: string): string {
const parts = key.split(".");
let cursor: unknown = dict;
for (const p of parts) {
if (cursor && typeof cursor === "object" && p in (cursor as Record<string, unknown>)) {
cursor = (cursor as Record<string, unknown>)[p];
} else {
return key;
}
}
return typeof cursor === "string" ? cursor : key;
}
export function t(key: TKey, params?: Record<string, string | number>): string {
const raw = resolve(dicts[currentLang], key);
if (!params) return raw;
return raw.replace(/\{(\w+)\}/g, (_, k) => (k in params ? String(params[k]) : `{${k}}`));
}
+587 -21
View File
@@ -23,6 +23,111 @@ export const zhCN = {
themeToggle: "切换主题",
themeLight: "浅色",
themeDark: "深色",
skill: {
scope: {
builtin: "内置",
global: "全局",
project: "项目",
},
runAs: {
subagent: "子代理",
inline: "内联",
},
generic: "技能",
},
exportReasoningSummary: "推理摘要",
exportToolLabel: "工具调用",
exportUserLabel: "用户消息",
empty: {
currentWorkspace: "当前工作区",
selectWorkspace: "选择一个工作区开始",
suggestion0: "开始新对话",
suggestion1: "打开设置",
suggestion2: "查看概览",
suggestion3: "浏览会话",
welcome: "欢迎使用 Reasonix",
},
errorLabel: "错误",
connecting: "连接中…",
session: {
format: "会话",
new: "新建会话",
},
setup: {
choose: "选择工作区",
description: "选择一个工作区开始工作",
notSelected: "未选择工作区",
saveAndStart: "保存并开始",
welcome: "欢迎",
workspace: "工作区",
},
tab: {
newTab: "+ 新建标签",
newTabTitle: "打开新标签",
},
titlebar: {
clearChat: "清除对话",
close: "关闭",
commandPalette: "命令面板",
contextPanel: "上下文面板",
copyMd: "复制为 Markdown",
exportMd: "导出为 Markdown",
maximize: "最大化",
minimize: "最小化",
more: "更多",
restore: "还原",
settings: "设置",
sidebar: "侧边栏",
windowControls: "窗口控制",
},
toast: {
cleared: "对话已清除",
copied: "已复制到剪贴板",
copiedMd: "已复制为 Markdown",
emptySession: "无消息可导出",
exportDialogTitle: "导出对话",
exportedMd: "已导出为 Markdown",
exportFailed: "导出失败",
langSwitched: "语言已切换",
modelSwitched: "模型 → {model}",
effortSwitched: "强度 → {effort}",
modeSwitched: "模式已切换",
newSession: "新会话已创建",
},
yolo: {
toast: "YOLO 模式已启用",
},
cmd: {
abort: "中止",
btw: "顺便说一下",
clearChat: "清除对话",
compact: "紧凑",
copyLast: "复制上条",
exportMd: "导出为 Markdown",
feedback: "反馈",
help: "帮助",
newSession: "新建会话",
retry: "重试",
switchModel: "切换模型",
toggleCurrency: "切换货币",
toggleLang: "切换语言",
toggleTheme: "切换主题",
},
header: {
abort: "中止",
clickToSelect: "点击选择",
copy: "复制",
copyMd: "复制为 Markdown",
export: "导出",
exportMd: "导出为 Markdown",
newChat: "新建对话",
noWorkspace: "无工作区",
running: "运行中…",
},
jumpToBottom: "跳到底部",
langEN: "English",
langZH: "中文",
splashSubtitle: "AI 驱动的编程助手",
},
changes: {
chatPlaceholder: "询问代码问题…",
@@ -56,6 +161,8 @@ export const zhCN = {
commentLine: "第",
commentEdit: "编辑",
commentDelete: "删除",
diffSourceGit: "Git 变更",
diffSourceSession: "上一轮变更",
diffSourceCheckpoint: "检查点",
checkpointEmpty: "暂无检查点",
restoreBtn: "恢复",
@@ -66,8 +173,6 @@ export const zhCN = {
createPlaceholder: "检查点名称…",
backToList: "返回列表",
reviewEmpty: "暂无可审查的更改",
diffSourceGit: "Git 变更",
diffSourceSession: "上一轮变更",
diffStyleUnified: "统一视图",
diffStyleSplit: "分栏视图",
expandAll: "全部展开",
@@ -101,29 +206,44 @@ export const zhCN = {
saved: "已保存:{fields}",
sectionApi: "DeepSeek API",
apiKey: "API 密钥",
apiKeyNotSet: "未设置",
apiKeySave: "保存密钥",
apiKeySet: "已设置",
apiSection: "API 配置",
notSet: "(未设置)",
replace: "替换",
pasteKey: "粘贴新的 sk-… 令牌",
saveKey: "保存密钥",
baseUrl: "基础 URL",
baseUrlPlaceholder: "https://api.deepseek.com(默认)",
baseUrlHint: "API 请求的基础 URL",
sectionDefaults: "默认设置",
preset: "预设",
presetAuto: "auto — flash 基线,困难时自动升级为 pro",
presetFlash: "flash — 始终使用 flash,不自动升级",
presetPro: "pro — 始终使用 pro",
effortSection: "推理强度",
modelCustom: "自定义模型 ID",
modelCustomHint: "任何 OpenAI 兼容的 ID(vLLM、Ollama、Together …)。",
modelCustomActive: "当前运行自定义 ID:{model}",
appliesNextTurn: "下一轮生效",
effort: "推理强度",
effortMax: "max(默认 — 最佳质量)",
effortHigh: "high(更便宜 / 更快)",
effortMax: "max(DeepSeek 扩展 — 标准 OpenAI / vLLM 会拒绝)",
effortHigh: "high(安全默认 — vLLM / Azure 兼容)",
effortMedium: "medium",
effortLow: "low(最快)",
webSearch: "网页搜索",
webSearchNote: "web_fetch + web_search 工具",
sectionCompute: "计算",
proNext: "/pro 单轮",
proArm: "为下一轮装备",
proArmed: "已装备 — 下一轮后自动解除",
proNextNote: "下一轮使用 deepseek-v4-pro,之后自动解除",
webSearchEngine: "搜索引擎",
webSearchEngineBing: "bing — 默认,国内裸 IP 直连,无需代理",
webSearchEngineSearxng: "searxng — 自托管(端点用 /se searxng <url> 配置)",
webSearchEngineMetaso: "metaso — 每日 100 次免费(国内友好,metaso.cn 可领免费 key)",
webSearchEngineTavily: "tavily — 每月 1000 次免费(设置 TAVILY_API_KEY)",
webSearchEnginePerplexity: "perplexity — AI 直接回答(设置 PERPLEXITY_API_KEY)",
webSearchEngineExa: "exa — AI 直接回答,每月 1000 次免费(设置 EXA_API_KEY)",
webSearchEngineBrave: "brave — 独立索引,每月 2000 次免费(设置 BRAVE_SEARCH_API_KEY)",
webSearchEngineOllama: "ollama — Ollama 云端网页搜索(设置 OLLAMA_API_KEY)",
webSearchEngineNote: "下一次 web_search 调用生效",
sectionBudget: "预算",
budget: "预算",
budgetHint: "设置支出限额",
budgetPlaceholder: "输入预算金额",
budgetOf: "/",
budgetSetCap: "设置上限",
budgetCustom: "自定义",
@@ -149,21 +269,145 @@ export const zhCN = {
skillPaths: "技能路径",
skillPathsPlaceholder: "/path/to/skills-a, /path/to/skills-b",
skillPathsNote: "英文逗号分隔 · 下次 /new 或新会话生效",
skillsEmpty: "无已加载技能",
skillsLoaded: "技能已加载",
subagentModelFlash: "flash",
subagentModelPro: "pro",
subagentModelHint: "技能派生独立 subagent 时使用的模型",
sectionRuntime: "运行时",
activeModel: "当前模型",
model: "模型",
modelFlashDesc: "Flash — 始终 flash",
modelProDesc: "Pro — 始终 pro",
modelPricingLine: "${hit} 命中 · ${miss} 未命中 · ${out} 输出 / 100 万 tok",
editMode: "编辑模式",
editModeNote: "在对话标签页头部切换",
editModeHint: "配置编辑模式",
showSystemEvents: "系统事件",
showSystemEventsHint: "在对话流中以细线显示压缩 / 中断 / 限速等系统事件",
shown: "显示",
hidden: "隐藏",
appMode: "应用模式",
sectionLanguage: "语言",
language: "语言",
languageHint: "切换语言",
langEn: "English",
langZhCn: "简体中文",
appearanceSection: "外观",
behaviorSection: "行为",
ruleAutoApprovalHint: "配置自动审批规则",
ruleAutoApprovalSection: "自动审批规则",
theme: "主题",
themeDark: "深色",
themeHint: "在浅色和深色主题之间切换",
themeLight: "浅色",
themeStyle: "主题风格",
themeStyleHint: "选择主题风格",
themeStyleGraphite: "石墨",
themeStyleGraphiteDesc: "冷色深色调,适合长时间使用。",
themeStyleSandstone: "砂岩",
themeStyleSandstoneDesc: "暖色浅色调,明亮环境更舒适。",
themeStylePorcelain: "瓷白",
themeStylePorcelainDesc: "高对比度浅色,简洁清爽。",
themeStyleMidnight: "午夜",
themeStyleMidnightDesc: "深色配冷色高光,更深邃。",
pageGeneralLabel: "通用",
pageGeneralDesc: "主题、字体、语言与工作目录。",
pageModelsLabel: "模型",
pageModelsDesc: "默认模型与推理强度。",
pageMcpLabel: "MCP 服务器",
pageMcpDesc: "接入外部工具服务器。",
pageSkillsLabel: "技能",
pageSkillsDesc: "可通过 /skill 调用的自定义技能。",
pageMemoryLabel: "记忆",
pageMemoryDesc: "跨会话保留的长期笔记。",
pageRulesLabel: "规则",
pageRulesDesc: "Shell 与路径访问的自动审批规则。",
pageBillingLabel: "账单",
pageBillingDesc: "API key、余额与会话预算。",
pageShortcutsLabel: "快捷键",
pageShortcutsDesc: "键盘快捷键参考。",
fontFamily: "字体",
fontFamilyHint: "选择字体",
fontFamilySans: "无衬线",
fontFamilySerif: "衬线",
fontFamilySystem: "系统",
fontScale: "字体大小",
fontScaleHint: "调整字体大小",
fontScaleLarge: "大",
fontScaleMedium: "中",
fontScaleSmall: "小",
currentWorkspace: "当前工作区",
defaultModelCurrent: "当前模型",
editor: "编辑器",
editorHint: "配置编辑器偏好",
maxOutput: "最大输出",
reasoningEffort: "推理强度",
reasoningEffortHint: "调整推理深度",
sessionCost: "会话成本",
balanceAvailable: "可用",
balanceLabel: "余额",
balanceLow: "余额不足",
cacheHitRate: "缓存命中率",
ctxWindow: "上下文窗口",
notSelected: "未选择",
parseError: "解析错误",
workspaceChange: "更改",
workspaceSection: "工作区",
mcpAdd: "添加",
mcpAddSection: "添加 MCP 服务器",
mcpBridged: "已桥接",
mcpConfigured: "已配置",
mcpEmpty: "无 MCP 服务器",
mcpNotBridged: "未桥接",
mcpRemove: "移除",
mcpSpecFormat: "JSON 格式",
mcpSpecLabel: "服务器规格",
memoryDesc: "配置记忆设置",
memorySection: "记忆",
shortcutAbort: "中止",
shortcutCloseTab: "关闭标签",
shortcutCommandPalette: "命令面板",
shortcutFocusComposer: "聚焦编辑器",
shortcutNewChat: "新建对话",
shortcutNewTab: "新建标签",
shortcutSettings: "设置",
shortcutSwitchTab: "切换标签",
qqAccessAllowlist: "允许列表",
qqAccessOpen: "开放",
qqAccessOwner: "所有者",
qqAccessOwnerWithAllowlist: "所有者 + 允许列表",
qqAccessRuntime: "运行时",
qqAppId: "App ID",
qqApplyAction: "应用",
qqApplyLabel: "应用",
qqAppSecret: "App Secret",
qqBack: "返回",
qqConfigure: "配置",
qqConfigureHint: "设置 QQ 集成",
qqConfigureTitle: "QQ 配置",
qqConnected: "已连接",
qqConnecting: "连接中…",
qqDisconnected: "已断开",
qqEnvironment: "环境",
qqFailed: "失败",
qqProduction: "生产环境",
qqSandbox: "沙箱环境",
qqSave: "保存",
qqSaveAndConnect: "保存并连接",
qqSection: "QQ 集成",
qqSummaryAppId: "App ID",
qqSummaryDetail: "详情",
qqSummaryMissing: "未配置",
qqTitle: "QQ 机器人",
},
chat: {
modeMirror: "TUI 镜像",
modeView: "会话视图",
placeholder: "输入提示词 — Enter 发送,Shift+Enter 换行 · / @ 打开选择器",
placeholderBusy: "请等待当前轮次完成…",
placeholderSteerBusy: "输入消息以引导当前任务 — 忙碌时不支持命令和选择器",
steerHint: "消息将作为附加指示引导当前轮次",
send: "发送",
new: "新建",
clear: "清除",
@@ -179,18 +423,16 @@ export const zhCN = {
eventStreamError: "事件流中断 — 正在重连…",
semanticBanner: "此项目未启用语义搜索。",
semanticBannerDesc:
"构建一次索引,模型即可按含义查找代码(“哪里处理认证失败?”),而不仅依赖精确字符串的 grep。",
"构建一次索引,模型即可按含义查找代码(\u201C哪里处理认证失败?\u201D),而不仅依赖精确字符串的 grep。",
semanticBannerBtn: "构建 →",
semanticBannerDismiss: "关闭(不再显示)",
slashCommands: "斜杠命令",
projectFiles: "项目文件",
effortTitle: "reasoning_effort — 下一轮生效",
effortMaxTitle: "max(默认 — 最佳质量)",
effortHighTitle: "high(更便宜 / 更快)",
presetTitle: "预设 — 模型承诺",
presetAutoTitle: "auto — flash 基线;困难轮次自动升级为 pro(NEEDS_PRO / 失败阈值)",
presetFlashTitle: "flash — 始终 flash;不自动升级。/pro 仍可用于一次性手动提升",
presetProTitle: "pro — 始终 pro;约 3 倍 flash 成本(5/31 折扣)。锁定困难的架构工作。",
effortMaxTitle: "max(DeepSeek 扩展)",
effortHighTitle: "high(安全默认 — vLLM / Azure 兼容)",
effortMediumTitle: "medium",
effortLowTitle: "low(最快)",
editGateTitle: "编辑门控 — Shift+Tab 在 TUI 中循环",
editReviewTitle: "review — 编辑和非允许列表的 shell 命令都会先询问",
editAutoTitle: "auto — 编辑自动应用,shell 仍会询问",
@@ -584,7 +826,7 @@ export const zhCN = {
builtWith: "构建来源",
currentTarget: "当前目标",
incompatibleHint:
"磁盘上的这个索引是为不同的 provider 或 model 构建的。运行“完全重建”即可替换。",
"磁盘上的这个索引是为不同的 provider 或 model 构建的。运行\u201C完全重建\u201D即可替换。",
runIndexHint: "运行索引以启用 semantic_search。",
reIndex: "重建索引",
build: "构建",
@@ -667,6 +909,12 @@ export const zhCN = {
shellBgTitle: "后台进程",
shellSubtitle: "模型想要运行一条 Shell 命令",
shellBgSubtitle: "长时间运行 — 批准后继续运行",
pathTitle: "沙箱外文件访问",
pathSubtitle: "{intent} · 通过 {tool}",
pathRead: "读取",
pathWrite: "写入",
pathSandboxLabel: "沙箱",
pathAllowPrefixLabel: "允许前缀",
runOnce: "运行一次",
alwaysAllow: '始终允许 "{prefix}"',
deny: "拒绝",
@@ -730,4 +978,322 @@ export const zhCN = {
hoursAgo: "{n} 小时前",
daysAgo: "{n} 天前",
},
cards: {
applied: "已应用",
cacheHit: "缓存命中",
checkpointRewind: "检查点回退",
cost: "费用",
diffApply: "应用",
diffApplyChanges: "应用更改",
diffAwaiting: "待审阅",
diffDiscard: "丢弃",
done: "完成",
elapsed: "耗时",
error: "错误",
errorName: "错误",
failed: "失败",
hits: "命中",
memoryCountSuffix: "条记忆",
memoryName: "记忆",
output: "输出",
planDefaultTitle: "计划",
prompt: "提示词",
compactionMeta: "{chars} 字符",
compactionName: "已压缩历史",
reasoningComplete: "推理完成",
reasoningName: "推理",
result: "结果",
running: "运行中",
searchName: "搜索",
shellAlwaysAllow: "始终允许",
shellAwaiting: "待审批",
shellExecuteHint: "执行此命令?",
shellReject: "拒绝",
shellRun: "运行",
shellRunning: "运行中",
streaming: "输出中",
subagentDone: "子代理完成",
subagentDoneProgress: "子代理完成 ({pct}%)",
subagentFailed: "子代理失败",
subagentRunning: "子代理运行中",
},
planBadge: {
blocked: "已阻塞",
done: "完成",
failed: "失败",
pending: "待处理",
running: "运行中",
},
composer: {
atHeader: "提及文件",
close: "关闭",
commandPalette: "命令面板",
commands: "命令",
commandsLabel: "命令",
confirm: "确认",
imageFilterName: "图片",
insertFile: "插入文件",
insertImage: "插入图片",
interrupt: "中断",
mentionFiles: "提及文件",
mentionLabel: "提及",
newline: "换行",
noMatches: "无匹配",
placeholder: "输入提示词…",
queue: "队列",
queueCount: "{count} 个排队",
select: "选择",
send: "发送",
slashHeader: "斜杠命令",
switchModel: "切换模型",
switchEffort: "切换推理强度",
workspaceRoot: "工作区根目录",
},
contextPanel: {
allow: "允许",
ask: "询问",
autoApproveTitle: "自动审批",
cacheKey: "缓存",
contextTokens: "上下文 tokens",
fileInContext: "在上下文中",
fileModified: "已修改",
filesCount: "{count} 个文件",
filesTab: "文件",
filesTitle: "文件",
freeKey: "空闲",
itemCount: "{count} 个项目",
mcpConfigured: "已配置",
mcpConnecting: "连接中…",
mcpDisabled: "已禁用",
mcpEmpty: "无 MCP 服务器",
mcpFailed: "失败",
mcpReady: "就绪",
mcpReadyAll: "全部就绪",
mcpReadySome: "部分就绪",
mcpTitle: "MCP",
mcpTools: "工具",
memoryTab: "记忆",
memoryTitle: "记忆",
noFilesMsg: "上下文中无文件",
noMemoriesMsg: "无记忆",
reservedKey: "保留",
ruleReadOnly: "只读",
ruleReview: "审阅",
ruleShellAllowlist: "Shell 允许列表",
rulesTab: "规则",
ruleWritesAsk: "写入需询问",
ruleYolo: "YOLO",
scopeGlobal: "全局",
scopeProject: "项目",
toolsTab: "工具",
usedKey: "已用",
},
dragDrop: {
overlay: "拖放文件到此处",
},
extraCards: {
approve: "批准",
balance: "余额",
cache: "缓存",
cacheHit: "缓存命中",
contextWindow: "上下文窗口",
doctorTitle: "诊断",
output: "输出",
prompt: "提示词",
reasoning: "推理",
reject: "拒绝",
sessionCost: "会话成本",
sessionUsage: "会话用量",
topToolsUsage: "热门工具",
unknownKind: "未知",
memoryUser: "用户",
memoryFeedback: "反馈",
memoryProject: "项目",
memoryReference: "参考",
},
jobs: {
empty: "无后台任务",
exited: "已退出",
kbClose: "关闭",
kbToggle: "切换",
running: "运行中",
stop: "停止",
stopAll: "全部停止",
stopAllTip: "停止所有任务",
stopOne: "停止",
title: "后台任务",
},
live: {
deliveredWaiting: "等待下一条消息",
reasoning: "推理",
running: "运行中",
secondsAgo: "{n} 秒前",
you: "你",
},
markdown: {
copied: "已复制!",
copy: "复制",
externalLinkTitle: "在新标签中打开",
filePillTitle: "打开文件",
localLinkTitle: "打开链接",
},
palette: {
abort: "中止",
abortHint: "中止当前请求",
about: "关于",
clearChat: "清除对话",
clearChatHint: "清除对话",
closeTab: "关闭标签",
closeTabHint: "关闭当前标签",
copyConv: "复制对话",
copyConvHint: "复制对话为 Markdown",
copyLast: "复制上条回复",
copyLastHint: "复制上条助手消息",
countSuffix: "个项目",
empty: "无匹配命令",
exportMd: "导出为 Markdown",
exportMdHint: "导出对话为 Markdown 文件",
focusComposer: "聚焦编辑器",
footClose: "关闭",
footMove: "移动",
footRun: "运行",
groupAction: "操作",
groupNav: "导航",
groupSettings: "设置",
groupWorkspace: "工作区",
newChat: "新建对话",
newChatHint: "开始新对话",
newTab: "新建标签",
newTabHint: "打开新标签",
pickWorkspace: "切换工作区",
pickWorkspaceHint: "更改工作区",
searchPlaceholder: "搜索命令…",
settings: "设置",
settingsHint: "打开设置",
},
panel: {
renderError: "面板崩溃",
},
sidebarPanel: {
approvalRules: "审批规则",
cancel: "取消",
commandPalette: "命令面板",
daysAgo: "{n} 天前",
delete: "删除",
deleteSession: "删除会话",
hoursAgo: "{n} 小时前",
justNow: "刚刚",
loading: "加载中…",
messageCount: "{count} 条消息",
minutesAgo: "{n} 分钟前",
newChat: "新建对话",
noMatches: "无匹配",
noSessions: "无会话",
recent: "最近",
searchSessions: "搜索会话…",
sessionTitle: "会话",
settings: "设置",
weeksAgo: "{n} 周前",
},
statusbar: {
balance: "余额",
busy: "忙碌",
cache: "缓存",
cacheHit: "缓存命中",
jobs: "任务",
jobsTip: "后台任务",
offline: "离线",
online: "在线",
switchCurrency: "切换货币",
switchTheme: "切换主题",
switchWorkspace: "切换工作区",
themeDark: "深色",
themeLight: "浅色",
themeStyleGraphite: "石墨",
themeStyleSandstone: "砂岩",
themeStylePorcelain: "瓷白",
themeStyleMidnight: "午夜",
thisTurn: "本轮",
tokens: "Tokens",
},
thread: {
activePlan: "活跃计划",
allowRead: "允许读取",
allowWrite: "允许写入",
alwaysAllow: "始终允许",
alwaysAllowPrefix: "始终允许 {prefix}",
approve: "批准",
approveRewrite: "批准重写",
cancel: "取消",
checkpointKind: "检查点",
checkpointSub: "保存当前状态",
checkpointTitle: "创建检查点",
collapse: "折叠",
continue: "继续",
copyMessage: "复制消息",
copyResponse: "复制回复",
execute: "执行",
keepOriginal: "保留原始",
keepSteps: "保留步骤",
optionCount: "{count} 个选项",
pathAccessKind: "路径访问",
planConfirmationKind: "计划审批",
planRevisionKind: "计划修订",
planRunning: "计划进行中",
planStepCount: "步骤 {done}/{total}",
readPathOutsideSandbox: "沙箱外读取路径",
refine: "优化",
reject: "拒绝",
revise: "修订",
revisionMeta: "修订",
rewritePlan: "重写计划",
risk: "风险评估",
riskMedium: "中等风险",
runBackgroundCommand: "后台运行",
runCommand: "运行命令",
shellConfirmationKind: "Shell 确认",
startPlan: "启动计划",
stop: "停止",
subagent: "子代理",
userChoiceKind: "用户选择",
writePathOutsideSandbox: "沙箱外写入路径",
you: "你",
},
workdir: {
browse: "浏览…",
cancel: "取消",
empty: "无工作区",
emptyDir: "无子目录。",
go: "前往",
goTip: "跳转到该路径",
loading: "加载中…",
openHere: "打开此目录",
pathPlaceholder: "绝对路径…",
promptWeb: "输入要打开的工作区绝对路径:",
searchPlaceholder: "搜索工作区…",
title: "工作区",
},
about: {
close: "关闭",
repo: "仓库",
sidebarLabel: "关于",
tagline: "AI 驱动的编程助手",
version: "版本",
},
effort: {
lowDesc: "最快 — 极少推理",
mediumDesc: "平衡",
highDesc: "默认 — vLLM / Azure 安全",
maxDesc: "DeepSeek 扩展;标准 OpenAI / vLLM 会拒绝",
},
editMode: {
plan: "计划",
planHint: "只读模式 · 所有写工具都不会派发",
review: "审阅",
reviewHint: "编辑和非允许列表的 shell 命令都会先询问",
auto: "自动",
autoHint: "编辑自动应用,shell 仍会询问",
yolo: "YOLO",
yoloHint: "编辑和 shell 都自动运行,绕过允许列表",
},
};
+81
View File
@@ -0,0 +1,81 @@
import type { SVGProps } from "react";
type IconProps = SVGProps<SVGSVGElement> & { size?: number };
function Ic({ size = 14, children, ...rest }: IconProps & { children: React.ReactNode }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
{...rest}
>
{children}
</svg>
);
}
export const I = {
plus: (p: IconProps) => (<Ic {...p}><path d="M12 5v14M5 12h14" /></Ic>),
search: (p: IconProps) => (<Ic {...p}><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></Ic>),
send: (p: IconProps) => (<Ic {...p}><path d="M4 12 20 4l-6 16-3-7-7-1Z" /></Ic>),
chev: (p: IconProps) => (<Ic {...p}><path d="m6 9 6 6 6-6" /></Ic>),
chevR: (p: IconProps) => (<Ic {...p}><path d="m9 6 6 6-6 6" /></Ic>),
check: (p: IconProps) => (<Ic {...p}><path d="m5 12 5 5L20 7" /></Ic>),
x: (p: IconProps) => (<Ic {...p}><path d="M6 6l12 12M18 6 6 18" /></Ic>),
terminal: (p: IconProps) => (<Ic {...p}><rect x="3" y="4" width="18" height="16" rx="2" /><path d="m7 9 3 3-3 3M13 15h4" /></Ic>),
brain: (p: IconProps) => (
<Ic {...p}>
<path d="M9 4a3 3 0 0 0-3 3v0a3 3 0 0 0-2 5 3 3 0 0 0 2 5 3 3 0 0 0 3 3h0a3 3 0 0 0 3-3V4" />
<path d="M15 4a3 3 0 0 1 3 3 3 3 0 0 1 2 5 3 3 0 0 1-2 5 3 3 0 0 1-3 3" />
</Ic>
),
list: (p: IconProps) => (<Ic {...p}><path d="M4 6h2M4 12h2M4 18h2M9 6h11M9 12h11M9 18h11" /></Ic>),
diff: (p: IconProps) => (<Ic {...p}><path d="M7 4v11a3 3 0 0 0 3 3h2M17 20V9a3 3 0 0 0-3-3h-2" /><circle cx="7" cy="20" r="2" /><circle cx="17" cy="4" r="2" /></Ic>),
globe: (p: IconProps) => (<Ic {...p}><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" /></Ic>),
link: (p: IconProps) => (<Ic {...p}><path d="M10 14a4 4 0 0 1 0-6l3-3a4 4 0 0 1 6 6l-2 2" /><path d="M14 10a4 4 0 0 1 0 6l-3 3a4 4 0 0 1-6-6l2-2" /></Ic>),
wrench: (p: IconProps) => (<Ic {...p}><path d="M14 7a4 4 0 1 0 4 4l3 3-3 3-3-3a4 4 0 0 1-4-4l-3-3-3 3 3 3a4 4 0 0 0 6 0" /></Ic>),
bot: (p: IconProps) => (<Ic {...p}><rect x="4" y="7" width="16" height="12" rx="3" /><path d="M12 3v4M8 12h.01M16 12h.01M9 16h6" /></Ic>),
archive: (p: IconProps) => (<Ic {...p}><rect x="3" y="3" width="18" height="5" rx="1" /><path d="M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M10 12h4" /></Ic>),
bookmark: (p: IconProps) => (<Ic {...p}><path d="M6 3h12v18l-6-4-6 4Z" /></Ic>),
warning: (p: IconProps) => (<Ic {...p}><path d="M12 3 2 21h20Z" /><path d="M12 10v5M12 18h.01" /></Ic>),
zap: (p: IconProps) => (<Ic {...p}><path d="M13 3 4 14h7l-1 7 9-11h-7Z" /></Ic>),
database: (p: IconProps) => (<Ic {...p}><ellipse cx="12" cy="5" rx="8" ry="3" /><path d="M4 5v6c0 1.7 3.6 3 8 3s8-1.3 8-3V5M4 11v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6" /></Ic>),
cpu: (p: IconProps) => (<Ic {...p}><rect x="5" y="5" width="14" height="14" rx="2" /><rect x="9" y="9" width="6" height="6" /><path d="M9 2v3M15 2v3M9 19v3M15 19v3M2 9h3M2 15h3M19 9h3M19 15h3" /></Ic>),
coin: (p: IconProps) => (<Ic {...p}><circle cx="12" cy="12" r="9" /><path d="M12 7v10M9 10h4a2 2 0 0 1 0 4H9" /></Ic>),
file: (p: IconProps) => (<Ic {...p}><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9Z" /><path d="M14 3v6h6" /></Ic>),
folder: (p: IconProps) => (<Ic {...p}><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z" /></Ic>),
image: (p: IconProps) => (<Ic {...p}><rect x="3" y="4" width="18" height="16" rx="2" /><circle cx="9" cy="10" r="2" /><path d="m3 18 5-5 4 4 3-3 6 6" /></Ic>),
paperclip: (p: IconProps) => (<Ic {...p}><path d="M21 12 12 21a5 5 0 0 1-7-7L14 5a3 3 0 0 1 4 4l-9 9a1 1 0 0 1-2-2l8-8" /></Ic>),
mic: (p: IconProps) => (<Ic {...p}><rect x="9" y="3" width="6" height="12" rx="3" /><path d="M5 11a7 7 0 0 0 14 0M12 18v3M9 21h6" /></Ic>),
sun: (p: IconProps) => (<Ic {...p}><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.5 1.5M17.5 17.5 19 19M5 19l1.5-1.5M17.5 6.5 19 5" /></Ic>),
moon: (p: IconProps) => (<Ic {...p}><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z" /></Ic>),
panel_l: (p: IconProps) => (<Ic {...p}><rect x="3" y="4" width="18" height="16" rx="2" /><path d="M9 4v16" /></Ic>),
panel_r: (p: IconProps) => (<Ic {...p}><rect x="3" y="4" width="18" height="16" rx="2" /><path d="M15 4v16" /></Ic>),
cog: (p: IconProps) => (<Ic {...p}><path d="M12 3.6 19.2 7.8v8.4L12 20.4 4.8 16.2V7.8Z" /><circle cx="12" cy="12" r="3.7" /></Ic>),
stop: (p: IconProps) => (<Ic {...p}><rect x="6" y="6" width="12" height="12" rx="2" /></Ic>),
play: (p: IconProps) => (<Ic {...p}><path d="M7 5v14l12-7Z" /></Ic>),
more: (p: IconProps) => (<Ic {...p}><circle cx="6" cy="12" r="1.6" fill="currentColor" /><circle cx="12" cy="12" r="1.6" fill="currentColor" /><circle cx="18" cy="12" r="1.6" fill="currentColor" /></Ic>),
pin: (p: IconProps) => (<Ic {...p}><path d="M15 3 9 9l-4 1 9 9 1-4 6-6ZM4 20l5-5" /></Ic>),
rotate: (p: IconProps) => (<Ic {...p}><path d="M3 12a9 9 0 1 0 3-6.7L3 8" /><path d="M3 3v5h5" /></Ic>),
branch: (p: IconProps) => (<Ic {...p}><circle cx="6" cy="4" r="2" /><circle cx="6" cy="20" r="2" /><circle cx="18" cy="8" r="2" /><path d="M6 6v12M6 14a6 6 0 0 0 6-6h4" /></Ic>),
at: (p: IconProps) => (<Ic {...p}><circle cx="12" cy="12" r="4" /><path d="M16 8v6a3 3 0 0 0 5-2 9 9 0 1 0-4 7" /></Ic>),
slash: (p: IconProps) => (<Ic {...p}><path d="M16 4 8 20" /></Ic>),
layers: (p: IconProps) => (<Ic {...p}><path d="m12 3 9 5-9 5-9-5Z" /><path d="m3 13 9 5 9-5M3 18l9 5 9-5" /></Ic>),
download: (p: IconProps) => (<Ic {...p}><path d="M12 4v12M6 12l6 6 6-6M4 20h16" /></Ic>),
upload: (p: IconProps) => (<Ic {...p}><path d="M12 20V8M6 12l6-6 6 6M4 4h16" /></Ic>),
history: (p: IconProps) => (<Ic {...p}><path d="M3 12a9 9 0 1 0 3-6.7L3 8M12 7v5l3 2" /></Ic>),
shield: (p: IconProps) => (<Ic {...p}><path d="M12 3 4 6v6c0 5 3.5 8 8 9 4.5-1 8-4 8-9V6Z" /><path d="m9 12 2 2 4-4" /></Ic>),
warn: (p: IconProps) => (<Ic {...p}><path d="M12 3 2 21h20Z" /><path d="M12 10v5M12 18h.01" /></Ic>),
help: (p: IconProps) => (<Ic {...p}><circle cx="12" cy="12" r="9" /><path d="M9.5 9a2.5 2.5 0 0 1 5 0c0 1.5-2.5 2-2.5 4M12 17h.01" /></Ic>),
refresh: (p: IconProps) => (<Ic {...p}><path d="M3 12a9 9 0 0 1 15-6.7L21 8M21 4v4h-4M21 12a9 9 0 0 1-15 6.7L3 16M3 20v-4h4" /></Ic>),
copy: (p: IconProps) => (<Ic {...p}><rect x="8" y="8" width="12" height="12" rx="2" /><path d="M4 16V6a2 2 0 0 1 2-2h10" /></Ic>),
};
export type IconKey = keyof typeof I;
-48
View File
@@ -1,48 +0,0 @@
export const TOKEN: string =
document.querySelector('meta[name="reasonix-token"]')?.getAttribute("content") ?? "";
export const MODE: "standalone" | "attached" =
(document.querySelector('meta[name="reasonix-mode"]')?.getAttribute("content") as
| "standalone"
| "attached"
| null) ?? "standalone";
export interface ApiOptions {
method?: string;
headers?: Record<string, string>;
body?: unknown;
}
export interface ApiError extends Error {
status: number;
body: unknown;
}
export async function api<T = unknown>(path: string, opts: ApiOptions = {}): Promise<T> {
const method = opts.method ?? "GET";
const url = `/api${path}${path.includes("?") ? "&" : "?"}token=${TOKEN}`;
const headers: Record<string, string> = { ...(opts.headers ?? {}) };
headers["X-Reasonix-Token"] = TOKEN;
if (opts.body !== undefined) headers["Content-Type"] = "application/json";
const res = await fetch(url, {
method,
headers,
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
});
const text = await res.text();
let parsed: unknown = null;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
parsed = { error: text };
}
if (!res.ok) {
const errMsg =
(parsed as { error?: string } | null)?.error ?? `${res.status} ${res.statusText}`;
const err = new Error(errMsg) as ApiError;
err.status = res.status;
err.body = parsed;
throw err;
}
return parsed as T;
}
-45
View File
@@ -1,45 +0,0 @@
export type BudgetState =
| { kind: "off"; spent: number }
| { kind: "running"; cap: number; spent: number; pct: number }
| { kind: "warn"; cap: number; spent: number; pct: number }
| { kind: "exhausted"; cap: number; spent: number; pct: number };
export function deriveBudgetState(
cap: number | null | undefined,
spent: number | null | undefined,
): BudgetState {
const safeSpent = typeof spent === "number" && spent >= 0 ? spent : 0;
if (typeof cap !== "number" || cap <= 0) {
return { kind: "off", spent: safeSpent };
}
const pct = (safeSpent / cap) * 100;
if (pct >= 100) return { kind: "exhausted", cap, spent: safeSpent, pct };
if (pct >= 80) return { kind: "warn", cap, spent: safeSpent, pct };
return { kind: "running", cap, spent: safeSpent, pct };
}
/** Default quick-cap menu — round dollar amounts users actually pick. */
export const QUICK_CAPS_USD: ReadonlyArray<number> = [1, 5, 10, 25, 50];
/** 1.5× / 2× / 4× the current cap, snapped to a "nice" round number per bucket. */
export function bumpSuggestions(currentCap: number): number[] {
if (currentCap <= 0) return [];
return [niceUp(currentCap * 1.5), niceUp(currentCap * 2), niceUp(currentCap * 4)];
}
function niceUp(n: number): number {
// Subtract a tiny epsilon before ceil so FP noise (0.4 * 1.5 = 0.6000…01)
// doesn't bump a value to the next bucket.
const eps = 1e-9;
if (n < 1) return Math.ceil((n - eps) * 10) / 10;
if (n < 10) return Math.ceil((n - eps) * 2) / 2;
if (n < 100) return Math.ceil(n - eps);
return Math.ceil((n - eps) / 5) * 5;
}
/** Tone class shared between the cockpit tile and the settings gauge. */
export function budgetTone(state: BudgetState): "" | "warn" | "err" {
if (state.kind === "exhausted") return "err";
if (state.kind === "warn") return "warn";
return "";
}
-13
View File
@@ -1,13 +0,0 @@
/** Browser extensions (userscripts, ad blockers) inject scripts that throw into our window. Their errors land in the global handlers as if they were ours — see #818. Filter them by origin. */
const THIRD_PARTY_ORIGIN_PREFIXES = [
"chrome-extension://",
"moz-extension://",
"safari-web-extension://",
"safari-extension://",
"ms-browser-extension://",
];
export function isThirdPartyError(error: unknown, filename?: string): boolean {
const hay = `${filename ?? ""}\n${(error as { stack?: string } | null)?.stack ?? ""}`;
return THIRD_PARTY_ORIGIN_PREFIXES.some((prefix) => hay.includes(prefix));
}
-68
View File
@@ -1,68 +0,0 @@
import htm from "htm";
import { h } from "preact";
import { useEffect, useState } from "preact/hooks";
import { isThirdPartyError } from "./bus-filter.js";
const html = htm.bind(h);
export const appBus = new EventTarget();
export const toastBus = new EventTarget();
export type ToastKind = "info" | "success" | "warn" | "error";
export function showToast(text: string, kind: ToastKind = "info", ttl = 3000): void {
toastBus.dispatchEvent(new CustomEvent("toast", { detail: { text, kind, ttl } }));
}
export interface ErrorReport {
error: unknown;
source: string;
info?: string;
ts: number;
}
export function reportAppError(error: unknown, source: string, info?: string): void {
console.error(`[reasonix dashboard] ${source}:`, error, info);
appBus.dispatchEvent(
new CustomEvent("error", { detail: { error, source, info, ts: Date.now() } }),
);
}
window.addEventListener("error", (ev) => {
if (!ev.error) return;
if (isThirdPartyError(ev.error, ev.filename)) return;
reportAppError(ev.error, "window", ev.message);
});
window.addEventListener("unhandledrejection", (ev) => {
if (isThirdPartyError(ev.reason)) return;
reportAppError(ev.reason, "promise");
});
interface Toast {
id: string;
text: string;
kind: ToastKind;
ttl: number;
}
export function ToastStack() {
const [toasts, setToasts] = useState<Toast[]>([]);
useEffect(() => {
const onToast = (ev: Event) => {
const detail = (ev as CustomEvent).detail as Omit<Toast, "id">;
const id = `${Date.now()}-${Math.random()}`;
const t: Toast = { id, ...detail };
setToasts((prev) => [...prev, t]);
setTimeout(() => setToasts((prev) => prev.filter((x) => x.id !== id)), t.ttl);
};
toastBus.addEventListener("toast", onToast);
return () => toastBus.removeEventListener("toast", onToast);
}, []);
if (toasts.length === 0) return null;
return html`
<div class="toast-stack">
${toasts.map((t) => html`<div key=${t.id} class="toast ${t.kind}">${t.text}</div>`)}
</div>
`;
}
-80
View File
@@ -1,80 +0,0 @@
export type HunkLineType = "add" | "del" | "ctx";
export interface HunkLine {
type: HunkLineType;
content: string;
oldLineNum?: number;
newLineNum?: number;
}
export interface Hunk {
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
lines: HunkLine[];
}
/** Parse a unified diff patch string into structured hunk arrays. No external deps. */
export function parseHunks(patch: string): Hunk[] {
if (!patch) return [];
const hunks: Hunk[] = [];
const rawLines = patch.split("\n");
let cursor = 0;
// Skip file headers (--- a/..., +++ b/...)
while (cursor < rawLines.length) {
const line = rawLines[cursor]!;
// Start of a hunk: @@ -oldStart[,oldLines] +newStart[,newLines] @@
const m = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
if (m) {
const oldStart = parseInt(m[1]!, 10);
const oldLen = m[2] !== undefined ? parseInt(m[2], 10) : 1;
const newStart = parseInt(m[3]!, 10);
const newLen = m[4] !== undefined ? parseInt(m[4], 10) : 1;
const lines: HunkLine[] = [];
let oldNum = oldStart;
let newNum = newStart;
cursor++;
while (
cursor < rawLines.length &&
!rawLines[cursor]!.startsWith("@@ ") &&
!rawLines[cursor]!.startsWith("diff ") &&
!rawLines[cursor]!.startsWith("--- ") &&
!rawLines[cursor]!.startsWith("index ")
) {
const l = rawLines[cursor]!;
if (l.startsWith("\\")) {
cursor++;
continue;
}
const ch = l[0]!;
const content = l.slice(1);
if (ch === "-") {
lines.push({ type: "del", content, oldLineNum: oldNum });
oldNum++;
} else if (ch === "+") {
lines.push({ type: "add", content, newLineNum: newNum });
newNum++;
} else {
lines.push({ type: "ctx", content, oldLineNum: oldNum, newLineNum: newNum });
oldNum++;
newNum++;
}
cursor++;
}
hunks.push({ oldStart, oldLines: oldLen, newStart, newLines: newLen, lines });
} else {
cursor++;
}
}
return hunks;
}
-158
View File
@@ -1,158 +0,0 @@
import htm from "htm";
import { Component, type ComponentChildren, h } from "preact";
import { useEffect, useState } from "preact/hooks";
import { t } from "../i18n/index.js";
import { MODE } from "./api.js";
import { type ErrorReport, appBus, reportAppError } from "./bus.js";
const html = htm.bind(h);
const REPO_URL = "https://github.com/esengine/reasonix";
function buildIssueBody({ error, source, info }: ErrorReport): string {
const ua = typeof navigator === "object" ? navigator.userAgent : "(unknown)";
const errMsg = (error as Error)?.message ?? String(error);
const stack = (error as Error)?.stack ?? "(no stack)";
return [
"**What happened**",
"(describe what you were doing — typing, switching tabs, clicking a tool path, etc.)",
"",
"**Error**",
"```",
`${source}: ${errMsg}`,
info ? `info: ${info}` : null,
"",
stack,
"```",
"",
"**Environment**",
`- Reasonix: ${MODE}`,
`- Browser: ${ua}`,
`- URL: ${location.pathname} (token redacted)`,
"",
"_Reported from the local dashboard's error overlay._",
]
.filter((l): l is string => l !== null)
.join("\n");
}
export function ErrorOverlay() {
const [err, setErr] = useState<ErrorReport | null>(null);
const [copied, setCopied] = useState(false);
useEffect(() => {
const onError = (ev: Event) => {
setErr((ev as CustomEvent).detail as ErrorReport);
setCopied(false);
};
appBus.addEventListener("error", onError);
return () => appBus.removeEventListener("error", onError);
}, []);
useEffect(() => {
if (!err) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setErr(null);
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [err]);
if (!err) return null;
const error = err.error as Error | undefined;
const errMsg = error?.message ?? String(error);
const stack = error?.stack ?? "(no stack)";
const issueUrl = `${REPO_URL}/issues/new?title=${encodeURIComponent(`[dashboard] ${errMsg.slice(0, 80)}`)}&body=${encodeURIComponent(buildIssueBody(err))}`;
const copyDetails = async () => {
try {
await navigator.clipboard.writeText(buildIssueBody(err));
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
/* clipboard blocked — user can still hit "report on GitHub" */
}
};
return html`
<div class="error-overlay">
<div class="error-overlay-card">
<div class="error-overlay-head">
<span class="error-overlay-icon">✦</span>
<div>
<div class="error-overlay-title">${t("error.title")}</div>
<div class="error-overlay-subtitle">${err.source} error · ${errMsg}</div>
</div>
</div>
<pre class="error-overlay-trace">${stack}</pre>
${
err.info
? html`<div class="error-overlay-info"><strong>info:</strong> ${err.info}</div>`
: null
}
<div class="error-overlay-help">
${t("error.body")}
</div>
<div class="error-overlay-actions">
<button class="primary" onClick=${copyDetails}>
${copied ? t("error.copied") : t("error.copyDetails")}
</button>
<a class="button" href=${issueUrl} target="_blank" rel="noopener noreferrer">
${t("error.reportOnGithub")}
</a>
<button onClick=${() => setErr(null)} style="margin-left: auto;">${t("error.dismiss")}</button>
</div>
</div>
</div>
`;
}
interface ErrorBoundaryProps {
children: ComponentChildren;
}
interface ErrorBoundaryState {
caught: boolean;
lastErr: Error | null;
attempts: number;
}
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { caught: false, lastErr: null, attempts: 0 };
}
static override getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
return { caught: true, lastErr: error };
}
override componentDidCatch(error: Error, info: { componentStack?: string }) {
reportAppError(error, "render", info?.componentStack ?? "");
const attempts = (this.state.attempts ?? 0) + 1;
if (attempts >= 3) {
this.setState({ attempts });
return;
}
setTimeout(() => this.setState({ caught: false, attempts }), 100);
}
override render() {
if (this.state.caught) {
if ((this.state.attempts ?? 0) >= 3) {
return html`
<div class="boot" style="flex-direction: column; gap: 12px;">
<div>${t("error.crashing", { name: "the error overlay has the trace" })}</div>
<button onClick=${() => this.setState({ caught: false, attempts: 0 })}>
${t("error.retry")}
</button>
</div>
`;
}
return html`<div class="boot">${t("error.recovering")}</div>`;
}
return this.props.children;
}
}
-232
View File
@@ -1,232 +0,0 @@
import { h } from "preact";
import { useState, useCallback, useEffect } from "preact/hooks";
import htm from "htm";
import { api, MODE } from "./api.js";
const html = htm.bind(h);
export interface TreeNode {
name: string;
path: string;
isDir: boolean;
children?: TreeNode[];
}
export interface OpenFile {
path: string;
name: string;
content: string;
language: string;
}
const EXT_ICONS: Record<string, string> = {
ts: "TS", tsx: "TS", js: "JS", jsx: "JS",
json: "{}", css: "#", scss: "#", html: "<>",
md: "MD", py: "PY", rs: "RS", go: "GO",
yaml: "Y", yml: "Y", toml: "T", xml: "<>",
svg: "<>", png: "[]", jpg: "[]", ico: "[]",
sh: "$", bash: "$", ps1: "$", bat: "$",
sql: "DB", graphql: "GQ", proto: "PB",
dockerfile: "D", makefile: "MK",
};
const EXT_LANG: Record<string, string> = {
ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript",
json: "json", css: "css", scss: "scss", html: "html",
md: "markdown", py: "python", rs: "rust", go: "go",
yaml: "yaml", yml: "yaml", toml: "toml", xml: "xml",
sh: "bash", bash: "bash", ps1: "powershell", bat: "batch",
sql: "sql", graphql: "graphql", proto: "protobuf",
dockerfile: "dockerfile", makefile: "makefile",
};
export function getFileIcon(name: string): { icon: string; cls: string } {
const ext = name.split(".").pop()?.toLowerCase() ?? "";
const icon = EXT_ICONS[ext] ?? "·";
const cls = ext || "file";
return { icon, cls };
}
export function getLanguage(name: string): string {
const ext = name.split(".").pop()?.toLowerCase() ?? "";
return EXT_LANG[ext] ?? ext;
}
function isBinaryExt(name: string): boolean {
const ext = name.split(".").pop()?.toLowerCase() ?? "";
const binary = new Set(["png", "jpg", "jpeg", "gif", "ico", "svg", "woff", "woff2", "ttf", "eot", "mp4", "webm", "mp3", "wav", "zip", "tar", "gz", "7z", "pdf"]);
return binary.has(ext);
}
interface ProjectTreeResult {
tree: TreeNode[];
}
export function useProjectTree() {
const [tree, setTree] = useState<TreeNode[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (MODE === "standalone") {
setLoading(false);
setTree(createDemoTree());
return;
}
let cancelled = false;
api<ProjectTreeResult>("/project-tree")
.then((r) => {
if (!cancelled) {
setTree(r.tree);
setLoading(false);
}
})
.catch((err) => {
if (!cancelled) {
setError((err as Error).message);
setLoading(false);
setTree(createDemoTree());
}
});
return () => { cancelled = true; };
}, []);
return { tree, loading, error };
}
interface FileReadResult {
content: string;
path: string;
size: number;
}
interface FileLoadingState {
[path: string]: boolean;
}
export function useFileTreeState(initialTree: TreeNode[]) {
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const [openFiles, setOpenFiles] = useState<OpenFile[]>([]);
const [activeFilePath, setActiveFilePath] = useState<string | null>(null);
const [loadingFiles, setLoadingFiles] = useState<FileLoadingState>({});
const toggleExpand = useCallback((path: string) => {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(path)) next.delete(path);
else next.add(path);
return next;
});
}, []);
const openFile = useCallback(async (node: TreeNode) => {
if (node.isDir) {
toggleExpand(node.path);
return;
}
if (isBinaryExt(node.name)) return;
const existing = openFiles.find((f) => f.path === node.path);
if (existing) {
setActiveFilePath(node.path);
return;
}
if (loadingFiles[node.path]) return;
setLoadingFiles((prev) => ({ ...prev, [node.path]: true }));
const lang = getLanguage(node.name);
if (MODE === "standalone") {
const mockContent = generateMockContent(node.name, lang);
setOpenFiles((prev) => [...prev, { path: node.path, name: node.name, content: mockContent, language: lang }]);
setActiveFilePath(node.path);
setLoadingFiles((prev) => {
const next = { ...prev };
delete next[node.path];
return next;
});
return;
}
try {
const encodedPath = node.path.split("/").map(encodeURIComponent).join("/");
const data = await api<FileReadResult>(`/file/${encodedPath}`);
setOpenFiles((prev) => [...prev, { path: node.path, name: node.name, content: data.content, language: lang }]);
setActiveFilePath(node.path);
} catch (err) {
console.error(`[file-tree] failed to load ${node.path}:`, err);
setOpenFiles((prev) => [...prev, { path: node.path, name: node.name, content: `// Failed to load file: ${(err as Error).message}\n`, language: lang }]);
setActiveFilePath(node.path);
} finally {
setLoadingFiles((prev) => {
const next = { ...prev };
delete next[node.path];
return next;
});
}
}, [openFiles, toggleExpand, loadingFiles]);
const closeFile = useCallback((path: string) => {
setOpenFiles((prev) => {
const next = prev.filter((f) => f.path !== path);
if (activeFilePath === path) {
const lastFile = next[next.length - 1];
setActiveFilePath(lastFile ? lastFile.path : null);
}
return next;
});
}, [activeFilePath]);
const activeFile = openFiles.find((f) => f.path === activeFilePath) ?? null;
return { expanded, openFiles, activeFilePath, activeFile, toggleExpand, openFile, closeFile, setActiveFilePath, loadingFiles };
}
function generateMockContent(name: string, lang: string): string {
const ext = name.split(".").pop()?.toLowerCase() ?? "";
if (ext === "json") return JSON.stringify({ name: "example", version: "1.0.0", dependencies: { react: "^18.0.0" } }, null, 2);
if (ext === "md") return "# Example Document\n\nThis is a sample markdown file.\n\n## Section\n\n- Item 1\n- Item 2\n\n```js\nconsole.log(\"hello\");\n```";
if (ext === "css") return "/* styles */\n.container {\n display: flex;\n padding: 16px;\n color: var(--fg-1);\n}";
if (ext === "html") return "<!doctype html>\n<html>\n<head><title>Example</title></head>\n<body>\n <h1>Hello</h1>\n</body>\n</html>";
if (ext === "py") return "def hello():\n print('Hello, World!')\n\nif __name__ == '__main__':\n hello()";
if (ext === "yaml" || ext === "yml") return "name: example\nversion: '1.0'\nservices:\n app:\n image: node:18\n ports:\n - '3000:3000'";
return `// ${name}\n// Language: ${lang}\n\nexport function example() {\n return \"Hello from ${name}\";\n}\n`;
}
export function createDemoTree(): TreeNode[] {
return [
{
name: "src", path: "src", isDir: true, children: [
{ name: "index.ts", path: "src/index.ts", isDir: false },
{ name: "app.tsx", path: "src/app.tsx", isDir: false },
{ name: "config.ts", path: "src/config.ts", isDir: false },
{
name: "components", path: "src/components", isDir: true, children: [
{ name: "Header.tsx", path: "src/components/Header.tsx", isDir: false },
{ name: "Sidebar.tsx", path: "src/components/Sidebar.tsx", isDir: false },
{ name: "Button.tsx", path: "src/components/Button.tsx", isDir: false },
]
},
{
name: "lib", path: "src/lib", isDir: true, children: [
{ name: "api.ts", path: "src/lib/api.ts", isDir: false },
{ name: "format.ts", path: "src/lib/format.ts", isDir: false },
]
},
]
},
{
name: "tests", path: "tests", isDir: true, children: [
{ name: "app.test.ts", path: "tests/app.test.ts", isDir: false },
{ name: "utils.test.ts", path: "tests/utils.test.ts", isDir: false },
]
},
{ name: "package.json", path: "package.json", isDir: false },
{ name: "tsconfig.json", path: "tsconfig.json", isDir: false },
{ name: "README.md", path: "README.md", isDir: false },
{ name: "styles.css", path: "styles.css", isDir: false },
{ name: "index.html", path: "index.html", isDir: false },
];
}
-69
View File
@@ -1,69 +0,0 @@
import { t } from "../i18n/index.js";
export function fmtUsd(n: number | null | undefined): string {
if (n === null || n === undefined) return "—";
if (n === 0) return "$0";
return `$${n.toFixed(n < 0.01 ? 6 : 4)}`;
}
/** Keep in sync with src/cli/ui/theme/tokens.ts USD_TO_CNY. */
const USD_TO_CNY = 7.2;
/** USD-internal cost rendered in the wallet's display currency. Undefined currency → CNY (matches CLI default). */
export function fmtCost(
usd: number | null | undefined,
currency: string | null | undefined,
fractionDigits?: number,
): string {
if (usd === null || usd === undefined) return "—";
const cur = currency ?? "CNY";
const amount = cur === "CNY" ? usd * USD_TO_CNY : usd;
if (amount === 0) return cur === "CNY" ? "¥0" : "$0";
const sym = cur === "CNY" ? "¥" : cur === "USD" ? "$" : `${cur} `;
const digits = fractionDigits ?? (Math.abs(amount) < 0.01 ? 6 : 4);
return `${sym}${amount.toFixed(digits)}`;
}
export function fmtPct(n: number | null | undefined): string {
if (n === null || n === undefined) return "—";
return `${(n * 100).toFixed(1)}%`;
}
export function fmtNum(n: number | null | undefined): string {
if (n === null || n === undefined) return "—";
return n.toLocaleString();
}
export function fmtBytes(n: number | null | undefined): string {
if (n === null || n === undefined) return "—";
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;
return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
export function fmtCompactNum(n: number | null | undefined): string {
if (n === null || n === undefined) return "—";
if (Math.abs(n) < 1000) return String(n);
if (Math.abs(n) < 1_000_000) {
const v = n / 1000;
return `${v % 1 === 0 ? v.toFixed(0) : v.toFixed(1)}K`;
}
if (Math.abs(n) < 1_000_000_000) {
const v = n / 1_000_000;
return `${v % 1 === 0 ? v.toFixed(0) : v.toFixed(1)}M`;
}
return `${(n / 1_000_000_000).toFixed(1)}B`;
}
export function fmtRelativeTime(iso: string | number | null | undefined): string {
if (!iso) return "—";
const ms = typeof iso === "number" ? iso : Date.parse(iso);
if (!Number.isFinite(ms)) return "—";
const dSec = (Date.now() - ms) / 1000;
if (dSec < 60) return t("fmt.justNow");
if (dSec < 3600) return t("fmt.minutesAgo", { n: Math.floor(dSec / 60) });
if (dSec < 86400) return t("fmt.hoursAgo", { n: Math.floor(dSec / 3600) });
if (dSec < 30 * 86400) return t("fmt.daysAgo", { n: Math.floor(dSec / 86400) });
return new Date(ms).toISOString().slice(0, 10);
}
-4
View File
@@ -1,4 +0,0 @@
import htm from "htm";
import { h } from "preact";
export const html = htm.bind(h);
-117
View File
@@ -1,117 +0,0 @@
import { useEffect, useState } from "preact/hooks";
import { TOKEN, api } from "./api.js";
type Listener = () => void;
export type DashboardLang = "en" | "zh-CN";
// [dashboardCode, backendCode] — add new languages here.
const LANG_REGISTRY: [DashboardLang, string][] = [
["en", "EN"],
["zh-CN", "zh-CN"],
];
const SUPPORTED = new Set(LANG_REGISTRY.map(([d]) => d));
const TO_BACKEND = new Map(LANG_REGISTRY);
const FROM_BACKEND = new Map(LANG_REGISTRY.map(([d, b]) => [b, d]));
const STORAGE_KEY = "rx.lang";
const listeners: Listener[] = [];
let currentLang: DashboardLang = loadFromStorage() ?? "en";
function loadFromStorage(): DashboardLang | null {
try {
const v = localStorage.getItem(STORAGE_KEY);
if (v !== null && SUPPORTED.has(v as DashboardLang)) return v as DashboardLang;
} catch {
/* private mode */
}
return null;
}
function toBackendLang(lang: DashboardLang): string {
return TO_BACKEND.get(lang) ?? lang;
}
function fromBackendLang(raw: string): DashboardLang {
return (FROM_BACKEND.get(raw) as DashboardLang) ?? "en";
}
/** Adopt server lang on startup; localStorage is render-cache only, never pushed back. */
export async function initLangFromServer(): Promise<void> {
try {
const res = await api<{ lang?: string }>("/settings");
const serverLang = res.lang ? fromBackendLang(res.lang) : null;
if (!serverLang || serverLang === currentLang) return;
currentLang = serverLang;
try {
localStorage.setItem(STORAGE_KEY, serverLang);
} catch {
/* ignore */
}
for (const cb of listeners) cb();
} catch {
/* offline — keep last-known value rendering */
}
}
export function getLang(): DashboardLang {
return currentLang;
}
export function setLang(lang: DashboardLang): void {
if (!SUPPORTED.has(lang)) return;
currentLang = lang;
try {
localStorage.setItem(STORAGE_KEY, lang);
} catch {
/* ignore */
}
for (const cb of listeners) cb();
// keepalive ensures the request completes even during page unload (refresh).
fetch(`/api/settings?token=${TOKEN}`, {
method: "POST",
headers: { "Content-Type": "application/json", "X-Reasonix-Token": TOKEN },
body: JSON.stringify({ lang: toBackendLang(lang) }),
keepalive: true,
}).catch((err) => console.error("[reasonix dashboard] lang persist:", err));
}
export function onLangChange(cb: Listener): () => void {
listeners.push(cb);
return () => {
const i = listeners.indexOf(cb);
if (i >= 0) listeners.splice(i, 1);
};
}
export function useLang(): DashboardLang {
const [lang, setLangState] = useState<DashboardLang>(currentLang);
useEffect(() => onLangChange(() => setLangState(currentLang)), []);
return lang;
}
type Nested = { [k: string]: string | Nested };
function get(translations: Nested | undefined, path: string): string | undefined {
let val: string | Nested | undefined = translations;
for (const part of path.split(".")) {
if (val === undefined || typeof val === "string") return undefined;
val = val[part];
}
return typeof val === "string" ? val : undefined;
}
export function createT(translations: Record<string, Nested>) {
return function t(path: string, params?: Record<string, string | number>): string {
let val = get(translations[currentLang] ?? translations.en, path);
if (val === undefined) val = get(translations.en, path);
if (val === undefined) return path;
if (!params) return val;
let result = val;
for (const [k, v] of Object.entries(params)) {
result = result.replaceAll(`{${k}}`, String(v));
}
return result;
};
}
-90
View File
@@ -1,90 +0,0 @@
import { useState, useCallback } from "preact/hooks";
export interface LineComment {
id: string;
file: string;
lineNumber: number;
content: string;
timestamp: number;
}
export interface LineCommentDraft {
file: string;
lineNumber: number;
content: string;
editingId?: string;
}
export function useLineComments() {
const [comments, setComments] = useState<LineComment[]>([]);
const [draft, setDraft] = useState<LineCommentDraft | null>(null);
const addComment = useCallback((file: string, lineNumber: number, content: string) => {
const id = `comment-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
setComments((prev) => [...prev, { id, file, lineNumber, content, timestamp: Date.now() }]);
setDraft(null);
}, []);
const updateComment = useCallback((id: string, content: string) => {
setComments((prev) => prev.map((c) => (c.id === id ? { ...c, content } : c)));
}, []);
const deleteComment = useCallback((id: string) => {
setComments((prev) => prev.filter((c) => c.id !== id));
}, []);
const startDraft = useCallback((file: string, lineNumber: number) => {
setDraft({ file, lineNumber, content: "" });
}, []);
const editComment = useCallback((id: string, content: string) => {
const comment = comments.find((c) => c.id === id);
if (comment) {
setDraft({ file: comment.file, lineNumber: comment.lineNumber, content, editingId: id });
}
}, [comments]);
const cancelDraft = useCallback(() => {
setDraft(null);
}, []);
const setDraftContent = useCallback((content: string) => {
setDraft((prev) => (prev ? { ...prev, content } : null));
}, []);
const submitDraft = useCallback(() => {
if (draft && draft.content.trim()) {
if (draft.editingId) {
updateComment(draft.editingId, draft.content.trim());
} else {
addComment(draft.file, draft.lineNumber, draft.content.trim());
}
setDraft(null);
}
}, [draft, addComment, updateComment]);
const commentsForFile = useCallback(
(file: string) => comments.filter((c) => c.file === file),
[comments],
);
const commentsForLine = useCallback(
(file: string, lineNumber: number) => comments.filter((c) => c.file === file && c.lineNumber === lineNumber),
[comments],
);
return {
comments,
draft,
addComment,
updateComment,
deleteComment,
startDraft,
editComment,
cancelDraft,
setDraftContent,
submitDraft,
commentsForFile,
commentsForLine,
};
}
-48
View File
@@ -1,48 +0,0 @@
export type IntervalUnit = "s" | "m" | "h";
export interface LoopRunStatus {
prompt: string;
intervalMs: number;
iter: number;
/** Wall-clock ms until the next fire — server reports a remaining duration, not an absolute. */
nextFireMs: number;
}
/** Quick-pick intervals in ms — covers the 95% of cases users actually run. */
export const INTERVAL_PRESETS_MS: ReadonlyArray<{ ms: number; label: string }> = [
{ ms: 30_000, label: "30s" },
{ ms: 60_000, label: "1m" },
{ ms: 5 * 60_000, label: "5m" },
{ ms: 15 * 60_000, label: "15m" },
{ ms: 60 * 60_000, label: "1h" },
{ ms: 6 * 60 * 60_000, label: "6h" },
];
const UNIT_TO_MS: Record<IntervalUnit, number> = {
s: 1_000,
m: 60_000,
h: 60 * 60_000,
};
const MIN_INTERVAL_MS = 5_000;
const MAX_INTERVAL_MS = 6 * 60 * 60_000;
/** Convert a "30" + "s" pair to ms, returning null if out of [5s, 6h]. */
export function parseCustomInterval(value: string, unit: IntervalUnit): number | null {
const n = Number.parseFloat(value);
if (!Number.isFinite(n) || n <= 0) return null;
const ms = Math.round(n * UNIT_TO_MS[unit]);
if (ms < MIN_INTERVAL_MS || ms > MAX_INTERVAL_MS) return null;
return ms;
}
/** Human-friendly "5m 12s" / "12s" / "2h 45m" — shows two largest non-zero units. */
export function formatRemaining(ms: number): string {
const safe = Math.max(0, Math.floor(ms / 1000));
const h = Math.floor(safe / 3600);
const m = Math.floor((safe % 3600) / 60);
const s = safe % 60;
if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`;
if (m > 0) return s > 0 ? `${m}m ${s}s` : `${m}m`;
return `${s}s`;
}
-169
View File
@@ -1,169 +0,0 @@
import hljs from "highlight.js/lib/common";
import { marked } from "marked";
export function escapeHtml(s: unknown): string {
if (s == null) return "";
return String(s)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
const SEARCH_REPLACE_RE = /<{7}\s*SEARCH\s*\n([\s\S]*?)\n={7}\s*\n([\s\S]*?)\n>{7}\s*REPLACE/;
export function renderSearchReplace(search: string, replace: string, file: string): string {
const safeSearch = typeof search === "string" ? search : String(search ?? "");
const safeReplace = typeof replace === "string" ? replace : String(replace ?? "");
const oldLines = safeSearch
.split("\n")
.map((l) => `<span class="diff-line del">- ${escapeHtml(l)}</span>`)
.join("\n");
const newLines = safeReplace
.split("\n")
.map((l) => `<span class="diff-line ins">+ ${escapeHtml(l)}</span>`)
.join("\n");
const header = file ? `<span class="diff-line hunk">▸ edit ${escapeHtml(file)}</span>\n` : "";
return `<pre class="diff-block">${header}${oldLines}\n${newLines}</pre>`;
}
export function renderUnifiedDiff(text: string): string {
const safe = typeof text === "string" ? text : String(text ?? "");
const lines = safe
.split("\n")
.map((l) => {
if (l.startsWith("+++") || l.startsWith("---")) {
return `<span class="diff-line meta">${escapeHtml(l)}</span>`;
}
if (l.startsWith("+")) return `<span class="diff-line ins">${escapeHtml(l)}</span>`;
if (l.startsWith("-")) return `<span class="diff-line del">${escapeHtml(l)}</span>`;
if (l.startsWith("@@")) return `<span class="diff-line hunk">${escapeHtml(l)}</span>`;
return escapeHtml(l);
})
.join("\n");
return `<pre class="diff-block">${lines}</pre>`;
}
const renderer = new marked.Renderer();
renderer.code = function reasonixCode(arg1: unknown, arg2?: string): string {
let text: unknown;
let lang: string | undefined;
if (arg1 && typeof arg1 === "object" && !Array.isArray(arg1)) {
text = (arg1 as { text?: unknown }).text;
lang = (arg1 as { lang?: string }).lang;
} else {
text = arg1;
lang = arg2;
}
if (text == null) text = "";
const codeText: string = typeof text === "string" ? text : String(text);
const sr = SEARCH_REPLACE_RE.exec(codeText);
if (sr) {
const [, search = "", replace = ""] = sr;
const file = typeof lang === "string" && lang.startsWith("edit:") ? lang.slice(5) : "";
return renderSearchReplace(search, replace, file);
}
if (lang === "diff") return renderUnifiedDiff(codeText);
if (lang && typeof lang === "string" && hljs.getLanguage(lang)) {
try {
const h = hljs.highlight(codeText, { language: lang, ignoreIllegals: true }).value;
return `<pre><code class="hljs language-${lang}">${h}</code></pre>`;
} catch {
/* fall through to auto */
}
}
try {
const auto = hljs.highlightAuto(codeText);
return `<pre><code class="hljs">${auto.value}</code></pre>`;
} catch {
return `<pre><code>${escapeHtml(codeText)}</code></pre>`;
}
};
marked.use({ renderer, gfm: true, breaks: false, pedantic: false });
export function renderMarkdownToString(text: string): string {
return marked.parse(text) as string;
}
const LANG_BY_EXT: Record<string, string> = {
ts: "typescript",
tsx: "typescript",
js: "javascript",
jsx: "javascript",
mjs: "javascript",
cjs: "javascript",
py: "python",
rs: "rust",
go: "go",
java: "java",
kt: "kotlin",
c: "c",
h: "c",
cpp: "cpp",
cc: "cpp",
hpp: "cpp",
cs: "csharp",
swift: "swift",
rb: "ruby",
php: "php",
sh: "bash",
bash: "bash",
zsh: "bash",
fish: "bash",
ps1: "powershell",
json: "json",
yaml: "yaml",
yml: "yaml",
toml: "ini",
xml: "xml",
html: "xml",
svg: "xml",
css: "css",
scss: "scss",
less: "less",
md: "markdown",
sql: "sql",
vue: "xml",
svelte: "xml",
tex: "latex",
proto: "protobuf",
dockerfile: "dockerfile",
};
export function langFromPath(path: string | null | undefined): string | null {
if (!path) return null;
const lower = path.toLowerCase();
if (lower.endsWith("dockerfile")) return "dockerfile";
const dot = lower.lastIndexOf(".");
if (dot < 0) return null;
const ext = lower.slice(dot + 1);
return LANG_BY_EXT[ext] ?? null;
}
export function renderHighlightedBlock(text: string, lang: string | null | undefined): string {
if (!text) return "";
const safeLang = lang && hljs.getLanguage(lang) ? lang : null;
try {
const out = safeLang
? hljs.highlight(text, { language: safeLang, ignoreIllegals: true })
: hljs.highlightAuto(text);
return `<pre class="md"><code class="hljs ${safeLang ? `language-${safeLang}` : ""}">${out.value}</code></pre>`;
} catch {
return `<pre><code>${escapeHtml(text)}</code></pre>`;
}
}
export function hlLine(text: string | null | undefined, lang: string | null | undefined): string {
if (text == null) return "";
if (text === "") return "";
try {
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(text, { language: lang, ignoreIllegals: true }).value;
}
return hljs.highlightAuto(text).value;
} catch {
return escapeHtml(text);
}
}
-46
View File
@@ -1,46 +0,0 @@
type SpecRecord = Record<string, unknown>;
function isRecord(value: unknown): value is SpecRecord {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function stringField(obj: SpecRecord, key: string): string | null {
const value = obj[key];
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function stringArgs(obj: SpecRecord): string[] {
const args = obj.args;
if (!Array.isArray(args)) return [];
return args.filter((arg): arg is string => typeof arg === "string" && arg.length > 0);
}
export function normalizeMcpSpec(spec: unknown): string | null {
if (typeof spec === "string") return spec;
if (!isRecord(spec)) return null;
const raw = stringField(spec, "raw") ?? stringField(spec, "spec");
if (raw) return raw;
const name = stringField(spec, "name") ?? stringField(spec, "label");
const command = stringField(spec, "command");
const url = stringField(spec, "url");
const transport = stringField(spec, "transport");
if (name && url) return `${name}=${transport === "streamable-http" ? "streamable+" : ""}${url}`;
if (name && command) return `${name}=${[command, ...stringArgs(spec)].join(" ")}`;
if (command) return [command, ...stringArgs(spec)].join(" ");
return null;
}
export function mcpSpecLabel(spec: unknown): string {
const text = normalizeMcpSpec(spec) ?? "";
const eq = text.indexOf("=");
return eq > 0 ? text.slice(0, eq) : text;
}
export function mcpSpecCommand(spec: unknown): string {
const text = normalizeMcpSpec(spec) ?? "";
const eq = text.indexOf("=");
return eq > 0 ? text.slice(eq + 1) : text;
}
-32
View File
@@ -1,32 +0,0 @@
import { useState, useCallback, useEffect } from "preact/hooks";
import { api } from "./api.js";
export interface FileDiff {
file: string;
additions: number;
deletions: number;
patch?: string;
status: "added" | "deleted" | "modified";
}
export function useReviewDiffs() {
const [diffs, setDiffs] = useState<FileDiff[]>([]);
const [loading, setLoading] = useState(false);
const loadDiffs = useCallback(async (ep: string = "/review-diffs") => {
setLoading(true);
try {
const data = await api<FileDiff[]>(ep);
setDiffs(Array.isArray(data) ? data : []);
} catch {
setDiffs([]);
} finally {
setLoading(false);
}
}, []);
const modifiedFiles = useCallback(() => new Set(diffs.map((d) => d.file)), [diffs]);
const modifiedCount = useCallback(() => diffs.length, [diffs]);
return { diffs, loading, modifiedFiles, modifiedCount, reload: loadDiffs };
}
+21
View File
@@ -0,0 +1,21 @@
const SESSION_PARAM = "session";
export function readSessionFromUrl(): string | null {
if (typeof window === "undefined") return null;
const raw = new URLSearchParams(window.location.search).get(SESSION_PARAM);
if (!raw) return null;
const trimmed = raw.trim();
return trimmed.length > 0 ? trimmed : null;
}
export function writeSessionToUrl(name: string | null): void {
if (typeof window === "undefined") return;
const url = new URL(window.location.href);
if (name && name.trim().length > 0) {
url.searchParams.set(SESSION_PARAM, name);
} else {
url.searchParams.delete(SESSION_PARAM);
}
if (url.href === window.location.href) return;
window.history.replaceState(null, "", url.href);
}
File diff suppressed because it is too large. Load diff
-45
View File
@@ -1,45 +0,0 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { type ApiError, api } from "./api.js";
export interface PollResult<T> {
data: T | null;
error: ApiError | Error | null;
loading: boolean;
refresh: () => Promise<void>;
}
export function usePoll<T = unknown>(path: string, intervalMs = 2000): PollResult<T> {
const [data, setData] = useState<T | null>(null);
const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState(true);
const refresh = useCallback(async () => {
try {
const next = await api<T>(path);
setData(next);
setError(null);
} catch (err) {
setError(err as Error);
} finally {
setLoading(false);
}
}, [path]);
useEffect(() => {
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
const tick = async () => {
if (cancelled) return;
await refresh();
if (cancelled) return;
timer = setTimeout(tick, intervalMs);
};
tick();
return () => {
cancelled = true;
if (timer) clearTimeout(timer);
};
}, [refresh, intervalMs]);
return { data, error, loading, refresh };
}
-15
View File
@@ -1,15 +0,0 @@
/** Pre-release with same core sorts BELOW the bare version — matches npm `latest` dist-tag semantics. */
export function compareVersions(a: string, b: string): number {
const [aCore = "0", aPre = ""] = a.split("-", 2);
const [bCore = "0", bPre = ""] = b.split("-", 2);
const aParts = aCore.split(".").map((p) => Number.parseInt(p, 10) || 0);
const bParts = bCore.split(".").map((p) => Number.parseInt(p, 10) || 0);
for (let i = 0; i < 3; i++) {
const diff = (aParts[i] ?? 0) - (bParts[i] ?? 0);
if (diff !== 0) return diff;
}
if (!aPre && !bPre) return 0;
if (!aPre) return 1;
if (!bPre) return -1;
return aPre < bPre ? -1 : aPre > bPre ? 1 : 0;
}
+44
View File
@@ -0,0 +1,44 @@
import "@fontsource/geist/400.css";
import "@fontsource/geist/500.css";
import "@fontsource/geist/600.css";
import "@fontsource/geist/700.css";
import "@fontsource/geist-mono/400.css";
import "@fontsource/geist-mono/500.css";
import "@fontsource/geist-mono/600.css";
import "@fontsource/inter/400.css";
import "@fontsource/inter/500.css";
import "@fontsource/inter/600.css";
import "@fontsource/inter/700.css";
import "./styles.css";
import "katex/dist/katex.min.css";
import { createRoot } from "react-dom/client";
import { App } from "./App";
import {
defaultStyleForTheme,
isTheme,
isThemeStyle,
themeForStyle,
} from "./theme";
const stored = localStorage.getItem("reasonix.theme");
const storedStyle = localStorage.getItem("reasonix.themeStyle");
if (isThemeStyle(storedStyle)) {
document.documentElement.dataset.themeStyle = storedStyle;
document.documentElement.dataset.theme = themeForStyle(storedStyle);
} else if (isTheme(stored)) {
document.documentElement.dataset.theme = stored;
document.documentElement.dataset.themeStyle = defaultStyleForTheme(stored);
}
const platform = /Mac|macOS/i.test(navigator.userAgent)
? "macos"
: /Windows/i.test(navigator.userAgent)
? "windows"
: "default";
document.documentElement.dataset.platform = platform;
document.body.dataset.platform = platform;
const host = document.getElementById("root");
if (!host) throw new Error("#root missing");
createRoot(host).render(<App />);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-259
View File
@@ -1,259 +0,0 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface HookHandler {
command?: string;
matcher?: string;
[k: string]: unknown;
}
interface HookRunRow {
hookName: string;
phase: "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop";
outcome: "ok" | "blocked" | "modified" | "error";
whenMs: number;
}
interface ScopeMeta {
path?: string | null;
hooks?: Record<string, HookHandler[]>;
}
interface MatrixCell {
on: boolean;
matcher?: string;
}
interface MatrixRow {
scope: "project" | "global";
command: string;
cells: Record<string, MatrixCell>;
}
function buildMatrix(data: HooksData): MatrixRow[] {
const rows = new Map<string, MatrixRow>();
for (const scope of ["project", "global"] as const) {
const hooks = data[scope].hooks ?? {};
for (const [event, handlers] of Object.entries(hooks)) {
for (const h of handlers ?? []) {
const cmd = h.command ?? "(no command)";
const key = `${scope}::${cmd}`;
let row = rows.get(key);
if (!row) {
row = { scope, command: cmd, cells: {} };
rows.set(key, row);
}
row.cells[event] = { on: true, matcher: h.matcher };
}
}
}
return [...rows.values()];
}
interface HooksData {
resolved: unknown[];
events: string[];
project: ScopeMeta;
global: ScopeMeta;
recentRuns?: ReadonlyArray<HookRunRow> | null;
}
export function HooksPanel() {
useLang();
const [data, setData] = useState<HooksData | null>(null);
const [error, setError] = useState<string | null>(null);
const [drafts, setDrafts] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(false);
const [info, setInfo] = useState<string | null>(null);
const [eventFilter, setEventFilter] = useState<string>("all");
const load = useCallback(async () => {
try {
const r = await api<HooksData>("/hooks");
setData(r);
setDrafts({
project: JSON.stringify(r.project.hooks ?? {}, null, 2),
global: JSON.stringify(r.global.hooks ?? {}, null, 2),
});
} catch (err) {
setError((err as Error).message);
}
}, []);
useEffect(() => {
load();
}, [load]);
const saveScope = useCallback(
async (scope: "project" | "global") => {
setBusy(true);
setError(null);
let parsed: unknown;
try {
parsed = JSON.parse(drafts[scope] ?? "{}");
} catch (err) {
setError(`${scope} JSON: ${(err as Error).message}`);
setBusy(false);
return;
}
try {
await api("/hooks/save", { method: "POST", body: { scope, hooks: parsed } });
await api("/hooks/reload", { method: "POST", body: {} });
setInfo(t("hooks.savedReloaded", { scope }));
setTimeout(() => setInfo(null), 3000);
await load();
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
},
[drafts, load],
);
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">${t("hooks.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
const sectionH3 = (text: string, sub?: 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}${sub ? html`<span style="margin-left:10px;color:var(--fg-4);font-weight:400;text-transform:none;letter-spacing:0">${sub}</span>` : null}
</h3>
`;
const matrixRows = buildMatrix(data);
const events =
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 ${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 }))}${
visibleRows.length === 0
? html`<div class="card" style="color:var(--fg-3)">
${t("hooks.noHooks")}
</div>`
: html`
<div class="card" style="padding:10px 14px;overflow-x:auto">
<div class="matrix" style=${`min-width:fit-content`}>
<div class="row h" style=${`grid-template-columns:${gridCols}`}>
<div>${t("hooks.colScript")}</div>
${events.map((ev) => html`<div>${ev}</div>`)}
</div>
${visibleRows.map(
(r) => html`
<div class="row" style=${`grid-template-columns:${gridCols}`}>
<div class="cell" title=${r.command}>
<span style="color:var(--fg-4);font-size:10px;margin-right:6px">${r.scope}</span>
<code class="mono" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${r.command}</code>
</div>
${events.map((ev) => {
const c = r.cells[ev];
if (!c?.on) return html`<div class="cell off">—</div>`;
return html`
<div class="cell on" title=${c.matcher ?? ""}>
${c.matcher ? html`<span style="font-size:10px;color:var(--c-warn)">${c.matcher}</span>` : "✓"}
</div>
`;
})}
</div>
`,
)}
</div>
</div>
`
}
${(["project", "global"] as const).map((scope) => {
const meta = data[scope];
return html`
${sectionH3(scope, meta.path ?? "(no path)")}
${
scope === "project" && !meta.path
? html`<div class="card" style="color:var(--fg-3)">
${t("hooks.noProject")}
</div>`
: html`
<div class="card">
<textarea
style="width:100%;height:240px;background:var(--bg-input);color:var(--fg-0);border:1px solid var(--bd);border-radius:var(--r);padding:10px;font-family:var(--font-mono);font-size:12.5px;line-height:1.55;resize:vertical"
value=${drafts[scope] ?? ""}
onInput=${(e: Event) =>
setDrafts({ ...drafts, [scope]: (e.target as HTMLTextAreaElement).value })}
disabled=${busy}
></textarea>
<div style="display:flex;gap:6px;margin-top:8px">
<button class="btn primary" disabled=${busy} onClick=${() => saveScope(scope)}>
${t("hooks.saveReload")}
</button>
<button class="btn ghost" disabled=${busy} onClick=${load}>${t("hooks.discard")}</button>
</div>
</div>
`
}
`;
})}
${sectionH3(t("hooks.recentRuns"), `${data.recentRuns?.length ?? 0}`)}
${
!data.recentRuns || data.recentRuns.length === 0
? html`<div class="card" style="color:var(--fg-3)">
${t("hooks.noRuns")}
</div>`
: html`
<div class="card" style="padding:0;overflow-x:auto">
<table class="tbl" style="width:100%;font-family:var(--font-mono);font-size:11.5px">
<thead>
<tr>
<th style="text-align:left;padding:8px 12px">${t("hooks.colWhen")}</th>
<th style="text-align:left;padding:8px 12px">${t("hooks.colPhase")}</th>
<th style="text-align:left;padding:8px 12px">${t("hooks.colHook")}</th>
<th style="text-align:left;padding:8px 12px">${t("hooks.colOutcome")}</th>
</tr>
</thead>
<tbody>
${data.recentRuns.map(
(r) => html`
<tr>
<td style="padding:6px 12px;color:var(--fg-3)">${fmtRelativeTime(r.whenMs)}</td>
<td style="padding:6px 12px;color:var(--fg-1)">${r.phase}</td>
<td style="padding:6px 12px;color:var(--fg-1)">${r.hookName}</td>
<td style="padding:6px 12px">
<span class=${`pill ${r.outcome === "ok" ? "ok" : r.outcome === "error" ? "err" : "warn"}`}>${r.outcome}</span>
</td>
</tr>
`,
)}
</tbody>
</table>
</div>
`
}
</div>
`;
}
-725
View File
@@ -1,725 +0,0 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { t, useLang } from "../i18n/index.js";
import { api } from "../lib/api.js";
import { fmtNum } from "../lib/format.js";
import { html } from "../lib/html.js";
import {
normalizeMcpSpec,
mcpSpecCommand as specCommand,
mcpSpecLabel as specLabel,
} from "../lib/mcp-spec.js";
interface McpServer {
label: string;
spec: string;
serverInfo?: { name?: string; version?: string };
protocolVersion?: string;
instructions?: string;
toolCount: number;
tools: { name: string; description?: string }[];
resources: { name: string; uri: string }[];
prompts: { name: string; description?: string }[];
}
interface McpData {
servers: McpServer[];
}
interface RegistryInstall {
runtime: string;
packageId?: string;
version?: string;
transport: string;
url?: string;
requiredEnv?: string[];
extraArgs?: string[];
}
interface RegistryEntryDto {
name: string;
title: string;
description: string;
source: "official" | "smithery" | "local";
install?: RegistryInstall;
popularity?: number;
homepage?: string;
iconUrl?: string;
}
/** Mirror of src/mcp/registry-fetch.ts:specStringFor — kept in sync to detect already-installed state without an extra round-trip. */
function specForEntry(e: RegistryEntryDto): string | null {
if (!e.install) return null;
const localName = e.name.split("/").pop() ?? e.name;
const safe = localName.replace(/[^a-zA-Z0-9_-]/g, "-").replace(/^-+|-+$/g, "") || "mcp";
const trail = e.install.extraArgs?.length ? ` ${e.install.extraArgs.join(" ")}` : "";
if (e.install.runtime === "remote" && e.install.url) {
if (e.install.transport === "streamable-http") return `${safe}=streamable+${e.install.url}`;
return `${safe}=${e.install.url}`;
}
if (e.install.runtime === "npm" && e.install.packageId) {
const pinned = e.install.version
? `${e.install.packageId}@${e.install.version}`
: e.install.packageId;
return `${safe}=npx -y ${pinned}${trail}`;
}
if (e.install.runtime === "pypi" && e.install.packageId) {
return `${safe}=uvx ${e.install.packageId}${trail}`;
}
return null;
}
function hideBrokenIcon(ev: Event): void {
(ev.target as HTMLImageElement).style.display = "none";
}
interface RegistryListResponse {
source: "official" | "smithery" | "local";
fromCache: boolean;
fetchedAt: number;
loaded: number;
hasMore: boolean;
matched: number;
entries: RegistryEntryDto[];
errors: string[];
}
type McpFilter = "all" | "live" | "unbridged" | "marketplace";
interface McpFailure {
spec: string;
name: string;
reason: string;
at: number;
}
export function McpPanel() {
useLang();
const [data, setData] = useState<McpData | null>(null);
const [specs, setSpecs] = useState<string[] | null>(null);
const [failures, setFailures] = useState<McpFailure[]>([]);
const [error, setError] = useState<string | null>(null);
const [info, setInfo] = useState<string | null>(null);
const [newSpec, setNewSpec] = useState("");
const [busy, setBusy] = useState(false);
const [open, setOpen] = useState<McpServer | null>(null);
const [openUnbridged, setOpenUnbridged] = useState<string | null>(null);
const [filter, setFilter] = useState<McpFilter>("all");
const [registry, setRegistry] = useState<RegistryListResponse | null>(null);
const [registryQuery, setRegistryQuery] = useState("");
const [registryLoading, setRegistryLoading] = useState(false);
const [openRegistry, setOpenRegistry] = useState<RegistryEntryDto | null>(null);
/** Display cap — grows by 50 each "load more" click. Server caps response size at this. */
const [displayLimit, setDisplayLimit] = useState(50);
const loadRegistry = useCallback(async (q: string, pages: number, limit: number) => {
setRegistryLoading(true);
try {
const params = new URLSearchParams();
if (q.trim()) params.set("q", q.trim());
params.set("pages", String(pages));
params.set("maxPages", String(Math.max(20, pages)));
params.set("limit", String(limit));
const r = await api<RegistryListResponse>(`/mcp/registry?${params.toString()}`);
setRegistry(r);
} catch (err) {
setError((err as Error).message);
} finally {
setRegistryLoading(false);
}
}, []);
useEffect(() => {
if (filter !== "marketplace") return;
if (registry) return;
void loadRegistry("", 1, displayLimit);
}, [filter, registry, loadRegistry, displayLimit]);
useEffect(() => {
if (filter !== "marketplace") return;
// Reset the display cap whenever the user retypes; new query = fresh top-50.
setDisplayLimit(50);
const handle = setTimeout(() => void loadRegistry(registryQuery, 1, 50), 300);
return () => clearTimeout(handle);
}, [registryQuery, filter, loadRegistry]);
const installFromRegistry = useCallback(async (entry: RegistryEntryDto) => {
setBusy(true);
try {
const r = await api<{
added: boolean;
alreadyPresent?: boolean;
bridged?: boolean;
spec: string;
}>("/mcp/registry/install", { method: "POST", body: { name: entry.name } });
if (r.alreadyPresent) {
setInfo(t("mcp.marketplaceAlready"));
} else if (r.bridged) {
setInfo(t("mcp.marketplaceInstalledBridged", { spec: r.spec }));
} else {
setInfo(t("mcp.marketplaceInstalled", { spec: r.spec }));
}
setTimeout(() => setInfo(null), 5000);
// Reload BOTH live + spec lists since hot-reload should have
// attached the new bridge.
await load();
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}, []);
const load = useCallback(async () => {
try {
const mcpData = await api<McpData>("/mcp");
setData({
...mcpData,
servers: (Array.isArray(mcpData.servers) ? mcpData.servers : []).map((server) => ({
...server,
spec: normalizeMcpSpec(server.spec) ?? "",
})),
});
const specResponse = await api<{ specs?: unknown[]; failures?: unknown[] }>("/mcp/specs");
const normalized = (Array.isArray(specResponse.specs) ? specResponse.specs : [])
.map(normalizeMcpSpec)
.filter((spec): spec is string => spec !== null && spec.length > 0);
setSpecs(normalized);
const rawFailures = Array.isArray(specResponse.failures) ? specResponse.failures : [];
const validFailures: McpFailure[] = [];
for (const f of rawFailures) {
if (typeof f !== "object" || f === null) continue;
const o = f as Record<string, unknown>;
const rawSpec = typeof o.spec === "string" ? o.spec : "";
const norm = normalizeMcpSpec(rawSpec);
if (!norm) continue;
validFailures.push({
spec: norm,
name: typeof o.name === "string" ? o.name : "",
reason: typeof o.reason === "string" ? o.reason : "",
at: typeof o.at === "number" ? o.at : 0,
});
}
setFailures(validFailures);
} catch (err) {
setError((err as Error).message);
}
}, []);
useEffect(() => {
load();
}, [load]);
const addSpec = useCallback(async () => {
if (!newSpec.trim()) return;
setBusy(true);
try {
const r = await api<{ requiresRestart?: boolean }>("/mcp/specs", {
method: "POST",
body: { spec: newSpec.trim() },
});
setInfo(r.requiresRestart ? t("mcp.savedRestart") : t("mcp.saved"));
setTimeout(() => setInfo(null), 4000);
setNewSpec("");
await load();
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}, [newSpec, load]);
const removeSpec = useCallback(
async (spec: string) => {
if (!confirm(t("mcp.removeConfirm", { spec }))) return;
setBusy(true);
try {
await api("/mcp/specs", { method: "DELETE", body: { spec } });
setInfo(t("mcp.removed"));
setTimeout(() => setInfo(null), 4000);
await load();
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
},
[load],
);
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">${t("mcp.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
const liveCount = data.servers.length;
const unbridgedSpecs = (specs ?? []).filter((spec) => !data.servers.some((s) => s.spec === spec));
const unbridgedCount = unbridgedSpecs.length;
const showLive = filter === "all" || filter === "live";
const showUnbridged = filter === "all" || filter === "unbridged";
const showMarketplace = filter === "marketplace";
return html`
<div class="sessions-grid">
<div class="sessions-list">
<div class="ssl-h" style="font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
${t("mcp.servers", { count: liveCount })}
</div>
<div style="padding:8px 12px 4px">
<div class="chips">
<span class=${`chip-f ${filter === "all" ? "active" : ""}`} onClick=${() => setFilter("all")}>${t("mcp.all")} <span class="ct">${liveCount + unbridgedCount}</span></span>
<span class=${`chip-f ${filter === "live" ? "active" : ""}`} onClick=${() => setFilter("live")}>${t("mcp.live")} <span class="ct">${liveCount}</span></span>
<span class=${`chip-f ${filter === "unbridged" ? "active" : ""}`} onClick=${() => setFilter("unbridged")}>${t("mcp.unbridged")} <span class="ct">${unbridgedCount}</span></span>
<span class=${`chip-f ${filter === "marketplace" ? "active" : ""}`} onClick=${() => setFilter("marketplace")}>${t("mcp.marketplace")}</span>
</div>
</div>
${
showMarketplace
? html`
<div style="padding:8px 12px;display:flex;gap:6px">
<input
type="text"
placeholder=${t("mcp.marketplaceSearch")}
value=${registryQuery}
onInput=${(e: Event) => setRegistryQuery((e.target as HTMLInputElement).value)}
style="flex:1;font-size:11px"
/>
</div>
${
registry
? html`<div style="padding:0 12px 6px;font-size:11px;color:var(--fg-3)">
${t("mcp.marketplaceCount", {
loaded: registry.loaded,
matched: registry.matched,
source: registry.source,
cached: registry.fromCache ? t("mcp.marketplaceCachedSuffix") : "",
})}
</div>`
: null
}
`
: html`
<div style="padding:8px 12px;display:flex;gap:6px">
<input
type="text"
placeholder=${t("mcp.specPlaceholder")}
value=${newSpec}
onInput=${(e: Event) => setNewSpec((e.target as HTMLInputElement).value)}
style="flex:1;font-size:11px"
/>
<button class="btn primary" disabled=${busy || !newSpec.trim()} onClick=${addSpec}>+</button>
</div>
`
}
${info ? html`<div style="padding:0 12px 8px"><span class="pill ok">${info}</span></div>` : null}
${error ? html`<div class="card accent-err" style="margin:0 12px 8px">${error}</div>` : null}
<div class="ssl-rows">
${
!showMarketplace && liveCount === 0 && unbridgedCount === 0
? html`<div style="color:var(--fg-3);padding:14px;font-size:12px">
${t("mcp.noServers")}
</div>`
: null
}
${
showMarketplace
? renderMarketplaceRows({
registry,
registryLoading,
openRegistry,
setOpenRegistry: (e) => {
setOpenRegistry(e);
setOpen(null);
setOpenUnbridged(null);
},
loadMore: () => {
const nextLimit = displayLimit + 50;
setDisplayLimit(nextLimit);
// Pages: walk far enough to fill the new cap (each page ≈ 30
// entries) plus a few-page lookahead so the next click also
// has fresh data.
const pagesNeeded = Math.ceil(nextLimit / 30) + 3;
void loadRegistry(registryQuery, pagesNeeded, nextLimit);
},
installedSpecs: new Set(specs ?? []),
})
: null
}
${
showLive
? data.servers.map(
(s) => html`
<div
class=${`ssl-row ${open?.label === s.label ? "sel" : ""}`}
onClick=${() => {
setOpen(s);
setOpenUnbridged(null);
}}
>
<span class="name">${s.label} <span class="pill ok">${t("mcp.live")}</span></span>
<span class="preview">${specCommand(s.spec)}</span>
<span class="meta"><span><span class="v">${fmtNum(s.toolCount)}</span> ${t("mcp.tools")}</span></span>
</div>
`,
)
: null
}
${
showUnbridged
? unbridgedSpecs.map((spec) => {
const failure = failures.find((f) => f.spec === spec);
return html`
<div
class=${`ssl-row ${openUnbridged === spec ? "sel" : ""}`}
onClick=${() => {
setOpenUnbridged(spec);
setOpen(null);
}}
>
<span class="name">${specLabel(spec)} <span class=${`pill ${failure ? "err" : ""}`}>${failure ? t("mcp.bridgeFailed") : t("mcp.unbridged")}</span></span>
<span class="preview">${specCommand(spec)}</span>
<span class="meta"><span class=${failure ? "" : "dim"} style=${failure ? "color:var(--c-err)" : ""}>${failure ? failure.reason : t("mcp.inConfig")}</span></span>
</div>
`;
})
: null
}
</div>
</div>
<div class="sessions-detail">
${
openRegistry != null
? renderRegistryDetail({
entry: openRegistry,
busy,
installedSpec: (() => {
const spec = specForEntry(openRegistry);
return spec && (specs ?? []).includes(spec) ? spec : null;
})(),
onInstall: () => installFromRegistry(openRegistry),
onUninstall: (spec: string) => removeSpec(spec),
onClose: () => setOpenRegistry(null),
})
: openUnbridged != null
? (() => {
const failure = failures.find((f) => f.spec === openUnbridged);
return html`
<div class="sessions-detail-h">
<span class="name">${specLabel(openUnbridged)}</span>
<span class="ws"><span class="pill">${failure ? t("mcp.bridgeFailedTitle") : t("mcp.unbridgedTitle")}</span></span>
<span class="actions">
<button class="btn" disabled=${busy} onClick=${() => removeSpec(openUnbridged)}
style="border-color:var(--c-err);color:var(--c-err)">${t("mcp.removeBtn")}</button>
<button class="btn ghost" onClick=${() => setOpenUnbridged(null)}>${t("common.back")}</button>
</span>
</div>
<div class="card" style="margin-bottom:12px">
<div class="card-h"><span class="title">${t("mcp.spec")}</span></div>
<code class="mono" style="font-size:11.5px;color:var(--fg-2);word-break:break-all">${openUnbridged}</code>
</div>
${
failure
? html`<div class="card accent-err">
<div class="card-h"><span class="title" style="color:var(--c-err)">${t("mcp.bridgeFailed")}</span></div>
<div class="card-b" style="font-size:13px;line-height:1.6">
<code class="mono" style="font-size:12px;color:var(--fg-1);word-break:break-word;white-space:pre-wrap">${failure.reason}</code>
<div style="margin-top:10px;color:var(--fg-3);font-size:12px">
${t("mcp.bridgeFailedHint")}
</div>
</div>
</div>`
: html`<div class="card accent-warn">
<div class="card-h"><span class="title" style="color:var(--c-warn)">${t("mcp.whyUnbridged")}</span></div>
<div class="card-b" style="font-size:13px;line-height:1.6">
${t("mcp.whyUnbridgedDesc")}
<div style="margin-top:10px;color:var(--fg-3);font-size:12px">
${t("mcp.whyUnbridgedHint")}
</div>
</div>
</div>`
}
`;
})()
: open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
${showMarketplace ? t("mcp.marketplacePickHint") : t("mcp.pickHint")}
</div>`
: html`
<div class="sessions-detail-h">
<span class="name">${open.label}</span>
<span class="ws">${open.serverInfo?.name ?? "—"} ${open.serverInfo?.version ? `v${open.serverInfo.version}` : ""} · ${open.protocolVersion ?? "—"}</span>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
<div class="card" style="margin-bottom:12px">
<div class="card-h"><span class="title">${t("mcp.spec")}</span></div>
<code class="mono" style="font-size:11.5px;color:var(--fg-2)">${open.spec}</code>
</div>
${
open.instructions
? html`<div class="card accent-brand" style="margin-bottom:12px">
<div class="card-b">${open.instructions}</div>
</div>`
: null
}
<h3 style="margin:18px 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
${t("mcp.toolsTitle", { count: open.tools.length })}
</h3>
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead><tr><th>${t("mcp.colName")}</th><th>${t("mcp.colDesc")}</th></tr></thead>
<tbody>
${open.tools.map(
(tool) =>
html`<tr><td><code class="mono">${tool.name}</code></td><td class="dim">${tool.description ?? ""}</td></tr>`,
)}
</tbody>
</table>
</div>
${
open.resources.length > 0
? html`
<h3 style="margin:18px 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
${t("mcp.resourcesTitle", { count: open.resources.length })}
</h3>
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead><tr><th>${t("mcp.colName")}</th><th>${t("mcp.colUri")}</th></tr></thead>
<tbody>
${open.resources.map(
(r) =>
html`<tr><td>${r.name}</td><td class="path">${r.uri}</td></tr>`,
)}
</tbody>
</table>
</div>
`
: null
}
${
open.prompts.length > 0
? html`
<h3 style="margin:18px 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
${t("mcp.promptsTitle", { count: open.prompts.length })}
</h3>
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead><tr><th>${t("mcp.colName")}</th><th>${t("mcp.colDesc")}</th></tr></thead>
<tbody>
${open.prompts.map(
(p) =>
html`<tr><td><code class="mono">${p.name}</code></td><td class="dim">${p.description ?? ""}</td></tr>`,
)}
</tbody>
</table>
</div>
`
: null
}
`
}
</div>
</div>
`;
}
interface MarketplaceRowsArgs {
registry: RegistryListResponse | null;
registryLoading: boolean;
openRegistry: RegistryEntryDto | null;
setOpenRegistry: (entry: RegistryEntryDto) => void;
loadMore: () => void;
installedSpecs: Set<string>;
}
function renderLoadMoreFooter({
registry,
registryLoading,
loadMore,
}: Pick<MarketplaceRowsArgs, "registry" | "registryLoading" | "loadMore">) {
if (!registry) return null;
const shown = registry.entries.length;
const total = registry.matched;
const moreCached = total > shown;
const moreOnNetwork = registry.hasMore;
const canDoSomething = moreCached || moreOnNetwork;
// Three states:
// 1. Loading — disabled button + spinner-ish label
// 2. More available — primary button + count of what's loaded
// 3. Exhausted — distinct success-tinted card so the user
// doesn't think the button stopped responding
if (canDoSomething) {
const label = registryLoading
? t("mcp.marketplaceLoading")
: t("mcp.marketplaceMoreLabel", {
shown,
total: moreOnNetwork ? `${total}+` : `${total}`,
});
return html`<div style="padding:10px 12px;display:flex;align-items:center;gap:10px">
<button class="btn primary" disabled=${registryLoading} onClick=${loadMore}>${label}</button>
<span style="font-size:11px;color:var(--fg-3)">
${moreOnNetwork ? t("mcp.marketplaceMoreHint") : t("mcp.marketplaceMoreCachedHint")}
</span>
</div>`;
}
return html`<div style="padding:12px;background:var(--bg-elev-2,rgba(36,143,242,0.07));border-top:1px solid var(--bd);display:flex;align-items:center;gap:8px;font-size:12px;color:var(--fg-2)">
<span style="color:var(--c-ok)">✓</span>
<span>${t("mcp.marketplaceExhaustedFull", { total })}</span>
</div>`;
}
function renderMarketplaceRows({
registry,
registryLoading,
openRegistry,
setOpenRegistry,
loadMore,
installedSpecs,
}: MarketplaceRowsArgs) {
if (!registry && registryLoading) {
return html`<div style="color:var(--fg-3);padding:14px;font-size:12px">${t("mcp.marketplaceLoading")}</div>`;
}
if (!registry || registry.entries.length === 0) {
return html`<div style="color:var(--fg-3);padding:14px;font-size:12px">${t("mcp.marketplaceNoMatches")}</div>`;
}
return html`
${registry.entries.map((e) => {
const sel = openRegistry?.name === e.name;
const tag = t("mcp.marketplaceSourceTag", { source: e.source });
const spec = specForEntry(e);
const installed = spec !== null && installedSpecs.has(spec);
const pop =
e.popularity !== undefined
? html` <span class="dim">· ${fmtNum(e.popularity)}</span>`
: null;
const icon = e.iconUrl
? html`<img src=${e.iconUrl} alt="" style="width:16px;height:16px;border-radius:3px;margin-right:6px;vertical-align:middle;object-fit:cover" loading="lazy" referrerpolicy="no-referrer" onError=${hideBrokenIcon} />`
: null;
return html`
<div class=${`ssl-row ${sel ? "sel" : ""}`} onClick=${() => setOpenRegistry(e)}>
<span class="name">${icon}${e.name} <span class="pill">${tag}</span>${installed ? html` <span class="pill ok">${t("mcp.marketplaceInstalledBadge")}</span>` : null}</span>
<span class="preview">${e.description}</span>
<span class="meta">${pop}</span>
</div>
`;
})}
${renderLoadMoreFooter({ registry, registryLoading, loadMore })}
`;
}
interface RegistryDetailArgs {
entry: RegistryEntryDto;
busy: boolean;
installedSpec: string | null;
onInstall: () => void;
onUninstall: (spec: string) => void;
onClose: () => void;
}
function renderRegistryDetail({
entry,
busy,
installedSpec,
onInstall,
onUninstall,
onClose,
}: RegistryDetailArgs) {
const installable = !!entry.install || entry.source === "smithery";
const installed = installedSpec !== null;
const specPreview = entry.install
? `${entry.install.runtime} · ${entry.install.transport}${
entry.install.packageId
? ` · ${entry.install.packageId}`
: entry.install.url
? ` · ${entry.install.url}`
: ""
}${entry.install.version ? `@${entry.install.version}` : ""}`
: "";
const icon = entry.iconUrl
? html`<img src=${entry.iconUrl} alt="" style="width:24px;height:24px;border-radius:4px;margin-right:8px;vertical-align:middle;object-fit:cover" loading="lazy" referrerpolicy="no-referrer" onError=${hideBrokenIcon} />`
: null;
return html`
<div class="sessions-detail-h">
<span class="name">${icon}${entry.name}${installed ? html` <span class="pill ok">${t("mcp.marketplaceInstalledBadge")}</span>` : null}</span>
<span class="ws">${t("mcp.marketplaceSourceTag", { source: entry.source })}${
entry.popularity !== undefined ? ` · ${fmtNum(entry.popularity)} uses` : ""
}${entry.homepage ? html` · <a href=${entry.homepage} target="_blank" rel="noopener noreferrer">homepage</a>` : ""}</span>
<span class="actions">
${
installed
? html`<button
class="btn"
disabled=${busy}
onClick=${() => onUninstall(installedSpec)}
style="border-color:var(--c-err);color:var(--c-err)"
>${t("mcp.marketplaceUninstall")}</button>`
: html`<button class="btn primary" disabled=${busy || !installable} onClick=${onInstall}>${t("mcp.marketplaceInstall")}</button>`
}
<button class="btn ghost" onClick=${onClose}>${t("common.back")}</button>
</span>
</div>
<div class="card" style="margin-bottom:12px">
<div class="card-b" style="font-size:13px;line-height:1.6">${entry.description || "—"}</div>
</div>
${
entry.install
? html`<div class="card" style="margin-bottom:12px">
<div class="card-h"><span class="title">${t("mcp.spec")}</span></div>
<div class="card-b">
<code class="mono" style="font-size:11.5px;color:var(--fg-2);word-break:break-all;display:block">${specPreview}</code>
${
installedSpec
? html`<div style="margin-top:8px;font-size:11px;color:var(--fg-3)">
<span class="dim">on disk:</span> <code class="mono">${installedSpec}</code>
</div>`
: null
}
</div>
</div>`
: entry.source === "smithery"
? html`<div class="card" style="margin-bottom:12px">
<div class="card-b" style="font-size:13px;line-height:1.6;color:var(--fg-3)">
${t("mcp.marketplaceFetchOnInstall")}
</div>
</div>`
: null
}
${
entry.install?.requiredEnv?.length
? html`<div class="card accent-brand" style="margin-bottom:12px">
<div class="card-h"><span class="title">${t("mcp.marketplaceEnvTitle")}</span></div>
<div class="card-b" style="font-size:13px">
${entry.install.requiredEnv.map(
(name) =>
html`<div><code class="mono" style="color:var(--c-warn)">${name}</code></div>`,
)}
<div style="margin-top:6px;color:var(--fg-3);font-size:12px">
${t("mcp.marketplaceEnvHint")}
</div>
</div>
</div>`
: null
}
${
installed
? html`<div class="card accent-warn">
<div class="card-b" style="font-size:12.5px;line-height:1.6">
${t("mcp.marketplaceRestartHint")}
</div>
</div>`
: null
}
`;
}
-183
View File
@@ -1,183 +0,0 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { fmtBytes, fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface MemoryFile {
name: string;
size: number;
mtime: string | number;
}
interface MemoryTree {
project: { path?: string | null; exists?: boolean };
global: { files: MemoryFile[] };
projectMem: { path?: string | null; files: MemoryFile[] };
}
type Scope = "project" | "global" | "project-mem";
export function MemoryPanel() {
useLang();
const [tree, setTree] = useState<MemoryTree | null>(null);
const [error, setError] = useState<string | null>(null);
const [open, setOpen] = useState<{ scope: Scope; name?: string } | null>(null);
const [body, setBody] = useState("");
const [busy, setBusy] = useState(false);
const [info, setInfo] = useState<string | null>(null);
const load = useCallback(async () => {
try {
setTree(await api<MemoryTree>("/memory"));
} catch (err) {
setError((err as Error).message);
}
}, []);
useEffect(() => {
load();
}, [load]);
const openFile = useCallback(async (scope: Scope, name?: string) => {
setOpen({ scope, name });
setBusy(true);
try {
const path =
scope === "project"
? "/memory/project"
: `/memory/${scope}/${encodeURIComponent(name ?? "")}`;
const r = await api<{ body: string }>(path);
setBody(r.body);
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}, []);
const save = useCallback(async () => {
if (!open) return;
setBusy(true);
setError(null);
try {
const path =
open.scope === "project"
? "/memory/project"
: `/memory/${open.scope}/${encodeURIComponent(open.name ?? "")}`;
await api(path, { method: "POST", body: { body } });
setInfo(t("memory.saved", { scope: open.scope + (open.name ? `/${open.name}` : "") }));
setTimeout(() => setInfo(null), 3000);
await load();
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}, [open, body, load]);
if (!tree && !error)
return html`<div class="card" style="color:var(--fg-3)">${t("memory.loading")}</div>`;
if (error && !tree) return html`<div class="card accent-err">${error}</div>`;
if (!tree) return null;
const fileRow = (scope: Scope, f: MemoryFile) => {
const sel = open && open.scope === scope && open.name === f.name;
return html`
<div
class=${`ssl-row ${sel ? "sel" : ""}`}
onClick=${() => openFile(scope, f.name)}
>
<span class="name">${f.name}</span>
<span class="meta">
<span class="dim">${scope}</span>
<span><span class="v">${fmtBytes(f.size)}</span></span>
<span>${fmtRelativeTime(f.mtime)}</span>
</span>
</div>
`;
};
const totalFiles =
(tree.project.path ? 1 : 0) +
tree.global.files.length +
tree.projectMem.files.length;
return html`
<div class="sessions-grid">
<div class="sessions-list">
<div class="ssl-h" style="font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
${t("memory.files", { count: totalFiles })}
</div>
<div class="ssl-rows">
${
tree.project.path
? html`
<div
class=${`ssl-row ${open?.scope === "project" ? "sel" : ""}`}
onClick=${() => openFile("project")}
>
<span class="name">
REASONIX.md
${
tree.project.exists
? html`<span class="pill ok">${t("memory.exists")}</span>`
: html`<span class="pill">${t("memory.create")}</span>`
}
</span>
<span class="preview">${tree.project.path}</span>
<span class="meta"><span class="dim">project</span></span>
</div>
`
: null
}
${tree.global.files.map((f) => fileRow("global", f))}
${tree.projectMem.files.map((f) => fileRow("project-mem", f))}
${
(tree.global.files.length === 0 &&
tree.projectMem.files.length === 0 &&
!tree.project.path)
? html`<div style="color:var(--fg-3);padding:14px;font-size:12px">
${t("memory.noFiles")}
</div>`
: null
}
</div>
</div>
<div class="sessions-detail">
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
${t("memory.pickHint")}
<div style="margin-top:12px;font-size:11.5px">
${t("memory.pickDesc")}
</div>
</div>`
: html`
<div class="sessions-detail-h">
<span class="name">
${open.scope}${open.name ? `/${open.name}` : ""}
</span>
<span class="ws">${t("memory.chars", { count: body.length.toLocaleString() })}</span>
<span class="actions">
<button class="btn primary" disabled=${busy} onClick=${save}>${t("common.save")}</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
${info ? html`<div style="margin-bottom:8px"><span class="pill ok">${info}</span></div>` : null}
${error ? html`<div class="card accent-err" style="margin-bottom:8px">${error}</div>` : null}
<textarea
style="width:100%;min-height:480px;background:var(--bg-input);color:var(--fg-0);border:1px solid var(--bd);border-radius:var(--r);padding:12px;font-family:var(--font-mono);font-size:13px;line-height:1.55;resize:vertical"
value=${body}
onInput=${(e: Event) => setBody((e.target as HTMLTextAreaElement).value)}
disabled=${busy}
></textarea>
<div style="margin-top:8px;color:var(--fg-3);font-size:11.5px">
${t("memory.reloadHint")}
</div>
`
}
</div>
</div>
`;
}
-336
View File
@@ -1,336 +0,0 @@
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 {
total: number;
deltaPct: number | null;
}
interface CockpitCacheKpi {
ratio: number;
deltaPp: number | null;
}
interface CockpitDailyCost {
date: string;
usd: number;
}
interface CockpitCurrentSession {
id: string;
turns: number;
totalCostUsd: number;
lastPromptTokens: number;
completionTokens: number;
}
interface CockpitToolCallsKpi {
total: number;
delta: number | null;
}
interface CockpitRecentPlan {
id: string;
title: string;
totalSteps: number;
completedSteps: number;
status: "active" | "done";
whenMs: number;
}
interface CockpitToolFeedRow {
name: string;
args: string;
level: "ok" | "warn" | "err";
whenMs: number;
}
interface CockpitData {
balance: { currency: string; total: string } | null;
tokens7d: CockpitKpi | null;
cacheHit7d: CockpitCacheKpi | null;
costTrend14d: ReadonlyArray<CockpitDailyCost> | null;
currentSession: CockpitCurrentSession | null;
toolCalls24h: CockpitToolCallsKpi | null;
recentPlans: ReadonlyArray<CockpitRecentPlan> | null;
toolActivity: ReadonlyArray<CockpitToolFeedRow> | null;
}
interface OverviewData {
mode: "standalone" | "attached";
version?: string;
latestVersion?: string;
session?: string | null;
model?: string;
editMode?: string;
planMode?: boolean | null;
pendingEdits?: number;
mcpServerCount?: number;
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") {
const muted = value === "—" || value === null || value === undefined;
return html`
<div class="kpi cock-w-1">
<div class="label">${label}</div>
<div class="value" style=${muted ? "color:var(--fg-4)" : ""}>${value ?? "—"}</div>
${delta != null ? html`<div class=${`delta ${deltaTone ?? ""}`}>${delta}</div>` : null}
</div>
`;
}
function deltaPctText(deltaPct: number | null): { text: string; tone: "up" | "down" | "flat" } {
if (deltaPct === null) return { text: t("overview.noPriorData"), tone: "flat" };
if (Math.abs(deltaPct) < 1) return { text: t("overview.stable"), tone: "flat" };
const arrow = deltaPct > 0 ? "▲" : "▼";
return {
text: t("overview.vsPrior", { arrow, pct: Math.abs(deltaPct).toFixed(0) }),
tone: deltaPct > 0 ? "up" : "down",
};
}
function deltaPpText(deltaPp: number | null): { text: string; tone: "up" | "down" | "flat" } {
if (deltaPp === null) return { text: t("overview.noPriorData"), tone: "flat" };
if (Math.abs(deltaPp) < 0.5) return { text: t("overview.stable"), tone: "flat" };
const arrow = deltaPp > 0 ? "▲" : "▼";
return { text: `${arrow} ${Math.abs(deltaPp).toFixed(1)}pp`, tone: deltaPp > 0 ? "up" : "down" };
}
function deltaCountText(delta: number | null): { text: string; tone: "up" | "down" | "flat" } {
if (delta === null || delta === 0) return { text: t("overview.stable"), tone: "flat" };
const arrow = delta > 0 ? "▲" : "▼";
return { text: `${arrow} ${Math.abs(delta)}`, tone: delta > 0 ? "up" : "down" };
}
function balanceKpi(c: CockpitData) {
if (!c.balance) return kpi(t("overview.balance"), "—", "open in TUI", "flat");
const symbol = c.balance.currency === "CNY" ? "¥" : c.balance.currency === "USD" ? "$" : "";
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);
return kpi(t("overview.tokens7d"), fmtCompactNum(c.tokens7d.total), d.text, d.tone);
}
function cacheHitKpi(c: CockpitData) {
if (!c.cacheHit7d) return kpi(t("overview.cacheHit"), "—", t("overview.noUsageYet"), "flat");
const pct = (c.cacheHit7d.ratio * 100).toFixed(0);
const d = deltaPpText(c.cacheHit7d.deltaPp);
return html`
<div class="kpi cock-w-1">
<div class="label">${t("overview.cacheHit")}</div>
<div class="value">${pct}<span class="unit">%</span></div>
<div class=${`delta ${d.tone}`}>${d.text}</div>
</div>
`;
}
function toolCallsKpi(c: CockpitData) {
if (!c.toolCalls24h) return kpi(t("overview.toolCalls24h"), "—", t("overview.noToolCalls"), "flat");
const d = deltaCountText(c.toolCalls24h.delta);
return kpi(t("overview.toolCalls24h"), fmtNum(c.toolCalls24h.total), d.text, d.tone);
}
function currentSessionBlock(c: CockpitData) {
if (!c.currentSession) {
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">${t("overview.currentSession")}</span></div>
<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">
${t("overview.noSession")}
</div>
</div>
`;
}
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>
<div class="card accent-brand" style="margin:0 0 8px;background:transparent;border:none;padding:0">
<div class="card-h"><span class="glyph">◆</span><span class="title">${s.id}</span><span class="meta">${s.turns} turn${s.turns === 1 ? "" : "s"}</span></div>
</div>
<div style="display:grid;grid-template-columns:repeat(3, 1fr);gap:8px;font-family:var(--font-mono);font-size:11px">
<div><span style="color:var(--fg-3)">${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">${fmtCost(s.totalCostUsd, currency)}</div></div>
</div>
</div>
`;
}
function costTrendSpark(c: CockpitData) {
if (!c.costTrend14d || c.costTrend14d.length === 0) {
return html`
<div class="chart cock-w-2">
<div class="chart-h"><span class="title">${t("overview.costTrend")}</span></div>
<div class="chart-v" style="color:var(--fg-4)">—<span class="unit">${t("overview.noUsageYet")}</span></div>
</div>
`;
}
const days = c.costTrend14d;
const total = days.reduce((s, d) => s + d.usd, 0);
const max = Math.max(...days.map((d) => d.usd), 0.0001);
const w = 400;
const h = 60;
const points = days
.map((d, i) => {
const x = days.length === 1 ? 0 : (i * w) / (days.length - 1);
const y = h - (d.usd / max) * (h - 6) - 3;
return `${x.toFixed(0)},${y.toFixed(0)}`;
})
.join(" ");
const area = `${points} ${w},${h} 0,${h}`;
const avg = total / days.length;
return html`
<div class="chart cock-w-2">
<div class="chart-h"><span class="title">${t("overview.costTrend")}</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} />
<polyline fill="rgba(121,192,255,.10)" stroke="none" points=${area} />
</svg>
</div>
</div>
`;
}
function recentPlansRail(c: CockpitData) {
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">${t("overview.recentPlans")}</span></div>
${
!c.recentPlans || c.recentPlans.length === 0
? html`<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">${t("overview.noPlans")}</div>`
: c.recentPlans.map(
(p) => html`
<div class=${`rail-step ${p.status === "done" ? "done" : "active"}`}>
<span class="g">${p.status === "done" ? "✓" : "⏵"}</span>
<span>${p.title} · ${p.completedSteps}/${p.totalSteps} step${p.totalSteps === 1 ? "" : "s"}</span>
<span style="margin-left:auto;color:var(--fg-4);font-family:var(--font-mono);font-size:10.5px">${fmtRelativeTime(p.whenMs)}</span>
</div>
`,
)
}
</div>
`;
}
function toolActivityFeed(c: CockpitData) {
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">${t("overview.toolActivity")}</span></div>
${
!c.toolActivity || c.toolActivity.length === 0
? html`<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">${t("overview.noToolCalls")}</div>`
: c.toolActivity.map(
(r) => html`
<div class=${`feed-row ${r.level}`}>
<span class="g">${r.level === "ok" ? "●" : r.level === "warn" ? "▲" : "✕"}</span>
<span class="name">${r.name}${r.args ? html` <span class="args">${r.args}</span>` : null}</span>
<span class="when" style="margin-left:auto">${fmtRelativeTime(r.whenMs)}</span>
</div>
`,
)
}
</div>
`;
}
export function OverviewPanel() {
useLang();
const { data, error, loading } = usePoll<OverviewData>("/overview", 2500);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">${t("overview.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("overview.failed", { error: error.message })}</div>`;
if (!data) return null;
const o = data;
const c: CockpitData = o.cockpit ?? {
balance: null,
tokens7d: null,
cacheHit7d: null,
costTrend14d: null,
currentSession: null,
toolCalls24h: null,
recentPlans: null,
toolActivity: 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";
return html`
<div style="display:flex;flex-direction:column;gap:14px">
${
o.mode === "standalone"
? html`<div class="card accent-warn">
<div class="card-h">
<span class="title" style="color:var(--c-warn)">${t("overview.standaloneTitle")}</span>
</div>
<div class="card-b">
${t("overview.standaloneDesc")}
</div>
</div>`
: null
}
<h3 style="margin:0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
${t("overview.cockpit")}
</h3>
<div class="cockpit">
${balanceKpi(c)}
${tokens7dKpi(c)}
${cacheHitKpi(c)}
${toolCallsKpi(c)}
${budgetKpi(o)}
${currentSessionBlock(c)}
${costTrendSpark(c)}
${recentPlansRail(c)}
${toolActivityFeed(c)}
${kpi(t("overview.toolsLoaded"), fmtNum(o.toolCount), o.toolCount ? t("overview.active") : "—", "flat")}
${kpi(t("overview.mcpServers"), fmtNum(o.mcpServerCount), o.mcpServerCount ? t("overview.allUp") : "—", o.mcpServerCount ? "up" : "flat")}
${kpi(t("overview.editMode"), o.editMode ?? "—", o.editMode === "yolo" ? t("overview.yoloWarning") : null, o.editMode === "yolo" ? "down" : "flat")}
${kpi(t("overview.version"), o.version ?? "—", versionDelta, versionTone)}
</div>
<h3 style="margin:0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
${t("overview.workingDir")}
</h3>
<div class="card">
<div class="card-h"><span class="title">${t("overview.projectRoot")}</span></div>
<code class="mono" style="color:var(--fg-2);font-size:12px">${o.cwd ?? "—"}</code>
</div>
</div>
`;
}
-225
View File
@@ -1,225 +0,0 @@
import { useCallback, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface PermissionsData {
editMode?: string;
currentCwd?: string | null;
project: string[];
builtin: string[];
}
interface Feedback {
kind: "ok" | "err" | "info";
text: string;
}
function groupByVerb(list: string[]): [string, string[]][] {
const groups = new Map<string, string[]>();
for (const entry of list) {
const sp = entry.indexOf(" ");
const verb = sp > 0 ? entry.slice(0, sp) : entry;
const tail = sp > 0 ? entry.slice(sp + 1) : "";
const arr = groups.get(verb) ?? [];
arr.push(tail);
groups.set(verb, arr);
}
return [...groups.entries()];
}
export function PermissionsPanel() {
useLang();
const { data, error, loading, refresh } = usePoll<PermissionsData>("/permissions", 5000);
const [draft, setDraft] = useState("");
const [busy, setBusy] = useState(false);
const [feedback, setFeedback] = useState<Feedback | null>(null);
const add = useCallback(async () => {
const prefix = draft.trim();
if (!prefix) return;
setBusy(true);
setFeedback(null);
try {
const res = await api<{ alreadyPresent?: boolean }>("/permissions", {
method: "POST",
body: { prefix },
});
if (res.alreadyPresent) setFeedback({ kind: "info", text: t("permissions.alreadyIn", { prefix }) });
else setFeedback({ kind: "ok", text: t("permissions.added", { prefix }) });
setDraft("");
await refresh();
} catch (err) {
setFeedback({ kind: "err", text: (err as Error).message });
} finally {
setBusy(false);
}
}, [draft, refresh]);
const remove = useCallback(
async (prefix: string) => {
if (!confirm(t("permissions.removeConfirm", { prefix }))) return;
setBusy(true);
setFeedback(null);
try {
await api("/permissions", { method: "DELETE", body: { prefix } });
setFeedback({ kind: "ok", text: t("permissions.removed", { prefix }) });
await refresh();
} catch (err) {
setFeedback({ kind: "err", text: (err as Error).message });
} finally {
setBusy(false);
}
},
[refresh],
);
const clearAll = useCallback(async () => {
if (!confirm(t("permissions.clearConfirm"))) return;
setBusy(true);
setFeedback(null);
try {
const res = await api<{ dropped: number }>("/permissions/clear", {
method: "POST",
body: { confirm: true },
});
setFeedback({
kind: "ok",
text: t("permissions.cleared", { count: res.dropped, y: res.dropped === 1 ? "y" : "ies" }),
});
await refresh();
} catch (err) {
setFeedback({ kind: "err", text: (err as Error).message });
} finally {
setBusy(false);
}
}, [refresh]);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">${t("permissions.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "permissions", error: error.message })}</div>`;
if (!data) return null;
const p = data;
const feedbackPill = feedback
? html`<span
class=${`pill ${feedback.kind === "err" ? "err" : feedback.kind === "ok" ? "ok" : "warn"}`}
>${feedback.text}</span>`
: null;
return html`
<div style="display:flex;flex-direction:column;gap:14px">
${
p.editMode === "yolo"
? html`<div class="card accent-warn">
<div class="card-h"><span class="title" style="color:var(--c-warn)">${t("permissions.yoloTitle")}</span></div>
<div class="card-b">
${t("permissions.yoloDesc")}
</div>
</div>`
: null
}
<div class="chips">
<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>
${
p.currentCwd
? html`
<div class="card">
<div class="card-h">
<span class="title">${t("permissions.addPrefix")}</span>
<span class="meta">${p.currentCwd}</span>
</div>
<div style="display:flex;gap:8px;align-items:center">
<input
type="text"
placeholder=${t("permissions.addPlaceholder")}
value=${draft}
onInput=${(e: Event) => setDraft((e.target as HTMLInputElement).value)}
onKeyDown=${(e: KeyboardEvent) => {
if (e.key === "Enter") add();
}}
disabled=${busy}
style="flex:1"
/>
<button class="primary" onClick=${add} disabled=${busy || !draft.trim()}>${t("common.add")}</button>
<button
class="danger"
onClick=${clearAll}
disabled=${busy || p.project.length === 0}
>${t("permissions.clearAll")}</button>
</div>
${feedbackPill ? html`<div style="margin-top:8px">${feedbackPill}</div>` : null}
</div>
`
: html`
<div class="card accent-warn">
<div class="card-b">
${t("permissions.standaloneWarning")}
</div>
</div>
`
}
<h3 style="margin:6px 0 0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
${t("permissions.projectAllowlist", { count: p.project.length })}
</h3>
${
p.project.length === 0
? html`<div class="card" style="color:var(--fg-3)">${t("permissions.nothingStored")}</div>`
: html`
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<th style="width:48px">${t("permissions.colNum")}</th>
<th>${t("permissions.colPrefix")}</th>
<th style="width:120px"></th>
</tr>
</thead>
<tbody>
${p.project.map(
(prefix, i) => html`
<tr>
<td class="dim">${i + 1}</td>
<td><code class="mono">${prefix}</code></td>
<td>
${
p.currentCwd
? html`<button
class="danger"
onClick=${() => remove(prefix)}
disabled=${busy}
>${t("common.remove")}</button>`
: null
}
</td>
</tr>
`,
)}
</tbody>
</table>
</div>
`
}
<h3 style="margin:6px 0 0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
${t("permissions.builtinTitle", { count: p.builtin.length })}
</h3>
<div class="card" style="font-family:var(--font-mono);font-size:11.5px;line-height:1.8">
${groupByVerb(p.builtin).map(
([verb, list]) => html`
<div style="margin-bottom:4px">
<span class="pill" style="margin-right:6px">${verb}</span>
<span style="color:var(--fg-2)">${list.join(" · ")}</span>
</div>
`,
)}
</div>
</div>
`;
}
-166
View File
@@ -1,166 +0,0 @@
import { useState } from "preact/hooks";
import { fmtPct, fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface PlanStep {
id: string;
title: string;
action?: string;
risk?: "low" | "medium" | "high";
}
interface ArchivedPlan {
session: string;
summary?: string;
steps: PlanStep[];
completedStepIds: string[];
completedSteps: number;
totalSteps: number;
completionRatio: number;
completedAt: string | number;
}
interface PlansData {
plans?: ArchivedPlan[];
}
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">${t("plans.idle")}</span>`;
}
export function PlansPanel() {
useLang();
const { data, error, loading } = usePoll<PlansData>("/plans", 8000);
const [openIdx, setOpenIdx] = useState<number | null>(null);
const [filter, setFilter] = useState("");
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>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "plans", error: error.message })}</div>`;
const plans = data?.plans ?? [];
if (plans.length === 0)
return html`<div class="card" style="color:var(--fg-3)">
${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()
? statusFiltered.filter(
(p) =>
p.session.toLowerCase().includes(filter.toLowerCase()) ||
(p.summary ?? "").toLowerCase().includes(filter.toLowerCase()),
)
: statusFiltered;
const open = openIdx !== null ? plans[openIdx] : null;
return html`
<div class="sessions-grid">
<div class="sessions-list">
<div class="ssl-h">
<input
type="text"
placeholder=${t("plans.filterPlaceholder")}
value=${filter}
onInput=${(e: Event) => setFilter((e.target as HTMLInputElement).value)}
style="flex:1"
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span
class=${`chip-f ${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 ${statusFilter === "done" ? "active" : ""}`}
onClick=${() => setStatusFilter("done")}
>
${t("plans.done")} <span class="ct">${plans.filter((p) => p.completionRatio >= 1).length}</span>
</span>
</div>
<div class="ssl-rows">
${filtered.map((p) => {
const idx = plans.indexOf(p);
const sel = idx === openIdx;
return html`
<div class=${`ssl-row ${sel ? "sel" : ""}`} onClick=${() => setOpenIdx(idx)}>
<span class="name">${p.summary ?? p.session} ${statusPill(p)}</span>
${
p.summary && p.session !== p.summary
? html`<span class="preview">${p.session}</span>`
: null
}
<span class="meta">
<span><span class="v">${p.totalSteps}</span> ${t("plans.steps")}</span>
<span><span class="v">${p.completedSteps} / ${p.totalSteps}</span> · ${fmtPct(p.completionRatio)}</span>
<span>${fmtRelativeTime(p.completedAt)}</span>
</span>
</div>
`;
})}
</div>
</div>
<div class="sessions-detail">
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
${t("plans.pickHint")}
</div>`
: html`
<div class="sessions-detail-h">
<span class="name">${open.summary ?? t("plans.noTitle")}</span>
<span class="ws">${open.session} · ${fmtRelativeTime(open.completedAt)}</span>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpenIdx(null)}>${t("common.back")}</button>
</span>
</div>
<h3 style="margin:0 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
${t("plans.stepTimeline", { done: open.completedSteps, total: open.totalSteps })}
</h3>
<div class="plan-timeline" style="margin-bottom:14px">
${open.steps.map((step, i) => {
const done = open.completedStepIds.includes(step.id);
const cls = done ? "done" : i === open.completedSteps ? "active" : "";
return html`
<div class=${`plan-step ${cls}`}>
<span class="lbl">${t("plans.step", { n: i + 1 })}</span>
<span class="name">${step.title}</span>
${step.action ? html`<span class="meta">${step.action}</span>` : null}
${
step.risk
? html`<span
class=${`pill ${step.risk === "high" ? "err" : step.risk === "medium" ? "warn" : ""}`}
style="align-self:flex-start;margin-top:4px"
>${step.risk}</span>`
: null
}
</div>
`;
})}
</div>
`
}
</div>
</div>
`;
}
File diff suppressed because it is too large. Load diff
-257
View File
@@ -1,257 +0,0 @@
import { useCallback, useState } from "preact/hooks";
import { ChatMessage } from "../components/chat-internals.js";
import { api } from "../lib/api.js";
import { fmtBytes, fmtNum, fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface SessionEntry {
name: string;
messageCount: number;
size: number;
mtime: string | number;
}
interface SessionsData {
sessions?: SessionEntry[];
currentSession?: string | null;
canSwitch?: boolean;
}
interface OpenSession {
name: string;
messages: unknown[] | null;
error?: string;
}
export function SessionsPanel() {
useLang();
const { data, error, loading, refresh } = usePoll<SessionsData>("/sessions", 5000);
const [open, setOpen] = useState<OpenSession | null>(null);
const [openLoading, setOpenLoading] = useState(false);
const [filter, setFilter] = useState("");
const [busy, setBusy] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const view = useCallback(async (name: string) => {
setOpen({ name, messages: null });
setOpenLoading(true);
try {
const detail = await api<{ messages: unknown[] }>(`/sessions/${encodeURIComponent(name)}`);
setOpen({ name, messages: detail.messages });
} catch (err) {
setOpen({ name, messages: null, error: (err as Error).message });
} finally {
setOpenLoading(false);
}
}, []);
const newSession = useCallback(async () => {
setBusy("new");
setActionError(null);
try {
await api("/sessions/new", { method: "POST" });
setOpen(null);
await refresh();
} catch (err) {
setActionError((err as Error).message);
} finally {
setBusy(null);
}
}, [refresh]);
const switchTo = useCallback(
async (name: string) => {
setBusy(`switch:${name}`);
setActionError(null);
try {
await api(`/sessions/${encodeURIComponent(name)}/switch`, { method: "POST" });
setOpen(null);
await refresh();
} catch (err) {
setActionError((err as Error).message);
} finally {
setBusy(null);
}
},
[refresh],
);
const remove = useCallback(
async (name: string) => {
if (!confirm(t("sessions.deleteConfirm", { name }))) return;
setBusy(`delete:${name}`);
setActionError(null);
try {
await api(`/sessions/${encodeURIComponent(name)}`, { method: "DELETE" });
if (open?.name === name) setOpen(null);
await refresh();
} catch (err) {
setActionError((err as Error).message);
} finally {
setBusy(null);
}
},
[open, refresh],
);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">${t("sessions.loading")}</div>`;
if (error)
return html`<div class="card accent-err">${t("common.loadingFailed", { name: "sessions", error: error.message })}</div>`;
const sessions = data?.sessions ?? [];
const currentSession = data?.currentSession ?? null;
const canSwitch = data?.canSwitch ?? false;
const filtered = filter.trim()
? sessions.filter((s) => s.name.toLowerCase().includes(filter.toLowerCase()))
: sessions;
return html`
<div class="sessions-grid">
<div class="sessions-list">
<div class="ssl-h" style="display:flex;gap:6px">
<input
type="text"
placeholder=${t("sessions.filterPlaceholder")}
value=${filter}
onInput=${(e: Event) => setFilter((e.target as HTMLInputElement).value)}
style="flex:1"
/>
<button
class="btn primary"
disabled=${!canSwitch || busy === "new"}
title=${canSwitch ? t("sessions.newHint") : t("sessions.attachRequired")}
onClick=${newSession}
>
${busy === "new" ? t("common.loading") : `+ ${t("sessions.newBtn")}`}
</button>
</div>
${
!canSwitch
? html`<div style="padding:0 12px 6px;font-size:11.5px;color:var(--fg-3)">${t("sessions.attachRequired")}</div>`
: null
}
${
actionError
? html`<div class="card accent-err" style="margin:0 12px 8px;padding:6px 10px;font-size:12px">${actionError}</div>`
: null
}
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f static active">${t("common.all")} <span class="ct">${sessions.length}</span></span>
${currentSession ? html`<span class="chip-f static">${t("sessions.activeChip")} <span class="ct">${currentSession}</span></span>` : null}
</div>
${
sessions.length === 0
? html`<div class="ctx-empty" style="padding:24px 12px;color:var(--fg-3)">${t("sessions.noSessions")}</div>`
: html`<div class="ssl-rows">
${filtered.map((s) => {
const isCurrent = currentSession === s.name;
return html`
<div
class=${`ssl-row ${open?.name === s.name ? "sel" : ""}`}
onClick=${() => view(s.name)}
>
<span class="name">
${isCurrent ? html`<span class="pill ok" style="margin-right:6px">${t("sessions.activePill")}</span>` : null}
${s.name}
</span>
<span class="meta">
<span><span class="v">${fmtNum(s.messageCount)}</span> ${t("sessions.msgs")}</span>
<span><span class="v">${fmtBytes(s.size)}</span></span>
<span>${fmtRelativeTime(s.mtime)}</span>
</span>
</div>
`;
})}
</div>`
}
</div>
<div class="sessions-detail">
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
${t("sessions.pickHint")}
</div>`
: (() => {
const isCurrent = currentSession === open.name;
return html`
<div class="sessions-detail-h">
<span class="name">
${isCurrent ? html`<span class="pill ok" style="margin-right:6px">${t("sessions.activePill")}</span>` : null}
${open.name}
</span>
<span class="ws">
${
open.messages
? t("sessions.messages", { count: open.messages.length, s: open.messages.length === 1 ? "" : "s" })
: t("common.loading")
}
</span>
<span class="actions">
${
canSwitch && !isCurrent
? html`<button class="btn primary" disabled=${busy === `switch:${open.name}`} onClick=${() => switchTo(open.name)}>${busy === `switch:${open.name}` ? t("common.loading") : t("sessions.switchBtn")}</button>`
: null
}
<button
class="btn"
disabled=${isCurrent || busy === `delete:${open.name}`}
title=${isCurrent ? t("sessions.cantDeleteActive") : t("sessions.deleteBtn")}
style="border-color:var(--c-err);color:var(--c-err)"
onClick=${() => remove(open.name)}
>${busy === `delete:${open.name}` ? t("common.loading") : t("sessions.deleteBtn")}</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
${
!canSwitch
? html`<div class="card accent-brand" style="margin-bottom:10px">
<div class="card-h"><span class="title">${t("sessions.resumeTitle")}</span></div>
<div class="card-b" style="font-size:12.5px;color:var(--fg-2)">
${t("sessions.resumeDesc")}
<code class="mono" style="display:block;margin-top:8px;padding:8px 10px;background:var(--bg-input);border-radius:var(--r);color:var(--fg-0);font-size:12px;user-select:all">reasonix chat --session ${open.name}</code>
</div>
</div>`
: null
}
${
openLoading
? html`<div style="color:var(--fg-3)">${t("sessions.loadingTranscript")}</div>`
: open.error
? html`<div class="card accent-err">${open.error}</div>`
: open.messages && open.messages.length > 0
? html`<div class="chat-feed" style="max-height:calc(100vh - 220px);overflow-y:auto">
${open.messages.map(
(m: any, i: number) => html`
<${ChatMessage}
key=${i}
msg=${{
id: `r-${i}`,
role:
m.role === "tool"
? "tool"
: m.role === "assistant"
? "assistant"
: m.role === "user"
? "user"
: "info",
text: m.content ?? "",
toolName: m.toolName,
}}
streaming=${false}
/>
`,
)}
</div>`
: html`<div style="color:var(--fg-3)">${t("sessions.emptyTranscript")}</div>`
}
`;
})()
}
</div>
</div>
`;
}
-718
View File
@@ -1,718 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { type DashboardLang, getLang, setLang, t, useLang } from "../i18n/index.js";
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";
interface SettingsData {
apiKey?: string | null;
baseUrl?: string;
preset?: string;
reasoningEffort?: string;
search?: boolean;
model?: string;
editMode?: string;
proNext?: boolean;
budgetUsd?: number | null;
/** Cumulative session spend (USD); null when no session is attached. */
sessionSpendUsd?: number | null;
skillPaths?: string[];
}
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() {
useLang();
const [data, setData] = useState<SettingsData | null>(null);
const [error, setError] = useState<string | null>(null);
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 {
const r = await api<SettingsData>("/settings");
setData(r);
setDraft({});
} catch (err) {
setError((err as Error).message);
}
}, []);
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>) => {
setSaving(true);
setError(null);
try {
await api("/settings", { method: "POST", body: fields });
await load();
setSaved(t("settings.saved", { fields: Object.keys(fields).join(", ") }));
setTimeout(() => setSaved(null), 3000);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
},
[load],
);
const skillPathsDraft = draft.skillPaths ?? data?.skillPaths ?? [];
const skillPathsText = Array.isArray(skillPathsDraft)
? skillPathsDraft.join(", ")
: String(skillPathsDraft ?? "");
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">${t("settings.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
const v = data;
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 fieldRow = (label: string, control: unknown, note?: string) => html`
<div style="display:flex;align-items:center;gap:10px;padding:6px 0">
<span style="flex:0 0 110px;font-family:var(--font-mono);font-size:11.5px;color:var(--fg-3)">${label}</span>
<div style="flex:1;display:flex;align-items:center;gap:8px">${control}</div>
${note ? html`<span style="color:var(--fg-3);font-size:11px">${note}</span>` : null}
</div>
`;
const currentLang = getLang();
return html`
<div style="max-width:760px;display:flex;flex-direction:column;gap:6px">
${saved ? html`<div><span class="pill ok">${saved}</span></div>` : null}
${error ? html`<div class="card accent-err">${error}</div>` : null}
${sectionH3(t("settings.sectionLanguage"))}
<div class="card">
${fieldRow(
t("settings.language"),
html`
<select
value=${currentLang}
onChange=${(e: Event) => {
const lang = (e.target as HTMLSelectElement).value as DashboardLang;
setLang(lang);
}}
>
<option value="en">${t("settings.langEn")}</option>
<option value="zh-CN">${t("settings.langZhCn")}</option>
</select>
`,
)}
</div>
${sectionH3(t("settings.sectionApi"))}
<div class="card">
${fieldRow(
t("settings.apiKey"),
html`<code class="mono" style="color:var(--fg-2);font-size:11.5px">${v.apiKey ?? t("settings.notSet")}</code>`,
)}
${fieldRow(
t("settings.replace"),
html`
<input
type="password"
placeholder=${t("settings.pasteKey")}
value=${draft.apiKey ?? ""}
onInput=${(e: Event) => setDraft({ ...draft, apiKey: (e.target as HTMLInputElement).value })}
style="flex:1"
/>
<button
class="btn primary"
disabled=${saving || !(draft.apiKey ?? "").trim()}
onClick=${() => save({ apiKey: draft.apiKey })}
>${t("settings.saveKey")}</button>
`,
)}
${fieldRow(
t("settings.baseUrl"),
html`
<input
type="text"
value=${draft.baseUrl ?? v.baseUrl ?? ""}
placeholder=${t("settings.baseUrlPlaceholder")}
onInput=${(e: Event) => setDraft({ ...draft, baseUrl: (e.target as HTMLInputElement).value })}
style="flex:1"
/>
<button
class="btn"
disabled=${saving || (draft.baseUrl ?? v.baseUrl ?? "") === (v.baseUrl ?? "")}
onClick=${() => save({ baseUrl: draft.baseUrl })}
>${t("common.save")}</button>
`,
)}
</div>
${sectionH3(t("settings.sectionDefaults"))}
<div class="card">
${fieldRow(
t("settings.preset"),
html`
<select
value=${["auto", "flash", "pro"].includes(v.preset ?? "") ? v.preset : "auto"}
onChange=${(e: Event) => save({ preset: (e.target as HTMLSelectElement).value })}
disabled=${saving}
>
<option value="auto">${t("settings.presetAuto")}</option>
<option value="flash">${t("settings.presetFlash")}</option>
<option value="pro">${t("settings.presetPro")}</option>
</select>
`,
t("settings.appliesNextTurn"),
)}
${fieldRow(
t("settings.effort"),
html`
<select
value=${v.reasoningEffort}
onChange=${(e: Event) => save({ reasoningEffort: (e.target as HTMLSelectElement).value })}
disabled=${saving}
>
<option value="max">${t("settings.effortMax")}</option>
<option value="high">${t("settings.effortHigh")}</option>
</select>
`,
t("settings.appliesNextTurn"),
)}
${fieldRow(
t("settings.webSearch"),
html`
<button
class=${`btn ${v.search ? "primary" : ""}`}
onClick=${() => save({ search: !v.search })}
disabled=${saving}
>${v.search ? t("common.on") : t("common.off")}</button>
`,
t("settings.webSearchNote"),
)}
</div>
${sectionH3(t("settings.sectionSkills"))}
<div class="card">
${fieldRow(
t("settings.skillPaths"),
html`
<input
type="text"
value=${skillPathsText}
placeholder=${t("settings.skillPathsPlaceholder")}
onInput=${(e: Event) =>
setDraft({
...draft,
skillPaths: (e.target as HTMLInputElement).value
.split(",")
.map((s) => s.trim())
.filter(Boolean),
})}
style="flex:1;font-family:var(--font-mono)"
/>
<button
class="btn"
disabled=${saving || skillPathsText === (v.skillPaths ?? []).join(", ")}
onClick=${() => save({ skillPaths: draft.skillPaths ?? [] })}
>${t("common.save")}</button>
`,
t("settings.skillPathsNote"),
)}
</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`<${ModelRow}
current=${v.model ?? "—"}
catalog=${catalog}
saving=${saving}
onPick=${(m: string) => save({ model: m })}
/>`,
t("settings.appliesNextTurn"),
)}
${fieldRow(
t("settings.editMode"),
html`<code class="mono">${v.editMode}</code>`,
t("settings.editModeNote"),
)}
</div>
</div>
`;
}
-296
View File
@@ -1,296 +0,0 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { t, useLang } from "../i18n/index.js";
import { api } from "../lib/api.js";
import { html } from "../lib/html.js";
interface SkillEntry {
name: string;
description?: string;
runs7d?: number;
}
interface SkillPathInfo {
dir: string;
scope: "custom";
status: string;
priority: number;
}
interface SkillsData {
paths: { project?: string; custom?: SkillPathInfo[] };
project: SkillEntry[];
custom: SkillEntry[];
global: SkillEntry[];
builtin: SkillEntry[];
}
type Scope = "project" | "custom" | "global" | "builtin";
export function SkillsPanel() {
useLang();
const [data, setData] = useState<SkillsData | null>(null);
const [error, setError] = useState<string | null>(null);
const [open, setOpen] = useState<{ scope: Scope; name: string } | null>(null);
const [body, setBody] = useState("");
const [busy, setBusy] = useState(false);
const [info, setInfo] = useState<string | null>(null);
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 {
setData(await api<SkillsData>("/skills"));
} catch (err) {
setError((err as Error).message);
}
}, []);
useEffect(() => {
load();
}, [load]);
const openSkill = useCallback(async (scope: Scope, name: string) => {
setOpen({ scope, name });
if (scope === "builtin" || scope === "custom") {
setBody("");
return;
}
setBusy(true);
try {
const r = await api<{ body: string }>(`/skills/${scope}/${encodeURIComponent(name)}`);
setBody(r.body);
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}, []);
const save = useCallback(async () => {
if (!open) return;
setBusy(true);
try {
await api(`/skills/${open.scope}/${encodeURIComponent(open.name)}`, {
method: "POST",
body: { body },
});
setInfo(t("skills.saved", { scope: open.scope, name: open.name }));
setTimeout(() => setInfo(null), 3000);
await load();
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}, [open, body, load]);
const remove = useCallback(async () => {
if (!open) return;
if (!confirm(t("skills.deleteConfirm", { scope: open.scope, name: open.name }))) return;
setBusy(true);
try {
await api(`/skills/${open.scope}/${encodeURIComponent(open.name)}`, { method: "DELETE" });
setOpen(null);
await load();
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}, [open, load]);
const create = useCallback(async () => {
if (!newName.trim()) return;
setBusy(true);
const stub = `---\nname: ${newName.trim()}\ndescription: TODO — one-line description that helps the model match this skill\n---\n\n# ${newName.trim()}\n\n`;
try {
await api(`/skills/${newScope}/${encodeURIComponent(newName.trim())}`, {
method: "POST",
body: { body: stub },
});
setNewName("");
await load();
openSkill(newScope, newName.trim());
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}, [newName, newScope, load, openSkill]);
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">${t("skills.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
const allWith = [
...data.project.map((s) => ({ scope: "project" as Scope, ...s })),
...data.custom.map((s) => ({ scope: "custom" as Scope, ...s })),
...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()
? scopeFiltered.filter(
(s) =>
s.name.toLowerCase().includes(filter.toLowerCase()) ||
(s.description ?? "").toLowerCase().includes(filter.toLowerCase()),
)
: scopeFiltered;
return html`
<div class="sessions-grid">
<div class="sessions-list">
<div class="ssl-h">
<input
type="text"
placeholder=${t("skills.filterPlaceholder")}
value=${filter}
onInput=${(e: Event) => setFilter((e.target as HTMLInputElement).value)}
style="flex:1"
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span
class=${`chip-f ${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 === "custom" ? "active" : ""}`}
onClick=${() => setScopeFilter("custom")}
>${t("skills.custom")} <span class="ct">${data.custom.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">
<select
value=${newScope}
onChange=${(e: Event) => setNewScope((e.target as HTMLSelectElement).value as "global" | "project")}
style="flex:0 0 auto;font-size:11.5px;padding:5px 6px"
>
<option value="global">${t("skills.global")}</option>
${data.paths.project ? html`<option value="project">${t("skills.project")}</option>` : null}
</select>
<input
type="text"
placeholder=${t("skills.newSkill")}
value=${newName}
onInput=${(e: Event) => setNewName((e.target as HTMLInputElement).value)}
style="flex:1;min-width:0"
/>
<button class="btn primary" disabled=${busy || !newName.trim()} onClick=${create} style="flex:0 0 auto">+</button>
</div>
<div class="ssl-rows">
${filtered.map((s) => {
const sel = open?.scope === s.scope && open?.name === s.name;
return html`
<div
class=${`ssl-row ${sel ? "sel" : ""}`}
onClick=${() => openSkill(s.scope, s.name)}
>
<span class="name">
${s.name}
${s.scope === "builtin" ? html`<span class="pill">${t("skills.builtin")}</span>` : null}
${s.scope === "custom" ? html`<span class="pill">${t("skills.custom")}</span>` : null}
</span>
<span class="preview">${s.description ?? t("skills.noDescription")}</span>
<span class="meta">
${
typeof s.runs7d === "number" && s.runs7d > 0
? html`<span><span class="v">${s.runs7d}</span> ${t("skills.runs7d")}</span>`
: null
}
<span class="dim">${s.scope}</span>
</span>
</div>
`;
})}
</div>
</div>
<div class="sessions-detail">
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
${t("skills.pickHint")}
</div>`
: open.scope === "builtin"
? (() => {
const builtin = data.builtin.find((b) => b.name === open.name);
return html`
<div class="sessions-detail-h">
<span class="name">${open.scope}/${open.name}</span>
<span class="ws"><span class="pill">${t("skills.readOnlyBuiltin")}</span></span>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
<div style="color:var(--fg-2);font-size:13px;line-height:1.6">
${builtin?.description ?? t("skills.noDescription")}
</div>
<div style="margin-top:14px;color:var(--fg-3);font-size:11.5px">
${t("skills.builtinDesc")}
</div>
`;
})()
: open.scope === "custom"
? (() => {
const custom = data.custom.find((b) => b.name === open.name);
return html`
<div class="sessions-detail-h">
<span class="name">${open.scope}/${open.name}</span>
<span class="ws"><span class="pill">${t("skills.readOnlyCustom")}</span></span>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
<div style="color:var(--fg-2);font-size:13px;line-height:1.6">
${custom?.description ?? t("skills.noDescription")}
</div>
<div style="margin-top:14px;color:var(--fg-3);font-size:11.5px;font-family:var(--font-mono)">
${data.paths.custom?.map((p) => html`<div>${p.status} · ${p.dir}</div>`)}
</div>
`;
})()
: html`
<div class="sessions-detail-h">
<span class="name">${open.scope}/${open.name}</span>
<span class="ws">${body.length.toLocaleString()} chars</span>
<span class="actions">
<button class="btn primary" disabled=${busy} onClick=${save}>${t("common.save")}</button>
<button class="btn" disabled=${busy} onClick=${remove}
style="border-color:var(--c-err);color:var(--c-err)">${t("common.delete")}</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
${info ? html`<div style="margin-bottom:8px"><span class="pill ok">${info}</span></div>` : null}
${error ? html`<div class="card accent-err" style="margin-bottom:8px">${error}</div>` : null}
<textarea
style="width:100%;min-height:520px;background:var(--bg-input);color:var(--fg-0);border:1px solid var(--bd);border-radius:var(--r);padding:12px;font-family:var(--font-mono);font-size:13px;line-height:1.55;resize:vertical"
value=${body}
onInput=${(e: Event) => setBody((e.target as HTMLTextAreaElement).value)}
disabled=${busy}
></textarea>
<div style="margin-top:8px;color:var(--fg-3);font-size:11.5px">
${t("skills.reloadHint")}
</div>
`
}
</div>
</div>
`;
}
-116
View File
@@ -1,116 +0,0 @@
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 {
version: string;
latestVersion: string | null;
sessions: { count: number; totalBytes: number; path: string };
memory: { fileCount: number; totalBytes: number; path: string };
semantic: { exists: boolean; fileCount?: number; totalBytes?: number; path: string };
usageLog: { bytes: number; path: string };
jobs: number | null;
reasonixHome: string;
}
export function SystemPanel() {
useLang();
const { data, error, loading } = usePoll<HealthData>("/health", 5000);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">${t("system.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "health", error: error.message })}</div>`;
if (!data) return null;
const h = data;
const upToDate = h.latestVersion ? compareVersions(h.version, h.latestVersion) >= 0 : null;
return html`
<div style="display:flex;flex-direction:column;gap:14px">
<h3 style="margin:0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">${t("system.healthChecks")}</h3>
<div class="health-grid">
<div class=${`health-item ${upToDate === false ? "warn" : ""}`}>
<div class="lbl">
${t("system.version")}
${
upToDate === null
? html`<span class="pill">${t("system.checking")}</span>`
: upToDate
? html`<span class="pill ok">${t("system.latest")}</span>`
: html`<span class="pill warn">${t("system.outOfDate")}</span>`
}
</div>
<div class="v">${h.version}</div>
<div class="meta">${
upToDate === null
? t("system.versionPending")
: upToDate
? t("system.upToDate")
: t("system.latestVer", { version: h.latestVersion ?? "" })
}</div>
</div>
<div class="health-item">
<div class="lbl">${t("system.sessions")} <span class="pill ok">${t("system.ok")}</span></div>
<div class="v">${fmtBytes(h.sessions.totalBytes)}</div>
<div class="meta">${fmtNum(h.sessions.count)} ${t("system.files")}</div>
</div>
<div class="health-item">
<div class="lbl">${t("system.memory")} <span class="pill ok">${t("system.ok")}</span></div>
<div class="v">${fmtBytes(h.memory.totalBytes)}</div>
<div class="meta">${fmtNum(h.memory.fileCount)} ${t("system.files")}</div>
</div>
<div class="health-item">
<div class="lbl">
${t("system.semanticIndex")}
${
h.semantic.exists
? html`<span class="pill ok">${t("system.built")}</span>`
: html`<span class="pill">${t("system.none")}</span>`
}
</div>
<div class="v">${h.semantic.exists ? fmtBytes(h.semantic.totalBytes) : "—"}</div>
<div class="meta">
${h.semantic.exists ? `${fmtNum(h.semantic.fileCount)} ${t("system.files")}` : t("system.runIndex")}
</div>
</div>
<div class="health-item">
<div class="lbl">${t("system.usageLog")} <span class="pill ok">${t("system.ok")}</span></div>
<div class="v">${fmtBytes(h.usageLog.bytes)}</div>
<div class="meta">~/.reasonix/usage.jsonl</div>
</div>
<div class="health-item">
<div class="lbl">
${t("system.backgroundJobs")}
${
h.jobs === null
? html`<span class="pill">${t("system.noSession")}</span>`
: html`<span class="pill ok">● ${fmtNum(h.jobs)}</span>`
}
</div>
<div class="v">${h.jobs === null ? "—" : t("system.running", { count: fmtNum(h.jobs) })}</div>
<div class="meta">${h.jobs === null ? t("system.attachHint") : t("system.shellSpawn")}</div>
</div>
</div>
<div class="card" style="padding:0">
<div class="card-h" style="padding:12px 14px 6px">
<span class="title">${t("system.paths")}</span>
</div>
<table class="tbl">
<tbody style="font-size:11.5px">
<tr><td class="dim" style="padding:5px 14px">${t("system.home")}</td><td class="path">${h.reasonixHome}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.sessionsPath")}</td><td class="path">${h.sessions.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.memoryPath")}</td><td class="path">${h.memory.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.semanticPath")}</td><td class="path">${h.semantic.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.usagePath")}</td><td class="path">${h.usageLog.path}</td></tr>
</tbody>
</table>
</div>
</div>
`;
}
-85
View File
@@ -1,85 +0,0 @@
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface ToolEntry {
name: string;
description?: string;
readOnly?: boolean;
flattened?: boolean;
}
interface ToolsData {
total: number;
planMode?: boolean;
tools: ToolEntry[];
}
interface ToolsError {
status?: number;
message: string;
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);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">${t("tools.loading")}</div>`;
const e = error as ToolsError | null;
if (e?.status === 503) {
return html`<div class="card accent-warn">${e.body?.error ?? t("common.loadingFailed", { name: "tools", error: "" })}</div>`;
}
if (e) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "tools", error: e.message })}</div>`;
if (!data) return null;
const d = data;
return html`
<div style="display:flex;flex-direction:column;gap:14px">
<div class="chips">
<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>
${
d.tools.length === 0
? html`<div class="card" style="color:var(--fg-3)">${t("tools.noTools")}</div>`
: html`
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<th>${t("tools.colTool")}</th>
<th>${t("tools.colFlags")}</th>
<th>${t("tools.colDesc")}</th>
</tr>
</thead>
<tbody>
${d.tools.map(
(tool) => html`
<tr>
<td><code class="mono">${tool.name}</code></td>
<td>
${tool.readOnly
? html`<span class="pill ok">${t("tools.readOnly")}</span>`
: html`<span class="pill acc">${t("tools.write")}</span>`}
${tool.flattened ? html` <span class="pill">${t("tools.flat")}</span>` : null}
</td>
<td class="dim">${toolDesc(tool.name, tool.description ?? "")}</td>
</tr>
`,
)}
</tbody>
</table>
</div>
`
}
</div>
`;
}
-276
View File
@@ -1,276 +0,0 @@
import { useEffect, useRef, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { fmtNum, fmtPct, fmtUsd } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
type UPlotInstance = {
destroy(): void;
setSize(opts: { width: number; height: number }): void;
};
type UPlotConstructor = new (
opts: unknown,
data: unknown,
el: HTMLElement,
) => UPlotInstance;
let uPlotPromise: Promise<UPlotConstructor> | null = null;
function loadUPlot(): Promise<UPlotConstructor> {
if (!uPlotPromise) {
uPlotPromise = import("uplot").then(
(m) => (m.default ?? m) as UPlotConstructor,
);
}
return uPlotPromise;
}
interface UsageDay {
day: string;
costUsd: number;
cacheSavingsUsd: number;
turns: number;
}
function UsageChart({ days }: { days: UsageDay[] }) {
const containerRef = useRef<HTMLDivElement>(null);
const plotRef = useRef<UPlotInstance | null>(null);
useLang();
useEffect(() => {
let cancelled = false;
loadUPlot().then((uPlot) => {
if (cancelled || !containerRef.current) return;
if (plotRef.current) {
plotRef.current.destroy();
plotRef.current = null;
}
if (!days || days.length === 0) return;
const xs = days.map((d) => Math.floor(Date.parse(d.day) / 1000));
const cost = days.map((d) => d.costUsd);
const saved = days.map((d) => d.cacheSavingsUsd);
const turns = days.map((d) => d.turns);
const data = [xs, cost, saved, turns];
const opts = {
width: containerRef.current.clientWidth,
height: 280,
cursor: { drag: { x: true, y: false } },
scales: {
x: { time: true },
y: { auto: true },
turns: { auto: true },
},
axes: [
{ stroke: "#94a3b8", grid: { stroke: "rgba(148, 163, 184, 0.08)" } },
{
scale: "y",
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)}`),
},
{
scale: "turns",
side: 1,
label: t("usage.axisTurns"),
stroke: "#94a3b8",
grid: { show: false },
},
],
series: [
{ label: t("usage.axisTime") },
{
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,
points: { show: true, size: 4 },
},
],
legend: { live: true },
};
plotRef.current = new uPlot(opts, data, containerRef.current);
});
const ro = new ResizeObserver(() => {
if (plotRef.current && containerRef.current) {
plotRef.current.setSize({ width: containerRef.current.clientWidth, height: 280 });
}
});
if (containerRef.current) ro.observe(containerRef.current);
return () => {
cancelled = true;
ro.disconnect();
if (plotRef.current) {
plotRef.current.destroy();
plotRef.current = null;
}
};
}, [days]);
return html`<div ref=${containerRef} style="width: 100%; min-height: 280px;"></div>`;
}
interface Bucket {
label: string;
turns: number;
cacheHitTokens: number;
cacheMissTokens: number;
costUsd: number;
cacheSavingsUsd: number;
claudeEquivUsd: number;
}
interface UsageSummary {
recordCount: number;
logSize: string;
buckets: Bucket[];
byModel: { model: string; turns: number }[];
subagents?: { total: number; costUsd: number; totalDurationMs: number };
}
export function UsagePanel() {
useLang();
const { data: summary, error, loading } = usePoll<UsageSummary>("/usage", 5000);
const [series, setSeries] = useState<UsageDay[] | null>(null);
useEffect(() => {
let cancelled = false;
(async () => {
try {
const s = await api<{ days?: UsageDay[] }>("/usage/series");
if (!cancelled) setSeries(s.days ?? []);
} catch {
/* keep null; chart hides */
}
})();
const interval = setInterval(async () => {
try {
const s = await api<{ days?: UsageDay[] }>("/usage/series");
if (!cancelled) setSeries(s.days ?? []);
} catch {
/* swallow */
}
}, 30_000);
return () => {
cancelled = true;
clearInterval(interval);
};
}, []);
if (loading && !summary)
return html`<div class="card" style="color:var(--fg-3)">${t("usage.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "usage", error: error.message })}</div>`;
if (!summary) return null;
const u = summary;
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>
`;
return html`
<div style="display:flex;flex-direction:column;gap:6px">
<div class="chips">
<span class="chip-f static active">${t("usage.records", { count: u.recordCount.toLocaleString() })}</span>
<span class="chip-f static">${u.logSize}</span>
</div>
${
series && series.length > 0
? html`
<div class="card" style="padding:18px">
<div class="card-h">
<span class="title">${t("usage.dailyUsage")}</span>
<span class="meta">${t("usage.dailyMeta")}</span>
</div>
<${UsageChart} days=${series} />
</div>
`
: null
}
${
u.recordCount === 0
? html`<div class="card" style="color:var(--fg-3);margin-top:8px">
${t("usage.noData")}
</div>`
: html`
${sectionH3(t("usage.windows"))}
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<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>
${u.buckets.map((b) => {
const hitRatio =
b.cacheHitTokens + b.cacheMissTokens > 0
? b.cacheHitTokens / (b.cacheHitTokens + b.cacheMissTokens)
: 0;
const claudeSavings =
b.claudeEquivUsd > 0 ? 1 - b.costUsd / b.claudeEquivUsd : 0;
return html`
<tr>
<td class="dim">${b.label}</td>
<td class="num">${fmtNum(b.turns)}</td>
<td class="num">${b.turns > 0 ? fmtPct(hitRatio) : "—"}</td>
<td class="num">${b.turns > 0 ? fmtUsd(b.costUsd) : "—"}</td>
<td class="num">${b.turns > 0 && b.cacheSavingsUsd > 0 ? fmtUsd(b.cacheSavingsUsd) : "—"}</td>
<td class="num">${b.turns > 0 ? fmtUsd(b.claudeEquivUsd) : "—"}</td>
<td class="num">${b.turns > 0 && claudeSavings > 0 ? fmtPct(claudeSavings) : "—"}</td>
</tr>
`;
})}
</tbody>
</table>
</div>
`
}
${
u.byModel.length > 0
? html`
${sectionH3(t("usage.mostUsed"))}
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<th>${t("usage.colModel")}</th>
<th>${t("usage.colTurns")}</th>
</tr>
</thead>
<tbody>
${u.byModel.slice(0, 5).map(
(m) => html`
<tr>
<td><code class="mono">${m.model}</code></td>
<td class="num">${fmtNum(m.turns)}</td>
</tr>
`,
)}
</tbody>
</table>
</div>
`
: null
}
</div>
`;
}
+541
View File
@@ -0,0 +1,541 @@
export type ReadyEvent = { type: "$ready" };
export type ProtocolErrorEvent = { type: "$error"; message: string };
export type TurnCompleteEvent = { type: "$turn_complete" };
export type PathAccessRequiredEvent = {
type: "$path_access_required";
id: number;
path: string;
intent: "read" | "write";
toolName: string;
sandboxRoot: string;
allowPrefix: string;
};
export type ConfirmRequiredEvent = {
type: "$confirm_required";
id: number;
kind: "run_command" | "run_background";
command: string;
};
export type ConfirmationChoice =
| { type: "deny"; denyContext?: string }
| { type: "run_once" }
| { type: "always_allow"; prefix: string };
export type ChoiceOption = {
id: string;
title: string;
summary?: string;
};
export type ChoiceRequiredEvent = {
type: "$choice_required";
id: number;
question: string;
options: ChoiceOption[];
allowCustom: boolean;
};
export type ChoiceVerdict =
| { type: "pick"; optionId: string }
| { type: "text"; text: string }
| { type: "cancel" };
export type PlanRequiredEvent = {
type: "$plan_required";
id: number;
plan: string;
steps?: unknown[];
summary?: string;
};
export type PlanVerdict =
| { type: "approve"; feedback?: string }
| { type: "refine"; feedback?: string }
| { type: "cancel"; feedback?: string };
export type PlanStep = {
id: string;
title: string;
action: string;
risk?: "low" | "med" | "high";
};
export type CheckpointRequiredEvent = {
type: "$checkpoint_required";
id: number;
stepId: string;
title?: string;
result: string;
notes?: string;
completed: number;
total: number;
};
export type CheckpointVerdict =
| { type: "continue" }
| { type: "revise"; feedback?: string }
| { type: "stop" };
export type RevisionRequiredEvent = {
type: "$revision_required";
id: number;
reason: string;
remainingSteps: PlanStep[];
summary?: string;
};
export type RevisionVerdict = { type: "accepted" } | { type: "rejected" } | { type: "cancelled" };
export type ModalKind =
| "shell"
| "path"
| "choice"
| "plan"
| "checkpoint"
| "revision"
| "edit-review";
export type ModalDismissedEvent = { type: "$modal_dismissed"; kind: ModalKind };
export type StepCompletedEvent = {
type: "$step_completed";
stepId: string;
title?: string;
result: string;
notes?: string;
};
export type PlanClearedEvent = { type: "$plan_cleared" };
export type SessionsEvent = {
type: "$sessions";
currentSession?: string | null;
items: {
name: string;
messageCount: number;
mtime: string;
summary?: string;
workspaceStatus?: "matched" | "legacy_missing_meta";
}[];
};
export type SessionUsageEvent = {
type: "$session_usage";
totalCostUsd: number;
totalPromptTokens: number;
totalCompletionTokens: number;
cacheHitTokens: number;
cacheMissTokens: number;
};
export type MentionResultsEvent = {
type: "$mention_results";
nonce: number;
query: string;
results: string[];
};
export type MentionPreviewEvent = {
type: "$mention_preview";
nonce: number;
path: string;
head: string;
totalLines: number;
};
export type TabOpenedEvent = {
type: "$tab_opened";
workspaceDir: string;
/** True when the frontend should focus this tab (user-opened, or the restored focused tab). */
active?: boolean;
};
export type TabClosedEvent = {
type: "$tab_closed";
};
export type McpSpecStatus = "configured" | "handshake" | "connected" | "failed" | "disabled";
export type McpSpecInfo = {
raw: string;
name: string | null;
transport: "stdio" | "sse" | "streamable-http";
summary: string;
parseError?: string;
status: McpSpecStatus;
statusReason?: string;
toolCount?: number;
};
export type McpSpecsEvent = {
type: "$mcp_specs";
specs: McpSpecInfo[];
bridged: boolean;
};
export type SkillScope = "project" | "global" | "builtin";
export type SkillInfo = {
name: string;
description: string;
scope: SkillScope;
path: string;
runAs: "inline" | "subagent";
model?: string;
};
export type SkillsEvent = {
type: "$skills";
items: SkillInfo[];
};
export type CtxBreakdownEvent = {
type: "$ctx_breakdown";
reservedTokens: number;
};
export type MemoryEntryInfo = {
kind: "project_file" | "global_file" | "structured";
name: string;
scope: "project" | "global";
path: string;
description: string;
type?: string;
};
export type MemoryEvent = {
type: "$memory";
entries: MemoryEntryInfo[];
};
export type MemoryDetail = MemoryEntryInfo & {
body: string;
createdAt?: string;
};
export type MemoryDetailEvent = {
type: "$memory_detail";
detail: MemoryDetail;
};
export type RetryResultEvent = { type: "$retry_result"; text: string };
export type BtwResultEvent = { type: "$btw_result"; question: string; answer: string };
export type JobInfo = {
id: number;
tabId: string;
sessionLabel: string;
command: string;
pid: number | null;
running: boolean;
exitCode: number | null;
startedAt: number;
outputTail: string;
spawnError?: string;
};
export type JobsEvent = {
type: "$jobs";
items: JobInfo[];
};
export type LoadedSegment =
| { kind: "text"; text: string }
| { kind: "reasoning"; text: string }
| {
kind: "tool";
callId: string;
name: string;
args: string;
result?: string;
ok?: boolean;
};
export type LoadedMessage =
| { kind: "user"; text: string }
| {
kind: "assistant";
turn: number;
segments: LoadedSegment[];
pending: false;
};
export type SessionLoadedEvent = {
type: "$session_loaded";
name: string;
messages: LoadedMessage[];
carryover: {
totalCostUsd: number;
cacheHitTokens: number;
cacheMissTokens: number;
};
};
export type SessionEmptyEvent = {
type: "$session_empty";
name: string;
sizeBytes: number;
};
export type NeedsSetupEvent = {
type: "$needs_setup";
reason: "no_api_key";
};
export type EditMode = "review" | "auto" | "yolo" | "plan";
export type ReasoningEffort = "low" | "medium" | "high" | "max";
export type WebSearchEngineName =
| "bing"
| "searxng"
| "metaso"
| "tavily"
| "perplexity"
| "exa"
| "brave"
| "ollama";
export type SettingsEvent = {
type: "$settings";
reasoningEffort: ReasoningEffort;
editMode: EditMode;
budgetUsd: number | null;
baseUrl?: string;
apiKeyPrefix?: string;
workspaceDir: string;
recentWorkspaces: string[];
model: string;
editor?: string;
webSearchEngine?: WebSearchEngineName;
subagentModels?: Record<string, "flash" | "pro">;
showSystemEvents?: boolean;
version: string;
};
export type QQSettingsEvent = {
type: "$qq_settings";
appId?: string;
appSecret?: string;
sandbox: boolean;
enabled: boolean;
configured: boolean;
runtimeState: "disconnected" | "connecting" | "connected" | "failed";
lastError?: string;
appIdPreview?: string;
access: string;
};
export type BalanceEvent = {
type: "$balance";
currency: string;
total: number;
isAvailable: boolean;
};
export type SettingsPatch = {
reasoningEffort?: ReasoningEffort;
editMode?: EditMode;
budgetUsd?: number | null;
baseUrl?: string;
workspaceDir?: string;
model?: string;
editor?: string;
webSearchEngine?: WebSearchEngineName;
subagentModels?: Record<string, "flash" | "pro">;
showSystemEvents?: boolean;
};
export type QQConfigPatch = {
appId?: string;
appSecret?: string;
sandbox: boolean;
};
export type UserMessageEvent = {
type: "user.message";
id: number;
ts: string;
turn: number;
text: string;
};
export type ModelTurnStartedEvent = {
type: "model.turn.started";
id: number;
ts: string;
turn: number;
model: string;
reasoningEffort: ReasoningEffort;
prefixHash: string;
};
export type ModelDeltaEvent = {
type: "model.delta";
id: number;
ts: string;
turn: number;
channel: "content" | "reasoning" | "tool_args";
text: string;
};
export type Usage = {
prompt_tokens?: number;
completion_tokens?: number;
total_tokens?: number;
prompt_cache_hit_tokens?: number;
prompt_cache_miss_tokens?: number;
};
export type ModelFinalEvent = {
type: "model.final";
id: number;
ts: string;
turn: number;
content: string;
reasoningContent?: string;
usage?: Usage;
costUsd?: number;
};
export type ToolPreparingEvent = {
type: "tool.preparing";
id: number;
ts: string;
turn: number;
callId: string;
name: string;
};
export type ToolIntentEvent = {
type: "tool.intent";
id: number;
ts: string;
turn: number;
callId: string;
name: string;
args: string;
};
export type ToolResultEvent = {
type: "tool.result";
id: number;
ts: string;
turn: number;
callId: string;
ok: boolean;
output: string;
};
export type StatusEvent = {
type: "status";
id: number;
ts: string;
turn: number;
text: string;
};
export type WarningEvent = {
type: "warning";
id: number;
ts: string;
turn: number;
text: string;
severity: "low" | "high";
};
export type KernelErrorEvent = {
type: "error";
id: number;
ts: string;
turn: number;
message: string;
recoverable: boolean;
};
export type IncomingEvent = { tabId?: string } & (
| ReadyEvent
| ProtocolErrorEvent
| TurnCompleteEvent
| ConfirmRequiredEvent
| PathAccessRequiredEvent
| ChoiceRequiredEvent
| PlanRequiredEvent
| SessionsEvent
| SessionUsageEvent
| SessionLoadedEvent
| SessionEmptyEvent
| NeedsSetupEvent
| SettingsEvent
| QQSettingsEvent
| BalanceEvent
| CheckpointRequiredEvent
| RevisionRequiredEvent
| ModalDismissedEvent
| StepCompletedEvent
| PlanClearedEvent
| MentionResultsEvent
| MentionPreviewEvent
| TabOpenedEvent
| TabClosedEvent
| McpSpecsEvent
| SkillsEvent
| CtxBreakdownEvent
| MemoryEvent
| MemoryDetailEvent
| JobsEvent
| UserMessageEvent
| ModelTurnStartedEvent
| ModelDeltaEvent
| ModelFinalEvent
| ToolPreparingEvent
| ToolIntentEvent
| ToolResultEvent
| StatusEvent
| WarningEvent
| KernelErrorEvent
| RetryResultEvent
| BtwResultEvent
);
export type OutgoingCommand = { tabId?: string } & (
| { cmd: "user_input"; text: string }
| { cmd: "abort" }
| { cmd: "confirm_response"; id: number; response: ConfirmationChoice; kind: "shell" | "path" }
| { cmd: "choice_response"; id: number; response: ChoiceVerdict }
| { cmd: "plan_response"; id: number; response: PlanVerdict }
| { cmd: "checkpoint_response"; id: number; response: CheckpointVerdict }
| { cmd: "revision_response"; id: number; response: RevisionVerdict }
| { cmd: "session_list" }
| { cmd: "session_delete"; name: string }
| { cmd: "session_load"; name: string }
| { cmd: "memory_read"; path: string }
| { cmd: "new_chat" }
| { cmd: "setup_save_key"; key: string }
| { cmd: "settings_get" }
| ({ cmd: "settings_save" } & SettingsPatch)
| { cmd: "qq_status_get" }
| { cmd: "qq_connect" }
| { cmd: "qq_disconnect" }
| ({ cmd: "qq_config_save" } & QQConfigPatch)
| { cmd: "mention_query"; query: string; nonce: number }
| { cmd: "mention_preview"; path: string; nonce: number }
| { cmd: "mention_picked"; path: string }
| { cmd: "tab_open"; workspaceDir?: string }
| { cmd: "tab_close" }
| { cmd: "tab_activate"; tabId: string }
| { cmd: "mcp_specs_get" }
| { cmd: "mcp_specs_add"; spec: string }
| { cmd: "mcp_specs_remove"; spec: string }
| { cmd: "skills_get" }
| { cmd: "skill_run"; name: string; args?: string }
| { cmd: "jobs_list" }
| { cmd: "jobs_stop"; jobId: number }
| { cmd: "jobs_stop_all" }
| { cmd: "compact_history" }
| { cmd: "retry" }
| { cmd: "btw"; text: string }
);
+63
View File
@@ -0,0 +1,63 @@
import { t } from "./i18n";
export interface QQDesktopSettingsState {
appId?: string;
appSecret?: string;
sandbox: boolean;
enabled: boolean;
configured: boolean;
runtimeState: "disconnected" | "connecting" | "connected" | "failed";
lastError?: string;
appIdPreview?: string;
access: string;
}
export function maskQQAppId(appId: string | undefined): string | undefined {
if (!appId) return undefined;
return appId.length > 6 ? `${appId.slice(0, 6)}...` : appId;
}
export function getQQConnectIntent(qq: QQDesktopSettingsState): "configure" | "connect" {
return qq.configured ? "connect" : "configure";
}
export function getQQStatusLabel(qq: QQDesktopSettingsState): string {
switch (qq.runtimeState) {
case "connected":
return t("settings.qqConnected");
case "connecting":
return t("settings.qqConnecting");
case "failed":
return t("settings.qqFailed");
default:
return t("settings.qqDisconnected");
}
}
export function describeQQAccessLabel(access: string): string {
const owner = /^owner (.+?)(?:, allowlist (\d+))?$/.exec(access);
if (owner) {
const openId = owner[1] ?? "unknown";
const count = owner[2];
if (count) return t("settings.qqAccessOwnerWithAllowlist", { openId, count });
return t("settings.qqAccessOwner", { openId });
}
const allowlist = /^allowlist (\d+)$/.exec(access);
if (allowlist) return t("settings.qqAccessAllowlist", { count: allowlist[1] ?? "0" });
const runtime = /^first-sender \(runtime only, (.+)\)$/.exec(access);
if (runtime) return t("settings.qqAccessRuntime", { openId: runtime[1] ?? "unknown" });
return t("settings.qqAccessOpen");
}
export function describeQQRowSummary(qq: QQDesktopSettingsState): string {
if (!qq.configured) return t("settings.qqSummaryMissing");
const appId = qq.appIdPreview ?? maskQQAppId(qq.appId) ?? "unknown";
return t("settings.qqSummaryDetail", {
appId: t("settings.qqSummaryAppId", { appId }),
environment: qq.sandbox ? t("settings.qqSandbox") : t("settings.qqProduction"),
access: describeQQAccessLabel(qq.access),
});
}
File diff suppressed because it is too large. Load diff
+91
View File
@@ -0,0 +1,91 @@
export const THEME = {
DARK: "dark",
LIGHT: "light",
} as const;
export type Theme = (typeof THEME)[keyof typeof THEME];
export function isTheme(value: unknown): value is Theme {
return value === THEME.DARK || value === THEME.LIGHT;
}
export const THEME_STYLE = {
GRAPHITE: "graphite",
SANDSTONE: "sandstone",
PORCELAIN: "porcelain",
MIDNIGHT: "midnight",
} as const;
export type ThemeStyle = (typeof THEME_STYLE)[keyof typeof THEME_STYLE];
export const DEFAULT_THEME_STYLE: Record<Theme, ThemeStyle> = {
dark: THEME_STYLE.GRAPHITE,
light: THEME_STYLE.SANDSTONE,
};
export const THEME_STYLE_THEME: Record<ThemeStyle, Theme> = {
graphite: THEME.DARK,
sandstone: THEME.LIGHT,
porcelain: THEME.LIGHT,
midnight: THEME.DARK,
};
export const THEME_STYLES = [
THEME_STYLE.GRAPHITE,
THEME_STYLE.SANDSTONE,
THEME_STYLE.PORCELAIN,
THEME_STYLE.MIDNIGHT,
] as const;
export function isThemeStyle(value: unknown): value is ThemeStyle {
return (
value === THEME_STYLE.GRAPHITE ||
value === THEME_STYLE.SANDSTONE ||
value === THEME_STYLE.PORCELAIN ||
value === THEME_STYLE.MIDNIGHT
);
}
export function themeForStyle(style: ThemeStyle): Theme {
return THEME_STYLE_THEME[style];
}
export function defaultStyleForTheme(theme: Theme): ThemeStyle {
return DEFAULT_THEME_STYLE[theme];
}
export const FONT_SCALE = {
SMALL: "small",
MEDIUM: "medium",
LARGE: "large",
} as const;
export type FontScale = (typeof FONT_SCALE)[keyof typeof FONT_SCALE];
export function isFontScale(value: unknown): value is FontScale {
return value === FONT_SCALE.SMALL || value === FONT_SCALE.MEDIUM || value === FONT_SCALE.LARGE;
}
export const FONT_SCALE_ZOOM: Record<FontScale, number> = {
small: 0.875,
medium: 1.0,
large: 1.125,
};
export const FONT_FAMILY = {
SANS: "sans",
SYSTEM: "system",
SERIF: "serif",
} as const;
export type FontFamily = (typeof FONT_FAMILY)[keyof typeof FONT_FAMILY];
export function isFontFamily(value: unknown): value is FontFamily {
return value === FONT_FAMILY.SANS || value === FONT_FAMILY.SYSTEM || value === FONT_FAMILY.SERIF;
}
export const FONT_FAMILY_STACK: Record<FontFamily, string> = {
sans: '"Geist", system-ui, sans-serif',
system: '-apple-system, system-ui, "Segoe UI", Roboto, sans-serif',
serif: 'Georgia, "Times New Roman", serif',
};
+38
View File
@@ -0,0 +1,38 @@
import { openUrl } from "@tauri-apps/plugin-opener";
import { t } from "../i18n";
import { I } from "../icons";
const REPO_URL = "https://github.com/esengine/DeepSeek-Reasonix";
export function AboutModal({ onClose }: { onClose: () => void }) {
const openGitHub = () => {
void openUrl(REPO_URL).catch(() => undefined);
};
return (
<div className="about-mask" onClick={onClose}>
<div className="about-modal" onClick={(e) => e.stopPropagation()}>
<button type="button" className="about-close" onClick={onClose} aria-label={t("about.close")}>
<I.x size={14} />
</button>
<div className="about-brand">
<div className="about-name">Reasonix</div>
<div className="about-tagline">{t("about.tagline")}</div>
</div>
<div className="about-meta">
<div className="about-row">
<span className="about-label">{t("about.version")}</span>
<code className="about-value">{__APP_VERSION__}</code>
</div>
<div className="about-row">
<span className="about-label">{t("about.repo")}</span>
<button type="button" className="about-link" onClick={openGitHub}>
<I.link size={12} />
<span>esengine/DeepSeek-Reasonix</span>
</button>
</div>
</div>
</div>
</div>
);
}
+750
View File
@@ -0,0 +1,750 @@
import { memo, useState, type ReactNode } from "react";
import { I } from "../icons";
import { Markdown } from "../Markdown";
import { t, useLang } from "../i18n";
import { Shortcut } from "./shortcut";
type Tone = "default" | "success" | "warning" | "danger" | "accent" | "violet";
export function Card({
tone = "default",
icon,
kind,
name,
meta,
defaultOpen = true,
compact = false,
children,
headRight,
}: {
tone?: Tone;
icon: ReactNode;
kind: string;
name?: ReactNode;
meta?: ReactNode;
defaultOpen?: boolean;
/** Slimmer header — used for thinking / tool-call process cards so they
* read as background detail rather than primary content. */
compact?: boolean;
children: ReactNode;
headRight?: ReactNode;
}) {
const [open, setOpen] = useState(defaultOpen);
return (
<div className={compact ? "card is-compact" : "card"} data-tone={tone} data-open={open}>
<button
type="button"
className="card-head"
onClick={() => setOpen((v) => !v)}
style={{
width: "100%",
background: "none",
border: "none",
textAlign: "left",
font: "inherit",
color: "inherit",
}}
>
<span className="ico">{icon}</span>
<span className="kind">{kind}</span>
{name ? <span className="name">{name}</span> : null}
<span className="grow" />
{meta ? <span className="meta">{meta}</span> : null}
{headRight}
<span className="chev">
<I.chev size={12} />
</span>
</button>
{open ? <div className="card-body">{children}</div> : null}
</div>
);
}
// ---- Plan ----
export type PlanItem = {
id: string | number;
status: "todo" | "active" | "done" | "failed" | "blocked" | "skipped";
text: string;
tool?: string;
note?: string;
};
function derivePlanBadge(items: PlanItem[]): { state: "running" | "done" | "failed" | "waiting" | "blocked"; label: string } {
if (items.some((x) => x.status === "failed")) return { state: "failed", label: t("planBadge.failed") };
if (items.some((x) => x.status === "blocked")) return { state: "blocked", label: t("planBadge.blocked") };
if (items.some((x) => x.status === "active")) return { state: "running", label: t("planBadge.running") };
if (items.length > 0 && items.every((x) => x.status === "done")) return { state: "done", label: t("planBadge.done") };
return { state: "waiting", label: t("planBadge.pending") };
}
function StatusIcon({ state, label }: { state: "running" | "done" | "failed" | "waiting" | "blocked"; label: string }) {
switch (state) {
case "running":
return <span className="spin-meta" role="img" aria-label={label} title={label} />;
case "done":
return <I.check size={10} style={{ color: "var(--success)" }} aria-label={label} />;
case "failed":
return <I.x size={10} style={{ color: "var(--danger)" }} aria-label={label} />;
case "waiting":
return <span className="status-dot warn" role="img" aria-label={label} title={label} />;
case "blocked":
return <I.slash size={10} style={{ color: "var(--warning)" }} aria-label={label} />;
}
}
export function PlanCardView({ items, title }: { items: PlanItem[]; title?: string }) {
useLang();
const resolvedTitle = title ?? t("cards.planDefaultTitle");
const done = items.filter((x) => x.status === "done").length;
const badge = derivePlanBadge(items);
return (
<Card
tone="accent"
icon={<I.list size={12} />}
kind="plan"
name={resolvedTitle}
meta={
<>
<span>
{done}/{items.length}
</span>
<StatusIcon state={badge.state} label={badge.label} />
<span className="meta-label">{badge.label}</span>
</>
}
>
<ul className="plan-list" style={{ listStyle: "none", margin: 0, padding: "8px 12px 12px" }}>
{items.map((it) => (
<li key={it.id} className="plan-item" data-status={it.status}>
<span className="ck">{it.status === "done" ? <I.check size={12} /> : null}</span>
<div>
<div className="text">{it.text}</div>
{it.tool || it.note ? (
<div className="sub">
{it.tool ? <span className="tool">{it.tool}</span> : null}
{it.note ? <span>{it.note}</span> : null}
</div>
) : null}
</div>
<span className="stat">{it.status === "active" ? <span className="spin" /> : null}</span>
</li>
))}
</ul>
</Card>
);
}
// ---- Reasoning ----
export function ReasoningCard({
text,
streaming,
tokens,
elapsed,
model,
}: {
text: string;
streaming: boolean;
tokens?: number;
elapsed?: string;
model?: string;
}) {
useLang();
return (
<Card
tone="violet"
icon={<I.brain size={12} />}
kind="reasoning"
name={t("cards.reasoningName")}
meta={
<>
{elapsed || tokens ? (
<span>
{elapsed ?? ""}
{elapsed && tokens ? " · " : ""}
{tokens ? `${tokens.toLocaleString()} t` : ""}
</span>
) : null}
{streaming ? (
<StatusIcon state="running" label={t("cards.streaming")} />
) : (
<StatusIcon state="done" label={t("cards.reasoningComplete")} />
)}
</>
}
defaultOpen={streaming}
compact
>
<div className="reason">
<div className="stream">
{text.split(/\n\n+/).map((para, i) => (
<p
key={i}
dangerouslySetInnerHTML={{
__html: para
.replace(/`([^`]+)`/g, '<span class="hl">$1</span>')
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>"),
}}
/>
))}
</div>
{model || tokens !== undefined ? (
<div className="meta">
{model ? (
<span>
<span className="k">{t("settings.model")}</span> {model}
</span>
) : null}
{tokens !== undefined ? (
<span>
<span className="k">{t("statusbar.tokens")}</span> {tokens.toLocaleString()}
</span>
) : null}
</div>
) : null}
</div>
</Card>
);
}
// ---- Shell ----
export function ShellCard({
command,
output,
state,
durationMs,
onApprove,
onReject,
onAlwaysAllow,
}: {
command: string;
output?: string;
state: "await" | "running" | "done" | "failed";
durationMs?: number;
onApprove?: () => void;
onReject?: () => void;
onAlwaysAllow?: () => void;
}) {
useLang();
const tone: Tone = state === "failed" ? "danger" : state === "done" ? "success" : "warning";
return (
<Card
tone={tone}
icon={<I.terminal size={12} />}
kind="shell"
name="shell"
compact
meta={
<>
{state === "await" ? (
<StatusIcon state="waiting" label={t("cards.shellAwaiting")} />
) : state === "running" ? (
<StatusIcon state="running" label={t("cards.shellRunning")} />
) : state === "failed" ? (
<StatusIcon state="failed" label={t("cards.failed")} />
) : (
<StatusIcon state="done" label={t("cards.done")} />
)}
{(state === "done" || state === "failed") && durationMs ? (
<span className="meta-dur">{(durationMs / 1000).toFixed(2)}s</span>
) : null}
</>
}
>
<div className="shell">
<div className="cmd">
<span className="prompt">$</span>
<span className="text">{command}</span>
</div>
{output ? (
<pre className="out">
{output.split("\n").map((ln, i) => {
if (ln.startsWith(" ✓") || ln.startsWith("✓"))
return (
<div key={i}>
<span className="ok">{ln}</span>
</div>
);
if (ln.startsWith(" ✗") || ln.startsWith("✗") || /error/i.test(ln))
return (
<div key={i}>
<span className="err">{ln}</span>
</div>
);
return <div key={i}>{ln}</div>;
})}
</pre>
) : null}
{state === "await" && onApprove ? (
<div className="approve-row">
<div className="why">
<b>{t("cards.shellAwaiting")}</b> — {t("cards.shellExecuteHint")}
</div>
<div className="actions">
{onAlwaysAllow ? (
<button type="button" className="btn ghost" onClick={onAlwaysAllow}>
{t("cards.shellAlwaysAllow")}
</button>
) : null}
{onReject ? (
<button type="button" className="btn" onClick={onReject}>
{t("cards.shellReject")} <Shortcut keys={["mod", "."]} />
</button>
) : null}
<button type="button" className="btn primary" onClick={onApprove}>
{t("cards.shellRun")} <Shortcut keys={["mod", "enter"]} />
</button>
</div>
</div>
) : null}
</div>
</Card>
);
}
// ---- Compaction ----
export function CompactionCard({ summary }: { summary: string }) {
useLang();
const charCount = summary.length;
return (
<Card
tone="default"
icon={<I.archive size={12} />}
kind="compaction"
name={t("cards.compactionName")}
meta={<span>{t("cards.compactionMeta", { chars: charCount.toLocaleString() })}</span>}
defaultOpen={false}
compact
>
<div className="compaction-body">
<Markdown source={summary} />
</div>
</Card>
);
}
// ---- Generic Tool ----
export function ToolCard({
name,
args,
result,
ok,
durationMs,
}: {
name: string;
args?: string;
result?: string;
ok?: boolean;
durationMs?: number;
}) {
useLang();
const running = result === undefined;
const tone: Tone = running ? "default" : ok === false ? "danger" : "success";
return (
<Card
tone={tone}
icon={<I.wrench size={12} />}
kind="tool"
name={name}
defaultOpen={false}
compact
meta={
<>
{running ? (
<StatusIcon state="running" label={t("cards.running")} />
) : ok === false ? (
<StatusIcon state="failed" label={t("cards.error")} />
) : (
<StatusIcon state="done" label={t("cards.done")} />
)}
{!running && durationMs !== undefined ? (
<span className="meta-dur">{durationMs} ms</span>
) : null}
</>
}
>
<div className="tool-call">
{args ? (
<div className="row">
<span className="k">args</span>
<span className="v">
<span className="str">{args.length > 600 ? `${args.slice(0, 600)}…` : args}</span>
</span>
</div>
) : null}
{result !== undefined ? (
<div className="row">
<span className="k">{ok === false ? t("cards.error") : t("cards.result")}</span>
<span className="v">
<span className={ok === false ? "num" : "str"}>
{result.length > 1200 ? `${result.slice(0, 1200)}…` : result}
</span>
</span>
</div>
) : null}
</div>
</Card>
);
}
// ---- Diff ----
export type DiffLine =
| { t: "hunk"; s: string }
| { t: "ctx"; l?: number; r?: number; s: string }
| { t: "add"; r: number; s: string }
| { t: "rm"; l: number; s: string };
export function DiffCard({
filename,
lines,
applied,
onApply,
onDiscard,
}: {
filename: string;
lines: DiffLine[];
applied?: boolean;
onApply?: () => void;
onDiscard?: () => void;
}) {
useLang();
const adds = lines.filter((x) => x.t === "add").length;
const rms = lines.filter((x) => x.t === "rm").length;
return (
<Card
tone={applied ? "success" : "accent"}
icon={<I.diff size={12} />}
kind="edit"
name={filename}
meta={
<>
<span style={{ color: "var(--success)" }}>+{adds}</span>
<span style={{ color: "var(--danger)" }}>−{rms}</span>
{applied ? (
<StatusIcon state="done" label={t("cards.applied")} />
) : (
<StatusIcon state="waiting" label={t("cards.diffAwaiting")} />
)}
</>
}
>
<div className="diff">
<div className="lines">
{lines.map((ln, i) => {
if (ln.t === "hunk")
return (
<div key={i} className="ln hunk">
<span className="code">{ln.s}</span>
</div>
);
const cls = ln.t === "add" ? "add" : ln.t === "rm" ? "rm" : "";
const l = ln.t === "ctx" ? ln.l : ln.t === "rm" ? ln.l : undefined;
const r = ln.t === "ctx" ? ln.r : ln.t === "add" ? ln.r : undefined;
return (
<div key={i} className={`ln ${cls}`}>
<span className="num">{l ?? ""}</span>
<span className="num">{r ?? ""}</span>
<span className="code">
{ln.t === "add" ? "+ " : ln.t === "rm" ? "− " : " "}
{ln.s}
</span>
</div>
);
})}
</div>
{!applied && (onApply || onDiscard) ? (
<div className="approve-row">
<div className="why">
<b>{t("cards.diffApplyChanges")}</b> · +{adds} / −{rms}
</div>
<div className="actions">
{onDiscard ? (
<button type="button" className="btn" onClick={onDiscard}>
{t("cards.diffDiscard")}
</button>
) : null}
{onApply ? (
<button type="button" className="btn primary" onClick={onApply}>
{t("cards.diffApply")} <Shortcut keys={["mod", "enter"]} />
</button>
) : null}
</div>
</div>
) : null}
</div>
</Card>
);
}
// ---- Error ----
export function ErrorCard({ message, hint, code }: { message: string; hint?: ReactNode; code?: string }) {
useLang();
return (
<Card
tone="danger"
icon={<I.warning size={12} />}
kind="error"
name={t("cards.errorName")}
meta={code ? <span className="pill-tag err">{code}</span> : null}
>
<div className="error-body">
<div className="msg-err">{message}</div>
{hint ? <div className="hint">{hint}</div> : null}
</div>
</Card>
);
}
// ---- Search results ----
export type SearchHit = { url: string; title: string; snippet: string };
export function WebSearchCard({ query, results }: { query: string; results: SearchHit[] }) {
useLang();
return (
<Card
tone="default"
icon={<I.globe size={12} />}
kind="web_search"
name={t("cards.searchName")}
meta={
<>
<span>"{query}"</span>
<span className="pill-tag ok">{results.length} {t("cards.hits")}</span>
</>
}
>
<div className="search-results">
{results.map((r, i) => (
<div className="search-result" key={i}>
<div className="url">
<span className="favicon" />
<span>{r.url}</span>
</div>
<div className="title">{r.title}</div>
<div className="snippet">{r.snippet}</div>
</div>
))}
</div>
</Card>
);
}
// ---- Subagent ----
export type SubAgentChild = {
avatar: string;
what: string;
role: string;
status: "done" | "running" | "queued";
};
export function SubagentCard({
name,
children,
status,
}: {
name: string;
children: SubAgentChild[];
status: "running" | "done" | "failed";
}) {
useLang();
const done = children.filter((c) => c.status === "done").length;
return (
<Card
tone="violet"
icon={<I.bot size={12} />}
kind="subagent"
name={name}
meta={
<>
<span>
{done} / {children.length} {t("cards.subagentDoneProgress")}
</span>
{status === "done" ? (
<StatusIcon state="done" label={t("cards.subagentDone")} />
) : status === "failed" ? (
<StatusIcon state="failed" label={t("cards.subagentFailed")} />
) : (
<StatusIcon state="running" label={t("cards.subagentRunning")} />
)}
</>
}
>
<div className="sub-card">
{children.map((c, i) => (
<div className="sub-row" key={i}>
<span className="av">{c.avatar}</span>
<div className="what">
<div>{c.what}</div>
<div className="role">{c.role}</div>
</div>
<span className="prog">
{c.status === "done" ? (
<I.check size={12} style={{ color: "var(--success)" }} />
) : c.status === "running" ? (
<span className="spin" />
) : null}
</span>
</div>
))}
</div>
</Card>
);
}
// ---- Memory rows ----
export type MemRow = { scope: string; txt: string };
export function MemoryCard({ rows }: { rows: MemRow[] }) {
useLang();
return (
<Card
tone="violet"
icon={<I.bookmark size={12} />}
kind="memory"
name={t("cards.memoryName")}
meta={<span>+ {rows.length} {t("cards.memoryCountSuffix")}</span>}
>
<div className="mem">
{rows.map((m, i) => (
<div className="mem-row" key={i}>
<span className="scope">{m.scope}</span>
<span className="txt">{m.txt}</span>
</div>
))}
</div>
</Card>
);
}
// ---- Image attachment ----
export function AttachCard({
filename,
meta,
preview,
}: {
filename: string;
meta: string;
preview?: string;
}) {
useLang();
return (
<Card
tone="default"
icon={<I.image size={12} />}
kind="image"
name={filename}
meta={<span>{meta}</span>}
>
<div className="attach-card">
<div className="ph">{preview ?? "PNG"}</div>
<div className="info">
<div className="n">{filename}</div>
<div className="m">{meta}</div>
</div>
<button type="button" className="btn ghost">
<I.download size={12} />
</button>
</div>
</Card>
);
}
// ---- Metric strip (inline) ----
export function MetricStrip({
cacheHit,
promptTokens,
outputTokens,
costLabel,
elapsed,
}: {
cacheHit?: number;
promptTokens?: number;
outputTokens?: number;
costLabel?: string;
elapsed?: string;
}) {
return (
<div className="metric-strip">
{cacheHit !== undefined ? (
<span className="item">
<I.zap size={11} style={{ color: "var(--accent)" }} />
<span>{t("cards.cacheHit")}</span>
<span className="v acc">{cacheHit}%</span>
</span>
) : null}
{promptTokens !== undefined ? (
<span className="item">
<span>{t("cards.prompt")}</span>
<span className="v">{promptTokens.toLocaleString()} t</span>
</span>
) : null}
{outputTokens !== undefined ? (
<span className="item">
<span>{t("cards.output")}</span>
<span className="v">{outputTokens.toLocaleString()} t</span>
</span>
) : null}
{costLabel ? (
<span className="item">
<I.coin size={11} />
<span>{t("cards.cost")}</span>
<span className="v ok">{costLabel}</span>
</span>
) : null}
{elapsed ? (
<span className="item">
<span>{t("cards.elapsed")}</span>
<span className="v">{elapsed}</span>
</span>
) : null}
</div>
);
}
// ---- Checkpoint marker (inline) ----
export function Checkpoint({
hash,
label,
onRewind,
}: {
hash: string;
label: string;
onRewind?: () => void;
}) {
useLang();
return (
<div className="checkpoint">
<I.history size={12} />
<span className="hash">{hash}</span>
<span>·</span>
<span>{label}</span>
{onRewind ? (
<button type="button" onClick={onRewind}>
{t("cards.checkpointRewind")}
</button>
) : null}
</div>
);
}
// ---- Plain text block (assistant content via markdown) ----
export const AssistantText = memo(function AssistantText({ text }: { text: string }) {
return (
<div className="msg-text">
<Markdown source={text} />
</div>
);
});
+805
View File
@@ -0,0 +1,805 @@
import {
type ChangeEvent,
type KeyboardEvent,
type RefObject,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import type React from "react";
import { open as openFileDialog } from "@tauri-apps/plugin-dialog";
import { t, type TKey } from "../i18n";
import { I } from "../icons";
import { fmtElapsed } from "./live";
import { Shortcut } from "./shortcut";
export type ReasoningEffort = "low" | "medium" | "high" | "max";
export type EditMode = "review" | "auto" | "yolo" | "plan";
type ModeEntry = { k: EditMode; label: TKey; icon: React.ReactNode; hint: TKey };
const EFFORTS: readonly ReasoningEffort[] = ["low", "medium", "high", "max"];
const MODE_INFO: ModeEntry[] = [
{ k: "plan", label: "editMode.plan", icon: <I.list size={11} />, hint: "editMode.planHint" },
{ k: "review", label: "editMode.review", icon: <I.shield size={11} />, hint: "editMode.reviewHint" },
{ k: "auto", label: "editMode.auto", icon: <I.zap size={11} />, hint: "editMode.autoHint" },
{ k: "yolo", label: "editMode.yolo", icon: <I.warn size={11} />, hint: "editMode.yoloHint" },
];
export function ModeSwitch({
mode,
onChange,
}: {
mode: EditMode;
onChange: (m: EditMode) => void;
}) {
return (
<div className="mode-switch" data-mode={mode}>
{MODE_INFO.map((m) => (
<button
key={m.k}
type="button"
className="ms-seg"
data-on={mode === m.k}
data-k={m.k}
onClick={() => onChange(m.k)}
title={t(m.hint)}
>
{m.icon}
<span>{t(m.label)}</span>
</button>
))}
</div>
);
}
export type SlashCmd = {
cmd: string;
desc: string;
run: () => void;
kb?: string;
insertOnly?: boolean;
};
export type MentionItem = {
name: string;
kind: "file" | "dir" | "url" | "agent" | "clip";
desc?: string;
};
export type Chip =
| { kind: "at"; label: string }
| { kind: "slash"; label: string };
type Popup =
| { kind: "slash"; query: string }
| { kind: "at"; query: string; nonce: number }
| null;
function slashIcon(cmd: string) {
const m: Record<string, React.ReactNode> = {
"/clear": <I.x size={12} />,
"/new": <I.plus size={12} />,
"/abort": <I.stop size={12} />,
"/copy": <I.layers size={12} />,
"/export": <I.download size={12} />,
"/model": <I.cpu size={12} />,
"/theme": <I.sun size={12} />,
"/lang": <I.globe size={12} />,
};
return m[cmd] || <I.slash size={12} />;
}
/** Parent dir of the current @ query, with trailing slash. `null` = no parent to show (at workspace root). */
function parentOfAtQuery(query: string): string | null {
const normalized = query.replace(/\\/g, "/");
const trailingSlash = normalized.endsWith("/");
const lastSlash = normalized.lastIndexOf("/");
if (lastSlash < 0) return null;
const dirContext = trailingSlash ? normalized.slice(0, -1) : normalized.slice(0, lastSlash);
if (!dirContext) return null;
const parentIdx = dirContext.lastIndexOf("/");
return parentIdx >= 0 ? `${dirContext.slice(0, parentIdx)}/` : "";
}
function atIcon(k: MentionItem["kind"]) {
if (k === "file") return <I.file size={12} />;
if (k === "dir") return <I.folder size={12} />;
if (k === "url") return <I.globe size={12} />;
if (k === "agent") return <I.bot size={12} />;
if (k === "clip") return <I.layers size={12} />;
return <I.at size={12} />;
}
export function Composer({
draft,
setDraft,
onSend,
onAbort,
disabled,
busy,
busyLabel,
busyElapsedMs,
modelLabel,
reasoningEffort,
onModelChange,
onEffortChange,
editMode,
onEditModeChange,
textareaRef,
slashCommands,
onMentionQuery,
onMentionPreview,
onMentionPicked,
mentionResults,
workspaceDir,
queuedSends,
onQueueWhileBusy,
onDequeueSend,
}: {
draft: string;
setDraft: (s: string) => void;
onSend: () => void;
onAbort: () => void;
disabled?: boolean;
busy?: boolean;
/** Replaces the hint-row left side while the agent is running — typically "Reasoning" or "Skill · <name>". */
busyLabel?: string;
busyElapsedMs?: number;
modelLabel: string;
reasoningEffort: ReasoningEffort;
onModelChange: (model: string) => void;
onEffortChange: (effort: ReasoningEffort) => void;
editMode: EditMode;
onEditModeChange: (mode: EditMode) => void;
textareaRef: RefObject<HTMLTextAreaElement | null>;
slashCommands: SlashCmd[];
onMentionQuery?: (q: string, nonce: number) => void;
onMentionPreview?: (path: string, nonce: number) => void;
onMentionPicked?: (path: string) => void;
mentionResults?: { nonce: number; query: string; results: string[] } | null;
workspaceDir?: string;
/** Messages typed while busy=true; rendered as removable chips above the textarea and auto-drained FIFO on turn-complete. */
queuedSends?: string[];
/** Called when the user presses Enter while busy with a non-empty draft. Owns clearing the draft. */
onQueueWhileBusy?: (text: string) => void;
onDequeueSend?: (index: number) => void;
}) {
const [chips, setChips] = useState<Chip[]>([]);
const [popup, setPopup] = useState<Popup>(null);
const [activeIdx, setActiveIdx] = useState(0);
const [modelMenuOpen, setModelMenuOpen] = useState(false);
const nonceRef = useRef(0);
const modelWrapRef = useRef<HTMLDivElement>(null);
// macOS Chinese IME fires compositionend before the confirm keydown.
const composingRef = useRef(false);
const compositionEndedAtRef = useRef(0);
// Programmatic draft transitions to "/" (e.g. /help suggestion in EmptyState, #929) must open the slash popup, since handleChange only fires on actual user input.
const prevDraftRef = useRef(draft);
useEffect(() => {
const prev = prevDraftRef.current;
prevDraftRef.current = draft;
if (draft === "/" && prev !== "/") {
setPopup({ kind: "slash", query: "" });
}
}, [draft]);
useEffect(() => {
if (!modelMenuOpen) return;
const onDown = (e: MouseEvent) => {
if (
modelWrapRef.current &&
!modelWrapRef.current.contains(e.target as Node)
) {
setModelMenuOpen(false);
}
};
window.addEventListener("mousedown", onDown);
return () => window.removeEventListener("mousedown", onDown);
}, [modelMenuOpen]);
const attachFile = async (filter?: "image") => {
try {
const picked = await openFileDialog({
multiple: false,
directory: false,
defaultPath: workspaceDir,
filters:
filter === "image"
? [
{
name: t("composer.imageFilterName"),
extensions: ["png", "jpg", "jpeg", "gif", "webp", "svg"],
},
]
: undefined,
});
if (typeof picked !== "string" || !picked) return;
const rel =
workspaceDir && picked.startsWith(workspaceDir)
? picked.slice(workspaceDir.length).replace(/^[\\/]+/, "")
: picked;
setDraft(draft ? `${draft.replace(/\s+$/, "")} @${rel} ` : `@${rel} `);
setChips((c) => [...c, { kind: "at", label: rel }]);
onMentionPicked?.(rel);
textareaRef.current?.focus();
} catch (err) {
console.error("attach failed", err);
}
};
const slashItems = useMemo(() => {
if (!popup || popup.kind !== "slash") return [];
const q = popup.query.toLowerCase();
if (!q) return slashCommands;
return slashCommands.filter((c) => c.cmd.toLowerCase().includes(q));
}, [popup, slashCommands]);
const atItems = useMemo<MentionItem[]>(() => {
if (!popup || popup.kind !== "at") return [];
if (!mentionResults || mentionResults.nonce !== popup.nonce) return [];
const base: MentionItem[] = mentionResults.results.map((path) => ({
name: path,
kind: path.endsWith("/") || path.endsWith("\\") ? "dir" : "file",
desc: path,
}));
// "../" entry (#1019): one level up whenever the @ query is inside a subdir.
const parent = parentOfAtQuery(popup.query);
if (parent !== null) {
base.unshift({
name: "..",
kind: "dir",
desc: parent ? `↑ ${parent}` : `↑ ${t("composer.workspaceRoot")}`,
});
}
return base;
}, [popup, mentionResults]);
const items =
popup?.kind === "slash" ? slashItems : popup?.kind === "at" ? atItems : [];
useEffect(() => {
setActiveIdx(0);
}, [items.length, popup?.kind]);
useEffect(() => {
if (!popup || popup.kind !== "at" || !onMentionQuery) return;
onMentionQuery(popup.query, popup.nonce);
}, [popup, onMentionQuery]);
const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
const v = e.target.value;
setDraft(v);
const trail = v.match(/(^|\s)([/@])([^\s]*)$/);
if (trail) {
const sigil = trail[2];
const query = trail[3] ?? "";
if (sigil === "/") {
setPopup({ kind: "slash", query });
} else {
const nonce = ++nonceRef.current;
setPopup({ kind: "at", query, nonce });
}
} else if (popup) {
setPopup(null);
}
};
const dismiss = () => setPopup(null);
const pickItem = (idx: number) => {
const it = items[idx];
if (!it || !popup) return;
if (popup.kind === "slash") {
const cmd = (it as SlashCmd).cmd;
const insertOnly = (it as SlashCmd).insertOnly === true;
if (insertOnly) {
const next = draft.replace(/[/@][^\s]*$/, "").trimEnd();
setDraft(next ? `${next} ${cmd} ` : `${cmd} `);
setChips((c) => [...c, { kind: "slash", label: cmd.replace(/^\//, "") }]);
} else {
const next = draft.replace(/[/@][^\s]*$/, "").trimEnd();
setDraft(next);
setChips((c) => [...c, { kind: "slash", label: cmd.replace(/^\//, "") }]);
(it as SlashCmd).run();
}
} else {
const mention = it as MentionItem;
if (mention.name === "..") {
const parent = parentOfAtQuery(popup.query) ?? "";
const next = draft.replace(/[@][^\s]*$/, `@${parent}`);
setDraft(next);
const nonce = ++nonceRef.current;
setPopup({ kind: "at", query: parent, nonce });
textareaRef.current?.focus();
return;
}
const next = draft.replace(/[/@][^\s]*$/, "").trimEnd();
setDraft(next ? `${next} @${mention.name} ` : `@${mention.name} `);
setChips((c) => [...c, { kind: "at", label: mention.name }]);
onMentionPicked?.(mention.name);
}
setPopup(null);
textareaRef.current?.focus();
};
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (popup) {
if (e.key === "ArrowDown") {
e.preventDefault();
setActiveIdx((i) => (items.length ? (i + 1) % items.length : 0));
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
setActiveIdx((i) =>
items.length ? (i - 1 + items.length) % items.length : 0,
);
return;
}
if (e.key === "Escape") {
e.preventDefault();
dismiss();
return;
}
if (e.key === "Tab" && popup.kind === "at" && items.length > 0) {
// Tab on a directory enters it — replaces `@src` with `@src/`
// and re-queries so the popup shows that directory's children.
// `..` is the synthetic parent-dir entry (#1019); same shape
// but rewrites to the parent path.
const it = items[activeIdx];
if (it && (it as MentionItem).kind === "dir") {
e.preventDefault();
const mention = it as MentionItem;
if (mention.name === "..") {
const parent = parentOfAtQuery(popup.query) ?? "";
const next = draft.replace(/[@][^\s]*$/, `@${parent}`);
setDraft(next);
const nonce = ++nonceRef.current;
setPopup({ kind: "at", query: parent, nonce });
return;
}
const dirPath = mention.name.replace(/\/+$/, "");
const next = draft.replace(/[@][^\s]*$/, `@${dirPath}/`);
setDraft(next);
const nonce = ++nonceRef.current;
setPopup({ kind: "at", query: `${dirPath}/`, nonce });
return;
}
}
if (e.key === "Enter") {
if (items.length > 0) {
e.preventDefault();
pickItem(activeIdx);
return;
}
dismiss();
}
}
if (composingRef.current || Date.now() - compositionEndedAtRef.current < 50) return;
if (e.key === "Enter" && !e.shiftKey && !popup) {
e.preventDefault();
if (busy) {
const text = draft.trim();
if (text && onQueueWhileBusy) {
onQueueWhileBusy(text);
setChips([]);
}
} else if (!disabled && draft.trim()) {
onSend();
setChips([]);
}
}
};
return (
<div className="composer-wrap">
<div className="composer-inner">
{queuedSends && queuedSends.length > 0 ? (
<div className="composer-queued">
<span className="composer-queued-label">
{t("composer.queueCount", { count: queuedSends.length })}
</span>
{queuedSends.map((text, i) => (
<span key={i} className="composer-queue-chip" title={text}>
<span className="text">{text}</span>
{onDequeueSend ? (
<span className="x" onClick={() => onDequeueSend(i)}>
<I.x size={10} />
</span>
) : null}
</span>
))}
</div>
) : null}
<div className="hint-row">
{busy && busyLabel ? (
<>
<span className="composer-busy-status">
<span className="composer-busy-pip" />
<span className="composer-busy-label">{busyLabel}</span>
<span className="composer-busy-time">
{fmtElapsed(busyElapsedMs ?? 0)}
</span>
</span>
<span className="grow" />
<ModeSwitch mode={editMode} onChange={onEditModeChange} />
<span className="hint-sep" />
<span>
<Shortcut keys={["enter"]} /> {t("composer.queue")} &nbsp;·&nbsp;{" "}
<Shortcut keys={["esc"]} /> {t("composer.interrupt")}
</span>
</>
) : (
<>
<span>
<Shortcut keys={["/"]} /> {t("composer.commands")} &nbsp;·&nbsp;{" "}
<Shortcut keys={["@"]} /> {t("composer.mentionFiles")}
&nbsp;·&nbsp; <Shortcut keys={["mod", "K"]} /> {t("composer.commandPalette")}
</span>
<span className="grow" />
<ModeSwitch mode={editMode} onChange={onEditModeChange} />
<span className="hint-sep" />
<span>
<Shortcut keys={["enter"]} /> {t("composer.send")} &nbsp;{" "}
<Shortcut keys={["shift", "enter"]} /> {t("composer.newline")}
</span>
</>
)}
</div>
<div className="composer">
{chips.length > 0 ? (
<div className="composer-tags">
{chips.map((c, i) => (
<span key={i} className={`chip ${c.kind}`}>
{c.kind === "slash" ? (
<I.slash size={11} />
) : (
<I.at size={11} />
)}
<span>{c.label}</span>
<span
className="x"
onClick={() =>
setChips((cs) => cs.filter((_, j) => j !== i))
}
>
<I.x size={10} />
</span>
</span>
))}
</div>
) : null}
<textarea
ref={textareaRef}
value={draft}
placeholder={t("composer.placeholder")}
onChange={handleChange}
onKeyDown={handleKeyDown}
onCompositionStart={() => {
composingRef.current = true;
}}
onCompositionEnd={() => {
composingRef.current = false;
compositionEndedAtRef.current = Date.now();
}}
rows={2}
disabled={disabled}
/>
<div className="composer-foot">
<button
type="button"
className="cf-btn"
title={t("composer.insertFile")}
onClick={() => void attachFile()}
>
<span className="ico">
<I.paperclip size={14} />
</span>
</button>
<button
type="button"
className="cf-btn"
title={t("composer.insertImage")}
onClick={() => void attachFile("image")}
>
<span className="ico">
<I.image size={14} />
</span>
</button>
<button
type="button"
className="cf-btn"
onClick={() => setPopup({ kind: "slash", query: "" })}
>
<span className="ico">
<I.slash size={14} />
</span>
<span className="label">{t("composer.commandsLabel")}</span>
</button>
<button
type="button"
className="cf-btn"
onClick={() => {
const nonce = ++nonceRef.current;
setPopup({ kind: "at", query: "", nonce });
}}
>
<span className="ico">
<I.at size={14} />
</span>
<span className="label">{t("composer.mentionLabel")}</span>
</button>
<span className="grow" />
<div ref={modelWrapRef} style={{ position: "relative" }}>
<button
type="button"
className="model-pill"
onClick={() => setModelMenuOpen((v) => !v)}
title={t("composer.switchModel")}
>
<I.brain size={12} />
<span>{modelLabel}</span>
<span className="badge">{reasoningEffort}</span>
<I.chev size={10} />
</button>
{modelMenuOpen ? (
<ModelEffortMenu
modelLabel={modelLabel}
currentEffort={reasoningEffort}
onPickModel={(m) => {
onModelChange(m);
setModelMenuOpen(false);
}}
onPickEffort={(e) => {
onEffortChange(e);
setModelMenuOpen(false);
}}
/>
) : null}
</div>
{busy ? (
<button
type="button"
className="send-btn"
style={{ background: "var(--danger)" }}
onClick={onAbort}
title={t("composer.interrupt")}
>
<I.stop size={14} />
</button>
) : (
<button
type="button"
className="send-btn"
disabled={disabled || !draft.trim()}
onClick={() => {
if (!disabled && draft.trim()) {
onSend();
setChips([]);
}
}}
>
<I.send size={14} />
</button>
)}
</div>
{popup ? (
<Popup
kind={popup.kind}
items={items}
activeIdx={activeIdx}
onPick={(i) => pickItem(i)}
onClose={dismiss}
onHover={(i, item) => {
setActiveIdx(i);
if (popup.kind === "at" && onMentionPreview) {
const path = (item as MentionItem).name;
onMentionPreview(path, popup.nonce);
}
}}
/>
) : null}
</div>
</div>
</div>
);
}
function Popup({
kind,
items,
activeIdx,
onPick,
onClose,
onHover,
}: {
kind: "slash" | "at";
items: (SlashCmd | MentionItem)[];
activeIdx: number;
onPick: (i: number) => void;
onClose: () => void;
onHover: (i: number, item: SlashCmd | MentionItem) => void;
}) {
const listRef = useRef<HTMLDivElement>(null);
useEffect(() => {
requestAnimationFrame(() => {
const el = listRef.current?.querySelector<HTMLElement>(`[data-active="true"]`);
el?.scrollIntoView({ block: "nearest" });
});
}, [activeIdx]);
return (
<div className="popup" onMouseDown={(e) => e.preventDefault()}>
<div className="ph">
<span className="tok">{kind === "slash" ? "/" : "@"}</span>
<span>
{kind === "slash"
? t("composer.slashHeader")
: t("composer.atHeader")}
</span>
<span className="grow" />
<span style={{ cursor: "pointer" }} onClick={onClose}>
<I.x size={11} />
</span>
</div>
<div className="popup-list" ref={listRef}>
{items.length === 0 ? (
<div
style={{
padding: "12px 8px",
fontSize: 11.5,
color: "var(--muted-2)",
fontFamily: "Geist Mono, monospace",
}}
>
{t("composer.noMatches")}
</div>
) : null}
{items.map((it, i) => (
<div
key={i}
className="popup-item"
data-active={i === activeIdx}
onClick={() => onPick(i)}
onMouseEnter={() => onHover(i, it)}
>
<span className="ico">
{kind === "slash"
? slashIcon((it as SlashCmd).cmd)
: atIcon((it as MentionItem).kind)}
</span>
<div className="nm">
{kind === "slash" ? (
<>
<span className="cmd">{(it as SlashCmd).cmd}</span>
<span className="desc">{(it as SlashCmd).desc}</span>
</>
) : (
<>
<span>{(it as MentionItem).name}</span>
{(it as MentionItem).desc ? (
<div className="desc">{(it as MentionItem).desc}</div>
) : null}
</>
)}
</div>
<span className="kb">
{kind === "slash" ? ((it as SlashCmd).kb ?? "") : ""}
</span>
</div>
))}
</div>
<div className="popup-foot">
<span>
<Shortcut keys={["updown"]} /> {t("composer.select")}
</span>
<span>
<Shortcut keys={["enter"]} /> {t("composer.confirm")}
</span>
<span>
<Shortcut keys={["esc"]} /> {t("composer.close")}
</span>
</div>
</div>
);
}
const KNOWN_MODELS: readonly string[] = ["deepseek-v4-flash", "deepseek-v4-pro"];
function ModelEffortMenu({
modelLabel,
currentEffort,
onPickModel,
onPickEffort,
}: {
modelLabel: string;
currentEffort: ReasoningEffort;
onPickModel: (model: string) => void;
onPickEffort: (effort: ReasoningEffort) => void;
}) {
const [draft, setDraft] = useState(modelLabel);
return (
<div
className="popup"
style={{
bottom: "calc(100% + 6px)",
left: "auto",
right: 0,
width: 280,
position: "absolute",
}}
>
<div className="ph">
<span className="tok">M</span>
<span>{t("composer.switchModel")}</span>
</div>
<div className="popup-list">
{KNOWN_MODELS.map((m) => (
<div
key={m}
className="popup-item"
data-active={m === modelLabel}
onClick={() => onPickModel(m)}
>
<span className="ico">
<I.brain size={12} />
</span>
<div className="nm">
<span className="cmd">{m}</span>
</div>
</div>
))}
<div style={{ padding: "6px 8px", display: "flex", gap: 6 }}>
<input
className="field mono"
style={{ flex: 1 }}
value={draft}
onChange={(e) => setDraft(e.target.value)}
placeholder="custom model id"
/>
<button
type="button"
className="btn"
disabled={!draft.trim() || draft.trim() === modelLabel}
onClick={() => onPickModel(draft.trim())}
>
{t("composer.confirm")}
</button>
</div>
</div>
<div className="ph" style={{ marginTop: 4 }}>
<span className="tok">E</span>
<span>{t("composer.switchEffort")}</span>
</div>
<div className="popup-list">
{EFFORTS.map((e) => (
<div
key={e}
className="popup-item"
data-active={e === currentEffort}
onClick={() => onPickEffort(e)}
>
<span className="ico">
<I.cpu size={12} />
</span>
<div className="nm">
<span className="cmd">{e}</span>
<div className="desc">{t(`effort.${e}Desc` as TKey)}</div>
</div>
</div>
))}
</div>
</div>
);
}
+321
View File
@@ -0,0 +1,321 @@
import { useMemo, useState } from "react";
import type { SessionFile, Settings, UsageStats } from "../App";
import { t, useLang } from "../i18n";
import { I } from "../icons";
import type { McpSpecInfo, MemoryDetail, MemoryEntryInfo } from "../protocol";
import { PanelErrorBoundary } from "./error-boundary";
type Tab = "files" | "tools" | "memory" | "rules";
const CONTEXT_MAX_TOKENS = 1_000_000;
export function ContextPanel({
settings,
usage,
mcpSpecs,
mcpBridged,
sessionFiles,
memory,
memoryDetail,
onReadMemory,
}: {
settings: Settings | null;
usage: UsageStats;
mcpSpecs: McpSpecInfo[];
mcpBridged: boolean;
sessionFiles: SessionFile[];
memory: MemoryEntryInfo[];
memoryDetail: MemoryDetail | null;
onReadMemory: (path: string) => void;
}) {
useLang();
const [tab, setTab] = useState<Tab>("files");
const reserved = usage.reservedTokens;
// After a warm cache turn the API counts the reserved prefix inside cacheHit;
// subtract to keep the bar segments visually disjoint. Cold cache shows the
// reserved portion in cacheMiss instead, so do the same for `used`.
const cached = Math.max(0, usage.cacheHitTokens - reserved);
const used = Math.max(0, usage.cacheMissTokens - Math.max(0, reserved - usage.cacheHitTokens));
const reservedPct = Math.min(100, (reserved / CONTEXT_MAX_TOKENS) * 100);
const usedPct = Math.min(100, (used / CONTEXT_MAX_TOKENS) * 100);
const cachedPct = Math.min(100, (cached / CONTEXT_MAX_TOKENS) * 100);
const free = Math.max(0, CONTEXT_MAX_TOKENS - reserved - used - cached);
return (
<aside className="ctx">
<div className="ctx-tabs">
<div className="ctx-tab" data-active={tab === "files"} onClick={() => setTab("files")}>
{t("contextPanel.filesTab")}
</div>
<div className="ctx-tab" data-active={tab === "tools"} onClick={() => setTab("tools")}>
{t("contextPanel.toolsTab")}
</div>
<div className="ctx-tab" data-active={tab === "memory"} onClick={() => setTab("memory")}>
{t("contextPanel.memoryTab")}
</div>
<div className="ctx-tab" data-active={tab === "rules"} onClick={() => setTab("rules")}>
{t("contextPanel.rulesTab")}
</div>
</div>
<div className="ctx-body">
<div className="ctx-block">
<div className="h">
<span>{t("contextPanel.contextTokens")}</span>
<span className="right">
{(reserved + used + cached).toLocaleString()} /{" "}
{CONTEXT_MAX_TOKENS.toLocaleString()}
</span>
</div>
<div className="meter">
<span className="rsvd" style={{ width: `${reservedPct}%` }} />
<span className="cached" style={{ width: `${cachedPct}%` }} />
<span className="used" style={{ width: `${usedPct}%` }} />
</div>
<div className="legend">
<span className="l">
<span className="sw r" />
{t("contextPanel.reservedKey")} <span className="v">{reserved.toLocaleString()}</span>
</span>
<span className="l">
<span className="sw c" />
{t("contextPanel.cacheKey")} <span className="v">{cached.toLocaleString()}</span>
</span>
<span className="l">
<span className="sw u" />
{t("contextPanel.usedKey")} <span className="v">{used.toLocaleString()}</span>
</span>
<span className="l">
{t("contextPanel.freeKey")} <span className="v">{free.toLocaleString()}</span>
</span>
</div>
</div>
<PanelErrorBoundary key={tab} label={tab}>
{tab === "files" && <CtxFiles files={sessionFiles} />}
{tab === "tools" && <CtxTools specs={mcpSpecs} bridged={mcpBridged} />}
{tab === "memory" && (
<CtxMemory entries={memory} detail={memoryDetail} onRead={onReadMemory} />
)}
{tab === "rules" && <CtxRules settings={settings} />}
</PanelErrorBoundary>
</div>
</aside>
);
}
type TreeNode =
| { kind: "dir"; depth: number; name: string; key: string }
| { kind: "file"; depth: number; name: string; key: string; status: "c" | "m" };
function buildSessionTree(files: SessionFile[]): TreeNode[] {
const sorted = [...files].sort((a, b) =>
a.path.replace(/\\/g, "/").localeCompare(b.path.replace(/\\/g, "/")),
);
const out: TreeNode[] = [];
const seenDirs = new Set<string>();
for (const f of sorted) {
const parts = f.path.replace(/\\/g, "/").split("/").filter(Boolean);
if (parts.length === 0) continue;
let prefix = "";
for (let i = 0; i < parts.length - 1; i++) {
const seg = parts[i] ?? "";
prefix = prefix ? `${prefix}/${seg}` : seg;
if (!seenDirs.has(prefix)) {
seenDirs.add(prefix);
out.push({ kind: "dir", depth: i, name: seg, key: `d:${prefix}` });
}
}
const leaf = parts[parts.length - 1] ?? "";
out.push({
kind: "file",
depth: parts.length - 1,
name: leaf,
key: `f:${f.path}`,
status: f.status,
});
}
return out;
}
function CtxFiles({ files }: { files: SessionFile[] }) {
const tree = useMemo(() => buildSessionTree(files), [files]);
return (
<div className="ctx-block">
<div className="h">
<span>{t("contextPanel.filesTitle")}</span>
<span className="right">
{files.length === 0 ? "—" : t("contextPanel.filesCount", { count: files.length })}
</span>
</div>
<div className="tree">
{files.length === 0 ? (
<div className="ctx-empty">{t("contextPanel.noFilesMsg")}</div>
) : (
tree.map((n) =>
n.kind === "dir" ? (
<div className="node" key={n.key} data-d={n.depth} data-kind="dir">
<span className="ico">
<I.folder size={12} />
</span>
<span className="nm">{n.name}/</span>
</div>
) : (
<div
className="node"
key={n.key}
data-d={n.depth}
data-kind="file"
title={n.name}
>
<span className="ico">
<I.file size={12} />
</span>
<span className="nm">{n.name}</span>
<span
className="dot"
data-s={n.status}
title={n.status === "m" ? t("contextPanel.fileModified") : t("contextPanel.fileInContext")}
/>
</div>
),
)
)}
</div>
</div>
);
}
function CtxTools({ specs, bridged }: { specs: McpSpecInfo[]; bridged: boolean }) {
const readyCount = specs.filter((s) => s.status === "connected").length;
return (
<div className="ctx-block">
<div className="h">
<span>{t("contextPanel.mcpTitle")}</span>
<span className="right">
{specs.length === 0
? "—"
: bridged
? t("contextPanel.mcpReadyAll", { count: specs.length })
: t("contextPanel.mcpReadySome", { ready: readyCount, count: specs.length })}
</span>
</div>
{specs.length === 0 ? (
<div className="ctx-empty">{t("contextPanel.mcpEmpty")}</div>
) : (
specs.map((s) => {
const dot =
s.status === "connected"
? "ok"
: s.status === "failed" || s.parseError
? "off"
: "pending";
const suffix = s.statusReason
? ` · ${s.statusReason}`
: s.status === "connected"
? typeof s.toolCount === "number"
? ` · ${t("contextPanel.mcpTools", { count: s.toolCount })}`
: ` · ${t("contextPanel.mcpReady")}`
: s.status === "handshake"
? ` · ${t("contextPanel.mcpConnecting")}`
: s.status === "disabled"
? ` · ${t("contextPanel.mcpDisabled")}`
: s.status === "failed"
? ` · ${t("contextPanel.mcpFailed")}`
: ` · ${t("contextPanel.mcpConfigured")}`;
return (
<div className="mcp-row" key={s.raw}>
<span className="ico">
<I.wrench size={12} />
</span>
<div className="body">
<div className="n">{s.name ?? s.summary}</div>
<div className="m">
{s.transport}
{suffix}
</div>
</div>
<span className="status" data-s={dot} />
</div>
);
})
)}
</div>
);
}
function CtxMemory({
entries,
detail,
onRead,
}: {
entries: MemoryEntryInfo[];
detail: MemoryDetail | null;
onRead: (path: string) => void;
}) {
return (
<div className="ctx-block">
<div className="h">
<span>{t("contextPanel.memoryTitle")}</span>
<span className="right">
{entries.length === 0 ? "—" : t("contextPanel.itemCount", { count: entries.length })}
</span>
</div>
{entries.length === 0 ? (
<div className="ctx-empty">{t("contextPanel.noMemoriesMsg")}</div>
) : (
<div className="mem">
{entries.map((m) => (
<button
type="button"
className="mem-row"
data-active={detail?.path === m.path}
key={m.path}
onClick={() => onRead(m.path)}
>
<span className="scope" data-s={m.scope}>
{m.scope === "project" ? t("contextPanel.scopeProject") : t("contextPanel.scopeGlobal")}
</span>
<span className="txt">{m.description || m.name}</span>
</button>
))}
{detail ? <pre className="mem-detail">{detail.body}</pre> : null}
</div>
)}
</div>
);
}
function CtxRules({ settings }: { settings: Settings | null }) {
const editMode = settings?.editMode ?? "review";
const items: { p: string; allow: boolean; desc: string }[] =
editMode === "yolo"
? [{ p: "*", allow: true, desc: t("contextPanel.ruleYolo") }]
: editMode === "auto"
? [
{ p: "read_file, list_directory, search_files, *", allow: true, desc: t("contextPanel.ruleReadOnly") },
{ p: "run_command (allowlist)", allow: true, desc: t("contextPanel.ruleShellAllowlist") },
{ p: "edit_file, write_file, run_command (other)", allow: false, desc: t("contextPanel.ruleWritesAsk") },
]
: [
{ p: "*", allow: false, desc: t("contextPanel.ruleReview") },
];
return (
<div className="ctx-block">
<div className="h">
<span>{t("contextPanel.autoApproveTitle")}</span>
<span className="right">{editMode}</span>
</div>
{items.map((r) => (
<div className="rule" key={r.p}>
<div className="top">
<span className={`pat ${r.allow ? "" : "deny"}`}>{r.p}</span>
<span className={`sw ${r.allow ? "" : "deny"}`}>
{r.allow ? t("contextPanel.allow") : t("contextPanel.ask")}
</span>
</div>
<div className="desc">{r.desc}</div>
</div>
))}
</div>
);
}
+37
View File
@@ -0,0 +1,37 @@
import { Component, type ReactNode } from "react";
import { t } from "../i18n";
type Props = { label: string; children: ReactNode };
type State = { error: Error | null };
export class PanelErrorBoundary extends Component<Props, State> {
state: State = { error: null };
static getDerivedStateFromError(error: Error): State {
return { error };
}
componentDidCatch(error: Error, info: { componentStack?: string | null }): void {
console.error(`[panel:${this.props.label}] render error`, error, info);
}
render(): ReactNode {
if (!this.state.error) return this.props.children;
return (
<div
className="ctx-empty"
style={{
color: "var(--danger, #e25555)",
padding: 12,
fontSize: 12,
whiteSpace: "pre-wrap",
wordBreak: "break-word",
}}
>
{t("panel.renderError", { panel: this.props.label })}
{": "}
{this.state.error.message}
</div>
);
}
}
+490
View File
@@ -0,0 +1,490 @@
import type { ReactNode } from "react";
import { I } from "../icons";
import { t, useLang } from "../i18n";
export type ApprovalTone = "ok" | "warn" | "danger" | "info" | "brand" | "ghost";
export function ApprovalCard({
kind,
tone = "info",
title,
sub,
body,
preview,
meta,
primaryLabel,
secondaryLabel,
tertiaryLabel,
onPrimary,
onSecondary,
onTertiary,
}: {
kind: string;
tone?: ApprovalTone;
title: string;
sub?: string;
body?: ReactNode;
preview?: ReactNode;
meta?: ReactNode;
primaryLabel?: string;
secondaryLabel?: string;
tertiaryLabel?: string;
onPrimary?: () => void;
onSecondary?: () => void;
onTertiary?: () => void;
}) {
useLang();
return (
<div className="approval" data-tone={tone}>
<div className="ap-head">
<span className="ap-ico">
<I.shield size={13} />
</span>
<div>
<div className="ap-kind">{kind}</div>
<div className="ap-title">{title}</div>
{sub ? <div className="ap-sub">{sub}</div> : null}
</div>
</div>
{body ? <div className="ap-body">{body}</div> : null}
{preview ? <div className="ap-preview">{preview}</div> : null}
<div className="ap-foot">
{onPrimary ? (
<button type="button" className="btn primary" onClick={onPrimary}>
{primaryLabel ?? t("extraCards.approve")}
</button>
) : null}
{onSecondary ? (
<button type="button" className="btn ghost" onClick={onSecondary}>
{secondaryLabel ?? t("extraCards.reject")}
</button>
) : null}
{onTertiary && tertiaryLabel ? (
<button type="button" className="btn ghost" onClick={onTertiary}>
{tertiaryLabel}
</button>
) : null}
<span className="grow" />
{meta ? <span className="meta">{meta}</span> : null}
</div>
</div>
);
}
// ---- Task Card (multi-step execution from active plan) ----
export type TaskStepView = {
n: string;
state: "queued" | "running" | "done" | "failed" | "blocked" | "skipped";
label: string;
hint?: string;
durationLabel?: string;
};
export function TaskCard({
title,
subtitle,
steps,
}: {
title: string;
subtitle?: string;
steps: TaskStepView[];
}) {
useLang();
const done = steps.filter((x) => x.state === "done").length;
const pct = steps.length ? (done / steps.length) * 100 : 0;
return (
<div className="task-card">
<div className="th">
<span className="ico">
<I.list size={13} />
</span>
<div>
<div className="tt">{title}</div>
{subtitle ? <div className="ss">{subtitle}</div> : null}
</div>
<span className="grow" />
<span className="ss">
{done}/{steps.length}
</span>
<div className="meter">
<span style={{ width: `${pct}%` }} />
</div>
</div>
<div className="tb">
{steps.map((st) => (
<div className="task-step" key={st.n} data-state={st.state}>
<span className="nx">step.{st.n}</span>
<span className="st" />
<div className="l">
{st.label}
{st.hint ? <div className="h">{st.hint}</div> : null}
</div>
<span className="t">{st.durationLabel ?? "—"}</span>
</div>
))}
</div>
</div>
);
}
// ---- Warn / Tip / Doctor ----
export function WarnCard({ title, body }: { title: string; body: ReactNode }) {
return (
<div className="warn-card">
<span className="ico">
<I.warn size={16} />
</span>
<div>
<div className="tt">{title}</div>
<div className="ds">{body}</div>
</div>
</div>
);
}
export type TipSection = { title: string; rows: ReactNode[] };
export function TipCard({
topic,
command,
sections,
footer,
}: {
topic: string;
command?: string;
sections: TipSection[];
footer?: ReactNode;
}) {
return (
<div className="tip-card">
<div className="head">
<span className="ico">
<I.help size={12} />
</span>
<span className="topic">{topic}</span>
<span className="grow" />
{command ? <span className="pill">{command}</span> : null}
</div>
{sections.map((sec, i) => (
<div className="sec" key={i}>
<div className="stt">{sec.title}</div>
{sec.rows.map((r, j) => (
<div className="row" key={j}>
{r}
</div>
))}
</div>
))}
{footer ? <div className="foot">{footer}</div> : null}
</div>
);
}
export type DoctorRow = { s: "ok" | "warn" | "fail"; nm: string; sub: string; v: string };
export function DoctorCard({ rows, headerSubtitle }: { rows: DoctorRow[]; headerSubtitle?: string }) {
useLang();
const c = { ok: 0, warn: 0, fail: 0 };
for (const r of rows) c[r.s]++;
return (
<div className="doctor-card">
<div className="dh">
<span className="ico">
<I.shield size={13} />
</span>
<div>
<div className="tt">{t("extraCards.doctorTitle")}</div>
{headerSubtitle ? (
<div
className="ss"
style={{
fontFamily: "Geist Mono, monospace",
fontSize: 10.5,
color: "var(--muted)",
}}
>
{headerSubtitle}
</div>
) : null}
</div>
<span className="grow" />
<div className="summary">
<span>
<span className="b ok">{c.ok}</span> ok
</span>
<span>
<span className="b warn">{c.warn}</span> warn
</span>
<span>
<span className="b err">{c.fail}</span> fail
</span>
</div>
</div>
{rows.map((r, i) => (
<div className="doctor-row" key={i} data-s={r.s}>
<span className="ic" data-mark={r.s === "ok" ? "✓" : r.s === "warn" ? "!" : "✕"} />
<div className="body">
<div className="nm">{r.nm}</div>
<div className="sub">{r.sub}</div>
</div>
<span className="v">{r.v}</span>
</div>
))}
</div>
);
}
// ---- Usage (full) ----
export function UsageFull({
promptTokens,
reasoningTokens,
outputTokens,
cacheHitTokens,
costLabel,
balanceLabel,
range,
}: {
promptTokens: number;
reasoningTokens: number;
outputTokens: number;
cacheHitTokens: number;
costLabel: string;
balanceLabel?: string;
range?: string;
}) {
useLang();
const fmt = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`);
const total = promptTokens + reasoningTokens + outputTokens + cacheHitTokens || 1;
const pct = (n: number) => Math.round((n / total) * 100);
return (
<div className="usage-full">
<div className="uh">
<div>
<div className="tt">{t("extraCards.sessionUsage")}</div>
{range ? <div className="ss">{range}</div> : null}
</div>
<span className="grow" />
</div>
<div className="ub">
<div className="ucol">
<div className="l">{t("extraCards.prompt")}</div>
<div className="v acc">{fmt(promptTokens)}</div>
<div className="pct">{pct(promptTokens)}%</div>
</div>
<div className="ucol">
<div className="l">{t("extraCards.reasoning")}</div>
<div className="v vio">{fmt(reasoningTokens)}</div>
<div className="pct">{pct(reasoningTokens)}%</div>
</div>
<div className="ucol">
<div className="l">{t("extraCards.output")}</div>
<div className="v ok">{fmt(outputTokens)}</div>
<div className="pct">{pct(outputTokens)}%</div>
</div>
<div className="ucol">
<div className="l">{t("extraCards.cacheHit")}</div>
<div className="v">{fmt(cacheHitTokens)}</div>
<div className="pct">{pct(cacheHitTokens)}%</div>
</div>
</div>
<div className="stack">
<span className="s1" style={{ width: `${pct(promptTokens)}%` }} />
<span className="s2" style={{ width: `${pct(reasoningTokens)}%` }} />
<span className="s3" style={{ width: `${pct(outputTokens)}%` }} />
<span className="s4" style={{ width: `${pct(cacheHitTokens)}%` }} />
</div>
<div className="uf">
<span className="x">
<span className="sw" style={{ background: "var(--accent)" }} />
{t("extraCards.prompt")}
</span>
<span className="x">
<span className="sw" style={{ background: "var(--violet)" }} />
{t("extraCards.reasoning")}
</span>
<span className="x">
<span className="sw" style={{ background: "var(--tone-ok)" }} />
{t("extraCards.output")}
</span>
<span className="x">
<span className="sw" style={{ background: "var(--border-strong)" }} />
{t("extraCards.cache")}
</span>
<span style={{ marginLeft: "auto" }}>
{t("extraCards.sessionCost", { costLabel })}
{balanceLabel ? ` · ${t("extraCards.balance", { balanceLabel })}` : ""}
</span>
</div>
</div>
);
}
// ---- Context window breakdown ----
export type CtxPart = { k: "system" | "tools" | "log" | "input"; label: string; value: string; widthPct: number };
export type CtxTopRow = { name: string; widthPct: number; value: string };
export function CtxCard({
totalLabel,
parts,
topTools,
}: {
totalLabel: string;
parts: CtxPart[];
topTools: CtxTopRow[];
}) {
useLang();
return (
<div className="ctx-card">
<div className="h">
<span className="tt">{t("extraCards.contextWindow")}</span>
<span className="grow" />
<span className="v">{totalLabel}</span>
</div>
<div className="bar">
{parts.map((p) => (
<span key={p.k} className={p.k} style={{ width: `${p.widthPct}%` }} />
))}
</div>
<div className="legend">
{parts.map((p) => {
const color =
p.k === "system"
? "var(--accent)"
: p.k === "tools"
? "var(--violet)"
: p.k === "log"
? "var(--tone-ok)"
: "var(--tone-warn)";
return (
<div key={p.k}>
<span className="sw" style={{ background: color }} />
<span className="l">{p.label}</span>
<span className="v">{p.value}</span>
</div>
);
})}
</div>
{topTools.length > 0 ? (
<div className="ttop">
<div className="stt">{t("extraCards.topToolsUsage")}</div>
{topTools.map((t, i) => (
<div className="row" key={i}>
<span className="n">{t.name}</span>
<div className="bbar">
<span style={{ width: `${t.widthPct}%` }} />
</div>
<span className="v">{t.value}</span>
</div>
))}
</div>
) : null}
</div>
);
}
// ---- Memory groups ----
export type MemGroupKey = "user" | "feedback" | "project" | "reference";
export type MemEntry = { text: string; meta?: string };
export type MemGroups = Partial<Record<MemGroupKey, MemEntry[]>>;
const GROUP_LABELS: Record<MemGroupKey, Parameters<typeof t>[0]> = {
user: "extraCards.memoryUser",
feedback: "extraCards.memoryFeedback",
project: "extraCards.memoryProject",
reference: "extraCards.memoryReference",
};
export function MemoryGroups({ data }: { data: MemGroups }) {
useLang();
const keys: MemGroupKey[] = ["user", "feedback", "project", "reference"];
return (
<div className="mem-groups">
{keys.map((g) => {
const rows = data[g] ?? [];
if (rows.length === 0) return null;
return (
<div key={g}>
<div className="gh" data-g={g}>
<span className="sw" />
<span>{t(GROUP_LABELS[g])}</span>
<span className="grow" />
<span className="cnt">{rows.length}</span>
</div>
{rows.map((r, i) => (
<div className="mrow" key={i}>
<span className="b">·</span>
<div className="t">{r.text}</div>
{r.meta ? <span className="meta">{r.meta}</span> : null}
</div>
))}
</div>
);
})}
</div>
);
}
// ---- Fallback ----
export function FallbackCard({ kindLabel, payload }: { kindLabel: string; payload: Record<string, string> }) {
useLang();
return (
<div className="fallback-card">
<div className="hd">{t("extraCards.unknownKind")}</div>
<div className="kv">
<span className="k">kind</span>
<span className="v">"{kindLabel}"</span>
{Object.entries(payload).map(([k, v]) => (
<span key={k} style={{ display: "contents" }}>
<span className="k">{k}</span>
<span className="v">{v}</span>
</span>
))}
</div>
</div>
);
}
// ---- LiveCard (pill variants) ----
export type LiveVariant =
| "thinking"
| "undo"
| "ctxPressure"
| "aborted"
| "retry"
| "checkpoint"
| "stepProgress"
| "mcpEvent"
| "sessionOp";
export function LiveCard({
variant,
icon,
body,
action,
onAction,
}: {
variant: LiveVariant;
icon: ReactNode;
body: ReactNode;
action?: string;
onAction?: () => void;
}) {
return (
<span className={`live-card ${variant === "stepProgress" ? "step" : ""}`} data-v={variant}>
<span className="lc-ico">{icon}</span>
<span className="lc-body">{body}</span>
{action ? (
<button type="button" className="lc-act" onClick={onAction}>
{action}
</button>
) : null}
</span>
);
}
+201
View File
@@ -0,0 +1,201 @@
import { useEffect, useMemo, useState } from "react";
import { I } from "../icons";
import { t, useLang } from "../i18n";
import type { JobInfo } from "../protocol";
import { Shortcut } from "./shortcut";
export function JobsPop({
open,
onClose,
jobs,
onStop,
onStopAll,
}: {
open: boolean;
onClose: () => void;
jobs: JobInfo[];
onStop: (jobId: number) => void;
onStopAll: () => void;
}) {
useLang();
const [tick, setTick] = useState(0);
useEffect(() => {
if (!open) return;
const id = window.setInterval(() => setTick((n) => n + 1), 600);
return () => window.clearInterval(id);
}, [open]);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
onClose();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [open, onClose]);
const running = useMemo(() => jobs.filter((j) => j.running), [jobs]);
const exited = useMemo(() => jobs.filter((j) => !j.running), [jobs]);
if (!open) return null;
return (
<div className="jobs-mask" onClick={onClose}>
<div className="jobs-pop" onClick={(e) => e.stopPropagation()}>
<div className="jobs-head">
<span className="ico">
<I.cpu size={13} />
</span>
<div>
<div className="tt">{t("jobs.title")}</div>
<div className="ss">
<span className="b ok">{running.length}</span> {t("jobs.running")} ·{" "}
<span className="b mut">{exited.length}</span> {t("jobs.exited")}
</div>
</div>
<span className="grow" />
{running.length > 0 ? (
<button
type="button"
className="btn danger sm"
onClick={onStopAll}
title={t("jobs.stopAllTip")}
>
<I.stop size={10} /> {t("jobs.stopAll")}
</button>
) : null}
</div>
<div className="jobs-body">
{jobs.length === 0 ? (
<div className="jobs-empty">{t("jobs.empty")}</div>
) : (
<>
{running.length > 0 ? <div className="jobs-grp">{t("jobs.running")}</div> : null}
{running.map((j) => (
<JobRow key={j.id} job={j} tick={tick} onStop={onStop} />
))}
{exited.length > 0 ? <div className="jobs-grp">{t("jobs.exited")}</div> : null}
{exited.map((j) => (
<JobRow key={j.id} job={j} tick={tick} onStop={onStop} />
))}
</>
)}
</div>
<div className="jobs-foot">
<div className="row">
<I.zap size={11} />
<span>
{t("jobs.running")} <span className="v">{running.length}</span>
</span>
<span>·</span>
<span>
{t("jobs.exited")} <span className="v">{exited.length}</span>
</span>
<span className="grow" />
<span>
<Shortcut keys={["mod", "J"]} /> {t("jobs.kbToggle")} ·{" "}
<Shortcut keys={["esc"]} /> {t("jobs.kbClose")}
</span>
</div>
</div>
</div>
</div>
);
}
function formatElapsed(ms: number): string {
if (ms < 1000) return `${ms}ms`;
const s = ms / 1000;
if (s < 60) return `${s.toFixed(1)}s`;
const m = Math.floor(s / 60);
const r = Math.floor(s % 60);
return `${m}m${r}s`;
}
function JobRow({
job,
tick,
onStop,
}: {
job: JobInfo;
tick: number;
onStop: (jobId: number) => void;
}) {
const [exp, setExp] = useState(false);
const elapsedMs = (job.running ? Date.now() : job.startedAt + 0) - job.startedAt;
const liveMs = job.running ? Date.now() - job.startedAt : elapsedMs;
// tick is referenced so the row re-renders for the running clock
void tick;
return (
<div className="job-row" data-status={job.running ? "running" : "exited"}>
<div className="jr-main" onClick={() => setExp((v) => !v)}>
<span className="jr-state">
{job.running ? (
<span className="spin" />
) : (
<I.history size={11} style={{ color: "var(--muted-2)" }} />
)}
</span>
<span className="jr-kind">
<I.terminal size={11} />
<span>shell</span>
</span>
<div className="jr-body">
<div className="nm" title={job.command}>
{job.command}
</div>
<div className="sub">
<span className="ses">{job.sessionLabel}</span>
{job.spawnError ? <span className="rk">· {job.spawnError}</span> : null}
{!job.running && job.exitCode !== null && job.exitCode !== 0 ? (
<span className="rk">· exit {job.exitCode}</span>
) : null}
</div>
</div>
<div className="jr-time">{formatElapsed(liveMs)}</div>
<div className="jr-act">
{job.running ? (
<button
type="button"
className="btn danger sm"
title={t("jobs.stopOne")}
onClick={(e) => {
e.stopPropagation();
onStop(job.id);
}}
>
<I.stop size={10} /> {t("jobs.stop")}
</button>
) : (
<span className="jr-exit" title={`exit ${job.exitCode ?? "—"}`}>
{job.exitCode === 0 ? "ok" : `exit ${job.exitCode ?? "?"}`}
</span>
)}
</div>
</div>
{exp ? (
<div className="jr-detail">
<div className="kv-grid">
<div>
<span className="k">job_id</span>
<span className="v">{job.id}</span>
</div>
<div>
<span className="k">pid</span>
<span className="v">{job.pid ?? "—"}</span>
</div>
<div>
<span className="k">elapsed</span>
<span className="v">{formatElapsed(liveMs)}</span>
</div>
</div>
{job.outputTail ? <pre className="jr-log">{job.outputTail}</pre> : null}
</div>
) : null}
</div>
);
}
+142
View File
@@ -0,0 +1,142 @@
import { useEffect, useRef, useState } from "react";
import { I } from "../icons";
import { t, useLang } from "../i18n";
export function fmtElapsed(ms: number): string {
const s = ms / 1000;
return s < 10 ? `${s.toFixed(1)}s` : `${Math.floor(s)}s`;
}
export function useElapsed(active: boolean, startAt?: number): number {
const [ms, setMs] = useState(0);
const start = useRef<number | null>(null);
useEffect(() => {
if (!active) {
setMs(0);
start.current = null;
return;
}
start.current = startAt ?? performance.now();
const id = setInterval(() => {
if (start.current !== null) setMs(performance.now() - start.current);
}, 80);
return () => clearInterval(id);
}, [active, startAt]);
return ms;
}
export function ThinkingPill({
phase = "thinking",
label,
elapsedMs,
}: {
phase?: "queued" | "thinking" | "tool";
label: string;
elapsedMs: number;
}) {
const color =
phase === "queued"
? "var(--muted)"
: phase === "tool"
? "var(--warning)"
: "var(--accent)";
return (
<div className="thinking">
<span className="dots" style={{ color }}>
<span style={{ background: color }} />
<span style={{ background: color }} />
<span style={{ background: color }} />
</span>
<span className="label">
<span className="sh">{label}</span>
</span>
<span className="timer">{fmtElapsed(elapsedMs)}</span>
</div>
);
}
export function LiveReasoning({ lines }: { lines: string[] }) {
useLang();
return (
<div className="live-reason">
<div className="head">
<span className="dot" /> {t("live.reasoning")}
</div>
{lines.map((line, i) => (
<div key={i}>
{line}
{i === lines.length - 1 ? <span className="stream-caret" /> : null}
</div>
))}
</div>
);
}
export function ToolRunningCard({
kind = "tool",
name,
elapsedMs,
logLines,
}: {
kind?: "shell" | "fetch" | "search" | "tool";
name: string;
elapsedMs: number;
logLines?: { text: string; tone?: "ok" | "dim" }[];
}) {
useLang();
const ic =
kind === "shell" ? <I.terminal size={12} /> : kind === "fetch" ? <I.globe size={12} /> : kind === "search" ? <I.search size={12} /> : <I.wrench size={12} />;
return (
<div className="skel-card">
<div className="h">
<span className="ico">{ic}</span>
<span className="kind">{kind}</span>
<span style={{ color: "var(--fg)", fontWeight: 500 }}>{name}</span>
<span className="grow" />
<span className="spin-meta" role="img" aria-label={t("live.running")} title={t("live.running")} />
<span className="timer">{fmtElapsed(elapsedMs)}</span>
</div>
{logLines && logLines.length > 0 ? (
<div className="live-log">
{logLines.map((ln, i) => (
<div
key={i}
className={`line ${ln.tone ?? ""}`}
style={{ animationDelay: `${i * 0.25}s` }}
>
{ln.text}
</div>
))}
</div>
) : (
<div className="body">
<div className="skel-line w-90" />
<div className="skel-line w-70" />
<div className="skel-line w-60" />
</div>
)}
</div>
);
}
export function PendingUserMsg({ text, elapsedMs }: { text: string; elapsedMs: number }) {
useLang();
return (
<div className="msg user">
<div className="avatar">YOU</div>
<div className="body">
<div className="who">
<span className="name">{t("live.you")}</span>
<span className="time">
{t("live.secondsAgo", { seconds: (elapsedMs / 1000).toFixed(1) })}
</span>
</div>
<div className="msg-text user-pending">{text}</div>
<div className="user-status">
<span className="spin" />
<span>{t("live.deliveredWaiting")}</span>
</div>
</div>
</div>
);
}
File diff suppressed because it is too large. Load diff
+60
View File
@@ -0,0 +1,60 @@
import type { ReactNode } from "react";
export type ShortcutKey = "mod" | "shift" | "enter" | "tab" | "esc" | "updown" | string;
function isMacPlatform(): boolean {
if (typeof document === "undefined") return false;
return document.documentElement.dataset.platform === "macos";
}
function keyLabel(key: ShortcutKey, mac: boolean): string {
switch (key) {
case "mod":
case "⌘":
return mac ? "⌘" : "Ctrl";
case "shift":
case "⇧":
return mac ? "⇧" : "Shift";
case "enter":
case "⏎":
return "Enter";
case "tab":
case "⇥":
return "Tab";
case "esc":
return "Esc";
case "updown":
case "↑↓":
return "↑↓";
default:
return key;
}
}
export function shortcutText(keys: readonly ShortcutKey[]): string {
const mac = isMacPlatform();
return keys.map((key) => keyLabel(key, mac)).join(mac ? "" : "+");
}
export function localizeShortcutText(text: string): string {
return text.replace(/⌘/g, keyLabel("mod", isMacPlatform()));
}
export function Shortcut({
keys,
className,
}: {
keys: readonly ShortcutKey[];
className?: string;
}): ReactNode {
const mac = isMacPlatform();
return (
<span className={["shortcut", className].filter(Boolean).join(" ")}>
{keys.map((key, index) => (
<kbd key={`${key}-${index}`} data-key={key}>
{keyLabel(key, mac)}
</kbd>
))}
</span>
);
}
+316
View File
@@ -0,0 +1,316 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import type { SessionInfo } from "../App";
import { t, useLang } from "../i18n";
import { I } from "../icons";
import { Shortcut } from "./shortcut";
type PendingDelete = {
name: string;
pretty: string;
x: number;
y: number;
};
function prettyName(s: SessionInfo): string {
if (s.summary && s.summary.trim()) return s.summary.trim();
const m = s.name.match(/^desktop-(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(?:-(\d+))?$/);
if (m) {
const [, , month, day, hh, mm, tab] = m;
return `${t("sidebarPanel.sessionTitle", {
month,
day,
hour: hh,
minute: mm,
})}${tab && tab !== "1" ? ` · #${tab}` : ""}`;
}
return s.name.replace(/^desktop-/, "").replace(/[-_]+/g, " ");
}
function relative(ms: number): string {
const min = ms / 60_000;
if (min < 1) return t("sidebarPanel.justNow");
if (min < 60) return t("sidebarPanel.minutesAgo", { n: Math.floor(min) });
const hr = min / 60;
if (hr < 24) return t("sidebarPanel.hoursAgo", { n: Math.floor(hr) });
const d = hr / 24;
if (d < 7) return t("sidebarPanel.daysAgo", { n: Math.floor(d) });
return t("sidebarPanel.weeksAgo", { n: Math.floor(d / 7) });
}
export function Sidebar({
sessions,
activeName,
loadingName,
onNewChat,
onLoadSession,
onDeleteSession,
onOpenSettings,
onOpenRules,
onOpenCommands,
onOpenAbout,
}: {
sessions: SessionInfo[];
activeName?: string;
/** Name of the session currently being loaded — drives the per-row spinner. */
loadingName?: string | null;
onNewChat: () => void;
onLoadSession: (name: string) => void;
onDeleteSession: (name: string) => void;
onOpenSettings: () => void;
onOpenRules: () => void;
onOpenCommands: () => void;
onOpenAbout: () => void;
}) {
useLang();
const [query, setQuery] = useState("");
const [pendingDelete, setPendingDelete] = useState<PendingDelete | null>(null);
const filtered = query
? sessions.filter((s) => {
const q = query.toLowerCase();
return (
prettyName(s).toLowerCase().includes(q) || s.name.toLowerCase().includes(q)
);
})
: sessions;
useEffect(() => {
if (!pendingDelete) return;
const onMouseDown = (e: MouseEvent) => {
const target = e.target as HTMLElement | null;
if (!target?.closest(".session-delete-popover")) setPendingDelete(null);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setPendingDelete(null);
};
window.addEventListener("mousedown", onMouseDown);
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("mousedown", onMouseDown);
window.removeEventListener("keydown", onKey);
};
}, [pendingDelete]);
return (
<aside className="sidebar">
<div className="side-head">
<button type="button" className="new-btn" onClick={onNewChat}>
<I.plus size={14} />
<span>{t("sidebarPanel.newChat")}</span>
<Shortcut keys={["mod", "N"]} />
</button>
<button
type="button"
className="icon-btn"
title={t("sidebarPanel.commandPalette")}
onClick={onOpenCommands}
>
<I.history size={14} />
</button>
</div>
<div className="search-row">
<div className="input">
<I.search size={13} />
<input
placeholder={t("sidebarPanel.searchSessions")}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<Shortcut keys={["mod", "K"]} />
</div>
</div>
<div className="session-list">
<div className="side-section">
<div className="label">
<span>{t("sidebarPanel.recent")}</span>
<span className="count">{filtered.length}</span>
</div>
{sessions.length === 0 ? (
<div
style={{
padding: "12px 8px",
fontSize: 11,
color: "var(--muted-2)",
fontFamily: "Geist Mono, monospace",
}}
>
{t("sidebarPanel.noSessions")}
</div>
) : filtered.length === 0 ? (
<div
style={{
padding: "12px 8px",
fontSize: 11,
color: "var(--muted-2)",
fontFamily: "Geist Mono, monospace",
}}
>
{t("sidebarPanel.noMatches")}
</div>
) : null}
{filtered.map((s) => {
const active = s.name === activeName;
const loading = s.name === loadingName;
const mtime = Date.parse(s.mtime);
const updated = Number.isFinite(mtime) ? relative(Date.now() - mtime) : s.mtime;
return (
<div
key={s.name}
className="session-item"
data-active={active}
data-loading={loading || undefined}
style={loadingName && !loading ? { opacity: 0.5, pointerEvents: "none" } : undefined}
onClick={() => onLoadSession(s.name)}
role="button"
tabIndex={0}
title={s.name}
onKeyDown={(e) => {
if (e.key === "Enter") onLoadSession(s.name);
}}
>
<span
className="state"
style={{
background: loading
? "var(--accent)"
: active
? "var(--accent)"
: "var(--border-strong)",
animation: loading ? "session-pulse 0.9s ease-in-out infinite" : undefined,
}}
/>
<div className="body">
<span className="title">{prettyName(s)}</span>
<span className="meta">
{loading ? (
<span>{t("sidebarPanel.loading")}</span>
) : (
<>
<span>{t("sidebarPanel.messageCount", { count: s.messageCount })}</span>
<span className="sep">·</span>
<span>{updated}</span>
</>
)}
</span>
</div>
<button
type="button"
className="delete-btn"
title={t("sidebarPanel.deleteSession")}
aria-label={t("sidebarPanel.deleteSession")}
onClick={(e) => {
e.stopPropagation();
const rect = e.currentTarget.getBoundingClientRect();
setPendingDelete({
name: s.name,
pretty: prettyName(s),
x: rect.right,
y: rect.bottom,
});
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") e.stopPropagation();
}}
>
<I.x size={12} />
</button>
</div>
);
})}
</div>
</div>
<div className="side-foot">
<div className="row" onClick={onOpenRules}>
<span className="ico">
<I.shield size={13} />
</span>
<span>{t("sidebarPanel.approvalRules")}</span>
</div>
<div className="row" onClick={onOpenAbout}>
<span className="ico">
<I.help size={13} />
</span>
<span>{t("about.sidebarLabel")}</span>
</div>
<div className="row" onClick={onOpenSettings}>
<span className="ico">
<I.cog size={13} />
</span>
<span>{t("sidebarPanel.settings")}</span>
<span className="right">
<Shortcut keys={["mod", ","]} />
</span>
</div>
</div>
{pendingDelete ? (
<SessionDeletePopover
target={pendingDelete}
onCancel={() => setPendingDelete(null)}
onConfirm={() => {
onDeleteSession(pendingDelete.name);
setPendingDelete(null);
}}
/>
) : null}
</aside>
);
}
function SessionDeletePopover({
target,
onCancel,
onConfirm,
}: {
target: PendingDelete;
onCancel: () => void;
onConfirm: () => void;
}) {
const ref = useRef<HTMLDivElement>(null);
const cancelRef = useRef<HTMLButtonElement>(null);
const [pos, setPos] = useState<{ left: number; top: number }>({
left: target.x,
top: target.y,
});
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const pad = 8;
const vw = window.innerWidth;
const vh = window.innerHeight;
let left = target.x;
let top = target.y;
if (left + rect.width + pad > vw) left = Math.max(pad, vw - rect.width - pad);
if (top + rect.height + pad > vh) top = Math.max(pad, vh - rect.height - pad);
if (left !== pos.left || top !== pos.top) setPos({ left, top });
cancelRef.current?.focus();
}, [target.x, target.y, pos.left, pos.top]);
return (
<div
ref={ref}
className="session-delete-popover"
role="dialog"
aria-modal="true"
style={{ left: pos.left, top: pos.top }}
>
<div className="msg">
{t("sidebarPanel.deleteSession")}
<span className="name">{target.pretty}</span>
</div>
<div className="actions">
<button ref={cancelRef} type="button" className="cancel" onClick={onCancel}>
{t("sidebarPanel.cancel")}
</button>
<button type="button" className="confirm" onClick={onConfirm}>
<I.x size={11} />
{t("sidebarPanel.delete")}
</button>
</div>
</div>
);
}
+68
View File
@@ -0,0 +1,68 @@
import { useEffect, useRef, useState } from "react";
import { t } from "../i18n";
const SPLASH_FLAG = "reasonix.splash.shown";
export function shouldShowSplash(): boolean {
try {
return sessionStorage.getItem(SPLASH_FLAG) !== "1";
} catch {
return true;
}
}
function markSplashShown() {
try {
sessionStorage.setItem(SPLASH_FLAG, "1");
} catch {
/* sessionStorage unavailable */
}
}
export function Splash({ onDone }: { onDone: () => void }) {
const [leaving, setLeaving] = useState(false);
const onDoneRef = useRef(onDone);
onDoneRef.current = onDone;
useEffect(() => {
const t1 = window.setTimeout(() => setLeaving(true), 1350);
const t2 = window.setTimeout(() => {
markSplashShown();
onDoneRef.current();
}, 1800);
return () => {
window.clearTimeout(t1);
window.clearTimeout(t2);
};
}, []);
useEffect(() => {
const skip = (e: KeyboardEvent) => {
if (e.key !== "Escape" && e.key !== "Enter" && e.key !== " ") return;
markSplashShown();
onDoneRef.current();
};
window.addEventListener("keydown", skip);
return () => window.removeEventListener("keydown", skip);
}, []);
const skipClick = () => {
markSplashShown();
onDone();
};
return (
<div className="splash" data-leaving={leaving} onClick={skipClick}>
<div className="splash-card">
<div className="splash-mark" />
<div className="splash-name">Reasonix</div>
<div className="splash-sub">{t("app.splashSubtitle")}</div>
<div className="splash-dots">
<span />
<span />
<span />
</div>
</div>
</div>
);
}
+198
View File
@@ -0,0 +1,198 @@
import { useEffect, useRef, useState } from "react";
import { I } from "../icons";
import { t } from "../i18n";
import type { Balance, Settings, UsageStats } from "../App";
import type { JobInfo } from "../protocol";
import { THEME, THEME_STYLES, type Theme, type ThemeStyle, themeForStyle } from "../theme";
import { localizeShortcutText } from "./shortcut";
const USD_TO_CNY = 7.2;
function formatMoney(amountUsd: number, currency: "CNY" | "USD"): string {
const symbol = currency === "CNY" ? "¥" : "$";
const amount = currency === "CNY" ? amountUsd * USD_TO_CNY : amountUsd;
return `${symbol} ${amount.toFixed(4)}`;
}
function tokenLabel(n: number): string {
if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
return `${n}`;
}
export function StatusBar({
settings,
balance,
usage,
busy,
ready,
currency,
theme,
themeStyle,
jobs,
jobsOpen,
onToggleJobs,
onSetThemeStyle,
onToggleCurrency,
onOpenSettings,
onOpenWorkdir,
}: {
settings: Settings | null;
balance: Balance | null;
usage: UsageStats;
busy: boolean;
ready: boolean;
currency: "CNY" | "USD";
theme: Theme;
themeStyle: ThemeStyle;
jobs: JobInfo[];
jobsOpen: boolean;
onToggleJobs: () => void;
onSetThemeStyle: (style: ThemeStyle) => void;
onToggleCurrency: () => void;
onOpenSettings: () => void;
onOpenWorkdir?: (anchor: { bottom: number; left: number }) => void;
}) {
const totalTokens = usage.cacheHitTokens + usage.cacheMissTokens;
const cacheHitPct = totalTokens > 0 ? Math.round((usage.cacheHitTokens / totalTokens) * 100) : 0;
const runningJobs = jobs.filter((j) => j.running).length;
const spent = formatMoney(usage.totalCostUsd, currency);
const balanceLabel = balance
? `${balance.currency === "USD" ? "$" : "¥"} ${balance.total.toFixed(2)}`
: "—";
const connState = !ready ? "off" : busy ? "running" : "online";
const [themeOpen, setThemeOpen] = useState(false);
const themePopRef = useRef<HTMLDivElement | null>(null);
const themeButtonRef = useRef<HTMLSpanElement | null>(null);
useEffect(() => {
if (!themeOpen) return;
const onPointerDown = (event: PointerEvent) => {
const target = event.target as Node;
if (themePopRef.current?.contains(target) || themeButtonRef.current?.contains(target)) return;
setThemeOpen(false);
};
window.addEventListener("pointerdown", onPointerDown);
return () => window.removeEventListener("pointerdown", onPointerDown);
}, [themeOpen]);
return (
<footer className="statusbar">
<span className="seg" title={`API · ${settings?.baseUrl ?? "api.deepseek.com"}`}>
<span
className={connState === "off" ? "sw warn" : "sw"}
style={connState === "off" ? { background: "var(--danger)" } : undefined}
/>
<span>{settings?.baseUrl?.replace(/^https?:\/\//, "") ?? "api.deepseek.com"}</span>
<span className="v">{!ready ? t("statusbar.offline") : busy ? t("statusbar.busy") : t("statusbar.online")}</span>
</span>
<span className="seg" title={t("statusbar.cacheHit")}>
<I.zap size={11} style={{ color: "var(--accent)" }} />
<span>{t("statusbar.cache")}</span>
<span className="v acc">{cacheHitPct}%</span>
</span>
<span className="seg">
<I.cpu size={11} />
<span>{t("statusbar.tokens")}</span>
<span className="v">{tokenLabel(totalTokens)}</span>
</span>
<span className="seg">
<I.coin size={11} />
<span>{t("statusbar.thisTurn")}</span>
<span className="v ok">{spent}</span>
</span>
<span className="grow" />
<span
className={`seg jobs ${jobsOpen ? "active" : ""}`}
onClick={onToggleJobs}
title={localizeShortcutText(t("statusbar.jobsTip"))}
>
<I.cpu size={11} />
<span>{t("statusbar.jobs")}</span>
<span className={runningJobs > 0 ? "v acc" : "v"}>{runningJobs}</span>
</span>
{settings?.workspaceDir ? (
<span
className="seg"
title={t("statusbar.switchWorkspace", { workspace: settings.workspaceDir })}
style={onOpenWorkdir ? { cursor: "pointer" } : undefined}
onClick={(e) => {
if (!onOpenWorkdir) return;
const r = (e.currentTarget as HTMLElement).getBoundingClientRect();
onOpenWorkdir({ bottom: window.innerHeight - r.top + 6, left: r.left });
}}
>
<I.folder size={11} />
<span className="v">{settings.workspaceDir.split(/[\\/]/).pop() || "ws"}</span>
</span>
) : null}
<span
className="seg"
title={`model · effort ${settings?.reasoningEffort ?? "high"}`}
onClick={onOpenSettings}
>
<I.brain size={11} style={{ color: "var(--violet)" }} />
<span className="v vio">{settings?.model ?? "—"}</span>
<span className="v">{settings?.reasoningEffort ?? "high"}</span>
</span>
<span className="seg" title={t("statusbar.switchCurrency")} onClick={onToggleCurrency}>
<I.coin size={11} />
<span>{t("statusbar.balance")}</span>
<span className="v ok">{balanceLabel}</span>
</span>
<span
ref={themeButtonRef}
className={`seg theme-trigger ${themeOpen ? "active" : ""}`}
title={t("statusbar.switchTheme")}
onClick={() => setThemeOpen((open) => !open)}
>
{theme === THEME.DARK ? <I.moon size={11} /> : <I.sun size={11} />}
<span className="v">
{t(`statusbar.themeStyle${themeStyle[0]!.toUpperCase()}${themeStyle.slice(1)}` as any)}
</span>
</span>
{themeOpen ? (
<div ref={themePopRef} className="theme-pop" role="menu" aria-label={t("settings.themeStyle")}>
<div className="theme-pop-head">
<div className="tt">{t("settings.themeStyle")}</div>
<div className="ss">{t("statusbar.switchTheme")}</div>
</div>
<div className="theme-pop-list">
{THEME_STYLES.map((style) => (
<button
key={style}
type="button"
className="theme-pop-item"
data-on={themeStyle === style}
data-style={style}
onClick={() => {
onSetThemeStyle(style);
setThemeOpen(false);
}}
>
<span className="style-swatches" aria-hidden="true">
<span />
<span />
<span />
</span>
<span className="txt">
<span className="nm">
{t(`statusbar.themeStyle${style[0]!.toUpperCase()}${style.slice(1)}` as any)}
</span>
<span className="md">
{themeForStyle(style) === THEME.DARK
? t("statusbar.themeDark")
: t("statusbar.themeLight")}
</span>
</span>
{themeStyle === style ? <I.check size={13} /> : null}
</button>
))}
</div>
</div>
) : null}
</footer>
);
}
+542
View File
@@ -0,0 +1,542 @@
import { isCompactionSummary, stripCompactionMarker } from "@reasonix/core-utils/compaction";
import { derivePrefix } from "@reasonix/core-utils/derive-prefix";
import { memo, useState, type ReactNode } from "react";
import { Copy } from "lucide-react";
import { I } from "../icons";
import { t, useLang } from "../i18n";
import type { AssistantSegment, ActivePlan, PendingPlan, PendingCheckpoint, PendingRevision, PendingConfirm, PendingChoice, SkillOrigin } from "../App";
import { AssistantText, CompactionCard, PlanCardView, ReasoningCard, ShellCard, ToolCard, type PlanItem } from "./cards";
import { ApprovalCard, TaskCard, type TaskStepView } from "./extra-cards";
export function TurnDivider({ label }: { label: string }) {
return (
<div className="turn-divider">
<span>{label}</span>
<span className="line" />
</div>
);
}
export const UserMsg = memo(function UserMsg({
text,
time,
skill,
}: {
text: string;
time?: string;
skill?: SkillOrigin;
}) {
useLang();
const [copied, setCopied] = useState(false);
const onCopy = async () => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 1200);
} catch {
/* ignore */
}
};
return (
<div className="msg user">
<div className="avatar">YOU</div>
<div className="body">
<div className="who">
<span className="name">{t("thread.you")}</span>
{skill ? (
<span className="skill-chip" title={`skill · ${skill.runAs}`}>
<I.zap size={10} /> /{skill.name}
{skill.runAs === "subagent" ? <span className="sub">{t("thread.subagent")}</span> : null}
</span>
) : null}
{time ? <span className="time">{time}</span> : null}
</div>
<div className="msg-text">{text}</div>
<div className="msg-actions">
<button
type="button"
className={`copy-btn ${copied ? "done" : ""}`}
onClick={onCopy}
title={t("thread.copyMessage")}
>
<Copy size={11} />
{copied ? t("markdown.copied") : null}
</button>
</div>
</div>
</div>
);
});
export const AssistantMsg = memo(function AssistantMsg({
segments,
pending,
model,
time,
onApproveConfirm,
onRejectConfirm,
onAlwaysAllowConfirm,
pendingConfirms,
}: {
segments: AssistantSegment[];
pending: boolean;
model?: string;
time?: string;
onApproveConfirm: (id: number) => void;
onRejectConfirm: (id: number) => void;
onAlwaysAllowConfirm: (id: number, prefix: string) => void;
pendingConfirms: PendingConfirm[];
}) {
const [copied, setCopied] = useState(false);
const content = segments
.filter((s): s is AssistantSegment & { kind: "text" } => s.kind === "text")
.map((s) => s.text)
.join("\n\n");
const onCopy = async () => {
try {
await navigator.clipboard.writeText(content);
setCopied(true);
setTimeout(() => setCopied(false), 1200);
} catch {
/* ignore */
}
};
return (
<div className="msg assistant">
<div className="avatar">DS</div>
<div className="body">
<div className="who">
<span className="name">Reasonix</span>
{model ? <span className="model">{model}</span> : null}
{time ? <span className="time">{time}</span> : null}
</div>
{segments.map((s, i) => {
if (s.kind === "text") {
if (!s.text.trim()) return null;
if (isCompactionSummary(s.text)) {
return <CompactionCard key={i} summary={stripCompactionMarker(s.text)} />;
}
return <AssistantText key={i} text={s.text} />;
}
if (s.kind === "reasoning") {
return (
<ReasoningCard
key={i}
text={s.text}
streaming={pending && i === segments.length - 1}
/>
);
}
// tool segment
const pendingConfirm =
(s.name === "run_command" || s.name === "run_background") && s.result === undefined
? pendingConfirms.find((c) => c.command === extractCommand(s.args))
: undefined;
if (s.name === "run_command" || s.name === "run_background") {
const cmd = extractCommand(s.args) ?? s.args;
const state: "await" | "running" | "done" | "failed" =
s.result === undefined
? pendingConfirm
? "await"
: "running"
: s.ok === false
? "failed"
: "done";
return (
<ShellCard
key={i}
command={cmd}
output={s.result}
state={state}
durationMs={s.durationMs}
onApprove={pendingConfirm ? () => onApproveConfirm(pendingConfirm.id) : undefined}
onReject={pendingConfirm ? () => onRejectConfirm(pendingConfirm.id) : undefined}
onAlwaysAllow={
pendingConfirm
? () => {
onAlwaysAllowConfirm(pendingConfirm.id, derivePrefix(cmd));
}
: undefined
}
/>
);
}
return (
<ToolCard
key={i}
name={s.name}
args={s.args}
result={s.result}
ok={s.ok}
durationMs={s.durationMs}
/>
);
})}
{content ? (
<div className="msg-actions">
<button
type="button"
className={`copy-btn ${copied ? "done" : ""}`}
onClick={onCopy}
title={t("thread.copyResponse")}
>
<Copy size={11} />
{copied ? t("markdown.copied") : null}
</button>
</div>
) : null}
</div>
</div>
);
});
function extractCommand(args: string): string | undefined {
if (!args) return undefined;
try {
const v = JSON.parse(args);
if (v && typeof v === "object" && typeof v.command === "string") return v.command;
} catch {
// ignore
}
return undefined;
}
export function PlanBanner({
plan,
onDismiss,
}: {
plan: ActivePlan;
onDismiss?: () => void;
}) {
useLang();
const total = plan.steps.length || 1;
const done = plan.completedStepIds.length;
const pct = (done / total) * 100;
const current = plan.steps.find((s) => !plan.completedStepIds.includes(s.id));
return (
<div className="plan-banner">
<span className="ico">
<I.list size={14} />
</span>
<div className="body">
<div className="t">
{t("thread.planRunning", { step: Math.min(done + 1, total), total })}
{current ? ` — ${current.title}` : ""}
</div>
<div className="s">{plan.plan}</div>
</div>
<div className="prog">
<div className="meter-mini">
<span style={{ width: `${pct}%` }} />
</div>
{onDismiss ? (
<button type="button" onClick={onDismiss}>
{t("thread.collapse")}
</button>
) : null}
</div>
</div>
);
}
export function ActivePlanCard({ plan }: { plan: ActivePlan }) {
useLang();
const done = new Set(plan.completedStepIds);
const items: PlanItem[] = plan.steps.map((s) => {
let status: PlanItem["status"];
if (done.has(s.id)) status = "done";
else if (s === plan.steps.find((x) => !done.has(x.id))) status = "active";
else status = "todo";
return {
id: s.id,
status,
text: s.title,
tool: s.action,
note: s.risk ? `${t("thread.risk")}: ${s.risk}` : undefined,
};
});
return <PlanCardView items={items} title={t("thread.activePlan")} />;
}
// ---- Approval bindings ----
export function PlanApprovalCard({
p,
onApprove,
onRefine,
onCancel,
}: {
p: PendingPlan;
onApprove: () => void;
onRefine: () => void;
onCancel: () => void;
}) {
useLang();
const stepCount = p.steps?.length ?? 0;
const sub = stepCount > 0 ? t("thread.planStepCount", { count: stepCount }) : undefined;
return (
<ApprovalCard
kind={t("thread.planConfirmationKind")}
tone="info"
title={t("thread.startPlan")}
sub={sub}
body={
<>
{p.summary ? <div style={{ marginBottom: 6 }}>{p.summary}</div> : null}
<div style={{ whiteSpace: "pre-wrap" }}>{p.plan}</div>
</>
}
meta={`plan/#${p.id}`}
primaryLabel={t("thread.approve")}
secondaryLabel={t("thread.cancel")}
tertiaryLabel={t("thread.refine")}
onPrimary={onApprove}
onSecondary={onCancel}
onTertiary={onRefine}
/>
);
}
export function CheckpointApprovalCard({
c,
onContinue,
onRevise,
onStop,
}: {
c: PendingCheckpoint;
onContinue: () => void;
onRevise: () => void;
onStop: () => void;
}) {
useLang();
return (
<ApprovalCard
kind={t("thread.checkpointKind")}
tone="brand"
title={c.title ?? t("thread.checkpointTitle", { completed: c.completed, total: c.total })}
sub={t("thread.checkpointSub", { completed: c.completed, total: c.total })}
body={
<>
<div style={{ whiteSpace: "pre-wrap" }}>{c.result}</div>
{c.notes ? (
<div style={{ marginTop: 8, fontSize: 11.5, color: "var(--muted)" }}>{c.notes}</div>
) : null}
</>
}
meta={`checkpoint · ${c.stepId}`}
primaryLabel={t("thread.continue")}
secondaryLabel={t("thread.stop")}
tertiaryLabel={t("thread.revise")}
onPrimary={onContinue}
onSecondary={onStop}
onTertiary={onRevise}
/>
);
}
export function RevisionApprovalCard({
r,
onAccept,
onReject,
}: {
r: PendingRevision;
onAccept: () => void;
onReject: () => void;
}) {
useLang();
return (
<ApprovalCard
kind={t("thread.planRevisionKind")}
tone="warn"
title={t("thread.rewritePlan")}
sub={t("thread.keepSteps", { n: r.remainingSteps.length })}
body={
<>
<div style={{ marginBottom: 8 }}>{r.reason}</div>
{r.summary ? (
<div style={{ fontSize: 11.5, color: "var(--muted)", marginBottom: 8 }}>{r.summary}</div>
) : null}
<ul style={{ margin: 0, paddingLeft: 18 }}>
{r.remainingSteps.map((s) => (
<li key={s.id} style={{ fontSize: 12, marginBottom: 2 }}>
{s.title}
{s.risk ? (
<span
style={{
marginLeft: 6,
fontSize: 10,
color:
s.risk === "high"
? "var(--tone-err)"
: s.risk === "med"
? "var(--tone-warn)"
: "var(--muted)",
}}
>
[{s.risk}]
</span>
) : null}
</li>
))}
</ul>
</>
}
meta={t("thread.revisionMeta")}
primaryLabel={t("thread.approveRewrite")}
secondaryLabel={t("thread.keepOriginal")}
onPrimary={onAccept}
onSecondary={onReject}
/>
);
}
export function ConfirmApprovalCard({
c,
onAllow,
onAlwaysAllow,
onDeny,
}: {
c: PendingConfirm;
onAllow: () => void;
onAlwaysAllow: (prefix: string) => void;
onDeny: () => void;
}) {
useLang();
const isBackground = c.kind === "run_background";
const prefix = derivePrefix(c.command);
return (
<ApprovalCard
kind={t("thread.shellConfirmationKind")}
tone="warn"
title={isBackground ? t("thread.runBackgroundCommand") : t("thread.runCommand")}
sub={c.command.length > 80 ? `${c.command.slice(0, 80)}…` : c.command}
preview={
<>
<span style={{ color: "var(--accent)" }}>$</span> {c.command}
</>
}
meta={t("thread.riskMedium", { kind: c.kind })}
primaryLabel={t("thread.execute")}
secondaryLabel={t("thread.reject")}
tertiaryLabel={t("thread.alwaysAllow", { prefix })}
onPrimary={onAllow}
onSecondary={onDeny}
onTertiary={() => onAlwaysAllow(prefix)}
/>
);
}
export function PathAccessApprovalCard({
p,
onAllow,
onAlwaysAllow,
onDeny,
}: {
p: {
id: number;
path: string;
intent: "read" | "write";
toolName: string;
sandboxRoot: string;
allowPrefix: string;
};
onAllow: () => void;
onAlwaysAllow: (prefix: string) => void;
onDeny: () => void;
}) {
useLang();
const isWrite = p.intent === "write";
return (
<ApprovalCard
kind={t("thread.pathAccessKind")}
tone="warn"
title={isWrite ? t("thread.writePathOutsideSandbox") : t("thread.readPathOutsideSandbox")}
sub={p.path}
preview={
<>
<div>{p.toolName} → {p.path}</div>
<div style={{ color: "var(--muted)", marginTop: 4 }}>
workspace: {p.sandboxRoot}
</div>
</>
}
meta={t("thread.riskMedium", { kind: p.intent })}
primaryLabel={isWrite ? t("thread.allowWrite") : t("thread.allowRead")}
secondaryLabel={t("thread.reject")}
tertiaryLabel={t("thread.alwaysAllowPrefix", { prefix: p.allowPrefix })}
onPrimary={onAllow}
onSecondary={onDeny}
onTertiary={() => onAlwaysAllow(p.allowPrefix)}
/>
);
}
export function ChoiceApprovalCard({
c,
onPick,
onCancel,
}: {
c: PendingChoice;
onPick: (optionId: string) => void;
onCancel: () => void;
}) {
useLang();
return (
<ApprovalCard
kind={t("thread.userChoiceKind")}
tone="info"
title={c.question}
sub={t("thread.optionCount", { count: c.options.length })}
body={
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
{c.options.map((o) => (
<button
key={o.id}
type="button"
className="btn"
style={{ justifyContent: "flex-start", textAlign: "left" }}
onClick={() => onPick(o.id)}
>
<div>
<div style={{ fontWeight: 600 }}>{o.title}</div>
{o.summary ? (
<div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>
{o.summary}
</div>
) : null}
</div>
</button>
))}
</div>
}
primaryLabel={t("thread.cancel")}
onPrimary={onCancel}
/>
);
}
export function activePlanToTaskSteps(plan: ActivePlan): TaskStepView[] {
const done = new Set(plan.completedStepIds);
return plan.steps.map((s, i) => ({
n: String(i + 1),
state: done.has(s.id) ? "done" : i === plan.completedStepIds.length ? "running" : "queued",
label: s.title,
hint: s.action,
durationLabel: undefined,
}));
}
export function ActivePlanTaskCard({ plan }: { plan: ActivePlan }) {
useLang();
return (
<TaskCard
title={t("thread.activePlan")}
subtitle={plan.summary}
steps={activePlanToTaskSteps(plan)}
/>
);
}
export function HeaderHint({ children }: { children: ReactNode }) {
return <div className="msg-text">{children}</div>;
}
+144
View File
@@ -0,0 +1,144 @@
import { useCallback, useEffect, useRef, useState } from "react";
const PIN_THRESHOLD = 80; // px from bottom to consider "pinned"
// Auto-scrolls while content grows; un-pins only on real user gestures.
// Scroll events are avoided because smooth scrollTo can fire them mid-flight.
export function useAutoScroll(
containerRef: React.RefObject<HTMLDivElement | null>,
contentRef: React.RefObject<HTMLDivElement | null>,
busy: boolean,
/** Optional boot-time restore: the offset the transcript should open at. */
getRestoreScrollTop?: () => number | null,
) {
const [showJumpButton, setShowJumpButton] = useState(false);
const isPinnedRef = useRef(true);
const wasBusyRef = useRef(busy);
const rafIdRef = useRef<number>(0);
const isAtBottom = useCallback(() => {
const el = containerRef.current;
if (!el) return true;
return el.scrollTop + el.clientHeight >= el.scrollHeight - PIN_THRESHOLD;
}, [containerRef]);
const refreshJumpButton = useCallback(() => {
const el = containerRef.current;
if (!el) return;
setShowJumpButton(
!isPinnedRef.current && el.scrollHeight > el.clientHeight + PIN_THRESHOLD,
);
}, [containerRef]);
const scrollToBottom = useCallback(
(smooth = true) => {
const el = containerRef.current;
if (!el) return;
isPinnedRef.current = true;
setShowJumpButton(false);
el.scrollTo({
top: el.scrollHeight,
behavior: smooth ? "smooth" : "instant",
});
},
[containerRef],
);
// User-intent detection: only these gestures un-pin. Scroll events are
// intentionally NOT listened to — they can't tell user gestures from our
// own scrollTo.
useEffect(() => {
const el = containerRef.current;
if (!el) return;
// rAF lets the gesture's scroll delta land before we measure.
let pendingFrame = 0;
const onUserGesture = () => {
if (pendingFrame) cancelAnimationFrame(pendingFrame);
pendingFrame = requestAnimationFrame(() => {
pendingFrame = 0;
isPinnedRef.current = isAtBottom();
refreshJumpButton();
});
};
el.addEventListener("wheel", onUserGesture, { passive: true });
el.addEventListener("touchmove", onUserGesture, { passive: true });
el.addEventListener("keydown", onUserGesture);
// pointerdown on the scrollbar gutter starts a drag-scroll. The
// drag itself fires no wheel/touch, but pointerdown's followup
// scroll arrives within a frame; one rAF measure catches it.
el.addEventListener("pointerdown", onUserGesture);
return () => {
if (pendingFrame) cancelAnimationFrame(pendingFrame);
el.removeEventListener("wheel", onUserGesture);
el.removeEventListener("touchmove", onUserGesture);
el.removeEventListener("keydown", onUserGesture);
el.removeEventListener("pointerdown", onUserGesture);
};
}, [containerRef, isAtBottom, refreshJumpButton]);
// Both busy edges re-pin: turn start = user just sent and expects to
// see the reply; turn end = settle on the final answer (issue #1182).
useEffect(() => {
if (wasBusyRef.current !== busy) {
scrollToBottom(true);
}
wasBusyRef.current = busy;
}, [busy, scrollToBottom]);
// Watch content size changes (streaming text, tool results, new
// messages) and follow the bottom while pinned.
useEffect(() => {
const content = contentRef.current;
if (!content) return;
const ro = new ResizeObserver(() => {
if (rafIdRef.current) cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = requestAnimationFrame(() => {
rafIdRef.current = 0;
const el = containerRef.current;
if (!el) return;
if (isPinnedRef.current) {
el.scrollTo({ top: el.scrollHeight, behavior: "instant" });
} else {
refreshJumpButton();
}
});
});
ro.observe(content);
return () => {
ro.disconnect();
if (rafIdRef.current) {
cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = 0;
}
};
}, [containerRef, contentRef, refreshJumpButton]);
// Initial scroll when the hook mounts (e.g. session loaded). Restores the
// saved offset if there is one (#1244), otherwise pins to the bottom.
useEffect(() => {
const el = containerRef.current;
if (!el) return;
const id = setTimeout(() => {
const restore = getRestoreScrollTop?.() ?? null;
if (restore != null && restore > PIN_THRESHOLD) {
// Mid-transcript restore: stay un-pinned so content growth and the
// ResizeObserver don't yank the view back to the bottom.
isPinnedRef.current = false;
el.scrollTop = restore;
refreshJumpButton();
} else {
isPinnedRef.current = true;
setShowJumpButton(false);
el.scrollTo({ top: el.scrollHeight, behavior: "instant" });
}
}, 60);
return () => clearTimeout(id);
}, [containerRef, getRestoreScrollTop, refreshJumpButton]);
return { showJumpButton, scrollToBottom };
}
+76
View File
@@ -0,0 +1,76 @@
import { useEffect } from "react";
const TEXT_INPUT_SELECTOR =
'input, textarea, [contenteditable=""], [contenteditable="true"], [contenteditable="plaintext-only"]';
function getTextAssistAttrs() {
return {
autoCorrect: "off" as const,
autoCapitalize: "off" as const,
spellCheck: false as const,
};
}
function isMacPlatform() {
if (typeof document === "undefined") return false;
return document.documentElement.dataset.platform === "macos";
}
function applyTextAssistAttrs(element: Element) {
if (!(element instanceof HTMLElement)) return;
if (
!(element instanceof HTMLInputElement) &&
!(element instanceof HTMLTextAreaElement) &&
!element.isContentEditable
) {
return;
}
const attrs = getTextAssistAttrs();
element.setAttribute("autocorrect", attrs.autoCorrect);
element.setAttribute("autocapitalize", attrs.autoCapitalize);
element.setAttribute("spellcheck", String(attrs.spellCheck));
element.spellcheck = attrs.spellCheck;
}
function applyWithin(root: ParentNode) {
if (root instanceof Element) {
applyTextAssistAttrs(root);
}
root.querySelectorAll(TEXT_INPUT_SELECTOR).forEach(applyTextAssistAttrs);
}
export function useDisableTextAssist() {
useEffect(() => {
if (typeof document === "undefined" || !isMacPlatform()) return;
const root = document.body;
if (!root) return;
applyWithin(root);
const handleFocusIn = (event: FocusEvent) => {
if (event.target instanceof Element) {
applyTextAssistAttrs(event.target);
}
};
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
mutation.addedNodes.forEach((node) => {
if (node instanceof Element) {
applyWithin(node);
}
});
}
});
document.addEventListener("focusin", handleFocusIn, true);
observer.observe(root, { childList: true, subtree: true });
return () => {
document.removeEventListener("focusin", handleFocusIn, true);
observer.disconnect();
};
}, []);
}
+190
View File
@@ -0,0 +1,190 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { I } from "../icons";
import { t, useLang } from "../i18n";
interface BrowseEntry {
name: string;
full: string;
}
interface BrowseResult {
path: string;
parent: string | null;
entries: BrowseEntry[];
}
async function fetchBrowse(path: string): Promise<BrowseResult> {
const token = document
.querySelector('meta[name="reasonix-token"]')
?.getAttribute("content") ?? "";
const params = new URLSearchParams();
if (path) params.set("path", path);
if (token && token !== "__REASONIX_TOKEN__") params.set("token", token);
const res = await fetch(`/api/browse?${params.toString()}`);
if (!res.ok) {
const text = await res.text();
throw new Error(text || `browse failed (${res.status})`);
}
return (await res.json()) as BrowseResult;
}
export function WorkdirInputModal({
open,
initialPath,
onCancel,
onConfirm,
}: {
open: boolean;
initialPath?: string;
onCancel: () => void;
onConfirm: (path: string) => void;
}) {
useLang();
const [typed, setTyped] = useState<string>(initialPath ?? "");
const [browse, setBrowse] = useState<BrowseResult | null>(null);
const [error, setError] = useState<string>("");
const [loading, setLoading] = useState(false);
const seededRef = useRef(false);
const navigate = useCallback(async (path: string) => {
setLoading(true);
setError("");
try {
const result = await fetchBrowse(path);
setBrowse(result);
setTyped(result.path);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
if (!open) {
seededRef.current = false;
return;
}
if (seededRef.current) return;
seededRef.current = true;
void navigate(initialPath ?? "");
}, [open, initialPath, navigate]);
if (!open) return null;
const trimmedTyped = typed.trim();
const canConfirm = trimmedTyped.length > 0 && !loading;
const sameAsCurrent = browse !== null && trimmedTyped === browse.path;
const handleConfirm = () => {
if (!canConfirm) return;
onConfirm(trimmedTyped);
};
const handleTypedKey = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Escape") {
e.preventDefault();
onCancel();
} else if (e.key === "Enter") {
e.preventDefault();
if (sameAsCurrent) {
handleConfirm();
} else {
void navigate(trimmedTyped);
}
}
};
return (
<div className="settings-mask" onMouseDown={onCancel}>
<div
className="workdir-input"
onMouseDown={(e) => e.stopPropagation()}
>
<div className="workdir-input-head">
<I.folder size={14} />
<span>{t("workdir.title")}</span>
<button
type="button"
className="close-btn"
onClick={onCancel}
title={t("workdir.cancel")}
>
<I.x size={13} />
</button>
</div>
<div className="workdir-input-pathrow">
<input
autoFocus
className="workdir-input-path"
value={typed}
placeholder={t("workdir.pathPlaceholder")}
onChange={(e) => setTyped(e.target.value)}
onKeyDown={handleTypedKey}
spellCheck={false}
/>
<button
type="button"
className="btn ghost"
onClick={() => void navigate(trimmedTyped)}
disabled={loading || trimmedTyped.length === 0}
title={t("workdir.goTip")}
>
{t("workdir.go")}
</button>
</div>
{error ? <div className="workdir-input-error">{error}</div> : null}
<div className="workdir-input-list">
{browse?.parent ? (
<div
className="workdir-input-row up"
onClick={() => void navigate(browse.parent!)}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") void navigate(browse.parent!);
}}
>
<span className="ic">↑</span>
<span>..</span>
</div>
) : null}
{browse?.entries.length === 0 && !loading ? (
<div className="workdir-input-empty">{t("workdir.emptyDir")}</div>
) : null}
{browse?.entries.map((e) => (
<div
key={e.full}
className="workdir-input-row"
onClick={() => void navigate(e.full)}
onDoubleClick={() => onConfirm(e.full)}
role="button"
tabIndex={0}
title={e.full}
onKeyDown={(ev) => {
if (ev.key === "Enter") void navigate(e.full);
}}
>
<span className="ic"><I.folder size={12} /></span>
<span className="n">{e.name}</span>
</div>
))}
{loading ? <div className="workdir-input-empty">{t("workdir.loading")}</div> : null}
</div>
<div className="workdir-input-foot">
<button type="button" className="btn ghost" onClick={onCancel}>
{t("workdir.cancel")}
</button>
<button
type="button"
className="btn primary"
onClick={handleConfirm}
disabled={!canConfirm}
>
{t("workdir.openHere")}
</button>
</div>
</div>
</div>
);
}
+142
View File
@@ -0,0 +1,142 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { I } from "../icons";
import { t, useLang } from "../i18n";
import { Shortcut } from "./shortcut";
type Anchor = { top?: number; bottom?: number; left: number };
export function WorkdirPop({
open,
onClose,
recent,
current,
anchor,
onPick,
onBrowse,
}: {
open: boolean;
onClose: () => void;
recent: string[];
current?: string;
anchor?: Anchor;
onPick: (path: string) => void;
onBrowse: () => void;
}) {
useLang();
const [query, setQuery] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!open) return;
setQuery("");
const id = window.setTimeout(() => inputRef.current?.focus(), 40);
return () => window.clearTimeout(id);
}, [open]);
const items = useMemo(() => {
const list = recent.length > 0 ? recent : current ? [current] : [];
const q = query.trim().toLowerCase();
if (!q) return list;
return list.filter((p) => p.toLowerCase().includes(q));
}, [recent, current, query]);
if (!open) return null;
const left = anchor?.left ?? 240;
const positionStyle =
anchor?.bottom !== undefined
? { bottom: anchor.bottom, left }
: { top: anchor?.top ?? 56, left };
return (
<div className="wd-mask" onMouseDown={onClose}>
<div className="wd-pop" style={positionStyle} onMouseDown={(e) => e.stopPropagation()}>
<div className="wd-head">
<I.folder size={12} />
<span>{t("workdir.title")}</span>
<span
style={{
marginLeft: "auto",
fontFamily: "Geist Mono, monospace",
fontSize: 10,
color: "var(--muted)",
}}
>
<Shortcut keys={["mod", "O"]} />
</span>
</div>
<input
ref={inputRef}
className="wd-search"
placeholder={t("workdir.searchPlaceholder")}
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Escape") {
e.preventDefault();
onClose();
} else if (e.key === "Enter" && items[0]) {
e.preventDefault();
onPick(items[0]);
onClose();
}
}}
/>
<div className="wd-list">
{items.length === 0 ? (
<div
style={{
padding: "16px 12px",
fontSize: 11.5,
color: "var(--muted)",
fontFamily: "Geist Mono, monospace",
}}
>
{t("workdir.empty")}
</div>
) : null}
{items.map((p) => {
const isCurrent = p === current;
const name = p.split(/[\\/]/).filter(Boolean).pop() ?? p;
return (
<div
key={p}
className="wd-row"
onClick={() => {
if (!isCurrent) onPick(p);
onClose();
}}
title={p}
>
<span className="ic">
<I.folder size={12} />
</span>
<div className="b">
<div className="p">{name}</div>
<div className="br">{p}</div>
</div>
{isCurrent ? (
<span className="pin">
<I.check size={11} />
</span>
) : null}
</div>
);
})}
</div>
<div className="wd-foot">
<button
type="button"
className="btn ghost"
onClick={() => {
onBrowse();
onClose();
}}
>
<I.plus size={11} /> {t("workdir.browse")}
</button>
</div>
</div>
</div>
);
}
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="vite/client" />
declare const __APP_VERSION__: string;
+26 -11
View File
@@ -1,16 +1,31 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"rootDir": ".",
"outDir": "dist",
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"esModuleInterop": true,
"isolatedModules": true,
"noEmit": true,
"declaration": false,
"declarationMap": false,
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"types": [],
"allowJs": true,
"checkJs": false
"baseUrl": ".",
"paths": {
"@tauri-apps/api/core": ["src/lib/tauri-bridge.ts"],
"@tauri-apps/api/event": ["src/lib/tauri-bridge.ts"],
"@tauri-apps/api/window": ["src/lib/tauri-bridge.ts"],
"@tauri-apps/api/webview": ["src/lib/tauri-bridge.ts"],
"@tauri-apps/plugin-dialog": ["src/lib/tauri-bridge.ts"],
"@tauri-apps/plugin-opener": ["src/lib/tauri-bridge.ts"],
"@tauri-apps/plugin-process": ["src/lib/tauri-bridge.ts"],
"@reasonix/core-utils/compaction": ["../packages/core-utils/src/compaction.ts"],
"@reasonix/core-utils/derive-prefix": ["../packages/core-utils/src/derive-prefix.ts"],
"@reasonix/core-utils": ["../packages/core-utils/src/index.ts"]
}
},
"include": ["src/**/*", "app.js"],
"exclude": ["dist", "node_modules"]
"include": ["src"]
}
+81
View File
@@ -0,0 +1,81 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { resolve } from "node:path";
export default defineConfig({
plugins: [
react(),
// 开发模式下:将生产路径重写为源码路径;移除不需要的 vendor CSS
{
name: "dev-html-rewrite",
transformIndexHtml(html: string) {
return html
.replace('/assets/app.js?token=__REASONIX_TOKEN__', '/src/main.tsx')
.replace('/assets/app.css?token=__REASONIX_TOKEN__', '/src/styles.css');
},
},
],
define: {
__APP_VERSION__: JSON.stringify("0.47.2"),
},
resolve: {
alias: {
"@reasonix/core-utils/compaction": resolve(__dirname, "../packages/core-utils/src/compaction.ts"),
"@reasonix/core-utils/derive-prefix": resolve(__dirname, "../packages/core-utils/src/derive-prefix.ts"),
"@reasonix/core-utils": resolve(__dirname, "../packages/core-utils/src/index.ts"),
"@tauri-apps/api/core": resolve(__dirname, "src/lib/tauri-bridge.ts"),
"@tauri-apps/api/event": resolve(__dirname, "src/lib/tauri-bridge.ts"),
"@tauri-apps/api/window": resolve(__dirname, "src/lib/tauri-bridge.ts"),
"@tauri-apps/api/webview": resolve(__dirname, "src/lib/tauri-bridge.ts"),
"@tauri-apps/plugin-dialog": resolve(__dirname, "src/lib/tauri-bridge.ts"),
"@tauri-apps/plugin-opener": resolve(__dirname, "src/lib/tauri-bridge.ts"),
"@tauri-apps/plugin-process": resolve(__dirname, "src/lib/tauri-bridge.ts"),
},
},
build: {
target: "es2022",
minify: "esbuild",
sourcemap: true,
outDir: "dist",
emptyOutDir: false, // 避免清空 dist 下原有的第三方资源 (如 vendor-css)
rollupOptions: {
input: {
app: resolve(__dirname, "src/main.tsx")
},
output: {
entryFileNames: "app.js",
chunkFileNames: "[name].js",
assetFileNames: (assetInfo) => {
if (assetInfo.name === "app.css" || assetInfo.name === "index.css") return "app.css";
// 字体等静态文件输出到 assets/ 子目录,匹配服务器 /assets/* 路由
if (/\.(woff2?|ttf|otf)$/.test(assetInfo.name ?? "")) return "assets/[name].[ext]";
return "[name].[ext]";
},
manualChunks(id) {
if (!id.includes("node_modules")) return;
if (id.includes("/katex/")) return "vendor-katex";
if (
id.includes("/react-markdown/") ||
id.includes("/remark-") ||
id.includes("/rehype-") ||
id.includes("/mdast-") ||
id.includes("/micromark") ||
id.includes("/unist-") ||
id.includes("/hast-")
)
return "vendor-markdown";
if (id.includes("/prism-react-renderer/")) return "vendor-prism";
if (id.includes("/lucide-react/")) return "vendor-icons";
if (id.includes("/react-virtuoso/")) return "vendor-virtuoso";
if (id.includes("/react/") || id.includes("/react-dom/") || id.includes("/scheduler/"))
return "vendor-react";
},
},
},
},
server: {
host: "127.0.0.1",
port: 3000,
strictPort: true
}
});
+25 -2
View File
@@ -1,18 +1,20 @@
{
"name": "reasonix-desktop",
"version": "0.43.0",
"version": "0.50.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "reasonix-desktop",
"version": "0.43.0",
"version": "0.50.0",
"dependencies": {
"@fontsource/geist": "^5.2.8",
"@fontsource/geist-mono": "^5.2.7",
"@fontsource/inter": "^5.2.8",
"@reasonix/core-utils": "file:../packages/core-utils",
"@tauri-apps/api": "^2.1.1",
"@tauri-apps/plugin-dialog": "^2.7.1",
"@tauri-apps/plugin-notification": "^2.0.0",
"@tauri-apps/plugin-opener": "^2.0.0",
"@tauri-apps/plugin-process": "^2.0.0",
"@tauri-apps/plugin-updater": "^2.0.0",
@@ -37,6 +39,14 @@
"vite": "^5.4.10"
}
},
"../packages/core-utils": {
"name": "@reasonix/core-utils",
"version": "0.1.0",
"devDependencies": {
"@types/node": "^22.9.0",
"typescript": "^5.6.3"
}
},
"node_modules/@babel/code-frame": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",
@@ -787,6 +797,10 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@reasonix/core-utils": {
"resolved": "../packages/core-utils",
"link": true
},
"node_modules/@rolldown/pluginutils": {
"version": "1.0.0-beta.27",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
@@ -1380,6 +1394,15 @@
"@tauri-apps/api": "^2.11.0"
}
},
"node_modules/@tauri-apps/plugin-notification": {
"version": "2.3.3",
"resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-notification/-/plugin-notification-2.3.3.tgz",
"integrity": "sha512-Zw+ZH18RJb41G4NrfHgIuofJiymusqN+q8fGUIIV7vyCH+5sSn5coqRv/MWB9qETsUs97vmU045q7OyseCV3Qg==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.8.0"
}
},
"node_modules/@tauri-apps/plugin-opener": {
"version": "2.5.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-opener/-/plugin-opener-2.5.4.tgz",
+3 -2
View File
@@ -1,7 +1,7 @@
{
"name": "reasonix-desktop",
"private": true,
"version": "0.48.1",
"version": "0.52.0",
"type": "module",
"scripts": {
"dev": "vite",
@@ -14,9 +14,10 @@
"@fontsource/geist": "^5.2.8",
"@fontsource/geist-mono": "^5.2.7",
"@fontsource/inter": "^5.2.8",
"@reasonix/core-utils": "workspace:*",
"@reasonix/core-utils": "file:../packages/core-utils",
"@tauri-apps/api": "^2.1.1",
"@tauri-apps/plugin-dialog": "^2.7.1",
"@tauri-apps/plugin-notification": "^2.0.0",
"@tauri-apps/plugin-opener": "^2.0.0",
"@tauri-apps/plugin-process": "^2.0.0",
"@tauri-apps/plugin-updater": "^2.0.0",
+34 -1
View File
@@ -23,12 +23,43 @@ if (!HOST_ARCH || !["win32", "darwin", "linux"].includes(PLAT)) {
const isWin = PLAT === "win32";
const targetExe = join(binDir, isWin ? "node.exe" : "node");
function adhocSignMac(binPath) {
// #1611: child node needs com.apple.security.inherit so it inherits the
// parent .app's TCC grants (Documents folder etc.) instead of re-prompting
// on every spawn. Ad-hoc is enough for TCC; CI later overlays Developer ID.
const ents = join(here, "..", "src-tauri", "entitlements", "node-helper.plist");
if (!existsSync(ents)) {
throw new Error(`entitlements missing: ${ents}`);
}
execSync(
`codesign --force --sign - --options runtime --entitlements "${ents}" "${binPath}"`,
{ stdio: "inherit" },
);
if (!hasMacTccInheritance(binPath)) {
throw new Error(`codesign did not apply com.apple.security.inherit to ${binPath}`);
}
}
function hasMacTccInheritance(binPath) {
try {
const out = execSync(`codesign -d --entitlements :- "${binPath}" 2>&1`, { encoding: "utf8" });
return out.includes("com.apple.security.inherit") && out.includes("<true/>");
} catch {
return false;
}
}
if (existsSync(targetExe) && statSync(targetExe).size > 1024 * 1024) {
if (PLAT === "darwin") {
try {
const archs = execSync(`lipo -archs "${targetExe}"`, { encoding: "utf8" }).trim();
if (archs.includes("arm64") && archs.includes("x86_64")) {
console.log(`${targetExe} already universal (${archs}) — delete to refetch`);
if (!hasMacTccInheritance(targetExe)) {
console.log(`${targetExe} universal but missing TCC inheritance — applying ad-hoc sign`);
adhocSignMac(targetExe);
} else {
console.log(`${targetExe} already universal + TCC-inheriting (${archs}) — delete to refetch`);
}
process.exit(0);
}
console.log(`${targetExe} present but not universal (${archs}) — rebuilding`);
@@ -128,6 +159,8 @@ if (PLAT === "darwin") {
rmSync(arm.extractDir, { recursive: true, force: true });
rmSync(x64.extractDir, { recursive: true, force: true });
adhocSignMac(targetExe);
const archs = execSync(`lipo -archs "${targetExe}"`, { encoding: "utf8" }).trim();
const mb = (statSync(targetExe).size / 1024 / 1024).toFixed(1);
console.log(`Done: ${targetExe} (${mb} MB, archs: ${archs})`);
+127 -2
View File
@@ -2041,6 +2041,18 @@ version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "mac-notification-sys"
version = "0.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29a16783dd1a47849b8c8133c9cd3eb2112cfbc6901670af3dba47c8bbfb07d3"
dependencies = [
"cc",
"objc2",
"objc2-foundation",
"time",
]
[[package]]
name = "markup5ever"
version = "0.38.0"
@@ -2151,6 +2163,20 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "notify-rust"
version = "4.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50ff2e74231b72c832d82982193b417f230945be6bdb5575b251d941d31adb00"
dependencies = [
"futures-lite",
"log",
"mac-notification-sys",
"serde",
"tauri-winrt-notification",
"zbus",
]
[[package]]
name = "num-conv"
version = "0.2.1"
@@ -2600,7 +2626,7 @@ checksum = "092791278e026273c1b65bbdcfbba3a300f2994c896bd01ab01da613c29c46f1"
dependencies = [
"base64 0.22.1",
"indexmap 2.14.0",
"quick-xml",
"quick-xml 0.39.4",
"serde",
"time",
]
@@ -2660,6 +2686,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "precomputed-hash"
version = "0.1.1"
@@ -2738,6 +2773,15 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "quick-xml"
version = "0.37.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"
dependencies = [
"memchr",
]
[[package]]
name = "quick-xml"
version = "0.39.4"
@@ -2768,6 +2812,35 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -2776,7 +2849,7 @@ checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
[[package]]
name = "reasonix-desktop"
version = "0.48.1"
version = "0.52.0"
dependencies = [
"anyhow",
"parking_lot",
@@ -2785,6 +2858,7 @@ dependencies = [
"tauri",
"tauri-build",
"tauri-plugin-dialog",
"tauri-plugin-notification",
"tauri-plugin-opener",
"tauri-plugin-process",
"tauri-plugin-updater",
@@ -3801,6 +3875,25 @@ dependencies = [
"url",
]
[[package]]
name = "tauri-plugin-notification"
version = "2.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01fc2c5ff41105bd1f7242d8201fdf3efd70749b82fa013a17f2126357d194cc"
dependencies = [
"log",
"notify-rust",
"rand",
"serde",
"serde_json",
"serde_repr",
"tauri",
"tauri-plugin",
"thiserror 2.0.18",
"time",
"url",
]
[[package]]
name = "tauri-plugin-opener"
version = "2.5.4"
@@ -3981,6 +4074,18 @@ dependencies = [
"toml 1.1.2+spec-1.1.0",
]
[[package]]
name = "tauri-winrt-notification"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b1e66e07de489fe43a46678dd0b8df65e0c973909df1b60ba33874e297ba9b9"
dependencies = [
"quick-xml 0.37.5",
"thiserror 2.0.18",
"windows",
"windows-version",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -5531,6 +5636,26 @@ dependencies = [
"zvariant",
]
[[package]]
name = "zerocopy"
version = "0.8.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "zerofrom"
version = "0.1.7"
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "reasonix-desktop"
version = "0.48.1"
version = "0.52.0"
edition = "2021"
publish = false
@@ -13,6 +13,7 @@ tauri-plugin-updater = "2"
tauri-plugin-process = "2"
tauri-plugin-opener = "2"
tauri-plugin-dialog = "2"
tauri-plugin-notification = "2"
tauri-plugin-window-state = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
@@ -17,6 +17,7 @@
"process:allow-restart",
"dialog:allow-open",
"dialog:allow-save",
"notification:default",
{
"identifier": "opener:allow-open-url",
"allow": [{ "url": "https://*" }, { "url": "http://*" }]
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<key>com.apple.security.cs.allow-dyld-environment-variables</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.inherit</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.inherit</key>
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
+85 -4
View File
@@ -4,7 +4,12 @@ mod rpc;
use rpc::{RpcState, rpc_kill, rpc_send, rpc_spawn};
use serde::Serialize;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
fn pasted_images_dir() -> PathBuf {
std::env::temp_dir().join("reasonix-pasted-images")
}
/// #892: bundled libwayland in AppImage can ABI-mismatch the host Wayland
/// compositor → WebKitWebProcess `abort()`s on EGL display creation. Redirect
@@ -178,12 +183,14 @@ fn open_in_editor(command: String, path: String, line: Option<u32>) -> Result<()
#[cfg(windows)]
{
// Spawn through cmd.exe so `.cmd` shims (code.cmd, cursor.cmd) resolve via PATH.
// Normalize forward slashes to backslashes — cmd.exe doesn't handle them reliably.
let normalized = path.replace('/', "\\");
cmd = Command::new("cmd");
cmd.arg("/c").arg(trimmed);
if let Some(l) = line {
cmd.arg("-g").arg(format!("{}:{}", path, l));
cmd.arg("-g").arg(format!("{}:{}", normalized, l));
} else {
cmd.arg(&path);
cmd.arg(&normalized);
}
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
@@ -208,6 +215,44 @@ fn write_text_file(path: String, content: String) -> Result<(), String> {
std::fs::write(&path, &content).map_err(|e| format!("write failed: {e}"))
}
fn sanitize_image_extension(raw: Option<&str>) -> String {
let cleaned = raw
.map(|s| s.trim().trim_start_matches('.').to_ascii_lowercase())
.unwrap_or_default();
let ok = !cleaned.is_empty()
&& cleaned.len() <= 8
&& cleaned.chars().all(|c| c.is_ascii_alphanumeric());
if ok { cleaned } else { "png".to_string() }
}
#[tauri::command]
fn save_clipboard_image(bytes: Vec<u8>, extension: Option<String>) -> Result<String, String> {
let ext = sanitize_image_extension(extension.as_deref());
let dir = pasted_images_dir();
std::fs::create_dir_all(&dir).map_err(|e| format!("mkdir failed: {e}"))?;
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("clock error: {e}"))?
.as_millis();
let path = dir.join(format!("reasonix-pasted-{ts}.{ext}"));
std::fs::write(&path, bytes).map_err(|e| format!("write failed: {e}"))?;
Ok(path.to_string_lossy().into_owned())
}
fn purge_old_pasted_images(max_age: Duration) {
let dir = pasted_images_dir();
let Ok(entries) = std::fs::read_dir(&dir) else { return };
let cutoff = SystemTime::now().checked_sub(max_age);
for entry in entries.flatten() {
let Ok(metadata) = entry.metadata() else { continue };
if !metadata.is_file() { continue }
let Ok(modified) = metadata.modified() else { continue };
if cutoff.is_some_and(|t| modified < t) {
let _ = std::fs::remove_file(entry.path());
}
}
}
fn main() {
#[cfg(target_os = "linux")]
linux_webkit_compat();
@@ -217,6 +262,7 @@ fn main() {
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_window_state::Builder::default().build())
.manage(RpcState::default())
.invoke_handler(tauri::generate_handler![
@@ -226,10 +272,12 @@ fn main() {
open_in_editor,
list_workspace_tree,
git_status,
write_text_file
write_text_file,
save_clipboard_image
])
.setup(|app| {
use tauri::Manager;
std::thread::spawn(|| purge_old_pasted_images(Duration::from_secs(24 * 60 * 60)));
if let Some(w) = app.get_webview_window("main") {
// HiDPI fit: the JSON config asks for 1024x720 logical px.
// On Windows laptops at 200% scale (1920x1080 → 960x540
@@ -272,3 +320,36 @@ fn main() {
}
});
}
#[cfg(test)]
mod tests {
use super::sanitize_image_extension;
#[test]
fn accepts_alphanumeric_extensions() {
assert_eq!(sanitize_image_extension(Some("png")), "png");
assert_eq!(sanitize_image_extension(Some("JPG")), "jpg");
assert_eq!(sanitize_image_extension(Some(".webp")), "webp");
assert_eq!(sanitize_image_extension(Some("svg")), "svg");
}
#[test]
fn falls_back_when_missing_or_invalid() {
assert_eq!(sanitize_image_extension(None), "png");
assert_eq!(sanitize_image_extension(Some("")), "png");
assert_eq!(sanitize_image_extension(Some(" ")), "png");
}
#[test]
fn rejects_path_separators_and_traversal() {
assert_eq!(sanitize_image_extension(Some("png/../../foo")), "png");
assert_eq!(sanitize_image_extension(Some("png\\foo")), "png");
assert_eq!(sanitize_image_extension(Some("../bin")), "png");
assert_eq!(sanitize_image_extension(Some("p.n.g")), "png");
}
#[test]
fn rejects_overlong_extensions() {
assert_eq!(sanitize_image_extension(Some("verylongext")), "png");
}
}
+5 -4
View File
@@ -98,15 +98,16 @@ fn resolve_cli(app: &AppHandle) -> Result<(String, Vec<String>)> {
}
/// Walk every PATH match for `node` and return the first one that is
/// (a) a real file > 100 KB and (b) NOT inside Windows' App Execution
/// Alias directory — those Microsoft Store stubs are 0-byte and triggered
/// the original "%1 is not a valid Win32 application" (error 193).
/// (a) a real file > 50 KB on macOS/Linux, or > 100 KB on Windows, and
/// (b) NOT inside Windows' App Execution Alias directory.
/// Threshold must accommodate Homebrew Node ~68 KB on arm64 macOS.
fn find_real_node() -> Result<PathBuf> {
let names: &[&str] = if cfg!(windows) {
&["node.exe", "node"]
} else {
&["node"]
};
let min_size: u64 = if cfg!(windows) { 100_000 } else { 50_000 };
let mut tried: Vec<String> = Vec::new();
for name in names {
if let Ok(iter) = which_all(*name) {
@@ -114,7 +115,7 @@ fn find_real_node() -> Result<PathBuf> {
let size = std::fs::metadata(&p).map(|m| m.len()).unwrap_or(0);
let lower = p.to_string_lossy().to_lowercase();
let is_ms_store_shim = lower.contains("windowsapps");
let too_small = size < 100_000;
let too_small = size < min_size;
if !too_small && !is_ms_store_shim {
return Ok(p);
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Reasonix",
"version": "0.48.1",
"version": "0.52.0",
"identifier": "dev.reasonix.desktop",
"build": {
"beforeDevCommand": "npm run dev",
+4
View File
@@ -16,6 +16,10 @@
]
},
"bundle": {
"macOS": {
"hardenedRuntime": true,
"entitlements": "entitlements/main.plist"
},
"resources": {
"binaries/node": "node"
}
+133 -1
View File
@@ -35,6 +35,7 @@ vi.mock("./theme", () => ({
}));
import { reduce } from "./App";
import { getThreadMaxWidth } from "./ui/thread-layout";
function initialState(): Parameters<typeof reduce>[0] {
return {
@@ -49,8 +50,19 @@ function initialState(): Parameters<typeof reduce>[0] {
pendingCheckpoints: [],
pendingRevisions: [],
activePlan: null,
usage: { totalCostUsd: 0, tokens: { input: 0, output: 0, cacheHit: 0, cacheMiss: 0 } },
usage: {
totalCostUsd: 0,
totalPromptTokens: 0,
totalCompletionTokens: 0,
cacheHitTokens: 0,
cacheMissTokens: 0,
lastCallCacheHit: null,
lastCallCacheMiss: null,
reservedTokens: 0,
liveLogTokens: 0,
},
sessions: [],
externalImportSources: [],
settings: null,
qq: null,
balance: null,
@@ -61,6 +73,7 @@ function initialState(): Parameters<typeof reduce>[0] {
skills: [],
sessionFiles: [],
memory: [],
memoryDetail: null,
jobs: [],
activeSkill: null,
queuedSends: [],
@@ -121,6 +134,85 @@ function makePathPrompt(
};
}
describe("Desktop App reducer — usage", () => {
it("falls back prompt tokens to cache miss tokens when cache fields are absent", () => {
const next = reduce(initialState(), {
t: "incoming",
event: {
type: "model.final",
id: 1,
ts: "2026-05-27T00:00:00.000Z",
turn: 1,
content: "ok",
usage: { prompt_tokens: 1234, completion_tokens: 56, total_tokens: 1290 },
costUsd: 0.001,
},
});
expect(next.usage.totalPromptTokens).toBe(1234);
expect(next.usage.cacheHitTokens).toBe(0);
expect(next.usage.cacheMissTokens).toBe(1234);
expect(next.usage.lastCallCacheMiss).toBe(1234);
});
it("settles the pending assistant message when an error ends the turn (#1660)", () => {
const base = initialState();
const state = {
...base,
busy: true,
messages: [
...base.messages,
{
kind: "assistant" as const,
turn: 1,
segments: [{ kind: "reasoning" as const, text: "thinking…" }],
pending: true,
},
],
};
const next = reduce(state, {
t: "incoming",
event: {
type: "error",
id: 1,
ts: "2026-05-27T00:00:00.000Z",
turn: 1,
message: "SSE body read failed: terminated",
recoverable: false,
},
});
expect(next.busy).toBe(false);
const assistant = next.messages.find((m) => m.kind === "assistant");
expect(assistant?.pending).toBe(false);
const error = next.messages.find((m) => m.kind === "error");
expect(error?.message).toBe("SSE body read failed: terminated");
});
it("keeps cumulative usage when live context breakdown refreshes", () => {
const base = initialState();
const next = reduce(
{
...base,
usage: {
...base.usage,
cacheHitTokens: 80,
cacheMissTokens: 20,
totalPromptTokens: 100,
},
},
{
t: "incoming",
event: { type: "$ctx_breakdown", reservedTokens: 10, logTokens: 42 },
},
);
expect(next.usage.cacheHitTokens).toBe(80);
expect(next.usage.cacheMissTokens).toBe(20);
expect(next.usage.liveLogTokens).toBe(42);
});
});
describe("Desktop App reducer — ApprovalPrompt integration", () => {
it("stores shell confirm with prompt on $confirm_required", () => {
const state = initialState();
@@ -232,4 +324,44 @@ describe("Desktop App reducer — ApprovalPrompt integration", () => {
expect(next.pendingConfirms).toHaveLength(0);
expect(next.pendingPathAccess).toHaveLength(0);
});
it("patches settings optimistically for desktop setting commands", () => {
const state: Parameters<typeof reduce>[0] = {
...initialState(),
settings: {
reasoningEffort: "medium",
editMode: "review",
budgetUsd: null,
workspaceDir: "/workspace",
recentWorkspaces: [],
model: "deepseek-v4-flash",
version: "0.50.1",
},
};
const next = reduce(state, {
t: "settings_patch",
patch: { reasoningEffort: "low", editMode: "auto" },
});
expect(next.settings?.reasoningEffort).toBe("low");
expect(next.settings?.editMode).toBe("auto");
});
});
describe("desktop thread layout", () => {
it("recomputes the thread cap from the latest viewport width", () => {
const side = 244;
const ctx = 320;
expect(
getThreadMaxWidth({ viewportWidth: 1000, visibleSide: side, visibleCtx: ctx }),
).toBe(580);
expect(
getThreadMaxWidth({ viewportWidth: 1400, visibleSide: side, visibleCtx: ctx }),
).toBe(756);
expect(
getThreadMaxWidth({ viewportWidth: 1800, visibleSide: side, visibleCtx: ctx }),
).toBe(1120);
});
});
Loaded 100 of 641 files, more files were not shown because too many files have changed in this diff. Show more