mirror of
https://github.com/NanmiCoder/cc-haha
synced 2026-08-01 16:43:37 +08:00
1336 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
b5e62e3251
|
fix(reverse-engineering): only ship 3 end-to-end verified MCP servers (live-smoked) + smoke script (#32)
* fix(reverse-engineering): declare missing tool-binary prereqs for 4 servers Real-world repro on a fresh Win11 machine showed 4 servers fail in ways the desktop one-click install couldn't surface, because their declared `prerequisites[]` only covered the runner (uvx / java) and not the underlying tool binary the runner needs at startup. Smoke from a clean machine (uvx just installed, no other tools): Before this PR -------------- ghidra ⚠️ spawned, no JSON-RPC response in 5s (uv pkg slow first start) radare2 ❌ prereq missing: radare2 ← already correct gdb ❌ prereq missing: gdb ← already correct lldb ❌ process exited (code=1) ← cause invisible jadx ⚠️ spawned, no JSON-RPC response in 5s ← cause invisible apktool ❌ process exited (code=1) ← cause invisible frida ❌ process exited (code=1) ← cause invisible After this PR (same machine, same tools) ---------------------------------------- ghidra ⚠️ spawned, no JSON-RPC response in 5s (unchanged — Ghidra is a GUI binary configured via GHIDRA_INSTALL_DIR, not a PATH command) radare2 ❌ prereq missing: radare2 gdb ❌ prereq missing: gdb lldb ❌ prereq missing: lldb ← now actionable jadx ❌ prereq missing: jadx ← now actionable apktool ❌ prereq missing: apktool ← now actionable frida ❌ prereq missing: frida ← now actionable → All actionable failures now route through the existing `PluginPrerequisitesModal` one-click install flow with per-platform install commands, instead of letting the server crash mid-startup. What this PR adds (servers.json) - lldb prereq adds `lldb` → win32 LLVM (winget/scoop), macOS xcode-select / brew, linux apt/dnf - jadx prereq adds `jadx` → win32 scoop, darwin brew, linux apt/snap - apktool prereq adds `apktool` → win32 scoop, darwin brew, linux apt/snap - frida prereq adds `frida` → uv tool / pipx / pip / brew (frida-tools is a Python pkg providing the `frida` CLI) Plus a sibling `scripts/smoke-reverse-engineering-mcps.ts` that: - reads the same plugin's `servers.json` - probes each prereq via `where` / `command -v` (same primitive as the desktop's `prerequisitesService`) - if all prereqs pass, spawns the server and sends an LSP-framed JSON-RPC `initialize` request, waits 5 s for the response - prints a status matrix + auto-generated install commands per platform (sourced from servers.json itself, not duplicated) - flags schema gaps where a server name implies a tool that's NOT in its prereq list (e.g. catches future regressions of this PR's fix, plus the existing ghidra/Ghidra-binary case is correctly excluded since Ghidra is GUI/env-var driven) Why a smoke script in the repo The existing `scripts/dev-mcp-test.ps1` is **only** the chrome-devtools browser-MCP environment launcher (Vite proxy + H5 token) — not an RE-plugin smoke. There was no equivalent reverse-engineering smoke, so each maintainer had to reproduce by hand. With this script, future "is the RE plugin healthy?" questions are one `bun run` away. Plugin version: 0.4.3 → 0.4.4 Verification - Manually ran `bun run scripts/smoke-reverse-engineering-mcps.ts` on a fresh Win11 26200 with uv 0.11.21 just installed: → 6/7 cleanly classified as `prereq missing`, 1/7 (ghidra) gets no response (expected — it needs `GHIDRA_INSTALL_DIR` to point at a user-installed Ghidra binary; not a PATH command). - The script's schema-gap heuristic correctly flags zero remaining gaps after this PR. Tested: live smoke on a real machine; before/after diff above. Not-tested: macOS / Linux paths (only Win32 install map exercised). The macOS/Linux paths are direct mirrors of the Win32 ones using the relevant native package managers, sourced from each tool's official install docs. Confidence: high Scope-risk: narrow * fix(reverse-engineering): only ship 3 end-to-end verified MCP servers Live smoke on a fresh Win11 26200 + an HTTP proxy showed that **4 of the 7 MCP servers in this plugin cannot be made to start** under any reachable upstream configuration: | Server | Upstream tried | Failure mode | |---------|------------------------------------------------------|---| | radare2 | npm @radareorg/radare2-mcp; drvcvt fork; r2 official | npm 404; drvcvt has no `dist/`; official is C/Meson requiring compile | | lldb | stass/lldb-mcp; stableversion/lldb_mcp | both upstream are single .py with no pyproject.toml | | jadx | zinja-coder/jadx-mcp-server; mseep-jadx PyPI | upstream raises `ModuleNotFoundError: 'src'`; PyPI republish is 0-byte placeholder | | apktool | zinja-coder/apktool-mcp-server; SecFathy/APktool-MCP | uv git fetch errors `Git operation failed`, persists past `uv cache clean`; SecFathy is unpackaged | The previous commit on this PR (3fef2390) added prerequisites entries for these 4 servers' tool binaries. That fix was correct in spirit but moot in practice, because even after every prereq is satisfied the servers still don't run — the failure isn't on the user's machine, it's in the upstream packaging. This commit takes the pragmatic step of removing the 4 broken servers from `mcp/servers.json` so users no longer see four permanently-red "Unavailable" cards in the desktop MCP page. The plugin now ships only the **3 servers that have been live-tested end-to-end**: | Server | Source | Verified state | |--------|---------------------------------------|---| | ghidra | uvx pyghidra-mcp | spawns; awaits user-set GHIDRA_INSTALL_DIR (by design) | | gdb | npx mcp-gdb | spawns; needs `gdb` on PATH (prereq declared) | | frida | uvx **frida-mcp** (PyPI v0.1.1) | ✅ initialize OK in 694 ms; serverInfo.name == "Frida" v1.27.2 | Note frida changed source: was `uvx --from git+...kahlo-mcp@main kahlo-mcp` (the upstream repo turned out to be a Node project in a `kahlo-mcp/` subdir, not a Python package — so uvx couldn't install it). The PyPI package `frida-mcp` is a clean, properly-packaged equivalent. What this commit changes - `plugins/reverse-engineering/mcp/servers.json` (-254/+0 net): remove radare2 / lldb / jadx / apktool entries; rewrite frida entry to use `uvx frida-mcp` (PyPI) instead of git+kahlo-mcp. - `plugins/reverse-engineering/.claude-plugin/plugin.json`: 0.4.4 → 0.4.5. - `plugins/reverse-engineering/README.md`: · summary changes "ships seven" → "ships three" with an inline note pointing at the new "Currently unbundled MCP servers" section · external-tool prereq table trimmed to ghidra/gdb/frida · new "Currently unbundled MCP servers" section explains exactly which upstream broke and how, plus how a user can wire the missing tools manually via shell + skills · References list marks the 4 removed servers as `(deferred)` with the specific upstream issue - `scripts/smoke-reverse-engineering-mcps.ts`: · transport fix — MCP stdio is NDJSON, not LSP-style Content-Length framing. The earlier draft's framing was the reason `frida-mcp` logged `Invalid JSON: EOF while parsing`; with NDJSON it now cleanly returns the initialize result. · schema-gap heuristic excludes `ghidra` (GUI binary, configured via env var, never on PATH) and `frida` (frida-mcp PyPI bundles its own Python frida client, no separate `frida` CLI needed). Verification Re-running smoke on a fresh checkout of this branch with proxy 127.0.0.1:7887: ``` === Reverse-engineering MCP smoke === Source: plugins\reverse-engineering\mcp\servers.json Servers: 3 ghidra ⚠️ spawned but no JSON-RPC response in 5010 ms gdb ❌ prereq missing: gdb frida ✅ initialize ok (694 ms) ``` 3/3 outcomes are correctly classified, 0 schema-gap warnings, and the "Install commands for missing prereqs" section guides the user to `scoop install gdb` / `pacman -S mingw-w64-x86_64-gdb` for the only missing tool on this machine. Tested: live smoke on a real Win11 box; before/after manifest count (7 → 3) reflected in plugin.json bump. Not-tested: macOS / Linux runtime smoke (only Win32 was exercised end- to-end in this iteration). Each server's install map remains correct across all three platforms. Confidence: high Scope-risk: narrow — single plugin, no server / desktop code changes. --------- Co-authored-by: 你的姓名 <you@example.com> |
||
|
|
ea82c6ec70 |
fix(trace): record aborted API calls instead of leaving them pending (#766)
When an upstream request was aborted mid-stream (SDK client timeout, stream idle watchdog, non-streaming fallback timeout, or user cancellation), the trace fetch hook waited on a clone of the response body that could hang forever, so the call never left "pending" in the trace panel — exactly the silent stall that misled the #766 report. - captureResponseTraceSnapshot reads the body with abort awareness: reader.cancel() on abort keeps the partial body, with a 2s grace backstop for runtimes where cancel cannot wake a hung read. - The fetch hook now records an error-state call on abort with the abort reason (e.g. the watchdog's stream idle timeout), duration, partial response body, and an api_call_aborted event; non-abort capture failures also record an error instead of inferring ok, and pre-response fetch rejections carry an aborted flag. - The trace detail panel shows an "Aborted" badge plus guidance for aborted calls, and labels the new api_call_aborted phase in all locales. Tested: bun test src/server/__tests__/trace-capture.test.ts Tested: bun run check:server Tested: cd desktop && bun run test -- --run && bun run lint |
||
|
|
67660ab4e5 |
fix(desktop): surface non-streaming fallback in chat status (#766)
api_retry heartbeats already reach the desktop status bar, but the
streaming-to-non-streaming fallback had no signal at all: the CLI only
flipped an internal flag, and the one-shot fallback response can take
minutes with zero incremental output, so the UI showed a bare spinner
the whole time.
- CLI: yield a {type:'system', subtype:'streaming_fallback', cause}
message at both fallback sites (stream error/watchdog and 404 stream
creation), mirroring the existing api_error -> api_retry path through
query.ts passthrough, QueryEngine SDK output, and the SDK schema.
- Server: translate it to a streaming_fallback ServerMessage;
unrecognized causes normalize to 'unknown' instead of dropping the
event.
- Desktop: track it as active-turn state (cleared at the same 12 sites
as apiRetry; a fallback notice supersedes the stale retry banner) and
render a neutral pill with the turn timer - expected state, not an
error, so no amber styling and nothing in the diagnostics panel.
- Retry banner now shows "retrying now" once the countdown elapses
instead of sticking at "waiting 0s".
With 62241a31 disabling the non-streaming fallback for desktop CLI
sessions, this notice mainly covers the 404 gateway path (which skips
the disable check), callers that re-enable fallback via env, and
non-desktop SDK consumers.
Constraint: Retries and fallbacks are expected states per the
diagnostics severity standard - lightweight active-turn UI only, no
error-panel entries, no transcript persistence.
Tested: bun test src/server/__tests__/ws-memory-events.test.ts
Tested: bun run check:server
Tested: cd desktop && bun run test -- --run
Tested: cd desktop && bun run lint
Not-tested: live provider outage reproduction; verified via unit
coverage of the translation, store lifecycle, and indicator rendering.
|
||
|
|
275dab39cc |
fix(native): run electron-builder through node
Avoid the bunx launcher for local Electron packaging after it can be terminated before Electron Builder starts. Use the installed Electron Builder CLI through Node for the macOS package script and desktop package shortcuts. Tested: SKIP_INSTALL=1 SKIP_PACKAGE_SMOKE=1 bash ./scripts/build-macos-arm64.sh Tested: bun run test:package-smoke --platform macos --package-kind release --artifacts-dir desktop/build-artifacts/macos-arm64 Tested: bash -n desktop/scripts/build-macos-arm64.sh Tested: git diff --check Not-tested: full bun run verify was not run because this is a narrow local packaging launcher fix. Confidence: high Scope-risk: narrow |
||
|
|
81599b2af9 |
fix: recover context meter right after compaction (#743)
The context usage indicator stayed at the pre-compact percentage (e.g.
100%) until the next API response arrived. Two stacked causes:
- The CLI anchors the displayed total to max(local estimate, last API
usage) so the meter never drops mid-turn — but preserved messages
(SM-compact / partial compact) still carried the pre-compact usage,
pinning the meter after compaction. buildPostCompactMessages now
zeroes token usage on preserved assistant copies, the established
stale placeholder that getCurrentUsage() skips, covering every
compaction path in one place. Originals are not mutated, so
transcript and cost accounting are unaffected.
- Right after compaction the CLI is often still busy, so the
indicator's refresh timed out ("Request timed out after 30s") and the
catch kept the stale context on screen with no later retry (auto
refresh is throttled to 10s and stops once the session goes idle).
compact_boundary now bumps a per-session compactCount; the indicator
force-refreshes on that nonce — bypassing the throttle and any
in-flight request that may still hold pre-compact data — and retries
once after 5s if the forced refresh fails.
Tested: bun test src/services/compact/
Tested: cd desktop && bun run test -- src/components/chat/ContextUsageIndicator.test.tsx src/stores/chatStore.test.ts
Tested: cd desktop && bun run lint
Confidence: high
Scope-risk: narrow
|
||
|
|
62241a31e5 |
fix(desktop): stop killing slow provider streams (#766)
Desktop injected a far stricter timeout stack than the terminal CLI, so healthy-but-slow third-party providers (sensenova/bailian/zhipu) died at exactly API_TIMEOUT_MS while the UI showed "running" forever: - API_TIMEOUT_MS is the SDK client's time-to-first-byte budget for streaming requests; these gateways send zero bytes (no headers, no SSE ping) until prefill finishes, which takes minutes at large contexts. Raise the default from 120s to the SDK's own 600s and widen the configurable range to 30-1800s. - Widen the desktop-forced stream watchdog idle window to 240s so silent thinking/prefill phases stop tripping the 90s default. - Disable the non-streaming fallback for desktop CLI sessions: a non-streaming request only responds after the FULL generation, so it can never finish inside the same budget and loops timeout aborts forever while the UI spins (also avoids double tool execution, upstream inc-4258). All three knobs respect caller env overrides. Repro: mock upstream whose SSE stays silent for 150s before a complete event sequence — terminal env completes; desktop env aborts at exactly 120s (client timeout) or 90s watchdog + non-streaming fallback loop; the fixed env completes both variants. Tested: bun test src/server/__tests__/network-settings.test.ts src/server/__tests__/conversation-service.test.ts src/server/__tests__/proxy-network-settings.test.ts Tested: cd desktop && bun run test -- src/stores/settingsStore.test.ts src/__tests__/generalSettings.test.tsx Tested: cd desktop && bun run lint Confidence: high Scope-risk: medium |
||
|
|
5cf8c1bb67 |
fix(desktop): queue active-turn prompts (#755)
Add pending user-message queue controls while a desktop turn is running, replay queued prompts into the transcript when the CLI accepts them, and flush remaining prompts after turn completion. Tested: cd desktop && bun run test -- src/components/chat/ChatInput.test.tsx Tested: cd desktop && bun run test -- src/stores/chatStore.test.ts Tested: bun test src/server/__tests__/ws-memory-events.test.ts Tested: bun run check:desktop Not-tested: bun run check:server remains blocked by unrelated E2E CORS preflight expectation, expected 403 but got 204. Confidence: medium Scope-risk: moderate |
||
|
|
88d04a6267 |
fix(desktop): include more sidebar sessions (#759)
Increase the desktop session list fetch window so noisy observer sessions are less likely to hide real user sessions from the sidebar. Tested: cd desktop && bun run test -- src/stores/sessionStore.test.ts src/components/layout/Sidebar.test.tsx Tested: bun run check:desktop Confidence: high Scope-risk: narrow |
||
|
|
90a50eca1c | Merge H5 access stability fixes (#767, #764) | ||
|
|
53d8e7ad77 |
feat(desktop): stabilize H5 access tokens, ports, and background sessions (#767, #764)
H5 远程访问的三处不稳定来源修复,让手机出门在外也能稳定连接、长任务不丢。 #767 令牌与端口固定: - 令牌明文持久化到 cc-haha/settings.json,重启后二维码/令牌随时可查、可复制; enable 复用现有令牌、disable 保留令牌,仅 regenerate 才轮换。手改 token 字段 即自定义固定令牌。完整令牌只经 local-trusted 面返回,远端 403。 - 新增可选固定端口 fixedPort,并在未配置时复用上次端口(desktop-server-state.json sticky,Electron/Tauri 双壳共享),反向代理/手机书签跨重启不失效;占用时回退随机。 #764 断连不杀正在运行的 CLI: - 客户端断开时若该会话仍在跑一轮任务,不再 30s 后强杀子进程,而是等任务跑完; 手机锁屏/切后台时长任务在后台跑完,重连即见结果。 - 空闲清理超时改为可配 disconnectGraceSeconds(H5 访问设置页,默认 30s), 经 disconnectGraceConfig 同步缓存供 close 处理读取。 server / Electron / Tauri / React 四层 + 五语言 i18n + 配套单测全部覆盖。 |
||
|
|
78a2fc978c | docs: update template | ||
|
|
6b4f7e4733 |
fix(desktop): expand tilde paths when revealing generated files (#776)
Reveal-in-Explorer/Finder rejected ~-prefixed paths because no layer expanded the tilde to the home directory. Expand it in the three path normalization entry points: server validateOpenPath, frontend resolveAbsolute, and Electron normalizeOpenPath. Tilde expansion is platform-aware (~\ only on win32, where backslash is a separator). |
||
|
|
34fe0761d2 |
fix(desktop): improve in-app browser preview menus (#761)
Tested: cd desktop && bun run test -- src/components/common/OpenWithMenu.test.tsx src/components/workspace/WorkspaceFileOpenWith.test.tsx src/components/browser/BrowserSurface.test.tsx src/lib/handlePreviewLink.test.ts src/lib/openWithContextForHref.test.ts Tested: bun run check:desktop Confidence: high Scope-risk: narrow |
||
|
|
8c99b0f892 |
feat(providers): support drag-and-drop reordering of the providers list
为服务商列表添加拖拽排序(#753)。复用项目已有的原生 HTML5 拖拽模式(对齐 Sidebar),零新增依赖;通过重排 providers.json 的数组顺序持久化,不引入 order 字段;仅行首手柄可拖,避免与行内操作按钮冲突;采用乐观更新 + 失败回滚。 后端: reorderProviders service、PUT /api/providers/reorder 路由、 ReorderProvidersSchema(校验 orderedIds 为现有 id 的排列)。 前端: providersApi.reorder、store action、Settings 拖拽手柄 UI、中/英/日/韩/繁文案。 测试: 后端 9 用例 + 前端 3 用例。 |
||
|
|
a932ebe017 |
fix(desktop): extend local API timeout (#773)
Tested: cd desktop && bun run test -- src/api/client.test.ts Tested: cd desktop && bun run lint Confidence: high Scope-risk: narrow |
||
|
|
ba3f16a602
|
docs: draft v0.5.12 release notes (Phase 4 wrap-up) (#30)
editor-lsp-foundation 47-task spec 收尾: - v0.5.11 已发,含 Phase 1 / 2 / 3 / 5(PR #23 / #24 / #26 / #27)。 - v0.5.12 是 Phase 4 (#29) 单 main feature 的 release notes 草稿, 也作为整个 47-task spec 的关闭 documentation:文末 "全景" section 列出所有 5 phase 的 PR + release 版本映射。 不发版;本 PR 仅放置 v0.5.12.md 占位,等下一次发版触发时由发版 流程消费。 _Tasks: 46, 47 (Phase 6 wrap-up)_ Co-authored-by: 你的姓名 <you@example.com> |
||
|
|
31230ef737
|
feat(desktop): bridge agent file edits to workspace panel (Phase 4) (#29)
Phase 4 of editor-lsp-foundation. The CLI agent's FileEditTool /
FileWriteTool / NotebookEditTool path was already vendored from upstream
and already drives the upstream LSP system. This PR bridges agent edits
into the desktop workbench (CodeMirror editor + workspace panel) without
touching the vendored tool code: the desktop chatStore observes the
agent's tool stream and refreshes/conflict-flags the panel itself.
Approach (option A in the spec discussion):
- chatStore: when a FILE_EDIT tool ('Edit'/'Write'/'NotebookEdit'/
'MultiEdit') completes, remember the toolUseId -> file_path mapping
in a per-session pending map. On the matching tool_result with
isError === false, consume the entry and call
workspacePanelStore.notifyAgentFileEdit(sessionId, absolutePath).
- workspacePanelStore.notifyAgentFileEdit: refreshes loadStatus when
the panel is open, and sets a 'source: agent' conflict on any open
editor buffer whose workspace-relative path matches the agent's
absolute path by suffix on a normalized segment boundary. Skips
buffers that already have a conflict so user-source banners aren't
clobbered. Uses sentinel hash 'agent-edit' because the chat tool
stream carries no content hash.
- Path matching normalizes backslashes -> forward slashes and trims
trailing slashes, then either equals or endsWith('/' + bufferPath)
to avoid foobar.ts matching bar.ts.
- Cleanup: clearPendingFileEdits added at the 3 existing pending-map
cleanup sites (disconnect, clear messages, new-session path).
Why no FileEditTool change:
The vendored upstream tool has no sessionId in ToolUseContext and
shouldn't import server WS modules from CLI process scope. The chat
stream already carries (sessionId, toolName, toolUseId, input, isError)
to the desktop and is the natural seam for desktop-side reactions —
same pattern the store already uses for TodoWrite -> useCLITaskStore
and Task* tools -> refreshTasks.
Tests:
- desktop/src/stores/workspacePanelStore.test.ts +6 (30/30 total)
Suffix match, Windows backslash, non-suffix substring rejection,
existing-conflict preservation, loadStatus when panel open, no
loadStatus when closed.
- desktop/src/stores/chatStore.test.ts +6 (112/112 total)
Edit/Write/NotebookEdit forwarding, isError gate, non-edit tool
isolation (Bash), single-fire on duplicate tool_result.
Verifier (independent agent) ran lint + both test suites + build +
bundle budget + 9 ad-hoc helper edge cases (Unicode paths, trailing
slash, identical absolute, deeper suffix mismatch). All PASS.
Bundle delta: +2.41 KB gz vs origin/main @ 95931d49 baseline
(97.59 KB headroom remaining).
_Requirements: 3.1, 3.2, 3.3, 8.1, 8.2 (adapted)_
Co-authored-by: 你的姓名 <you@example.com>
|
||
|
|
f144700b57 | Merge: unify token usage display across desktop and CLI (#757) | ||
|
|
a94e5b641a |
fix: unify token usage display across desktop and CLI (#757)
Token counts were rendered with five inconsistent formats across the chat UI (header "181,117 t", in-progress bare "↓ 2514", background agents "12,345 tokens", compact summary "1.5k", trace "1.2k"), and the in-progress count was actually stale: the server never set the status event's tokens field, so the indicator showed the previous turn's value (hence "first message shows nothing", "sometimes appears, never moves"). - Add shared desktop lib/formatTokenCount; route header, streaming indicator, background agents, compact summary, and trace through it. - Header shows compact "124.3k tokens" with the exact count on hover. - Add common.tokens i18n key (en/zh/zh-TW/jp/kr). - Estimate the in-progress count from streamed chars (÷4, mirroring the CLI spinner) via a new streamingResponseChars per-session field, reset on each send; drop the dead status.tokens/elapsed fields. - CLI spinner rows use formatTokens to drop the "1.0k" artifact. |
||
|
|
a4e3306753 | release: v0.5.11 | ||
|
|
535d777ec4
|
fix(providers): route 'Fetch Models' through server to bypass mixed-content / CORS (#28)
* fix(providers): route 'Fetch Models' through server to bypass mixed-content / CORS The "获取模型 / Fetch Models" button in the provider settings dialog used to call upstream `/v1/models` directly from the renderer with `fetch()`. That works for HTTPS providers whose endpoint sets permissive CORS headers (e.g. api.openai.com, api.anthropic.com), but fails for any plain-`http://` provider — most commonly self-hosted relay endpoints like `http://47.116.22.0:3000`. Two failure modes both surface as the same opaque "Failed to fetch": 1. Mixed-content block. The desktop renderer runs in a secure context (Tauri at `tauri://localhost`, Electron with web security on), and modern webviews refuse to fetch plain-HTTP URLs from a secure-context page. The request never leaves the browser. 2. CORS-missing. Even when reachable, many self-hosted relays do not return `Access-Control-Allow-Origin` for `/v1/models`, so the browser blocks the response. The "Test Connection" button never had this problem because it already proxies through `POST /api/providers/{id}/test`, which runs on the local server (Node, no webview restrictions). The fix routes "Fetch Models" through the same server so it inherits the same isolation. What this PR adds Server side - ApiError.badGateway(message) — new 502 helper for upstream failures. - POST /api/providers/fetch-models with the new FetchModelsSchema (zod): { baseUrl: url, apiKey: non-empty, apiFormat: 'anthropic' | 'openai_chat' | 'openai_responses' default 'anthropic' }. - ProviderService.fetchUpstreamModels(input) — server-side GET against `${baseUrl}/v1/models` (or `${baseUrl}/models` if baseUrl already ends in `/v1`), reusing the existing network-proxy / timeout plumbing. Sets Bearer for OpenAI-compatible formats, x-api-key + anthropic-version for native Anthropic. Returns `{ status, data }` where `data` is the upstream JSON verbatim. Non-2xx upstreams surface as ApiError.badGateway with the upstream's `error.message` if the body has one. Network failures and timeouts also map to badGateway with a clear message. Desktop side - providersApi.fetchModels(input) — new client wrapping the endpoint. - handleFetchModels in Settings.tsx now calls providersApi.fetchModels instead of fetching directly. The existing `extractModelEntries` parser already accepts arbitrary upstream JSON (data / models / items / results arrays, plus { id | name | model } per entry), so no parsing change was needed. Tests - 5 new ProviderService unit tests covering the wire shape: · OpenAI format → Bearer header, GET /v1/models, no x-api-key · Anthropic format → x-api-key + anthropic-version, no Authorization · URL hygiene — strips trailing slashes, doesn't duplicate /v1 · Non-2xx upstream → ApiError 502 with `HTTP {status}: {message}` · Network error → ApiError 502 with "Upstream fetch failed: ..." Verification - `bun test src/server/__tests__/providers.test.ts -t "fetchUpstreamModels"` → 5/5 pass. - `bun run lint` (desktop): tsc --noEmit clean (after `bun install` to pick up the @codemirror packages added by an earlier PR — orthogonal to this change). - All existing provider tests unchanged (no regression in test file). Tested: server unit (5 cases covering wire shape, URL hygiene, error paths); existing testProviderConfig tests still pass; desktop tsc clean. Not-tested: live smoke against an actual self-hosted relay (no provider fixture configured locally). The bug repro is well-understood: the secure-context webview's mixed-content block is documented browser behaviour and the fix removes the renderer-side fetch entirely. Confidence: high Scope-risk: narrow * test(providers): add desktop-side fetchModels client test (clears change-policy block) Locks the renderer→server contract: providersApi.fetchModels must POST to the local server with baseUrl/apiKey/apiFormat in the body, NOT fetch the upstream URL directly. The same-origin assertion guards against any future regression that reintroduces the mixed-content / CORS bug class. Two cases: - success path: upstream JSON forwarded verbatim, body shape locked - error path: 502 from server surfaces upstream message in thrown error --------- Co-authored-by: 你的姓名 <you@example.com> |
||
|
|
8a0eef4ad4 |
fix(desktop): clarify MCP configuration title
Replace the editable MCP server heading with neutral configuration copy so the settings page does not imply an update action is running. Fixes #763 Tested: cd desktop && bun run test -- src/__tests__/mcpSettings.test.tsx Tested: cd desktop && bun run lint Not-tested: full verify and coverage, scoped desktop copy/test change only Confidence: high Scope-risk: narrow |
||
|
|
9238481e86 |
fix(desktop): trust loopback web dev access
Allow local browser origins such as 127.0.0.1, localhost, and ::1 to use the desktop server without H5 token flow, while keeping LAN and public origins behind H5 access rules. Also make Vite SPA healthcheck fallback to the default loopback backend and document scoped verification expectations. Tested: bun test src/server/__tests__/h5-access-policy.test.ts Tested: bun test src/server/__tests__/h5-access-auth.test.ts Tested: bun test src/server/middleware/cors.test.ts Tested: cd desktop && bun run test -- src/lib/desktopRuntime.test.ts --run Tested: git diff --check Not-tested: bun run verify and coverage were intentionally skipped for this scoped local-dev fix. Scope-risk: moderate |
||
|
|
3d02e3a91a |
fix(proxy): establish OpenAI prompt cache semantics (#789)
Strip the rotating billing attribution line before converting system prompts to OpenAI Chat/Responses requests, forward a stable prompt_cache_key derived from the client session, request stream usage explicitly on Chat streams, and map cached_tokens back to Anthropic cache_read_input_tokens with exclusive input accounting. |
||
|
|
d7b8fb032c |
fix(desktop): preview exit plan approvals (#793)
Show ExitPlanMode approvals as a rendered plan preview in desktop chat, forward plan feedback and requested prompt permissions through the desktop WebSocket permission response, and keep permission-mode restoration owned by the CLI runtime. Tested: bun run verify Confidence: high Scope-risk: moderate |
||
|
|
2f243fe920 |
fix(desktop): stabilize Windows settings toggles (#788, #791)
Prevent Settings General checkbox focus/reflow from using off-row sr-only inputs, close stale native preview views when leaving session pages, and avoid Windows notification enable-time smoke side effects. Tested: cd desktop && bun run test -- src/__tests__/generalSettings.test.tsx --reporter verbose Tested: cd desktop && bun run test -- src/components/layout/ContentRouter.test.tsx --reporter verbose Tested: cd desktop && bun run test -- src/lib/desktopNotifications.test.ts --reporter verbose Tested: cd desktop && bun run lint Tested: bun run check:desktop Confidence: medium Scope-risk: narrow |
||
|
|
52aa3c5c02 |
feat(desktop): add Auto-dream setting (#800)
Expose the existing CLI Auto-dream switch in General settings with an explicit opt-in confirmation before enabling background memory consolidation. Tested: bun run check:desktop Tested: ./bin/claude-haha --help Tested: CLAUDE_CONFIG_DIR temp settings true/false autoDreamEnabled check Tested: real provider Auto-dream trigger against temporary memory copy Scope-risk: narrow Confidence: high |
||
|
|
00b4ead0ca |
fix(trace): show tool call durations (#799)
Compute tool spans from paired tool results, surface session wall/model/tool timing, and keep pending spans updated with elapsed time. Tested: cd desktop && bun run test -- --run src/lib/traceViewModel.test.ts src/pages/TraceSession.test.tsx Tested: cd desktop && bun run test -- --run src/pages/TraceList.test.tsx Tested: bun run check:desktop Scope-risk: narrow |
||
|
|
58d5221ca1 |
feat(activity): add plugin and skill usage insights
Add historical tool and skill aggregation to activity stats, compact the token summary, and show Codex-style activity insights with plugin/skill ranking. Tested: bun test src/utils/__tests__/stats.test.ts Tested: bun run check:persistence-upgrade Tested: bun run check:desktop Not-tested: bun run check:server (previous full run exposed unrelated conversations WebSocket timeouts; focused stats and persistence checks passed) Confidence: medium Scope-risk: moderate |
||
|
|
c97bd55a57 |
fix(desktop): restore native window dragging (#770 #796)
Remove the Windows renderer-side drag delta fallback and keep frameless window movement on Electron app-region handling. Reject drag movement payloads on the legacy IPC channel so window drags cannot mutate bounds through repeated setPosition calls. Tested: cd desktop && bun run test --run src/hooks/useElectronWindowDragRegions.test.tsx electron/ipc/capabilities.test.ts src/lib/desktopHost/electronHost.test.ts Tested: bun run check:desktop Tested: bun run check:native Confidence: high Scope-risk: narrow |
||
|
|
978dfb2efb |
fix(desktop): repair Windows updater and installer flow (#801)
Prevent stale same-version update metadata from surfacing another install prompt, avoid showing a fake desktop version fallback, and configure the Windows NSIS installer to expose install directory selection. Fixes #801 Tested: bun run verify Confidence: high Scope-risk: moderate |
||
|
|
be4984009c |
fix(desktop): hide Windows subprocess consoles (#802)
Ensure Electron sidecar launch and Windows taskkill calls hide console windows, and pass the same hidden-window spawn option through desktop CLI and scheduled-task subprocess launches. Tested: cd desktop && bun test ./electron/services/sidecarManager.test.ts Tested: bun test src/server/__tests__/conversation-service.test.ts src/server/__tests__/cron-scheduler-launcher.test.ts Tested: bun run check:native Tested: bun run check:server Not-tested: Windows GUI quit smoke Confidence: medium Scope-risk: narrow |
||
|
|
dd72901ba3 |
fix(desktop): render generated Mermaid labels in previews (#803)
Normalize generated flowchart labels before Mermaid rendering so Markdown previews handle labels with HTML breaks, braces, and bracketed type text. Tested: bun run check:desktop Scope-risk: narrow |
||
|
|
ae32599ba8 |
fix(trace): stabilize live trace updates
Keep live trace polling sensitive to in-place call changes, scope detail section collapse state by trace session, and expose trace rows with list/button semantics. Tested: cd desktop && bun run test -- TraceList.test.tsx TraceSession.test.tsx Tested: cd desktop && bun run lint Tested: bun test src/server/__tests__/trace-capture.test.ts Confidence: medium Scope-risk: narrow |
||
|
|
8179a99967 |
fix: allow mapped-drive workspaces in bypass mode
Mapped Windows drives can resolve to UNC paths before the CLI starts. Treat the UNC prefix as safe only after the target has already been proven to be inside the allowed working directory, while keeping sensitive paths and out-of-workspace UNC writes behind safety checks. Tested: bun test src\\utils\\permissions\\filesystem.test.ts Tested: real local app server/WebSocket session with deepseek-v4-pro and --dangerously-skip-permissions wrote through X:\\project without a permission_request. Not-tested: full check:server is still red on this Windows checkout due pre-existing unrelated failures in shell env, H5/local-file, MCP, FileRead CJK, and a darwin-only expectation. Confidence: high Scope-risk: narrow |
||
|
|
8ac3ea395a
|
feat(solo): wire LSP error count into Tier-1 signals (Phase 5) (#27)
* feat(solo): wire LSP error count into Tier-1 signals + cleanup suggestion
Phase 5 of editor-lsp-foundation (tasks 41-45):
- src/server/services/soloSuggestions.ts: SoloSignalsTier1 gains
lspErrorCount field + new ruleLspError. Rule fires on positive
integer counts only (defensive against undefined / 0 / non-integer
/ negative). Score 80 — high enough to outrank other 'cleanup'
candidates (todo-marker / sync-upstream / stash) via the existing
per-category dedup pass, and to outrank test-gap / ship / finish-wip /
release base scores so the user is told to clear type errors first
whenever the LSP reports any.
- src/server/services/soloSignalsService.ts: gatherSoloSignalsTier1 now
accepts an optional `getLspErrorCount` provider. Wrapped in
Promise.allSettled so an LSP failure / missing prereq silently
leaves lspErrorCount undefined — the rule then sits the round out
rather than nagging users about a setup problem they didn't ask
about. Existing callers don't pass the option, so no behavioral
drift on the current call sites; the manager will inject a real
provider when the LspManager singleton from Phase 3 is wired into
the Solo welcome-card pipeline.
- desktop/src/i18n/locales/{en,zh,zh-TW,jp,kr}.ts: 3 keys ×
5 locales = 15 entries for solo.suggest.lspError.{title,detail,
taskPrompt}. The other LSP-related i18n keys mentioned in the
spec (lsp.indicator.*, editor.unsupportedEncoding, editor.conflict.*,
editor.unsavedClose.*) are deferred to the component-integration PR
that swaps Phase 2/3's hardcoded English for translated labels —
shipping keys without callers would create dead code that drifts
out of sync before integration lands.
- src/server/services/soloSuggestions.test.ts: 6 new tests for
ruleLspError covering undefined / 0 / non-integer / negative gates,
positive-count emission, per-category dedup outranks
todo / sync-upstream when LSP errors exist.
- src/server/services/soloSuggestions.i18n.test.ts: fixtureWithEverySignal
now includes lspErrorCount, so the existing en.ts contract scan
automatically validates the 3 new keys.
Tested:
- bun test src/server/services/soloSuggestions.test.ts (44/44, +6 new)
- bun test src/server/services/soloSignalsService.test.ts
- bun test src/server/services/soloSuggestions.i18n.test.ts
- 61/61 across 3 Solo-related test files
- bun run lint (desktop tsc --noEmit clean — 5 locales × TranslationKey
mapped Record gates the additions)
Note: pre-existing e2e/business-flow failures (~44) on origin/main
remain untouched.
_Requirements: 14.1, 14.2, 14.3, 14.4, 14.5, 15.6_
* test(desktop): add i18n contract test for solo.suggest.lspError
Phase 5 follow-up: change-policy CI gate refused PR #27 because the
desktop locale changes shipped without a matching desktop test —
production code in `desktop/src/i18n/locales/*.ts` requires a
desktop-side test. The server-side i18n contract test
(soloSuggestions.i18n.test.ts) only validates en.ts, leaving the
4 other locales unchecked at the desktop boundary.
This test mirrors that contract on the desktop side: 5 locales × 3
keys = 15 presence checks, plus interpolation checks for {count} and
absence-of-params check for the static detail key. 18/18 passing.
The test imports each locale as a named export (the file's `export
const zh: Record<TranslationKey, string>` is repeated across all
five locale files, so `zh-TW.ts` needs `import { zh as zhTW }` to
disambiguate at the call site).
Tested:
- bun run test src/i18n/lspError.test.ts (18/18 pass)
---------
Co-authored-by: 你的姓名 <you@example.com>
|
||
|
|
96f578e5d3
|
feat: LSP manager + status indicator foundation (Phase 3) (#26)
* feat(server): LSP foundation infra — feature flag, JSON-RPC framer, process limits
Phase 3 base layer (tasks 18-20 of editor-lsp-foundation):
- src/server/services/lspFeatureFlag.ts: local opt-in switch.
spec called for `feature('LSP_FOUNDATION')` from `bun:bundle`, but
that table is build-time vendored from upstream Anthropic CLI and
fork code can't register new flag names there. So Phase 3 ships its
own check: dev (NODE_ENV !== 'production') is on by default; prod
is opt-in via `CLAUDE_CODE_LSP=1` env var. Pure function so unit
tests can stub `process.env` directly. 5/5 tests pass.
- src/server/services/lspJsonRpc.ts: minimal Content-Length-framed
JSON-RPC. encodeLspFrame(payload) emits the wire bytes;
LspFrameDecoder accepts arbitrary stream chunks (LSP servers split
frames mid-header / mid-body / multiple-per-chunk) and yields
complete frames per push(). Throws LspFrameDecodeError on missing
or non-numeric Content-Length. ~110 lines, no vscode-jsonrpc
dependency. 10/10 tests pass.
- src/server/services/lspProcessLimits.ts: poll-fallback strategy
(5 s sample interval, terminate after 2 consecutive overages).
spec also lists posix-rlimit and windows-job-object — those need
native bindings or N-API plugins we don't carry yet, so this PR
ships poll-fallback only and exposes a stable LspProcessLimits
interface so a future PR can plug in native strategies without
touching call sites. Sampler is abstract (manager passes a real
ps/Get-Process wrapper in production; tests pass a synthetic
array). 5/5 tests pass.
Tested:
- bun test src/server/services/lspFeatureFlag.test.ts (5/5)
- bun test src/server/services/lspJsonRpc.test.ts (10/10)
- bun test src/server/services/lspProcessLimits.test.ts (5/5)
_Requirements: 7.2, 7.4, 15.3 (adapted)_
* feat(server,desktop): LspManager + LspStatusIndicator (Phase 3 wave 2)
Phase 3 main pieces (tasks 21-27 of editor-lsp-foundation):
Server:
- src/server/services/lspManager.ts: LspManager service. Per-workspace
lazy spawn via injected LspClientFactory; sha-clean state machine
(starting -> ready -> unavailable with 5 reasons). mapLspSeverity
maps LSP wire severity 1-4 -> error/warning/info/hint, anything
else -> error. makeDiagnosticComparator orders by severity ->
in-edited-file -> path -> line -> column. truncateDiagnostics
caps at top-20 entries / 5 distinct files. Idle eviction
(default 600 s) + restart cap (2 attempts in 60 s rolling window
-> restart-cap-exhausted). probeHostCommand from prerequisitesService
is reused.
- src/server/services/lspManager.test.ts: 18 tests covering severity
map / comparator / truncation / spawnIfNeeded gate / prereq-missing /
init-failed / ready+diagnostics flow / shutdownWorkspace /
onStateChange listeners / getPrerequisites delegation / sorted+
truncated diagnostics on real flow.
- src/server/events/lspStateChanged.ts: type-only WS event shape
for `lsp.state.changed` so producers and consumers stay aligned.
- src/server/api/sessions.ts: GET /api/sessions/:id/lsp/state. Gated
by isLspFeatureEnabled() — returns 404 FEATURE_DISABLED in
production unless CLAUDE_CODE_LSP=1.
Desktop:
- desktop/src/types/lsp.ts: desktop-side mirror of LSP wire types.
Mirrored manually rather than imported across boundaries because
there's no shared types module yet.
- desktop/src/components/workspace/LspStatusIndicator.tsx: status
pill + dropdown. CheckCircle / AlertCircle / Loader2 / AlertTriangle
via lucide-react (already a dep). Labels: "Ready" / "N errors
detected" / "9999+ errors detected" cap / "Starting language
server…" / "Language server unavailable". Single context action:
prereq-missing -> Install... button; other unavailable -> Retry.
Dropdown lists diagnostics with messages truncated at 200 chars,
empty list shows "No diagnostics". Keyboard a11y (Tab/Enter/Space/
ArrowUp/ArrowDown/Esc) + aria-live polite mirror.
- desktop/src/components/workspace/LspStatusIndicator.test.tsx: 11
RTL tests covering all five state visuals + error count cap +
Install vs Retry action gating + dropdown empty state + message
truncation + keyboard activation + aria-live mirror.
Stability fix:
- src/server/services/lspProcessLimits.test.ts: bumped sleep from 20 ms
to 60 ms in the "swallows sampler error" test — Windows + bun
scheduler occasionally fails to fire 5 ms intervals twice within
20 ms. 5/5 stable now.
Tested:
- bun test src/server/services/lspFeatureFlag.test.ts (5/5)
- bun test src/server/services/lspJsonRpc.test.ts (10/10)
- bun test src/server/services/lspProcessLimits.test.ts (5/5)
- bun test src/server/services/lspManager.test.ts (18/18)
- bun run test src/components/workspace/LspStatusIndicator.test.tsx (11/11)
- bun run lint (tsc --noEmit clean, both desktop and server)
- bun run check:bundle-budget (delta +0.33 KB gz, 99.67 KB headroom)
- bun run build (clean, 1.27s)
Note: pre-existing e2e/business-flow failures (~44) on origin/main
baseline remain untouched by this change.
_Requirements: 6.1-6.5, 7.1-7.6, 9.1-9.5, 12.1-12.4, 13.1-13.10, 15.1, 15.3_
---------
Co-authored-by: 你的姓名 <you@example.com>
|
||
|
|
5e304ea661
|
feat(solo): wire Solo Pipeline mode end-to-end (toggle + WS + handler + prompt) (#25)
* feat(solo): wire Solo Pipeline mode end-to-end (toggle + WS + handler + prompt) Lights up the Solo Pipeline foundation that PR #16 / #17 staged. The prompt text, suggestion engine, and Tier-1 signals are already on main; this PR plugs them into the runtime so a user toggle actually flips the CLI subprocess into Solo's 5-stage workflow. What this PR adds (one PR, 4 layers, mirror of coordinator mode): 1. WS protocol — `set_pipeline_mode { flavor: 'solo' | 'normal' }` - src/server/ws/events.ts: ClientMessage variant - desktop/src/types/chat.ts: matching desktop variant 2. Server handler — `handleSetPipelineMode` - src/server/ws/handler.ts: new in-memory `soloPipelineModeSessions` Set, switch case in the message dispatcher, and a sibling of `handleSetCoordinatorMode` that defers restart until the active turn completes (same enqueueRuntimeTransition geometry). - Mutual exclusion enforced server-side: enabling Solo clears coordinator for the same session and vice versa, so the CLI subprocess never sees both `--append-system-prompt` addenda. - `RuntimeSettings.soloPipelineMode` threaded through all three getRuntimeSettings return paths. - Session cleanup deletes from both sets. 3. CLI args — `getSoloPipelineSystemPrompt()` injection - src/server/services/conversationService.ts: when `options.soloPipelineMode === true`, append the Solo prompt via `--append-system-prompt`, lazy-required from the existing `src/coordinator/soloPipelinePrompt.ts` (zero-cost when the flag is off, no module-load on default builds). - src/utils/systemPrompt.ts: parallel env-driven branch (CLAUDE_CODE_SOLO_PIPELINE_MODE) for users launching the CLI by hand, checked BEFORE coordinator's branch so Solo wins if both env vars are somehow set. 4. Desktop UI + state — toggle in the `+` menu - desktop/src/stores/sessionRuntimeStore.ts: new `soloPipelineModes` map with localStorage persistence under `cc-haha-session-solo-pipeline`, mirroring `coordinatorModes`. `setSoloPipelineMode`, `clearSelection`, `moveSelection` updated to keep the new map in lockstep with siblings. - desktop/src/stores/chatStore.ts: `setSessionSoloPipelineMode` action with mutual-exclusion logic — flipping Solo on clears the coordinator flag (locally + over the wire); the coordinator setter has the symmetric branch. Connect-time replay also now re-emits `set_pipeline_mode` on reconnect when persisted. - desktop/src/components/chat/ChatInput.tsx: parallel button to the coordinator `+`-menu entry, lucide `linear_scale` icon, primary-color check when active. - i18n: `chat.soloPipelineMode` key added in en / zh / zh-TW / jp / kr — all 5 locales required by the i18n contract. Tests added - src/server/__tests__/conversations.test.ts: getRuntimeArgs appends Solo prompt under soloPipelineMode=true, omits it when off, and emits two distinct `--append-system-prompt` slots (one per mode) if both flags are passed (defensive — the WS handler enforces exclusion, but getRuntimeArgs must still produce a deterministic shape). - desktop/src/stores/chatStore.test.ts: persist-without-live-session, push-when-live, and BOTH directions of mutual exclusion (Solo enables → coordinator clears, and vice versa) — verified to flip both the local store and the wire payload in lockstep. Verification - `bun test src/coordinator/soloPipelinePrompt.test.ts` — 11/11 (pre-existing, unchanged: confirms the prompt text contract held). - `bun test src/server/__tests__/conversations.test.ts -t "Solo"` — 3/3 new tests pass. - `bun test src/server/services/soloSuggestions.i18n.test.ts` — i18n contract still passes after adding the new key. - `bun run lint` (desktop): tsc --noEmit clean, exit 0. - `bun run test stores/chatStore.test.ts -t "Solo|coordinator"` — 4/4. - `bun run test stores/sessionRuntimeStore.test.ts` — 6/6 (pre-existing, confirms backward compatibility of the runtime store with the new soloPipelineModes field). Constraint: must coexist with the parallel coordinator-mode work (B1 #15, B2 #18, worker-continue #21, research-fork #22) already on main. Solo shares the COORDINATOR_MODE feature flag with coordinator (gating both in the same product wave) and uses the same restart geometry. Confidence: high Scope-risk: narrow Tested: server unit (getRuntimeArgs Solo branch + mutual-exclusion arg shape); desktop store unit (Solo persistence + bi-directional exclusion); i18n contract; full desktop tsc. Not-tested: live agent-browser smoke (no provider model wired in this PR); next session resume of a Solo session (in-memory only per v1, same as coordinator mode). * feat(solo): always-visible status chip in chat header for Solo / coordinator mode Closes the steering contract that says "must be explicit about current mode" — until now, the toggle in ChatInput's `+` menu was the only surface that showed mode state, and that menu is closed by default. A user who enabled Solo and then minimized the menu had no way to tell from the chat view whether they were still in Solo mode. This adds a persistent chip in the chat header session-meta strip (next to the existing `↗ Continued` hand-off chip), one chip per active mode. The chips: - Render only when the corresponding mode is on for the active session (mutually exclusive at the action layer, but the rendering is defensive — both could theoretically appear and that is harmless). - Use lucide material symbols `hub` (orchestration) and `linear_scale` (Solo) at 12px to match the chip-strip type scale. - Carry tooltips explaining what the mode does and where to toggle it. - Use the same primary-color treatment as the hand-off chip so the whole strip reads as one band of "session-level facts about this conversation". - Have `data-testid` selectors (`session-coordinator-chip`, `session-solo-chip`) for downstream test access. i18n: 4 new keys × 5 locales (en/zh/zh-TW/jp/kr). Verification: `bun run lint` clean (tsc --noEmit), no new diagnostics. The runtime store reads were already wired in the previous commit on this branch (sessionRuntimeStore.soloPipelineModes), so the chip is a pure rendering layer with no behavior change. Tested: tsc clean; existing handoff-chip pattern reused (proven locally rendered already). Not-tested: per-locale visual snapshot (no snapshot suite for this header). Manual smoke recommended in the merged build. Confidence: high Scope-risk: narrow * revert(solo): drop systemPrompt env-driven branch to clear CLI-core change-policy block Removes the CLAUDE_CODE_SOLO_PIPELINE_MODE branch from src/utils/systemPrompt.ts (CLI core file). The desktop Solo wireup does NOT depend on this branch — it injects the Solo prompt via --append-system-prompt through conversationService.getRuntimeArgs. The reverted branch was a defensive addition for users who launch the CLI manually with the env var set; that path can be re-added in a follow-up PR with the allow-cli-core-change label and a co-located test file. Manual CLI users wanting Solo can pass --append-system-prompt themselves until the follow-up lands. Desktop toggle path remains fully functional. Confidence: high Scope-risk: narrow (single file, single block) --------- Co-authored-by: 你的姓名 <you@example.com> |
||
|
|
3fb246ca6a
|
feat: CodeMirror editor + atomic save + conflict banner foundation (Phase 2) (#24)
* feat(desktop): add CodeMirror deps + bundle budget + encoding utils
Phase 2 foundation pieces (tasks 6-7 of editor-lsp-foundation):
- Add 9 @codemirror/* dependencies (state, view, commands, search, language,
autocomplete, lang-{javascript,json,markdown}). Tree-shaking keeps the
current bundle delta at +0.00 KB until WorkspaceEditor.tsx imports them
in task 8.
- Add scripts/check-bundle-budget.ts + bun script "check:bundle-budget".
Asserts dist/assets/*.js gzipped total <= baseline + 100 KB. Baseline
captured at origin/main @ 95931d49 (post-R5, pre-CodeMirror) = 3299.76 KB.
- Add encodingDetect.ts: detectEncoding(bytes) -> 'utf-8' | 'utf-8-bom' |
'unsupported' (uses TextDecoder fatal:true to map invalid UTF-8 to
unsupported); detectLineEnding(text) -> 'LF' | 'CRLF' | 'CR' (dominant
style with LF as fallback for empty/single-line buffers).
Tested:
- bun run test src/components/workspace/encodingDetect.test.ts -- --run (18/18 pass)
- bun run scripts/check-bundle-budget.ts (OK, +0.00 KB delta)
_Requirements: 1.3, 1.6, 1.7, 1.8_
* feat(server,desktop): workspace file save endpoint + buffer/conflict store
Phase 2 backend pieces (tasks 9-12 of editor-lsp-foundation):
Server:
- src/server/events/workspaceFileSaved.ts: shared emitter
emitWorkspaceFileSaved() so both write paths (user now, agent in PR-4)
funnel through one well-typed WS message shape.
- src/server/services/workspaceFileService.ts: WriteWorkspaceFileSchema
(Zod), atomic write (temp file + fsync + rename, Windows EBUSY/EPERM
retry 3x50ms), realpath-based symlink containment, BOM/CRLF/CR
round-trip, sha256 stale-base check (409 on hash mismatch), structured
400/404/409/500 error bodies, post-write workspace.file.saved emit.
- src/server/api/sessions.ts: POST /api/sessions/:id/workspace/file
routes through new handleSessionWorkspacePost; GET path unchanged.
- src/server/services/workspaceFileService.test.ts: 17 tests covering
200 / 400 (bad request, path-escape, parent-missing, absolute-path) /
404 session-missing / 409 stale-base / BOM round-trip / CRLF round-trip /
CR round-trip / temp-file-not-leaked / 10 MiB content cap. Includes
symlink-escape coverage on POSIX (skipped on Windows where symlink
creation needs elevation).
Desktop store:
- desktop/src/stores/workspacePanelStore.ts: bufferStateByTabId record,
WorkspaceBufferState/Conflict types, initBuffer / setBufferState /
applyExternalSave / acknowledgeConflict / clearBuffer actions.
applyExternalSave is the WS-driven entry point — clean buffers rebase
silently when content is supplied; dirty buffers raise a conflict
banner. acknowledgeConflict('reload') resets to base, 'keepMine' /
'openConflict' just dismiss the banner. closePreviewTabs and
clearSession now drop matching buffer state to prevent leaks.
Tested:
- bun test src/server/services/workspaceFileService.test.ts (17/17 pass)
- bun run lint (server tsc clean)
- bun run test src/stores/workspacePanelStore.test.ts (24/24 pass — store
extension is purely additive, R5 tests still green)
Note: pre-existing e2e/business-flow failures in src/server/__tests__/e2e
remain untouched by this change (44 fails on baseline, no new fails
introduced).
_Requirements: 1.5, 2.1-2.9, 3.1-3.3_
* feat(desktop): WorkspaceEditor + ConflictBanner + UnsavedChangesModal
Phase 2 UI pieces (tasks 8, 13, 14, 15 of editor-lsp-foundation):
- desktop/src/components/workspace/WorkspaceEditor.tsx: CodeMirror 6
editor wrapping the workspace panel buffer state. Hooks
EditorView.updateListener -> setBufferState for live dirty tracking,
picks language by extension (ts/tsx/js/jsx/json/md), wires Save to
sessionsApi.saveWorkspaceFile (R2 atomic write endpoint), refreshes
base hash on success, falls back to a read-only message when
detectEncoding returns 'unsupported'. External rebases (e.g. clean
buffer applyExternalSave) are pushed back into the EditorView via
dispatch.
- desktop/src/components/workspace/ConflictBanner.tsx: clean buffer ->
single Reload button; dirty buffer -> three buttons (Reload (discard),
Keep mine, Open conflict view). Renders workspace-relative path,
hash first 8 hex, relative timestamp refreshing every 60 s.
- desktop/src/components/workspace/UnsavedChangesModal.tsx: Discard /
Save / Cancel modal. Cancel is the default focus, Esc triggers it.
While saving, all three buttons disable and the host calls onSave
which only resolves close on success. 30 s in-prompt timeout fires
onTimeout (host owns the toast).
- desktop/src/components/workspace/WorkspaceEditor.test.tsx: 8 RTL
tests covering buffer init / encoding detection / unsupported
fallback / dirty marker / unsaved-changes modal flows / conflict
banner clean-vs-dirty layouts.
- desktop/src/api/sessions.ts: SaveWorkspaceFileInput +
SaveWorkspaceFileResult types and sessionsApi.saveWorkspaceFile
POST helper.
Bundle delta: +0.28 KB gz (CodeMirror 6 + 3 lang packs imported but
WorkspaceEditor is not yet wired into WorkspacePanel — that integration
ships in a follow-up PR alongside Phase 3 LSP work, keeping this PR
focused on the foundation).
Tested:
- bun run lint (tsc --noEmit clean)
- bun run test (workspacePanelStore 24/24, encodingDetect 18/18,
WorkspaceEditor 8/8, WorkspacePanel 27/27 — 77/77 across 4 files)
- bun run check:bundle-budget (delta +0.28 KB gz, 99.72 KB headroom)
- bun run build (clean, 1.20s)
_Requirements: 1.1-1.8, 3.2-3.5, 4.1-4.6_
---------
Co-authored-by: 你的姓名 <you@example.com>
|
||
|
|
95931d498d
|
feat(desktop): default workspace panel to 'all' view (#23)
R5 changes the workspace panel's default activeView from 'changed' to
'all' and removes the loadStatus auto-switching logic. Users now see
the all-files tree on first open, regardless of whether the session
has changed files. Explicit setActiveView still wins and survives
subsequent loadStatus calls via hasUserSelectedView.
The downstream WorkspacePanel component tests that asserted the old
"auto-switch to changed view" behavior are updated:
- 4 tests now explicitly setActiveView('changed') when they need to
exercise the changed-files list.
- 2 tests are rewritten/renamed (R5 prefix) to assert the new
"default to all, never auto-flip" contract instead of the old
switch-back behavior.
Tested:
- bun run lint (tsc --noEmit clean)
- bun run test workspacePanelStore.test.ts (24/24 passed)
- bun run test WorkspacePanel.test.tsx (27/27 passed)
- bun run build (clean, 1.21s, no bundle impact)
Note: 3 pre-existing failures in electron/services/{sidecarManager,terminal}.test.ts
exist on origin/main baseline and are unrelated to this change.
Co-authored-by: 你的姓名 <you@example.com>
|
||
|
|
e6332810ed
|
feat(coordinator): research-fork opt-in — let coordinator mode use a single fork path for cache-sharing fan-out (#22)
Resolves the only path that could plausibly cut coordinator-mode token
cost without changing architecture. Coordinator mode normally rejects
implicit forks (the orchestrator is supposed to delegate to typed
workers); this opt-in carves out a narrow window for cache-sharing
research fan-out only.
Why
===
Coordinator-mode parallel research dispatches several workers of the
same type. Each worker prefills its own system prompt + full tool
schema, easily 10-30k tokens × N workers. Fork's byte-identical API
prefix bypasses that entirely — the parent's prompt cache is fully
reused, marginal cost is just the directive bytes. On a 3-worker
research fan-out we expect ~10x prefill savings for the research
phase.
Out of scope: implementation/verification spawns still go through
typed workers (independent context, independent cache). This PR is
about research only.
What's in this PR
=================
- forkSubagent.ts
- New helper: isCoordinatorResearchForkEnabled() — gated on
feature('FORK_SUBAGENT') + isCoordinatorMode() + non-interactive
+ CLAUDE_CODE_COORDINATOR_RESEARCH_FORK=1.
- New constant: COORDINATOR_RESEARCH_FORK_SUBAGENT_TYPE = 'fork'
(single source of truth for what callers spell as subagent_type).
- New ForkMode union: 'normal' | 'coordinator-research'.
- buildForkedMessages / buildChildMessage now take an optional mode
parameter (default 'normal'). 'coordinator-research' adds rule 11
to the boilerplate: "RESEARCH FORK: do not modify files; report
findings instead". The first 10 rules are byte-identical to the
normal mode (cache-friendly), and the framing tag at the top is
unchanged so isInForkChild's recursive-fork guard fires for both
modes.
- AgentTool.tsx
- Adds a coord-research-fork branch in the agent-resolution code:
`subagent_type === 'fork'` + isCoordinatorResearchForkEnabled() →
routes through the same fork path as an omitted subagent_type.
- The omitted-subagent_type path in coordinator mode is unchanged
(still requires explicit type, with the existing helpful error).
- Computed forkMode threads through to buildForkedMessages.
- invocationLimiter.ts
- 'fork' default cap = 10 (between verification's 5 and the 8
fallback). Generous for legitimate parallel research, tight enough
that pathological loops show up before the budget runs out.
- forkSubagent.test.ts (new, 11 cases)
- Env-flag gating across all combinations.
- Boilerplate rule-11 injection in research mode + byte-identical
first 10 rules across modes (cache contract).
- Recursive-fork guard fires for both mode variants.
- Subagent type constant matches the literal "fork".
- invocationLimiter.test.ts
- One new case: default cap for 'fork' is 10.
- scripts/dev-coordinator-e2e.ps1
- Adds 8th e2e step: type constant, boilerplate variants, recursion
guard cross-mode, env-flag gate.
Why opt-in (and double-gated)
=============================
- Lazy-delegation lint and specialist redirect are blacklists: specific
anti-patterns, near-zero false positives, safe to default on.
- Coordinator research fork is a positive-space affordance: "the
coordinator MAY use a fork for research." Defaulting it on would
encourage forks for spawns that legitimately want a clean context
(e.g. adversarial verification), which conflicts with coordinator's
independent-worker philosophy.
- Two gates needed: feature('FORK_SUBAGENT') is the bundle-time
feature flag (we share its plumbing), CLAUDE_CODE_COORDINATOR_RESEARCH_FORK=1
is the user-level opt-in. Both must be on.
Risks considered
================
- Boilerplate divergence between modes would defeat the parent prompt
cache. Mitigated: research-mode boilerplate IS the normal-mode
boilerplate plus rule 11 at the end; first 10 rules are byte-identical
(covered by a test asserting that property explicitly).
- Recursive-fork guard could miss the new boilerplate. Mitigated: the
framing tag at the top is unchanged across modes (covered by tests).
- Model abuses 'fork' for non-research spawns. Mitigated: rule 11 in
the boilerplate forbids file modifications + invocationLimiter cap
10 contains pathological loops + opt-in flag means nothing changes
for users who don't turn it on.
Verification
============
- src/tools/AgentTool/forkSubagent.test.ts ............. 11/11 pass
- src/tools/AgentTool/invocationLimiter.test.ts ........ 14/14 pass
- All B1+B2+B3+B4 unit tests .......................... 144/144 pass
- scripts/dev-coordinator-e2e.ps1 ..................... GREEN (8 steps)
- get_diagnostics on changed files .................... clean
Tested: bun test src/tools/AgentTool/forkSubagent.test.ts (11/11); all coordinator unit tests (144/144); scripts/dev-coordinator-e2e.ps1 step 8 GREEN
Not-tested: live coordinator session with the flag on producing actual cache savings (telemetry-only follow-up; the flag is gated and the boilerplate contract is enforced by test)
Confidence: high
Scope-risk: narrow
Constraint: must NOT change buildChildMessage's first 10 rules (cache identity); must NOT change the boilerplate framing tag (recursion guard); must NOT widen the gate to non-coordinator paths (fork stays mutex with normal coordinator delegation by default)
Rejected: defaulting the gate on (positive-space affordance, false-positive cost too high); adding `fork_research` as a new AgentTool input parameter (schema change rejected on B2 by the same logic — too much blast radius); changing fork's tool pool to forbid Edit/Write in research mode (would break useExactTools cache identity; soft-constrained by rule 11 instead)
Directive: when telemetry shows enough adoption to validate the cache savings, consider exposing a /coord-fork slash command alongside the env flag for easier experimentation; do NOT promote to default-on without that data
Co-authored-by: 你的姓名 <you@example.com>
|
||
|
|
dbeb7750a1
|
feat(coordinator): worker-continue advisor — recommend SendMessage when a recent worker already loaded the same files (#21)
The roadmap calls for "worker-continue defaulting": coordinator mode
should prefer SendMessage to reuse a previous worker's prompt cache
instead of spawning a fresh one when it would re-load the same files.
This ships the spawn-time advisor that surfaces the recommendation.
What's in this PR
=================
- src/tools/AgentTool/workerContinueAdvisor.ts (new)
Pure heuristic. Inputs: candidate-prompt + list of recently-completed
panel agent tasks (with their touched files). Output: best continue
candidate (most overlap, ties broken by recency) or null. Pure
ranking — caller materialises the candidate list, this module is
policy-only.
- extractFilePathsFromPrompt: path-with-extension + bare known-extension
filename matching, normalised to lowercase forward slashes for
cross-OS comparison.
- extractTouchedFilesFromActivities: pulls file_path (Read/Edit/Write/
NotebookEdit) and path (Grep/Glob — directory mention as a weaker
signal) from ProgressTracker.recentActivities. Bash command strings
deliberately skipped (false-positive risk).
- findContinueCandidate: scores by overlap size, requires same
subagent_type (SendMessage to a type-mismatched worker would have it
executing the wrong specialist's contract), filters out
non-completed tasks and tasks older than 30 minutes.
- src/tools/AgentTool/workerContinueAdvisor.test.ts (new, 27 cases)
Covers all four extraction paths, type-mismatch / non-completed /
too-old filters, tie-breaking by recency, case-insensitive overlap,
Windows-style path normalisation, env-flag gating, error message
contract (no key="value" fragments — same rule as specialistRouter).
- src/tools/AgentTool/AgentTool.tsx
Opt-in coordinator-only enforcement: when CLAUDE_CODE_COORDINATOR_CONTINUE_HINT=1
and we're in coordinator mode with an explicit subagent_type, we
collect completed panel tasks (isPanelAgentTask + status === completed
+ evictAfter !== 0), build the candidate list, and throw
formatContinueHintError if a winner is found. Same opt-in shape as
CLAUDE_CODE_GP_DEFAULT_STRICT / CLAUDE_CODE_COORDINATOR_SPECIALIST_ROUTER /
CLAUDE_CODE_COORDINATOR_TASK_SPEC_STRICT for predictable rollback.
Logged via tengu_agent_continue_hint with shared_files count and
candidate age for adoption tracking.
- scripts/dev-coordinator-e2e.ps1
Adds a 7th e2e step asserting:
- Same-type worker overlap → continuation recommended.
- Type mismatch → no recommendation.
- File-free prompt → no recommendation.
- Error message contract preserved (agentId, SendMessage, env flag).
Why opt-in (not default-on)
===========================
- Lazy-delegation lint and specialist redirect are blacklists: specific
anti-patterns, near-zero false positives, safe to default on.
- Worker-continue is a positive-space heuristic: "the model could have
done X better." Hard-failing a fresh spawn when the model legitimately
wants a clean context (e.g. adversarial verification with no prior-
approach anchoring) would be more annoying than helpful.
- Same opt-in shape as B2's task-spec strictness for predictable rollback
and gradual team adoption.
Verification
============
- src/tools/AgentTool/workerContinueAdvisor.test.ts ........ 27/27 pass
- All B1+B2+B3 unit tests ................................. 132/132 pass
- scripts/dev-coordinator-e2e.ps1 ......................... GREEN (7 steps)
- get_diagnostics on changed files ........................ clean
Tested: bun test src/tools/AgentTool/workerContinueAdvisor.test.ts (27/27); all coordinator unit tests (132/132); scripts/dev-coordinator-e2e.ps1 step 7 GREEN
Not-tested: live coordinator session with the hint flag on (covered by the e2e module-level assertion of the throw + error shape; full live-LLM gate intentionally deferred to provider-credentialed runs)
Confidence: high
Scope-risk: narrow
Constraint: must NOT change AgentTool's input schema; must reuse the formatSpecialistRedirectMessage prose style to avoid the textual-tool_use regression; must require subagent_type match (SendMessage to a wrong-type worker would execute the wrong contract)
Rejected: defaulting the hint on (false-positive cost on legitimate fresh-context spawns); using prompt-string equality instead of file-overlap (would miss continuations where wording differs but the work is the same); recording Bash command strings as touched files (false-positive risk — `git status` is not a file touch)
Directive: when ProgressTracker.recentActivities is enlarged past 5 entries, revisit candidate-collection cost (currently linear over panel tasks × constant 5 activities — fine for typical sessions, but a 100-task panel × 50-activity tracker would warrant a memoised set)
Co-authored-by: 你的姓名 <you@example.com>
|
||
|
|
3ae7eceb72
|
feat(coordinator): B2 first slice — task-spec quality assessor (positive-space complement to lazy-delegation) (#18)
The B2 roadmap calls for a structured task-spec parameter on AgentTool
({goal, success_criteria, files_in_scope, ...}). That changes the model-
facing tool schema and is its own larger PR. This first slice ships the
*validation* half as a pure heuristic so we can warn on under-specified
worker briefs without touching the tool contract — a small, reversible
step toward the structured spec.
What's in this PR
=================
- src/tools/AgentTool/taskSpecQuality.ts (new)
Pure-function assessor. Scores a worker prompt across four dimensions:
- hasConcreteAction (imperative verb: fix / add / refactor / ...)
- hasFileReference (path with extension, bare *.ts/*.json/..., or `code` span)
- hasSuccessCriteria ("should/must/return/report/verify/...")
- hasAdequateDetail (>= 80 chars)
Buckets to {well-specified, adequate, underspecified}. The bucketing is
conservative on the "underspecified" verdict — single-action one-liners
like "Run the test suite and report failures" stay in 'adequate' / better.
- src/tools/AgentTool/taskSpecQuality.test.ts (new, 18 cases)
Covers the 4 dimensions, 3 buckets, false-positive guards (ordinary prose
is not a file reference; bare filenames with known extensions are),
defensive nullish input, env-flag gating, and error-formatting contract
(no key="value" fragments — same rule as specialistRouter).
- src/tools/AgentTool/AgentTool.tsx
Opt-in coordinator-only enforcement: when CLAUDE_CODE_COORDINATOR_TASK_SPEC_STRICT=1
and we're in coordinator mode with an explicit subagent_type, an
underspecified prompt throws formatThinSpecError() with the missing
dimensions listed and a re-write hint. Skips the fork path (no
subagent_type) since fork inherits the parent's full context.
- scripts/dev-coordinator-e2e.ps1
Adds a 6th e2e step asserting full-brief / "fix it" / one-liner buckets
and the error message contract. Header comment updated to describe B1+B2.
Why opt-in (not default-on like lazy-delegation)
================================================
- Lazy-delegation is a blacklist: a *specific* anti-pattern, false-positive
rate near zero, safe to default on.
- Task-spec strictness is fuzzier: "the prompt is too thin" overlaps with
legitimate one-liners. A hard failure on a false positive is more
annoying than helpful, so it's gated behind an env flag teams turn on
when they want stricter quality.
- The same opt-in pattern as CLAUDE_CODE_GP_DEFAULT_STRICT and
CLAUDE_CODE_COORDINATOR_SPECIALIST_ROUTER for predictable rollback.
Verification
============
- src/tools/AgentTool/taskSpecQuality.test.ts ........ 18/18 pass
- All B1+B2 unit tests ............................... 105/105 pass
- scripts/dev-coordinator-e2e.ps1 .................... GREEN (6 steps)
- get_diagnostics on changed files ................... clean
Workflow note
=============
This PR was authored from a `git worktree` rooted at `.b2-wt/` (added to
`.git/info/exclude` locally), basing on the B1 PR head `8e1ca468`. Stacks
on top of #15. If #15 lands first this is fast-forward; if not it can be
rebased onto main once B1 merges.
Tested: bun test src/tools/AgentTool/taskSpecQuality.test.ts (18/18); scripts/dev-coordinator-e2e.ps1 GREEN
Not-tested: live coordinator session with the strict flag on (covered by the e2e module-level assertion of the throw + error shape)
Confidence: high
Scope-risk: narrow
Constraint: must NOT change AgentTool's input schema (the structured-spec parameter is a separate, larger PR); must reuse the formatSpecialistRedirectMessage prose style to avoid the textual-tool_use regression
Rejected: defaulting the strict check on (false-positive rate too high for the no-warning blacklist treatment); adding a structured spec parameter inline (schema change blast radius doesn't fit B2's "small, reversible" scope)
Directive: when adding the structured spec parameter (B2 second slice), wire assessTaskSpec onto BOTH the structured object (ensure all four dimensions present) AND the legacy free-text prompt (back-compat); keep the env flag for force-strict-on regardless of structured input
Co-authored-by: 你的姓名 <you@example.com>
|
||
|
|
5077d0e59d
|
feat(coordinator): B1 nudges — lazy-delegation lint, near-limit reminder, specialist redirect, stall watchdog, mode advice (#15)
* feat(coordinator): B1 nudges — lazy-delegation lint, near-limit reminder, specialist redirect, stall watchdog, mode advice Five guardrails for coordinator mode that don't need new architecture, just better signals. All gated and reversible by env flag. 1. Lazy-delegation lint (lazyDelegationCheck.ts) AgentTool prompts containing "based on the findings", "as the worker reported", "implement the recommendations", etc. are rejected with a re-write hint. The coordinator system prompt already warns against these phrases; this enforces the rule at the tool boundary so the model can't slip. Off via CLAUDE_CODE_LAZY_DELEGATION_CHECK=0. 2. Coordinator specialist redirect (AgentTool.tsx) When coordinator mode picks subagent_type='worker' for a prompt that matches a specialist keyword (code review / security audit / root cause / refactor / migrate / docs / performance / commit / test), redirect to the specialist via the existing suggestSpecialist rules. Off via CLAUDE_CODE_COORDINATOR_SPECIALIST_ROUTER=0. 3. Invocation-limiter near-limit reminder (invocationLimiter.ts) On the LAST allowed invocation of a built-in agent type, prepend a <system-reminder> to the worker's result so the coordinator reads "you're at the cap" alongside the report and can change tack before the next call is hard-blocked. Tracked via tengu_agent_invocation_near_limit. 4. Stall watchdog (agentStallDetector.ts + LocalAgentTask hook) runAgent now drives a stall detector via setInterval. When a worker doesn't yield for >=90s the panel row's progress.summary gains a "(stalled NNs) ..." prefix; cleared on next yield. UI render path unchanged — only the summary string is rewritten through the existing AgentLine consumer. 5. Mode advice heuristic (modeAdvice.ts) Pure-function classifier that reads the user's first message and recommends normal vs coordinator. Banner integration is intentionally left for a follow-up PR; only the module + tests + e2e ship here. Verification ============ - src/tools/AgentTool/ ............................. 87 / 87 pass - src/utils/modeAdvice.test.ts ..................... 21 / 21 pass - scripts/dev-coordinator-e2e.ps1 (5-step e2e smoke) GREEN Runs each module against its real exports — lazy lint accepts/rejects, router redirects, limiter near-limit fires once, stall detector transitions, mode advice routes a migration to coordinator and a typo to normal. Untouched / out of scope ======================== - No UI files changed (CoordinatorAgentStatus.tsx is a react/compiler artifact in this repo; we route the stall signal through the existing progress.summary consumer instead of touching the renderer). - No server / desktop / adapter changes. - Mode-advice banner integration into the entrypoint is deferred to B2. - Sync agent path keeps existing behavior (BackgroundHint UI). Stall detector only attaches in the async / backgrounded path where the coordinator panel is actually rendering. Tested: bun test src/tools/AgentTool/ src/utils/modeAdvice.test.ts (105/105 pass); scripts/dev-coordinator-e2e.ps1 GREEN Not-tested: bun run check:server (long-running quality gate; deferred to CI / pre-merge) Confidence: high Scope-risk: narrow Constraint: AGENTS.md specialist routing rules and existing invocationLimiter cap defaults preserved Rejected: writing a new LocalAgentTaskState.stalled field (would require touching the AgentLine renderer); using the LLM for specialist routing (latency cost; the existing rule-based suggestSpecialist already produces stable results) Directive: B2 should integrate modeAdvice into the entrypoint banner and consider deferring CoordinatorAgentStatus.tsx into a non-compiled source path before adding richer UI signals * feat(coordinator): wire mode-advice banner into first-prompt path (completes B1 #5) The modeAdvice module shipped in the prior commit with tests but no real caller. This integrates it so it actually runs. What changed ============ - handlePromptSubmit.ts: maybeNotifyModeAdvice() runs on the FIRST prompt of a fresh session (messages.length === 0). It compares the heuristic recommendation against the launched mode (isCoordinatorMode()) and, on a mismatch, shows a one-time advisory notification. Best-effort: wrapped in try/catch so it can never block a prompt. Gated on: - empty message history (fires once per session) - !skipSlashCommands (no nagging remote/bridge clients that can't relaunch) - feature('COORDINATOR_MODE') (advice is meaningless without the mode) - non-empty, non-slash input - modeAdvice.ts: fixed banner copy. The CLI has NO /coordinator slash command — coordinator mode is selected at launch via CLAUDE_CODE_COORDINATOR_MODE. The old copy told users to "Toggle with /coordinator off/on", which does not exist. New copy references the real env-var mechanism. - modeAdvice.test.ts: assert the banner names CLAUDE_CODE_COORDINATOR_MODE instead of the fake slash command. - scripts/dev-coordinator-e2e.ps1: assert the banner references the real mechanism and does NOT contain a /coordinator command string. Verification ============ - src/utils/modeAdvice.test.ts ............. 21/21 pass - scripts/dev-coordinator-e2e.ps1 .......... GREEN (87 unit + 5 e2e) - get_diagnostics on changed files ......... clean Notes ===== - No in-session toggle exists in the pure CLI, so the banner is informational ("next session, consider the other mode") rather than an action prompt. Desktop has set_coordinator_mode over WS; a future PR can make the banner actionable there. - addNotification is threaded from REPL onSubmit + executeQueuedInput, so the direct-input path reaches the banner. Tested: bun test src/utils/modeAdvice.test.ts (21/21); scripts/dev-coordinator-e2e.ps1 GREEN Not-tested: live CLI banner render (no Ink harness); covered by the module + e2e instead Confidence: high Scope-risk: narrow Rejected: inventing a /coordinator slash command to match the original banner copy (would be a larger, separate feature); showing the banner on every prompt (noisy — gated to first prompt only) Directive: when an in-session coordinator toggle lands, make this banner actionable (clickable / keybinding hint) instead of env-var informational --------- Co-authored-by: 你的姓名 <you@example.com> |
||
|
|
52d67f4239
|
fix(server): bump WebSocket echo test timeout from 5s to 12s/15s after main regression (#20)
The "Business Flow: WebSocket Chat > should echo message and transition through states" test in src/server/__tests__/e2e/business-flow.test.ts has been timing out at exactly 5000ms in CI on PRs that touch any other server surface (PR #18 reproduced it twice, including a clean rerun). Root cause ========== The test waits for a full WS turn (connected -> status:thinking -> content_start -> content_delta -> message_complete -> status:idle) against the mock SDK CLI. CI logs show: [WS] Client connected for session: ws-test-2 (T+0) [ConversationService] CLI started successfully ... (T+3.0s) test fails after 5s (T+5.0s) The mock CLI itself is fast (synchronous JSON.stringify + immediate ws.send), but spawning the child + having it dial back into the test server eats ~3s on GitHub-hosted runners. That left only 2s for the rest of the turn, which used to fit but now doesn't. The "now doesn't" is the regression: PR #16 / #17 added several new services under src/server/services/ (soloSignalsService.ts, soloSuggestions.ts, soloSuggestions.i18n.test.ts, etc.). Server startup imports/initializes the new code paths, pushing CLI bootstrap past the 5s budget. Crucially, PR #17's server-checks job was SKIPPED at merge time (the PR was missing the `allow-cli-core-change` label, so change-policy stopped the run), so the regression landed on main without ever exercising server-checks. Verification of the diagnosis: - PR #15 (B1) ran full server-checks against this same test on 2026-06-11 and passed before the soloSignals services landed. - PR #18 (B2) — same test surface, no src/server/__tests__ change — fails twice in a row at exactly 5000ms on this exact test, with no other test failing. - All 1397 other tests pass. What this PR changes ==================== Surgical: bump THIS one test only. - Internal `setTimeout(close, 5000)` -> 12000ms. Gives the WS turn ~9s of headroom after the typical 3s CLI bootstrap, well clear of the observed 5s ceiling. - Bun:test framework timeout (third arg of `it`) set to 15000ms — must exceed the internal 12s so the resolve() path wins and the assertions actually run, not the framework killing the whole test. - Comment in the test explains the headroom + why the framework timeout must be larger than the internal one. No behavior change for the passing case. What this PR does NOT do ======================== - No change to other tests, mock-sdk-cli, or any production code. - No change to coverage thresholds / baseline. - Does not address the deeper question of WHY server startup got slower. That belongs to a separate `perf(server)` follow-up — bumping this one timeout is the safe, immediate unblock so other PRs (e.g. the queued B2 #18) can land without re-fighting this regression. Verification ============ - Test contract unchanged: still asserts the same five message types, same first-status-is-thinking invariant. - Local run is blocked by an unrelated adapter dep (worktree `bun install` not done; CI has the full dependency tree). CI will exercise the change. Recommend rerunning a stuck B2-style PR after this lands to confirm the unblock. Tested: read of the test contract + mock-sdk-cli to confirm the bump preserves all five expected stream events; local server-checks blocked by missing whatsapp adapter dep in this worktree (unrelated) Not-tested: actual CI run on this branch (will run automatically on PR open) Confidence: high — surgical timeout bump on one flaky-in-CI test, no production code touched Scope-risk: narrow Constraint: do NOT widen the scope to fix the underlying server startup regression in this PR; that needs its own perf investigation and separate review Rejected: bumping ALL ws-test internal timeouts (no evidence the others are at risk; widening scope past the actual failure violates "every changed line should trace back to a failing test"); investigating + fixing the server startup regression here (different surface, different reviewers, would block the urgent unblock) Directive: file a follow-up issue for "server startup time regression after solo services" so the underlying cause gets investigated; this PR is the unblock, not the cure Co-authored-by: 你的姓名 <you@example.com> |
||
|
|
d2830f91de
|
feat(tabbar): mouse-wheel horizontal scroll on hover, scrollbar hidden (#19)
Hovering the tab strip and spinning the wheel now moves the strip
horizontally — same UX as native browser tab bars. The scrollbar itself
stays hidden so the strip looks like clean app chrome.
Three coordinated changes:
1. The scroll region's overflow flips from overflow-x-hidden to
overflow-x-auto so native scroll mechanics kick in. The visible
scrollbar is suppressed via the existing project pattern of
Tailwind arbitrary-value utilities — [scrollbar-width:none]
covers Firefox and modern Chromium, [&::-webkit-scrollbar]:hidden
covers older WebKit and the embedded Electron renderer.
2. New non-passive 'wheel' listener on the scroll region: when the
cursor is over it AND the wheel input is deltaY-dominated (i.e.
a plain vertical mouse wheel, no trackpad), translate to
horizontal scrollLeft and preventDefault so the page below the
tab bar doesn't ALSO scroll. Trackpad horizontal swipe input
(deltaX-dominated) passes through untouched so its native
momentum / direction feel survives.
3. Pre-existing test 'keeps the overflow button flush against window
controls on Windows' selected the scroll region by class name
'.overflow-x-hidden' — bumped to '.overflow-x-auto' to match the
new geometry.
Tested:
- bun run test src/components/layout/TabBar.test.tsx — 27/27 (24
existing + 3 new):
* 'exposes the scroll region with overflow-x-auto and a hidden
scrollbar' — pins the CSS contract
* 'translates a vertical wheel into a horizontal scroll on the
tab strip' — fires wheel{deltaY:120}, asserts scrollLeft=120
* 'passes horizontal wheel input through untouched (trackpad
sideways swipe)' — fires wheel{deltaX:80,deltaY:10}, asserts
scrollLeft unchanged
- bun run lint (desktop tsc --noEmit) — clean
Confidence: high. Scope-risk: narrow — single component, two-line CSS
swap + an isolated effect, no API or store changes.
Co-authored-by: 你的姓名 <you@example.com>
|
||
|
|
6b5482e3b7
|
feat(solo): tier-1 signals + pipeline prompt + i18n keys (foundation pieces 2-3) (#17)
Three more Solo Pipeline mode foundation pieces, all developed in parallel with the in-flight coordinator-mode optimization on a separate branch (zero file overlap with that AI's work area). Wiring layer follows in a single integration PR after coordinator stabilizes. 1. soloSignalsService — Tier-1 signal collector pairing with the pure buildSoloSuggestions engine from PR #16. Each signal gathers independently under Promise.allSettled so one failing probe never blocks the others, with hard timeouts and per-signal caps: - stashCount via 'git stash list' (4s timeout) - missingTestFiles via on-disk sibling-test detection on dirtyFiles only (caps fs.access fan-out at 20 paths) - todoHits via TODO/FIXME/XXX/HACK regex over dirtyFile heads (max 8 hits, max 20 files scanned, 8KB head per file) - releaseMismatch detects the three failure modes our release flow bites on: notes-missing / version-not-bumped / tag-not-pushed (the v0.5.9 push-tag lesson is encoded directly in the third) - gitInProgress via fs.access on .git/MERGE_HEAD / rebase-* / CHERRY_PICK_HEAD, with worktree gitfile-pointer support 2. soloPipelinePrompt — sibling to coordinatorMode.ts. Owns the static 5-stage system prompt (plan -> implement -> test -> review (HUMAN GATE) -> land), Stage 0 intent triage so the toggle does NOT fire on chat / hello, and entry-stage shortcuts ('review' / 'land') so suggestion-card clicks can skip directly to the relevant stage. Predicate isSoloPipelineMode reads CLAUDE_CODE_SOLO_PIPELINE_MODE, gated on the COORDINATOR_MODE bundle feature flag. 3. i18n keys for the suggestion engine — 26 new keys per locale across all 5 (en/zh/zh-TW/jp/kr). en.ts is the source of truth, the others mirror via Record<TranslationKey, string>. Tested: 66/66 pass across the four Solo modules: - soloSuggestions: 23 (engine, scoring, dedup, foreign-dirty downscore) - soloSignalsService: 30 (each signal isolated + filesystem fixtures) - soloSuggestions.i18n.test: 2 (cross-module key contract — every i18n key the engine emits MUST exist in en.ts, prevents the easy 'forgot to add the locale string' regression) - soloPipelinePrompt: 11 (predicate gating, prompt structural invariants — Stage 0 + 5 stages + HUMAN GATE + entry shortcuts + git-safety repetition in Stage 5) Desktop tsc --noEmit clean — all 5 locales satisfy the contract. Confidence: high. Scope-risk: narrow (additive, isolated; the wiring layer that consumes these is a separate later PR). Co-developed alongside another AI's coordinator B1/B2 optimization on feat/coordinator-b2-task-spec — zero file overlap by design (their branch touches AgentTool/coordinatorMode internals; this PR adds new siblings + a separate /coordinator/soloPipelinePrompt.ts file). Co-authored-by: 你的姓名 <you@example.com> |
||
|
|
be7baafc6a
|
feat(solo): pure-function suggestion engine for upcoming Solo Pipeline mode (#16)
Foundation for Solo mode's project-aware welcome — when the user toggles Solo on without a concrete task, we want to greet them with ranked guesses of what they might want to do next instead of an empty prompt. This PR lands the brain (zero-token, zero I/O, fully deterministic) so the eventual wiring layer (waiting on the in-flight coordinator-mode optimization) can drop straight on top. Engine takes the existing zero-cost project snapshot (RecentActivityResult) plus an optional Tier-1 enrichment bag (stash count, test-gap detection, TODO grep against dirtyFiles, version-vs-notes mismatch, mid-flight git state) and emits up to 5 ranked SoloSuggestions. Each carries an i18n key and an entryStage hint so the consumer can route the user past stages that don't apply (e.g. 'review' for already-shipped commits, 'land' for release prep). Design constraints baked in: - Pure function. No git spawning, no LLM, no I/O. Tier-1 signals are passed in by the host who decides which to gather. - Deterministic. (activity, tier1, now) -> stable output. Tests rely on this for stable assertions. - Bounded. Final list capped at 5; per-category dedup keeps the highest- scoring entry per category. - Locale-neutral. Returns translation keys + interpolation params, not rendered strings — desktop translates with the active locale. Score table chosen with deliberate headroom for boosters (recency 0-15, sample 0-10, file-specific 0-10) so the priority order survives any boost combination: resolve-conflict 100 > test-gap 55 > ship 35 > finish-wip 30 > release 28 > cleanup 20 > generic 0. Foreign-dirty-file detection: when most dirtyFiles look unrelated to the previous session's edited-files sample (e.g. another agent's parked work in the same worktree — exactly the situation we're in right now while the coordinator-mode AI works), the finish-wip suggestion downscores by 15 and switches to a copy that hints at foreign authorship. Coupling boundary: imports from projectActivityService only. No chat / WS / coordinator surfaces, so the upcoming Solo wiring can sit on top without circular deps. Tested: 23 / 23 unit tests covering each rule, dedup, capping, scoring, determinism, recency boost, code-source detection, foreign-dirty downscore. Confidence: high. Scope-risk: narrow (additive, isolated module, zero code paths touched outside the new files). Co-authored-by: 你的姓名 <you@example.com> |
||
|
|
4dd2ebd579
|
fix(plugins): smart 'Install all' with PATH refresh + per-manager fallthrough (#14)
User report: clicking 'Install all' on the reverse-engineering plugin's
missing-prereq modal showed cascading 'X command not found' errors even
after winget reported success — root cause was that the running terminal's
PATH never refreshed, so the next probe / install command couldn't see the
newly-installed binary. Compounded by the fact that the user's host had
neither winget nor scoop, and the deduped prereq row only carried the
first-encountered server's install map, dropping the powershell 'irm | iex'
fallback that ghidra's manifest declared.
Two coordinated fixes:
1. Server: pluginService.checkPluginPrerequisites now MERGES install maps
across all servers declaring the same command (deduped by manager+cmd).
So uvx now surfaces winget + scoop + powershell-irm together in the
modal, not just the first server's two-step list.
2. Desktop: new smartInstallScript helper builds ONE base64-encoded
PowerShell wrapper that:
- Probes each missing command BEFORE running its installer (idempotent
re-clicks, partial state)
- For each install option in declared order, first checks whether the
manager itself is on PATH; if not, skips the option silently with a
yellow 'manager not on PATH' note instead of letting the user see
'winget: command not found'
- After each install attempt, reloads PATH from machine + user
registry into the running PowerShell process — fixes the root issue
- Auto-appends winget non-interactive flags so the install doesn't
hang on license confirmation
- Walks all install options until one produces the binary on PATH
- Prints a colored summary (already-installed / installed-via-X / failed)
On Windows, the modal switches to this single-encoded-command path.
On macOS/Linux it keeps the existing per-command injection (POSIX shells
respect PATH updates from install scripts themselves, no equivalent
issue).
End-to-end exerciser: scripts/test-mcp-install.ps1 fetches a plugin's
live prereq state from the local API server, prints the smart-install
plan with manager-availability annotations, and (with -Run) executes
the wrapper for real, then re-fetches to verify post-install state.
Tested:
- bun test src/server/services/pluginService.test.ts: 5/5 (mergeInstallMap)
- bun test desktop/src/lib/smartInstallScript.test.ts: 11/11
- Live dry-run via test-mcp-install.ps1 against reverse-engineering
plugin: shows winget+scoop+powershell-irm fallback chain for uvx as
expected (merged from ghidra + lldb + jadx + apktool + frida)
- Desktop tsc --noEmit clean
Confidence: high. Scope-risk: narrow.
Tested: scripts/test-mcp-install.ps1 -Plugin reverse-engineering (dry run)
Not-tested: -Run path against a fresh VM (the install commands themselves
are unchanged data; only the wrapper logic changed).
Co-authored-by: 你的姓名 <you@example.com>
|
||
|
|
f2ede6c4df | release: v0.5.10 |