16 Commits

Author SHA1 Message Date
小橙子
1401107509
feat: harden agent routing, ship welcome surfaces, and unblock browser MCP smoke (#1)
* feat(agent-tool): rewrite contradictory review verdicts at the harness layer

The code-reviewer and security-reviewer subagents end with a parseable
verdict (`REVIEW: APPROVE` / `SECURITY: PASS`) and their prompts forbid
emitting the positive form alongside `[CRITICAL]` or `[HIGH]` findings.
That rule is enforced only in prose, so when the model slips, the
parent agent reads "APPROVE" and ships.

Add a pure post-processing pass over the subagent's final text in
`finalizeAgentTool`: detect the verdict line, look for severity tags
above it, rewrite to `CHANGES_NEEDED` when they conflict, and prepend
a one-line audit notice so the parent (and a human reading the
transcript) can see the harness intervened. Logs a
`tengu_agent_sentinel_mismatch` analytics event for fleet visibility.

Debugger's `ROOT CAUSE: FOUND` is intentionally out of scope — its
"evidence from a real command" rule isn't mechanically verifiable.

Tested: bun test src/tools/AgentTool/sentinelCheck.test.ts (11 cases)
Confidence: high
Scope-risk: narrow

* feat(agent-tool): show subagent_type in tool-use transcript line

Each `Agent` tool call previously rendered as just its description in
the transcript, which made it invisible whether the main agent picked
a specialist or fell back to the default. Diagnosing "why didn't it
use code-reviewer?" required reading analytics or guessing.

Append `→ <subagent_type>` to the rendered description when the type
is explicit. Omitted (general-purpose default or fork) keeps the old
format — absence of the marker is itself the signal.

Tested: visual smoke only — pure UI render change with no behaviour
Confidence: high
Scope-risk: narrow

* feat(agent-tool): nudge verification subagent after edits accumulate

Verification is the only built-in agent that's *required* by the
session-specific guidance for non-trivial implementations, but the
trigger condition ("3+ file edits / backend / infra change") is
evaluated by the main agent from its own work — a classic LLM
self-audit failure mode. The model can convince itself that 4 edits
"are mostly one core change with small adjustments" and skip
verification entirely.

Add a `verification_gate_reminder` attachment that fires once when
the main thread accumulates `editCount >= threshold` (default 3)
file-mutating tool uses (Edit / Write / NotebookEdit) without
invoking the verification subagent. The reminder renders as a
`<system-reminder>` block on the next turn telling the model to
spawn `subagent_type="verification"` before reporting completion,
along with a permission to skip if the change is genuinely trivial.

A verification subagent invocation resets the counter; a previously
fired reminder suppresses re-firing until the next reset, so the
nudge isn't spammed every turn.

Subagents don't see the reminder (it's main-thread only). The gate
also no-ops when the verification agent isn't loaded in the current
session (e.g. SDK build with built-ins disabled). Disabled by
`CLAUDE_CODE_VERIFICATION_GATE_OFF=1`; threshold tuned via
`CLAUDE_CODE_VERIFICATION_GATE_THRESHOLD=N`.

Tested: bun test src/utils/verificationGate.test.ts (10 cases)
Confidence: high
Scope-risk: moderate

* feat(agent-tool): tighten subagent routing and ship real coordinator mode

The flat 15-agent routing has three known weak spots that this commit
addresses together because they share AgentTool.tsx call-path edits:

1. **General-purpose default is a vacuum cleaner.** Omitting
   `subagent_type` falls back to general-purpose, which has full tool
   access and cheerfully takes on review/security/perf/migration work
   that a specialist would have done better and cheaper. Add a regex
   heuristic over the prompt: when it strongly signals a specialist
   (e.g. "code review", "security audit", "root cause", "migrate from
   X to Y") and that specialist is available, refuse the default and
   throw an error pointing the model at the right type. Disabled with
   `CLAUDE_CODE_GP_DEFAULT_STRICT=0`. Skipped in fork and coordinator
   modes (they have their own routing).

2. **No bound on verifier-style loops.** The verification prompt says
   "On FAIL: fix, resume, repeat until PASS" — if the verifier
   incorrectly keeps flagging the same change, the loop only stops
   when the token budget runs out. Add a per-session counter for each
   built-in agent type. Cap defaults are 5 for verification (loop
   target) and 8 for everything else. When exceeded, throw with a
   message asking the model to consult the user. Caps tunable per
   type via `CLAUDE_CODE_AGENT_LIMIT_<TYPE>=N`; off via
   `CLAUDE_CODE_AGENT_LIMITER_OFF=1`. Counts main-thread invocations
   only.

3. **Coordinator mode was a stub.** The `coordinator/workerAgent.ts`
   that `getBuiltInAgents()` requires when `COORDINATOR_MODE` is on
   was an auto-generated Proxy returning nothing useful. Replace with
   a real registry: a new `WORKER_AGENT` (full-tool-access generic
   delegate matching the existing coordinator prompt's
   `subagent_type: "worker"` references) plus the 11 specialists
   minus general-purpose, claude-code-guide, statusline-setup. Also
   harden the coordinator's own prompt with a "you orchestrate, you
   do not implement" rule (no direct Edit/Write/NotebookEdit) and a
   specialist roster table so the coordinator picks the right
   delegate. Improve the AgentTool error message when coordinator
   mode receives a request without `subagent_type`.

Constraint: cannot restrict the coordinator's own tool pool at the
tool layer without invasive changes to main-thread tool assembly —
enforcement is prompt-level, consistent with the rest of the
architecture.

Rejected: a tighter heuristic that requires a domain-specific phrase
(e.g. "review THIS PR") was considered for #1 but rejected — too
narrow to catch the routing problems we actually see in fleet logs.

Tested: bun test src/tools/AgentTool/specialistRouter.test.ts
        bun test src/tools/AgentTool/invocationLimiter.test.ts
        bun test src/coordinator/workerAgent.test.ts
        (29 cases total, all pass)
Confidence: medium
Scope-risk: moderate
Directive: if specialistRouter false-positives in production, prefer
  tightening the regexes over removing the gate — the failure mode
  it catches (general-purpose taking specialist work) is worse than
  the failure mode of an extra retry.

* docs(desktop): add local Chrome DevTools MCP testing guide

Document the workflow for driving the desktop UI end-to-end via
Chrome DevTools MCP without going through Electron. The pure-browser
dev path normally fails — CSP blocks non-loopback origins, the
H5-disabled CORS gate blocks cross-origin browsers, and the desktop's
loopback exemption clears the H5 token so even the loopback path
401s. The stable bypass is a Vite proxy that same-origins API
traffic to the renderer.

This commit covers the docs side only:
- `docs/desktop/10-local-mcp-testing.md`: full how-to with Quick
  Start, MCP control snippets, can/can't test matrix, the exact
  reproduction recipes for each `feat/agent-routing-hardening`
  change (sentinel, gp-strict, limiter, verification gate, routing
  observability), a Windows-specific `electron:dev` workaround, and
  a fault dictionary mapping the symptoms each blocker produces back
  to its cause.
- `docs/desktop/index.md`: link the new section in the docs index.
- `.kiro/steering/desktop-mcp-testing.md`: concise rule file with
  `inclusion: manual` so it loads via #-mention only when relevant,
  not as default-included context.

The Vite proxy itself is intentionally NOT committed here. The docs
explain it as a dev-only change the developer adds locally and
either reverts or commits to a separate `feat/desktop-browser-dev-proxy`
branch — the production renderer relies on Electron IPC for the
server URL and must not see the dev proxy in main.

Tested: docs render via VitePress local preview; steering file
loads via Kiro `#desktop-mcp-testing` mention; instructions
verified against the live setup that produced
artifacts/desktop-bootstrapped.png and artifacts/desktop-agents-page.png.
Confidence: high
Scope-risk: narrow

* feat(desktop): unblock pure-browser dev MCP smoke with proxy + forceH5

The standalone-browser dev workflow (vite + Chrome DevTools MCP)
fails three ways without these escape hatches:

1. CSP `connect-src` only allows loopback origins, so the renderer
   can't talk to the API server cross-origin even on a LAN.
2. With H5 access disabled the server returns 403 to all
   cross-origin browser requests.
3. With H5 access enabled the desktop's loopback exemption
   (`requiresH5AuthForServerUrl` returns false for `localhost:1420`)
   calls `setAuthToken(null)`, so `buildSessionWebSocketUrl` omits
   `?token=`, and the session WS handshake 401s into a 1006 close
   reconnect loop. The UI shows "处理中..." but the message never
   reaches the server — `wsManager.connections` stays `{}`, server
   stdout is silent, and no `POST /api/sessions/.../message` ever
   fires.

Two dev-only changes break that deadlock without affecting
production:

- `desktop/vite.config.ts`: add `server.proxy` for `/health`,
  `/api`, `/ws`, `/local-file`, `/preview-fs` to `127.0.0.1:3456`.
  Same-origins all backend traffic so CSP and CORS pass. Vite dev
  only — Electron production path is unaffected because Electron
  resolves the server URL via IPC at runtime.

- `desktop/src/lib/desktopRuntime.ts`: add a `?forceH5=1` query
  param check in `initializeBrowserServerUrl`. When present, treat
  the URL as needing H5 auth even if it's loopback, so the H5 token
  survives bootstrap and gets attached to the session WS URL. In
  production the param is never set, so behavior is identical.

Workflow with both in place:

  http://localhost:1420/?serverUrl=http%3A%2F%2Flocalhost%3A1420
  &forceH5=1&h5Token=<TOKEN>

Verified end-to-end via WS sniffer + server log:
- ws://localhost:1420/ws/<sid>?token=... opens
- recv {"type":"connected","sessionId":"..."}
- server logs "[WS] Client connected" + "Starting CLI for ..."
- Sending a "use Task with subagent_type=Explore" prompt produced
  a `tool_use_complete` for the Agent tool with
  `input.subagent_type="Explore"` exactly as routed.

Also rewrites `docs/desktop/10-local-mcp-testing.md` to record:
- both patches as required steps (was missing the forceH5 piece)
- exact PowerShell commands to mint a one-shot H5 token
- the WebSocket sniffer script and three-signal diagnosis recipe
  for "is the backend actually processing"
- the Item 5 (routing observability) gap: the change in
  `src/tools/AgentTool/UI.tsx` only affects CLI/Ink rendering;
  the desktop's separate `ToolCallGroup.tsx` doesn't surface
  `subagent_type` and would need its own follow-up patch.

Tested: ran `bun run src/server/index.ts` + `bun run dev` in the
desktop/, opened the documented URL via Chrome DevTools MCP,
sent a Task-with-explicit-subagent_type chat message, observed
the full WS frame sequence and server log lines listed above.
Confidence: high
Scope-risk: narrow
Directive: do not generalize the forceH5 escape hatch to a
  permanent feature — when it's needed, the dev-mode
  loopback-clears-token branch is doing the right thing for
  Electron and should not be removed.

* feat(desktop): show subagent_type badge next to Agent tool header

The CLI/Ink change in src/tools/AgentTool/UI.tsx surfaces routing
in the terminal transcript as `<description> → <subagent_type>`,
but the desktop renderer is independent (`ToolCallGroup.tsx` /
`AgentCallCard`) and was dropping that signal entirely. Diagnosing
"why didn't it use code-reviewer?" required reading analytics or
guessing.

Add a small `→ <subagent_type>` chip next to the Agent header in
AgentCallCard. The badge mirrors the CLI behavior:
- Renders only when `input.subagent_type` is a non-empty string;
  general-purpose / fork / omitted defaults stay quiet.
- Carries `title="subagent_type: <name>"` for hover detail.
- Uses the same border-pill treatment as other secondary
  transcript chips so it doesn't compete with the description.

Verified end-to-end via the local Chrome DevTools MCP path: a
real chat with `subagent_type=Explore` renders `Agent → Explore
查找specialistRouter相关文件` in the live transcript, screenshot
saved to artifacts/desktop-routing-arrow-highlighted.png.

Tested: cd desktop && bun run test -- --run -t "subagent_type"
        2 tests pass:
        - renders subagent_type as → Explore badge next to Agent header
        - omits subagent_type badge when input has no subagent_type
Confidence: high
Scope-risk: narrow

* feat(desktop): MCP tool visibility, per-tool toggle, marketplace install

Surface MCP capabilities so the agent never under-uses a configured server,
and add a one-click install path for new servers.

Tool visibility & control:
- GET /api/mcp/:name/tools returns the live tool catalog (handles disabled /
  needs-auth / host-preflight-failed / connected states)
- POST /api/mcp/:name/tools/:tool/toggle hides a single tool from the agent,
  persisted to ~/.claude.json disabledMcpTools (user scope, all projects);
  fetchToolsForClient filters on it and the cache is invalidated on toggle
- Desktop MCP detail page gains an Overview/Tools tab strip (both edit and
  read-only views) listing name, description, annotations, JSON schema, plus
  an inline enable/disable switch with a "hidden from agent" marker

Marketplace:
- Curated builtin catalog (14 servers across 8 categories) plus opt-in remote
  catalog sources cached under ~/.claude/cc-haha/mcp-marketplace.json
- Endpoints: list / refresh / add-source / remove-source
- Desktop marketplace page with category grouping, install dialog (with
  required-env prompts), and source management

Plugins:
- Plugin list rows get inline enable/disable + uninstall, matching the MCP
  settings UX, instead of requiring users to open the detail panel
- Extract shared ToggleSwitch component

Tested: bun test src/server/__tests__/mcp.test.ts (tools list + per-tool
toggle + marketplace), cd desktop && bun run lint, mcpSettings vitest, and a
browser smoke pass via the local Chrome DevTools MCP flow (tool toggle
persistence, marketplace render, plugin enable/disable + uninstall dialog).
Not-tested: full bun run verify gate
Scope-risk: moderate

* fix(agent-tool): rephrase gp-strict error to stop poisoning sessions

Live testing surfaced an unintended side effect of the gp-strict
redirect message. The original wording embedded attribute-style
fragments like `subagent_type="code-reviewer"`. When that error
came back to the model as a tool result, the model copied the
shape into a TEXTUAL `<tool_use name="Agent">{...}` block instead
of issuing a real tool call — and every subsequent Agent call in
that session degraded to text. Confirmed by inspecting the
session JSONL via /api/sessions: messages 4..N in the affected
session were `assistant: text(...)` carrying simulated tool_use
XML, not `tool_use` content blocks. Reproduced with two unrelated
models (claude-haiku-4.5 and mimo-v2.5-pro) on the same poisoned
session, and crucially DID NOT reproduce in a fresh session with
either model — so the failure is the message text inducing
text-form mimicry, not the model itself.

Fix:
- Extract the redirect text into `formatSpecialistRedirectMessage`
  in specialistRouter.ts so it has its own test surface.
- Rephrase as prose that names the parameter and value without
  any `key="value"` assignment-and-quotes form. New shape:

    "This task looks like a job for the code-reviewer specialist
     rather than the general-purpose default. Re-call Agent with
     the subagent_type parameter set to code-reviewer. ..."

- Wire AgentTool.tsx through the helper so the throw site is one
  line.

Add a regression assertion to specialistRouter.test.ts that the
formatted message contains NO `key="value"` shapes, no XML-ish
open tags, and no `"subagent_type":` JSON fragments — across all
ten specialist names. This is the property the live failure
violated; lock it.

The invocation-limiter message uses shell-style `KEY=N` syntax
(not `key="value"`), did not exhibit the same behavior in
testing, and is left untouched.

Tested: bun test src/tools/AgentTool/specialistRouter.test.ts
        17 pass (13 existing + 4 new), 61 expect() calls
Confidence: high
Scope-risk: narrow
Directive: any future change to redirect/error text returned
  to the model should preserve the no-key="value" property.

* feat(orchestration): require copying project tool rules into sub-agent prompts

Live test on the desktop `+` orchestration mode showed mimo-v2.5-pro fan
out three sub-agents in parallel for a multi-task PR review prompt — but
none of the dispatched prompts mentioned the project's mandated codegraph
MCP tool. The sub-agents fell back to plain Bash + git diff + grep, so the
project's preferred code-exploration tooling went unused.

Root cause: the orchestrator's `Propagate project conventions` rule was a
soft "for example, restate codegraph rules" bullet. The model read it as
optional. Built-in specialist system prompts (code-reviewer, security-
reviewer, debugger, etc.) explicitly enumerate Bash/grep/git as inspection
tools and never mention codegraph; CLAUDE.md is loaded but the system
prompt outweighs it. The orchestrator was the only place the gap could be
closed, and it skipped it.

This commit upgrades the rule from optional to REQUIRED in the
orchestration system prompt, names the concrete check ("scan CLAUDE.md,
AGENTS.md, .claude/rules"), and tells the orchestrator to copy matching
rules verbatim. Read-only research agents (Explore, Plan) are called out
explicitly because they run with omitClaudeMd:true and absolutely depend
on the orchestrator to forward project tool conventions.

A new ORCHESTRATION_PROPAGATE_RULES_MARKER export plus a regression test
in conversations.test.ts lock the imperative phrasing so it can't be
quietly downgraded back to a soft suggestion.

Wiring is unchanged: built-in code-reviewer/security-reviewer/commit-pr
already inherit CLAUDE.md and have MCP tools available. This is purely a
prompt-strength change, only active when the user enables the desktop
`+` orchestration toggle.

Tested: bun test src/server/__tests__/conversations.test.ts (new test
plus the two existing orchestration-prompt tests pass).
Confidence: high
Scope-risk: narrow

* fix(verification-gate): preserve reminder flag across verification reset

Caught by an orchestrator-mode code-reviewer dispatch on this branch.

When a verification subagent invocation reset the edit counter, the early
return in getVerificationGateState() hardcoded reminderAlreadyFired:false,
discarding any reminderFired flag we'd accumulated walking back from the
tail. Concretely: if a verification_gate_reminder fired AFTER the verify
(i.e. newer than verify in the transcript), the reverse walk would set
reminderFired=true on its way to the verify boundary, then throw it away
on the early return. The gate would then inject a fresh reminder every
turn while the post-verify edit count stayed above the threshold,
ballooning the prompt.

Fix: carry the accumulated reminderFired through the early return. The
reminder we saw is necessarily newer than this verify (we're walking
backwards from the tail and only got here after seeing it), so it's the
valid signal that the model was already nudged for the current edit batch.

Tests: extend verificationGate.test.ts with a "preserves a reminder fired
AFTER a verification reset (no spam loop)" case that fails on the old
hardcoded false and passes with the fix. The pre-existing "ignores a
reminder that fired BEFORE a verification reset" test still passes because
in that ordering the reminder is older than the verify, so reminderFired
stays false on the way back.

Tested: bun test src/utils/verificationGate.test.ts (11/11 pass).
Confidence: high
Scope-risk: narrow

* chat(i18n): rename `协调模式` to `编排模式` (zh / zh-TW)

Brings the simplified- and traditional-Chinese label for the desktop `+`
menu's orchestration toggle in line with the English (Orchestration mode),
Japanese (オーケストレーションモード), and Korean (오케스트레이션 모드)
labels — all five locales now use the same `orchestration` word family.
`协调` was accurate but vague; `编排` matches the term Chinese
developers already see in LangChain, CrewAI, AutoGen, and Anthropic docs,
and tells a user reading just the label what the toggle actually does
(plan → fan out → synthesize) rather than a generic `coordinate`.

UI-text only. No behavior, store, WS message, or i18n-key changes.

* feat(desktop): welcome-screen task cards with one-click orchestration

Adds four quick-start task cards to the new-session welcome screens — both
EmptySession (the no-session-yet entry) and ActiveSession's empty state
(when a fresh session tab has no messages yet). Each card pre-fills the
composer with a starter prompt for a common workflow:

  - Pre-merge code review        (auto-enables Orchestration mode)
  - Investigate a failing test   (auto-enables Orchestration mode)
  - Write unit tests             (no orchestration)
  - Explain unfamiliar code      (no orchestration)

Cards flagged `orchestrate: true` automatically turn on Orchestration
mode for the session that gets created (or for the live session in
ActiveSession's empty state), so a new user sees fan-out behavior on
first contact instead of having to discover the `+` menu first. This is
the intended discovery surface for the orchestration directive shipped on
this branch.

Plumbing:
  - WelcomeTaskCards.tsx is a shared component used by both welcome
    surfaces, so card list, copy, and styles stay in one place.
  - EmptySession owns its own composer textarea, so card click flips
    component state directly (setInput + draftOrchestrate flag) and the
    flag is applied via setSessionCoordinatorMode after createSession()
    resolves and before connectToSession() — chatStore replays the
    persisted toggle on connect, so the CLI launches with the right
    --append-system-prompt.
  - ActiveSession's session is already live, so a card click dispatches a
    `cc-haha:composer-prefill` window event that ChatInput listens for
    and applies to its composer state when the sessionId matches the
    active tab. Orchestration cards call setSessionCoordinatorMode
    directly, which sends `set_coordinator_mode` over WS and triggers a
    CLI restart with the orchestration directive — verified live: the
    server logs `[WS] Restarted CLI for <id> with runtime override`
    immediately after the click.
  - Cards never disable an existing Orchestration toggle. Non-orchestration
    cards simply leave the toggle alone, so users who pre-enabled
    Orchestration via the `+` menu don't have it silently turned off.
  - Hidden on phone-sized H5 viewports (composer is already dense there).

i18n: ten new keys under `empty.tasks.*` with localizations for en,
zh, zh-TW, jp, kr (the same five locales the orchestration label
already covers). The orchestration hint reads `将通过编排模式分派给
专家子代理处理` in zh — aligning with the
`协调模式`→`编排模式` rename shipped in the previous commit.

Tests: five new tests in EmptySession.test.tsx covering: cards render on
desktop, hidden on mobile, click pre-fills the composer, orchestration
cards persist coordinator mode after submit, non-orchestration cards
leave coordinator mode untouched. `bun run vitest` 22/22 pass.
`bun run lint` (tsc --noEmit) clean.

Tested live in browser: clicked the Pre-merge review card → composer
filled with the 78-char zh prompt → localStorage carries
`coordinator-modes[<sessionId>]: true` → server log shows the CLI
restarted with `--append-system-prompt`. Screenshot:
artifacts/desktop-welcome-task-cards.png.

Confidence: high
Scope-risk: narrow

* chore(scripts): one-click MCP smoke setup for Windows

Wraps the recurring 4-step setup from docs/desktop/10-local-mcp-testing.md
into a single idempotent script. Same workflow we'd otherwise type by hand
every time we want to drive the desktop UI from Chrome DevTools MCP.

scripts/dev-mcp-test.ps1 does:
  1. Health-check the API server on :3456 — fail fast with the start
     command if it's down.
  2. Health-check Vite on :1420 — fail fast with the start command if
     it's down.
  3. Confirm Vite's /health proxy is wired through to the server (catches
     stale vite.config.ts).
  4. Ensure http://localhost:1420 is in H5 allowedOrigins (PUT only when
     missing).
  5. Regenerate a fresh H5 token via /api/h5-access/regenerate.
  6. Build the full URL with serverUrl + forceH5=1 + h5Token, copy it to
     the clipboard, and print it.
  7. With -Open, also Start-Process the URL in the default browser.
  8. With -Quiet, only print the URL on stdout (for piping into other
     tools, e.g. un run mcp:test:open chaining).

Surfaced via two npm scripts:
  bun run mcp:test         # generate URL + clipboard
  bun run mcp:test:open    # also open in default browser

Deliberate non-goals:
  - Does NOT start server / Vite. Those are persistent dev processes the
    developer wants to control lifecycle for; auto-starting them from a
    one-shot script makes "is it still running?" questions ambiguous and
    leaves zombies on script exit. The script tells the user the exact
    command to run if either is down.
  - Does NOT touch Electron. This workflow is the documented browser path
    for Chrome DevTools MCP smoke; the Electron path doesn't need any of
    this and runs through bun run electron:dev.
  - Does NOT modify vite.config.ts proxy or desktopRuntime.ts forceH5
    bypass. Both are already on this branch, and validation of those two
    being correctly wired is what step 3 covers.

Doc: docs/desktop/10-local-mcp-testing.md grew a new "step 0 一键脚本"
section pointing at the script and naming the two npm targets, ahead of
the original 4 manual steps so future maintainers find the script first.

Verified by running it: server + vite both up, allowedOrigins pre-existed
so no PUT needed, fresh token issued, URL copied to clipboard, browser
launched into the welcome screen with the four task cards rendering
correctly. Screenshot in artifacts/desktop-welcome-task-cards-final.png.

Confidence: high
Scope-risk: narrow

* feat(desktop): zero-token "Recent activity" panel with hand-off button

Closes the painful gap where opening a new chat in a project means
re-explaining "what was I just doing" to the model. The user explicitly
called out that they don't want the obvious fix (auto-feeding the
previous transcript or an LLM-generated summary) because that burns
tokens on every new session.

This ships a different shape: derive the activity summary on the server
from on-disk state (session JSONL + git working tree), render it as a
read-only panel on the welcome screen so the user sees it, and only
move bytes into the model when the user explicitly clicks "Continue
from here" — and even then, only a 4-5 line hand-off paragraph (~60
tokens), not the previous transcript.

Server (zero LLM, all derivation):
  - GET /api/projects/recent-activity?workDir=<abs>&excludeSessionId=<id>
  - projectActivityService.getRecentActivity reads:
      - sessionService.listSessions to find the most recent meaningful
        session (skips empty messageCount=0 sessions and any
        excludeSessionId, e.g. the just-created Untitled tab in
        ActiveSession's empty welcome state, so the panel surfaces the
        ACTUAL previous work session).
      - Streams that session's JSONL and derives:
          * lastUserMessageExcerpt (160 chars max, mid-word ellipsis)
          * filesEdited list — Edit/Write/NotebookEdit tool_use file_paths,
            de-duplicated in first-appearance order, capped at 8.
        Hard-capped at 50k JSONL lines so giant transcripts don't hang
        the welcome render.
      - getRepositoryContext (existing, cached) for branch + default
        branch + dirty state, plus two cheap git rev-list/status calls
        for ahead/behind counts and exact dirty file count.
  - Strict timeouts on each git command so the panel never blocks UI.
  - Wired into router.ts under case 'projects'.

Frontend:
  - RecentActivityCard reads via projectsApi.recentActivity.
  - Two paths into it:
      1. EmptySession (sidebar "New session" → user picks workDir):
         shows once a workDir is chosen. "Open this session" switches
         to the previous tab; "Continue from here" prefills the
         hand-off into the empty composer's textarea.
      2. ActiveSession's empty welcome state (sidebar "在 X 中新建会话"
         creates a session immediately): excludeSessionId={activeTabId}
         skips the brand-new empty session, hideContinueSessionButton
         hides "Open this session" since the user is already on an
         empty tab. "Continue from here" dispatches the existing
         cc-haha:composer-prefill window event so ChatInput picks it
         up — same plumbing the welcome task cards use.
  - Auto-refreshes every 60s — git state changes between renders
    (commits in another terminal, etc.) get picked up without UI work.
  - Hidden on phone-sized H5 (composer is dense enough already).

Hand-off paragraph contents (i18n'd, ~60-100 tokens):
  Last session on <branch>: "<title>".
  Files touched: <up-to-5-files> (+N more).
  Local is ahead of upstream by N commit(s).
  N file(s) have uncommitted changes.

  Please continue from there. Pick up by ...(describe the next step).

Token cost summary:
  - Render: 0 tokens. Pure on-disk derivation, never sent to a model.
  - "Open this session": 0 tokens. Just a tab switch.
  - "Continue from here": ~60-100 tokens, ONLY if the user types more
    and presses send. The user sees the prefill in the textarea before
    sending and can edit or delete it.

i18n: 18 new keys (empty.recentActivity.*) localized for the same five
locales as the orchestration toggle (en/zh/zh-TW/jp/kr).

Live-tested via Chrome DevTools MCP on this branch:
  - Opened cc-haha welcome path.
  - Server returns correct shape: branch=feat/agent-routing-hardening,
    aheadCount=6, dirtyCount=13, lastSession with 10 messages and
    correct title.
  - excludeSessionId correctly skips the empty just-created session and
    surfaces the previous "请审查我当前分支..." session.
  - "Continue from here" click prefills the textarea with the 152-char
    Chinese hand-off paragraph; localStorage and WS state untouched
    (zero token cost confirmed).
  - Screenshots: artifacts/desktop-recent-activity-card.png and
    artifacts/desktop-recent-activity-handoff.png.

bun run lint passes (tsc --noEmit clean).

Confidence: high
Scope-risk: moderate (new endpoint, but read-only and isolated; new UI
panel, but additive only — empty workdir or no prior sessions just
hides the card)
Tested: live MCP smoke per above.
Not-tested: server-side unit tests for projectActivityService (planned
follow-up; live integration validated the happy path end-to-end).

* fix(desktop): compact recent-activity card so composer stays in view

Live MCP smoke caught a layout regression. Welcome screen vertical
budget on a 923px viewport is roughly:
  79  tab bar
  + ~250 hero block (logo + title + subtitle)
  + ~165 task cards
  + ~222 composer (ChatInput in hero variant)
  + ~64  flex padding
  ≈ 780px before activity panel

The first cut of RecentActivityCard rendered a 235px column block
(title row, chips row, italic excerpt row, file-chips row, action row).
Together with the task cards that pushed total content to ~410px
beyond what fits, and ActiveSession's empty-state wrapper used
flex flex-1 + justify-center without overflow handling — so the
sibling ChatInput got pushed below viewport bottom (composer.bottom
1112 on a 923 viewport, visible:false confirmed via DOM measurement).

Two changes:

1. Compact the card to ~127px (down 108px, roughly half) by collapsing
   to a single horizontal row: icon | title + chips column | action
   buttons. The italic last-user-message excerpt and the file-name
   chip strip both go away — they're nice-to-haves, not load-bearing.
   The data they carried is preserved: filesEditedCount stays as a
   chip with a tooltip showing the first 5 file basenames; the lead
   excerpt is still in the hand-off paragraph the "Continue from here"
   button injects, so the user gets it where it counts (in the
   composer) instead of as ambient ornament on the welcome screen.
   Action buttons collapse their labels under sm: breakpoints to keep
   the card single-row even in narrow side panels.

2. Add min-h-0 + overflow-y-auto to ActiveSession's isEmpty wrapper.
   Belt-and-suspenders: future taller content (extra cards, longer
   localized strings) now scrolls inside the welcome region instead of
   shoving the composer offscreen. Composer remains a flex sibling and
   stays anchored at the bottom regardless of content height above it.

Verified live in MCP browser:
  recentActivity height: 235 → 127px
  composer.bottom: 1112 (offscreen) → 907 (visible, on a 923 viewport)
  textareaVisible: false → true
  Tested across two projects with very different activity profiles
  (cc-haha: short title + 0 files edited; layout-editor: long title +
  20 files edited + 1876 messages). Both render in single horizontal
  row.
  Screenshot: artifacts/desktop-recent-activity-compact.png

bun run lint passes (tsc --noEmit clean).

Confidence: high
Scope-risk: narrow (CSS / layout only, no behavioral change).

---------

Co-authored-by: 你的姓名 <you@example.com>
2026-06-10 06:40:48 +08:00
程序员阿江(Relakkes)
386a41e606 feat(desktop): enable Electron migration path
Introduce the Electron desktop shell alongside the existing React renderer and local Bun server boundary. The migration keeps the DesktopHost contract explicit across Tauri, Electron, and browser runtimes while adding Electron main/preload services for dialogs, shell, notifications, updates, tray/window lifecycle, terminal, preview WebContentsView, app mode, and release/package validation.

The commit also carries the latest local main desktop command updates, including agent slash entries and hidden-by-default markdown thinking details, so the packaged Electron build matches the current main UX surface.

Constraint: React renderer, local Bun server, REST/WebSocket, and sidecar boundaries must remain reusable during the migration
Constraint: macOS dev packages are ad-hoc signed and cannot prove Developer ID notarization or Gatekeeper release launch
Rejected: Browser-only smoke validation | it cannot exercise native dialogs, keychain prompts, notification behavior, or packaged app startup
Confidence: medium
Scope-risk: broad
Directive: Do not remove Tauri host support until signed Electron release artifacts pass native OS smoke on macOS, Windows, and Linux
Tested: bun run check:desktop
Tested: cd desktop && bun run check:electron
Tested: CSC_IDENTITY_AUTO_DISCOVERY=false bun run electron📦dir
Tested: bun run test:package-smoke --platform macos --package-kind dir --artifacts-dir desktop/build-artifacts/electron
Tested: Computer Use read packaged Electron app window at desktop/build-artifacts/electron/mac-arm64/Claude Code Haha.app
Not-tested: Developer ID signed/notarized Gatekeeper launch
Not-tested: Real OS notification click-to-session action
Not-tested: Windows and Linux packaged app smoke on real hosts
2026-06-01 22:43:16 +08:00
程序员阿江(Relakkes)
83a96ef13d Keep pre-push fast by moving coverage out of the hook
Daily pushes should catch policy and path-aware local failures without making every contributor wait for full coverage. The hook now runs a new quality:push entrypoint that reuses the PR quality gate while skipping coverage; verify, quality:pr, and CI still retain the full coverage gate for PR readiness.

Constraint: Forks and local contributors need a faster default push path
Rejected: Remove coverage from quality:pr | PR readiness and CI still need the ratcheted coverage signal
Confidence: high
Scope-risk: narrow
Directive: Keep pre-push on quality:push; use verify or quality:pr when coverage evidence is required
Tested: bun test scripts/pr/quality-contract.test.ts scripts/git-hooks/install.test.ts
Tested: bun run check:policy
Tested: bun run quality:push
Not-tested: Live provider smoke; intentionally remains opt-in
2026-05-16 19:11:48 +08:00
程序员阿江(Relakkes)
fa47adc33a fix: prevent upgrade crashes from stale persistence
Desktop users can carry provider indexes, managed settings, localStorage state, and native update state from builds that no longer match current readers. This adds startup migrations and recovery paths before server and React state are consumed, plus a persistence upgrade gate so future storage protocol changes ship with old-format fixtures.

Constraint: Existing installs may contain malformed or legacy JSON/localStorage that must not block startup.
Constraint: Local verify should evaluate the current worktree diff rather than unrelated detached-worktree history.
Rejected: Treat invalid persisted state as fatal | reproduces white-screen and startup failure behavior for existing users.
Rejected: Bypass PR policy locally | hides real gate behavior and does not fix detached-worktree false positives.
Confidence: high
Scope-risk: moderate
Directive: Any local JSON, localStorage, or app config shape change must add a migration fixture and keep `bun run check:persistence-upgrade` green.
Tested: bun run check:persistence-upgrade; bun run check:policy; bun run check:desktop; bun run check:server; bun run check:native; bun run verify (9 passed, 1 coverage baseline failure)
Not-tested: Live provider baseline; existing user configs beyond covered fixtures
2026-05-06 23:20:21 +08:00
程序员阿江(Relakkes)
b156be8d8d feat: make PR quality verification self-enforcing
Contributors and coding agents need one local command that both reports and enforces the quality contract. This change turns the PR gate into the shared verification entrypoint, adds path-selected local lanes, tightens coverage accounting around changed lines, and documents the repair loop in contributor and agent-facing guidance.

Constraint: Ordinary PR verification must stay non-live and runnable without provider credentials
Constraint: Coverage policy updates in this commit require maintainer approval before push/merge
Rejected: Keep quality guidance only in docs | agents need executable scripts and AGENTS.md instructions to follow the loop consistently
Confidence: high
Scope-risk: broad
Directive: Do not bypass `bun run verify` for production changes; fix failed lanes and coverage reports instead of lowering thresholds
Tested: bun run check:policy
Tested: ALLOW_CLI_CORE_CHANGE=1 ALLOW_COVERAGE_BASELINE_CHANGE=1 bun run verify
Not-tested: live provider baseline; no provider credentials were required for this non-live PR gate
2026-05-06 22:33:43 +08:00
程序员阿江(Relakkes)
9719726cd2 feat: make quality gates observable and enforceable
The repository now has a measurable PR quality path instead of a loose set of
manual checks. Coverage, quarantine governance, provider smoke, desktop smoke,
and workflow wiring all produce durable reports that contributors and maintainers
can inspect without reconstructing terminal output.

This also fixes the desktop smoke current-runtime path so browser-driven smoke
runs use the desktop default active provider instead of forcing the official
current model, and records that runtime decision as an artifact.

Constraint: Default PR gates must remain non-live and contributor-safe while live model checks stay explicit.
Constraint: Release packaging is still GitHub Actions based, so release preflight must run before the build matrix.
Rejected: Make live provider or desktop smoke mandatory on every PR | secrets, quotas, and model availability are maintainer-controlled.
Rejected: Let PRs lower coverage baselines in the same change | base-branch ratchet comparison must remain authoritative.
Confidence: high
Scope-risk: moderate
Directive: Do not relax coverage or quarantine policy without a maintainer approval label and a fresh quality report.
Tested: ALLOW_CLI_CORE_CHANGE=1 ALLOW_COVERAGE_BASELINE_CHANGE=1 bun run quality:gate --mode pr
Tested: bun run quality:gate --mode baseline --allow-live --only provider-smoke:* --provider-model nvidia-custom:main:nvidia-custom-main --artifacts-dir /tmp/quality-gate-live-smoke
Tested: bun run quality:gate --mode baseline --allow-live --only desktop-smoke:* --provider-model current:current:current-runtime --artifacts-dir /tmp/quality-gate-desktop-smoke-fixed
Tested: git diff --check
Not-tested: Full live release mode with multiple providers in hosted CI; provider credentials and quota remain maintainer-controlled.
2026-05-06 16:25:10 +08:00
程序员阿江(Relakkes)
2459488703 Harden provider auth, adapter paths, and notification retries
This captures the pending worktree fixes before applying them to the
current local main. The changes tighten IM adapter path and credential
handling, preserve retry behavior for failed desktop notifications, and
make Azure/OpenAI provider auth and stop reasons reflect actual runtime
state.

Constraint: Worktree was detached from an older local main with pending uncommitted fixes
Rejected: Merge the detached HEAD directly | would also replay unrelated stale history
Rejected: Leave notification dedupe as fire-and-forget | failed sends consumed retry keys
Confidence: high
Scope-risk: broad
Directive: Keep adapter absolute-path matching constrained to configured work roots
Tested: git diff --check
Not-tested: full quality gate before local main integration
2026-05-04 21:37:30 +08:00
程序员阿江(Relakkes)
5b2b5c0d1a Trigger Dosu from PR triage comments
The PR triage workflow mentioned Dosu inside inline-code formatting and before the final footer, which did not reliably wake the bot. Move the handoff so the last non-empty comment line is a plain-text @dosubot request, matching the working PR template pattern.

Constraint: GitHub bot mentions can be sensitive to markdown formatting and comment placement.

Rejected: Leave the mention as a copy-paste hint | it does not satisfy the maintainer need for automatic bot triggering.

Confidence: high

Scope-risk: narrow

Directive: Keep the generated triage comment's final non-empty line as a plain-text @dosubot request.

Tested: bun run check:policy

Tested: git diff --check

Tested: bun run check:pr
2026-05-02 22:07:03 +08:00
程序员阿江(Relakkes)
5f59c693c4 Let contributors choose quality-gate providers
The live baseline previously accepted provider UUIDs, which made the gate hard to run on another contributor's machine. Add a local provider listing command and resolve quality-gate targets from stable provider-name selectors while keeping UUIDs and current runtime support.

Constraint: Provider configuration is local machine state under CLAUDE_CONFIG_DIR and must not expose API keys.

Rejected: Require contributors to inspect providers.json manually | too error-prone and leaks implementation detail into the workflow

Confidence: high

Scope-risk: narrow

Directive: Keep live-provider baseline selection copyable from quality:providers before adding more live test lanes.

Tested: bun test scripts/quality-gate/providerTargets.test.ts

Tested: bun test scripts/quality-gate/*.test.ts scripts/quality-gate/baseline/*.test.ts

Tested: bun run quality:providers

Tested: bun run quality:gate --mode baseline --dry-run --provider-model codingplan:main --provider-model minimax:main

Tested: bun run quality:gate --mode baseline --dry-run --provider-model custom:haiku

Tested: bun run quality:gate --mode pr --dry-run

Tested: bun run check:server
2026-05-02 15:35:59 +08:00
程序员阿江(Relakkes)
f6511ab278 Protect release confidence with live agent baselines
The desktop product needs a repeatable local gate that can prove the core Coding Agent loop still works after changes, not only that unit tests pass. This adds a quality-gate runner with PR, baseline, and release modes, structured reports, explicit quarantine metadata, and fixture-based live baseline cases that can run across provider/model targets.

Constraint: Existing check:pr and CI policy behavior must remain usable while the stronger baseline grows around it
Constraint: Default PR gates must not require real model credentials or provider quota
Rejected: Build a standalone QA platform first | too heavy before the baseline task shape is proven
Rejected: Keep unstable server exclusions hardcoded in run-server-tests | hides quarantine policy from reports and future review
Confidence: medium
Scope-risk: moderate
Directive: Expand baseline cases by adding focused fixtures and verifiers; do not make normal PR checks depend on live providers
Tested: bun test scripts/quality-gate/*.test.ts scripts/quality-gate/baseline/*.test.ts
Tested: bun run check:server
Tested: bun run quality:gate --mode baseline --allow-live --provider-model 2944f963-ce75-45b7-bac1-6e4f57df0970:kimi-k2.6:volc-kimi-k2.6 --provider-model 9c78d3df-7fb5-44c7-8436-3a41c3a59231:MiniMax-M2.7-highspeed:minimax-m2.7
Not-tested: desktop UI browser smoke and native release mode in this commit
2026-05-02 13:00:55 +08:00
程序员阿江(Relakkes)
fdf5fe2653 Protect PR merges with scoped quality gates
Pull requests need a deterministic way to show changed areas, required checks, missing-test signals, and CLI-core risk before review. This adds a path-based policy gate, local impact reporting, PR triage labels/comments, and reusable check scripts so reviewers can evaluate blast radius without trusting contributor claims.

Constraint: CLI core should remain effectively frozen unless a maintainer explicitly overrides it.
Constraint: Default PR checks must be safe for external forks and avoid live model/provider calls.
Rejected: Run live provider tests on every PR | secrets, cost, network, and vendor instability would make the gate noisy and unsafe.
Rejected: Use Dosu as the merge gate | AI review is useful for risk explanation, but deterministic Actions must own blocking checks.
Confidence: high
Scope-risk: moderate
Directive: Keep real model/provider smoke tests in maintainer-controlled workflows; do not make them required for untrusted PRs.
Tested: bun run check:impact
Tested: bun run check:policy
Tested: ruby YAML parse for PR workflows
Tested: git diff --check
Tested: bun run check:native
Tested: npm run docs:build
Tested: bun run scripts/pr/run-server-tests.ts
Tested: bun run check:adapters
Tested: bun run check:desktop
Not-tested: GitHub-hosted pull_request_target label/comment execution before opening this PR
2026-05-02 11:01:07 +08:00
程序员阿江(Relakkes)
febd842557 Keep desktop WebFetch usable on third-party providers
Desktop sessions were failing before the actual fetch because Anthropic's domain preflight can be unreachable on restricted networks, and the next runtime path was missing turndown for HTML-to-Markdown conversion.

This change defaults desktop sessions to skip the preflight unless the user explicitly overrides it, exposes that behavior as a desktop General setting, seeds new settings JSON with the desktop-safe default, and adds regression coverage for both the runtime default and the UI toggle. It also adds the missing turndown dependency so successful fetches can continue through HTML reduction instead of failing at module resolution.

Constraint: Desktop must keep an escape hatch for users who want upstream preflight restored explicitly
Rejected: Force skipWebFetchPreflight globally for every session | would silently change CLI and non-desktop behavior
Rejected: UI-only toggle without runtime default | existing desktop users would still fail until they manually opened settings
Confidence: high
Scope-risk: moderate
Reversibility: clean
Directive: Keep desktop-specific WebFetch behavior scoped to desktop session detection and explicit user settings; do not broaden it to general CLI flows without separate validation
Tested: bun test src/tools/WebFetchTool/utils.test.ts; cd desktop && bun run lint; cd desktop && bunx vitest run src/__tests__/generalSettings.test.tsx; runtime import verification for turndown via node
Not-tested: End-to-end desktop packaging smoke test against a freshly built DMG/app bundle
2026-04-20 20:53:03 +08:00
程序员阿江(Relakkes)
467bc85300 feat(docs): 集成 vitepress-plugin-mermaid 支持 Mermaid 流程图渲染
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 11:26:29 +08:00
程序员阿江(Relakkes)
1d7cbb845a feat: enlarge hero image and add medium-zoom for image lightbox
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 23:50:13 +08:00
程序员阿江(Relakkes)
007b8abab8 docs: add VitePress documentation site with i18n and GitHub Pages deployment
- Set up VitePress with bilingual support (Chinese root + English /en/)
- Create unified sidebar navigation with all doc sections
- Add custom Anthropic brand theme (#D97757)
- Create Quick Start pages (zh/en) from README content
- Migrate 7 .en.md files to docs/en/ directory structure
- Translate memory/agent/skills docs to English (9 files)
- Generate English-only architecture diagrams (11 images via PicTactic)
- Copy English-ready images for agent/skills sections (21 images)
- Configure custom domain (claudecodehaha.relakkesyang.org)
- Localize Chinese UI labels (sidebar, outline, footer)
- Add documentation site badge to READMEs
- Fix dead links and update cross-references for VitePress

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 22:21:45 +08:00
程序员阿江(Relakkes)
124912c71d feat: fix leaked source to be locally runnable
- Restore full Ink TUI startup chain (cli.tsx entry point)
- Create stub .md files for verify skill (Bun text loader hang fix)
- Create stub types for filePersistence and SDK modules
- Fix Enter key not working (modifiers-napi missing, added try-catch)
- Remove overly conservative LOCAL_RECOVERY early return
- Add README with setup instructions
- Add .env.example template
- Add bin/claude-haha entry script and preload.ts

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 01:30:48 +08:00