mirror of
https://github.com/wu736139669/hapi.git
synced 2026-08-05 06:24:37 +00:00
0725fabe84e7a047e44bd98c10ed10da95826c27
52
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
abf9cb02a5 |
fix(pi): resume archived sessions safely (#1308)
* fix(pi): resume archived sessions safely * fix(pi): harden native resume startup * fix(pi): harden resume termination evidence * fix(runner): persist resume process evidence * fix(runner): track resume process generations * fix(runner): verify full session tree shutdown * fix(pi): block pre-mapping resume dedup |
||
|
|
223be6d60f |
fix(cli): don't lose the queued message when a remote launch fails (#1058)
* fix(cli): cap and back off consecutive remote launch failures claudeRemoteLauncher's respawn loop retried claudeRemote() immediately on every throw with no backoff or limit. A deterministic launch failure (bad auth, invalid model/args, spawn failure) respawned in a tight loop instead of giving up, hammering the same failure forever. Track whether onReady() fired at least once per attempt to tell an immediate/deterministic failure apart from a failure after real progress, back off between immediate-failure retries, and after 3 consecutive immediate failures drop the message that keeps triggering them and reset the streak, instead of respawning forever. The session keeps running so a later, unrelated message still gets its own budget. The streak reset on a non-throwing attempt is itself gated on having reached onReady, not applied unconditionally -- otherwise a message that keeps getting parked and re-picked-up on alternating attempts (e.g. an isolated command hitting the same deterministic failure) would reset the streak every other attempt and the cap would never fire. * fix(cli): restore queued message when remote launch fails before delivery MessageQueue2.collectBatch() acks a message (fires onBatchConsumed, which the hub uses to mark it consumed) at dequeue time, before the message ever reaches the SDK. If claudeRemote() then throws before onReady -- e.g. the process dies right after picking up the message -- the catch block only logged and retried, so the message vanished: the hub already thinks it was delivered, but the CLI never acted on it. Track the message returned from nextMessage() (whether freshly dequeued or held in `pending` across a mode change) as in-flight until the next onReady confirms it was handled, and restore it to the front of the queue (preserving isolation via unshiftIsolated when needed) if the attempt throws and will be retried. Restoring happens even if the throw races with a user-initiated switch/exit, so a message is not silently dropped by that unrelated shutdown either. When the immediate-failure cap from the previous commit is reached, the in-flight message is dropped instead of restored: unshifting it back would just feed it into another immediate failure on the very next attempt, storming again. This mirrors cursorLegacyRemoteLauncher's existing drop-and-reset policy on its own consecutive-failure cap. * fix(cli): preserve localId when restoring a failed message batch MessageQueue2.collectBatch() already collects each queue item's localId (it fires onBatchConsumed with the full list to ack them), but only exposed the joined `message` string to callers, discarding the per-item localIds and their original boundaries in the process. When claudeRemoteLauncher restores a dequeued-but-undelivered batch after a launch failure, it re-added the joined string as a single new queue item with no localId, orphaning the retried prompt from the hub row(s) it originated from (and from cancel-by-localId). Expose the pre-join `items` breakdown (message + localId per item) alongside the existing joined `message` field on collectBatch()/waitForMessagesAndGetAsString() -- purely additive, so the other callers of waitForMessagesAndGetAsString() (grok, kimi, opencode, cursor, codex, runAgentSession) are unaffected. On restore, unshift each original item individually in reverse order, so the localId and relative order of a multi-message batch are both preserved instead of just the first item's. * fix(cli): reset immediate-failure streak on a delivered non-onReady success claudeRemote.ts's /clear handling delivers the queued message to the SDK, then calls onSessionReset()/onCompletionEvent() and returns successfully without ever calling onReady(). The success-path streak reset only cleared on reachedReadyThisAttempt, so a successful /clear between two unrelated immediate launch failures did not reset the streak: an unrelated message's very next failure could hit the 3-in-a-row cap after just 1 failure, and the resulting banner would misreport "3 times in a row". Track whether nextMessage() actually handed a message to the SDK this attempt (deliveredMessageThisAttempt), separately from whether the attempt reached onReady, and reset the streak on either signal. The livelock-prone case this guards against (a message parked into `pending` and the attempt returning without ever delivering anything) leaves both flags false, so it still does not reset the streak. |
||
|
|
5a377e38b9 | fix(codex): defer session persistence until user activity | ||
|
|
43e7b6bef7 |
fix(cli): compute macOS machine-health memory from vm_stat (#990)
* fix(cli): add darwin vm_stat memory percent parser Add readDarwinMemoryUsedPercent, a pure parser that computes macOS used memory as App Memory + Wired + Compressed (anonymous + wired-down + occupied-by-compressor pages), matching Activity Monitor's "Memory Used" figure. Page size is parsed from the vm_stat header rather than hardcoded, since it differs between Apple Silicon (16KB) and Intel (4KB) Macs. Not wired up yet; covered by unit tests, including a verbatim vm_stat capture from a 16GB Mac mini where the pre-fix total - freemem() path reported 99% (counting reclaimable cache as used) while App+Wired+ Compressed is 79% — the number a user sees in Activity Monitor. * fix(cli): wire darwin memory percent into computeMemoryPercent Add a platform() === 'darwin' branch that shells out to vm_stat (1s timeout, guarded by try/catch) and feeds its output to readDarwinMemoryUsedPercent. On any failure or undefined result it falls through to the existing total - freemem() fallback, matching the Linux branch's structure. This fixes the Machine capacity tooltip showing a stuck ~99% "High pressure" warning on macOS runners: os.freemem() there counts reclaimable file cache as used, so it reports near-total usage. Summing only App Memory + Wired + Compressed reports the same figure Activity Monitor shows. |
||
|
|
26a24bb6ce |
feat(web,hub,cli): show machine health in session sidebar (#962)
* feat(web,hub,cli): show machine load in session sidebar Runners attach OS health snapshots to machine-alive heartbeats; the hub caches them and the web session list renders load or CPU between the machine label and session count. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web,cli): show CPU and RAM pressure in machine health badge Sidebar label now combines CPU and RAM percentages for overload signaling; load stays in the tooltip on Unix. Prime CPU sampling so the first heartbeat includes usage, not just memory. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(web): visual machine health meters with tooltip Replace bare CPU/RAM text with labeled mini bar gauges, chip border tint by severity, and a HoverTooltip explaining capacity and overload guidance. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): widen machine health tooltip with horizontal layout Allow a generous popover width and lay CPU/RAM/load out side by side so the capacity tooltip reads wider and less tall than the chip. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): anchor machine health tooltip to row left edge Wide tooltip was align=end on the chip, so it grew left off-screen. Use row-span positioning on the machine tile button instead. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(web): machine host card with OS label and inline health Turn the session sidebar machine row into a bordered host panel with OS metadata and side-by-side CPU/RAM meters embedded in the tile instead of a flat label line matching project rows. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): keep machine host tile single-row height Collapse the machine header back to one py-1.5 row with OS and compact inline health beside the name, and restore the original project indent without the extra nested rail or second header line. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(web): show CPU core count in machine health tooltip When the runner reports cpuCount, the tooltip reads "CPU across all 6 cores" instead of the generic all-cores label. Co-authored-by: Cursor <cursoragent@cursor.com> * docs: add machine health sidebar screenshots Dogfood captures for the session sidebar machine tile and capacity tooltip, for upstream PR review. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): clear machine-alive priming timeout on disconnect Track the 50ms CPU priming setTimeout and clear it in stopKeepAlive so disconnect/shutdown during the delay cannot leave a stray interval alive. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: drop dogfood screenshots from upstream PR diff Review evidence lives in the PR discussion only; no need to ship PNGs in the repo long-term. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): truncate long machine OS/host metadata in sidebar row Bound the metadata span so a long hostname cannot push the health chip or session count off-screen in narrow sidebars. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): reveal machine health tooltip on keyboard row focus Wire MACHINE_ROW_TOOLTIP_FOCUS_CLASS and aria-describedby on the machine header button so keyboard users can read the health tooltip like session rows. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): use MemAvailable for Linux RAM pressure on Bun Bun's os.freemem() reflects MemFree (~1% on cache-heavy hosts), which made sidebar RAM read ~99% while btop showed ~40% used. Parse /proc/meminfo MemAvailable instead so used percent matches operator tools. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(web,cli): show machine uptime in sidebar tiles and tooltip Collect os.uptime() as uptimeSeconds on keepalive and render compact up 1h 54m in the machine meta row plus an Uptime line in the health tooltip. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): anchor machine health tooltip to chip not row align=row positioned the tooltip below the full machine header button, so the collapsible project panel painted over it on hover. Use align=end with a min-width panel so mouse and keyboard tooltips stay visible. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
b3add07ad7 |
fix: detect stale PID in runner state after abnormal shutdown (#931)
* fix: verify PID belongs to hapi before treating runner as alive After OS upgrade, stale runner.state.json PID can be reused by unrelated processes. The old kill(pid, 0) check passes for any process, causing start-sync to loop with 'Runner already running' indefinitely. Now uses ps/wmic to confirm the process command line contains 'hapi' before considering the runner alive. Falls back to alive-only check if ps/wmic fails. * fix: precise runner process detection and wmic fallback * fix: add fallback for ps failure in non-Windows branch |
||
|
|
e23ae1b265 |
feat: add Pi Coding Agent support (#862)
* docs: spec for hapi-pi-agent-backend
* docs: spec retrospect for hapi-pi-agent-backend
* docs: plan for hapi-pi-agent-backend
* docs: plan retrospect for hapi-pi-agent-backend
* feat(pi): add hapi pi command with JSONL transport and event converter
- PiTransport: spawn pi --mode rpc, JSONL stdio, ENOENT/EPIPE handling
- PiEventConverter: Pi AgentEvent → HAPI AgentMessage conversion
- runPi: session lifecycle, dual-track event routing, model switching
- pi command: CLI registration with PI_PERMISSION_MODES
- Shared: add 'pi' to AGENT_FLAVORS, FLAVOR_CAPS, FLAVOR_LABELS
30 tests passing (15 transport + 15 converter)
* fix(pi): add Pi RPC types, fix double-cleanup/double-start/converter safety net
- Add cli/src/pi/types.ts with PiAgentEvent/PiResponseEvent discriminated unions
- PiTransport: constructor uses options object, double-start guard, drop log
- PiEventConverter: typed events via type assertions, top-level try/catch
- runPi: safeCleanup guard prevents double-cleanup race, sendAgentMessage
for converted events, keepAlive() for session pings
- 33 tests passing
* docs: dev phase reviews and test results for hapi-pi-agent-backend
- Business logic review: pass (0 must_fix)
- Standards review: pass (0 must_fix)
- Taste review: P0 types issue fixed in code
- Robustness review v2: pass (v1 3 MUST_FIX all fixed)
- Integration review: pass (0 must_fix)
- Test results: 33 passing, all type errors resolved
* docs: taste review v2 pass after type definition fixes
* docs: dev retrospect for hapi-pi-agent-backend
* test: test execution for hapi-pi-agent-backend (20/20 pass)
* fix: add taste_review symlink for gate pattern match
* docs: test retrospect for hapi-pi-agent-backend
* fix(web): add pi to MODEL_OPTIONS Record type
* ci: PR and CI evidence for hapi-pi-agent-backend
* docs: overall retrospect for hapi-pi-agent-backend (all 5 phases)
* test(pi): add buffer split, missing fields, and handleResponse tests
- PiTransport: buffer cross-chunk reassembly test
- PiEventConverter: tool_execution_end with missing result/toolCallId
- handleResponse: 10 tests covering all branches (error, get_state,
set_model, new_session, abort, prompt, unknown command)
- Extract handleResponse to accept onUpdate callback for testability
- Total: 46 tests passing (was 33)
* fix(pi): set requiresRuntimeAssets to false — pi runs as subprocess, no native tools needed
* refactor(cli): lazy import ensureRuntimeAssets to reduce startup overhead
* docs: add 15 manual E2E protocol test cases (TC-4-xx) based on real Pi RPC capture
- TC-4-01 to TC-4-15: manual tests covering tool execution, thinking
lifecycle, multi-turn, abort, error scenarios, model switch, cleanup
- Priority: P0 (tool fields, failure, thinking, multi-turn, abort)
> P1 (basic conversation, write tool, model switch, usage) > P2 (edge cases)
- Includes actual Pi RPC event sequence from live capture as reference
- e2e-test-plan.md updated with test environment setup instructions
- Total test cases: 35 (6 unit + 14 integration + 15 manual)
* test: E2E protocol test results for hapi-pi (11/15 pass)
P0/P1 automated tests (8/8 pass):
- TC-4-01: Basic text conversation ✓
- TC-4-02: Tool read (field names verified) ✓
- TC-4-03: Tool write (file created) ✓
- TC-4-04: Tool failure (isError=true) ✓
- TC-4-05: Thinking lifecycle + usage ✓
- TC-4-06: Multi-turn context retention ✓
- TC-4-07: Abort generation ✓
- TC-4-14: Token count ✓
- TC-4-15: Extension UI events ignored ✓
P2 results:
- TC-4-10: Invalid token → 401 ✓
- TC-4-12: Ctrl+C cleanup, no orphans ✓
- TC-4-08: ENOENT (harness issue, exit code correct)
- TC-4-11: set_model not supported by Pi (success=false)
- TC-4-13: Pi crash (harness output capture issue)
* test: fix TC-4-11 result — Pi set_model works with correct provider/modelId
Previous test used invalid provider='' + modelId='deepseek-chat'.
Re-tested with provider='deepseek' + modelId='deepseek-v4-flash':
- set_model success=true
- model switched glm-5.1 → deepseek-v4-flash
- subsequent prompt confirmed working
Final E2E results: 12/15 PASS, 2 FAIL (test harness), 1 SKIP
* chore: remove .xyz-harness/ from git tracking, add to .gitignore
Local harness workflow artifacts should not be tracked in the repo.
* fix(pi): resolve web UI bugs for hapi-pi integration
Five bugs fixed for end-to-end pi session via hapi web UI:
1. runner buildCliArgs: add 'pi' branch to spawn correct command
(was falling back to 'claude', launching wrong agent)
2. runPi: implement real keep-alive (2s interval) to prevent hub
30s timeout marking session inactive
3. runPi: bump keep-alive to active state during agent/turn_start
4. sessionResume: add 'pi' to flavor switch and resume condition
(was returning undefined, causing 'cannotResume' on inactive session)
5. PiEventConverter: emit codex-compatible {type:'message',message:...}
/{type:'reasoning',message:...} with streamId; dedup by skipping
text_start/text_end (only send deltas) to avoid triple-rendered text
6. PiTransport: fallback to stdout 'end' event when child process
close event doesn't fire (bun spawn quirk)
Verified end-to-end: web UI shows pi reasoning + reply correctly,
session stays online, no duplicate text.
* fix(pi): address 4 web UI display bugs in hapi-pi integration
Three of four follow-up bugs reported after the initial fix (6c28949):
1. Stuck in 'queued' status — fix
Pi's runner doesn't use MessageQueue2, so the base session's
onBatchConsumed hook never fires. Add a FIFO of pending localIds
in runPi and emit messages-consumed on agent_start. turn_start
is intentionally skipped (it can fire multiple times per agent
run after tool calls). A prompt rejection from Pi also consumes
the localId so the next prompt isn't poisoned.
2. AI thinking only displays ':' — fix
Pi emits pure incremental deltas (text_delta / thinking_delta)
per token. The web reducer dedupes reasoning by streamId WITHIN
one message's content array only — separate wire messages
produce separate renders. Without accumulation, 50 deltas = 50
reasoning renders, of which the reducer keeps only the last
delta (a single character like ':').
3. Output text on separate lines — fix
Same root cause as #2 but for text: the reducer appends each
text AgentMessage as a new agent-text block (no dedup), so 50
deltas become a 50-row character-by-character column.
4. Tool call execution status (in_progress -> completed)
The tool result wire CodexMessage type is 'tool-call-result'
(with callId + is_error?); the internal AgentMessage 'tool_result'
is converted to that. Status mapping is preserved.
Implementation: extract a PiMessageAccumulator class (testable in
isolation) that mirrors codex's ReasoningProcessor pattern:
- message_start resets state and streamId
- text_delta / thinking_delta append to internal text / reasoning
- text_start/thinking_start/text_end/thinking_end ignored (they
carry full partial state — would duplicate)
- message_end flushes (max 1 reasoning + 1 text message, in order)
- turn_end safety net flushes if active
- flushIfActive() exposed for transport close / crash
The converter now routes AgentMessage through convertAgentMessage
so the wire format is codex-shaped (matches opencode/gemini/kimi
path). AgentMessage 'text' and CodexMessage 'message' both gain
optional id; convertAgentMessage preserves caller-provided id for
streamId-based dedup on the web side.
Tests: 16 new PiMessageAccumulator tests + 5 updated
PiEventConverter tests + 4 messageConverter tests, all passing.
Full suite: 909/910 (1 unrelated macOS path normalization). tsc
clean.
* fix(pi): review round 1 - 1 must-fix issue
The web session-resume helper referenced metadata.piSessionId, but the
shared MetadataSchema does not define the field, and the back-end has no
path to populate it (Pi session resume is out of scope per spec.md).
This caused web typecheck to fail and would also have produced a
runtime 'resume_unavailable' from the hub if a user tried to resume a Pi
session that had any user messages (the stale 'flavor === pi' branch in
inactiveSessionCanResume claimed resume was supported).
Revert the two early Pi branches from the web resume helper. Add a
comment pointing at the spec and noting what to undo when back-end
resume ships (re-add 'case pi' + 'piSessionId' on MetadataSchema +
extend hub resolveAgentResumeId).
* fix(pi): review round 2 - 4 must-fix issues
1. cli/src/runner/run.ts buildCliArgs: stop forwarding --resume to the pi
binary. Pi session resume is out of scope (no piSessionId on
Metadata), so forwarding would create an orphan session the hub can't
track. Hub already returns null from resolveAgentResumeId for
flavor='pi' and falls through to fresh spawn; this just hardens the
runner layer to match.
2. cli/src/pi/runPi.ts: cache currentProvider from get_state and use it
for subsequent set_model RPCs. Pi's set_model requires both provider
and modelId, but the bootstrap-time code emitted provider: '' which
Pi rejects. The bootstrap-time model is still applied by Pi at
startup, so suppressing set_model until get_state arrives is a no-op
for same-model configs rather than a wrong-model emit.
3. web/src/components/AssistantChat/modelOptions.ts: add explicit pi
branches to getModelOptionsForFlavor and getNextModelForFlavor.
Without them, Pi sessions fell through to the Claude preset cycler,
which would push sonnet/opus ids into a Pi session via
set-session-config. Mirrors the opencode handling introduced earlier.
Tests added/updated: buildCliArgs covers pi + claude resume; handleResponse
mirror test covers provider caching; modelOptions tests cover pi
no-fallback behavior for both option list and cycler.
* fix(pi): add session resume support and fix review issues
- Add piSessionId to MetadataSchema (shared/src/schemas.ts)
- Persist piSessionId from get_state response to metadata (cli/src/pi/runPi.ts)
- Pass --session-id to Pi spawn on resume (cli/src/pi/runPi.ts)
- Add pi branch to resolveAgentResumeId (hub/src/sync/syncEngine.ts)
- Add case 'pi' to resolveAgentSessionIdFromMetadata (web/src/lib/sessionResume.ts)
- Replace pi resume skip guard with --session-id forwarding (cli/src/runner/run.ts)
- Preserve piSessionId in pickExistingSessionMetadata (cli/src/agent/sessionFactory.ts)
- Add pi badge to AgentFlavorIcon (web/src/components/AgentFlavorIcon.tsx)
- Fix transport.onClose crash-marking on normal shutdown (cli/src/pi/runPi.ts)
* fix(pi): review round 1 - 3 must-fix issues
- resume.ts: add pi branch to dispatchLocalResume() so hapi resume
dispatches to runPi instead of falling through to cursor
- runPi.ts: accept existingSessionId and use bootstrapExistingSession
when resuming, matching other agents' pattern
- agentCommandOptions.ts: parse --session-id in addition to --resume
so runner-spawned pi resume actually forwards the session ID
- types.ts: export PiPermissionMode alongside other agent permission
mode types for consistent import convention
* fix(pi): review round 2 - 2 must-fix issues
* refactor(workflow): improve pi-adaptation-review-loop robustness
- Switch from structured output to file-based JSON output for reliability
- Replace per-round file limit (20→30) with clear wording (remove misleading split-commits instruction)
- Return { data, error } from readResultFile() to surface parse/validation failures in abortReason
- Fix lastMustFix sentinel: initialize to null, use ?? for explicit N/A reporting
- Add getAgentDirs() to dynamically discover agent dirs from cli/src/
- Document rollbackTo() atomic-round design intent
- Add isValidIssue() validation, runFinalCleanup() helper, git repo pre-check
* test(pi): add coverage for pi flavor across shared, cli, and web
- shared/flavors.test.ts: pi/kimi capability, label, known, supports
- shared/modes.test.ts: PI_PERMISSION_MODES contract, per-mode checks
(7-mode allowed/denied matrix)
- web/AssistantChat/modelOptions.test.ts: pi shortcut vs Claude
cycler, normalize filter (auto/default/whitespace), kimi/cursor/
opencode cross-flavor consistency
- web/lib/sessionResume.test.ts: piSessionId resolver, cross-flavor
stale-id protection, inactiveSessionCanResume for pi, regression
coverage for all 6 other flavors
- web/components/AgentFlavorIcon.test.tsx: pi badge styling
(bg-[#5b21b6]), Un fallback, case/whitespace normalize,
className override
- cli/commands/agentCommandOptions.test.ts: --session-id
(pi-specific flag), --resume alias, PI mode validation,
--yolo vs explicit-mode priority
137 new test cases, all passing. Full suite: 96 files / 933 tests
green (unrelated apiMachine.test.ts macOS /private/var path issue
remains as documented in handoff).
* feat(pi): implement P0 — context budget bar + dynamic model discovery
P0-1: Context Budget Bar
- Add pi branch to modelConfig.ts getContextBudgetTokens()
- Conservative 200K default context window for Pi sessions
P0-2: CLI-side model discovery
- Add get_available_models to PiRpcCommand type
- Auto-send get_available_models after get_state in runPi.ts
- Cache model list and push to session metadata
- Register ListPiModels RPC handler with promise-based transport query
P0-3: Hub-side routing
- Add listPiModelsForSession to rpcGateway and syncEngine
- Add REST endpoint GET /sessions/:id/pi-models (pi sessions only)
P0-4: Web-side rendering
- Add PiModelSummary type to shared apiTypes
- Add usePiModels hook (TanStack Query, stale 60s)
- Add getSessionPiModels to API client
- Add sessionPiModels query key
- Wire piModelOptions into SessionChat availableModelOptions
- Model dropdown renders discovered models or falls back to Default
* fix(pi): address code review findings + pre-existing test issue
Review fixes:
- Fix race condition in sendPiRpcAndWait: use incremental id as key
instead of command type, preventing resolver overwrite on concurrent
calls (e.g. auto-discovery + ListPiModels RPC)
- Extract parsePiModels() to eliminate duplicated model parsing logic
between handleResponse and ListPiModels RPC handler (DRY)
- Add resolvePendingRpc() call in error response path to prevent
promise leaks when Pi rejects an RPC with an id
- Add piModelsState.error guard to onModelChange in SessionChat,
matching the pattern used by codex and cursor flavors
Pre-existing fix:
- Fix apiMachine.test.ts symlink assertion on macOS (/var vs
/private/var) by applying realpathSync to the expected path
* feat(pi): P1 — session rename sync, thinking level UI, skills/commands
P1-1: Session Rename → Pi notification
- Add set_session_name to PiRpcCommand
- Register RenamePiSession RPC handler in CLI
- Hub syncEngine.renameSession now forwards to Pi CLI for active sessions
- Hub rpcGateway + REST endpoint added
P1-2: Thinking Level support
- Add Pi thinking level constants to shared/src/piThinkingLevel.ts
(off/minimal/low/medium/high/xhigh)
- Add ThinkingLevel capability to Pi flavor in flavors.ts
- sessionConfigRpc now supports effortMode for Pi thinking level
- runPi captures thinkingLevel from get_state and forwards via
set_thinking_level
- Hub effort endpoint accepts pi sessions (was claude-only)
- Web: piThinkingLevelOptions.ts + HappyComposer renders Pi options
when flavor=pi
P1-3: Skills/Commands discovery
- Add get_commands to PiRpcCommand, auto-discover after get_state
- Register ListPiCommands + ListSlashCommands RPC handlers in CLI
(maps Pi commands to HAPI SlashCommand format)
- Hub: listPiCommandsForSession + REST GET /sessions/:id/pi-commands
- Web: usePiCommands hook + api client + query keys
Also fixes:
- Pre-existing ZodError.errors → ZodError.issues in hub/socket/server.ts
- Updated test expectation for effort endpoint error message
* feat(pi): implement P2 features — steer, queue modes, history, native images
P2-1: Steer/Follow-up
- Track piIsStreaming state from agent_start/turn_start/turn_end/agent_end
- When streaming, onUserMessage sends steer instead of prompt
- Added PiSteer/PiFollowUp RPC methods + hub routing + REST endpoints
P2-2: Queue modes
- Added set_steering_mode/set_follow_up_mode to PiRpcCommand
- CLI RPC handlers with mode state tracking
- Hub routing + REST POST endpoints
- Web API client methods
P2-3: History replay
- Added get_messages to PiRpcCommand
- CLI handler converts Pi AgentMessage to PiMessageEntry format
- Hub RPC routing + REST GET /sessions/:id/pi-messages
- Web usePiMessages hook + query key
P2-4: Native image passing
- Added PiImageContent type for base64 image data
- extractPiImages() helper reads attachment files as base64
- prompt/steer commands now include images field
- Falls back to @path text reference for non-image/unreadable files
* feat(pi): implement P3 advanced features — compact, fork, clone, switch, stats, export
P3 features for Pi agent integration:
- Compact: compact RPC with custom instructions, set_auto_compaction toggle
- Fork: fork at entry ID, get_fork_messages for fork context
- Clone: clone current Pi session
- Switch Session: switch Pi to a different session by path
- Session Stats: get token counts, message counts, cost
- HTML Export: export session as HTML file
All features follow existing P2 pattern:
- CLI: RPC handlers in runPi.ts with sendPiRpcAndWait
- Hub: rpcGateway + syncEngine routing + REST endpoints
- Web: API client methods + query keys + type exports + hooks (stats, fork messages)
Total: 8 new REST endpoints, 9 RPC handlers, 6 web API methods
Typecheck: all 3 packages pass (cli+hub+web)
Tests: 1155 pass (263 hub + 803 web + 89 shared), 0 failures
* refactor(pi): clean up runPi.ts imports and readability
- Replace require('fs') with top-level import { readFileSync } from 'fs'
- Extract handleGetState() as standalone function from handleResponse
switch case (get_state case: 35 lines → 4 lines dispatch)
Typecheck: all 3 packages pass
Tests: 1066 pass (263 hub + 803 web), 0 failures
* fix(pi): remove native image passing, fix version pollution
- Remove extractPiImages helper and PiImageContent type: all
attachments now use @path text references via
formatMessageWithAttachments, consistent with every other agent
- Remove images field from prompt/steer/follow_up RPC commands
- Remove unused readFileSync import
- Restore cli/package.json version from test pollution
(0.0.0-integration-test-should-be-auto-cleaned-up-51369 → 0.20.0)
Typecheck: all 3 packages pass
Tests: 1286 pass, 0 failures
* refactor(pi): extract hub helper, unify web hooks, fix import style
- Hub: extract withPiSession helper eliminating boilerplate across 15
Pi REST endpoints (~400 lines → ~150 lines)
- Web: unify usePiForkMessages and usePiSessionStats to return
destructured typed fields matching usePiModels/usePiCommands pattern
- Web: move 15 Pi response types from inline import() to top-level
named imports in api/client.ts
- CLI: remove duplicate PiCommandSummary/PiCommandsResponse from
types.ts, re-export from @hapi/protocol/apiTypes
Typecheck: all 3 packages pass
Tests: 1286 pass, 0 failures
* chore: untrack .agents/skills and .pi, fix .xyz-harness in gitignore
* refactor: remove unused text message id from converter layer, update gitignore
* fix: update tests for pi resume support and text id removal
* fix: restore cursor resume branch in buildCliArgs
* refactor: remove pi-specific rename from syncEngine, align with other agents
* refactor: remove effort field from sessionConfigRpc, Pi self-handles RPC
Pi agent now self-handles SetSessionConfig RPC (like Claude) using
the existing field, instead of adding a parallel
field to the shared sessionConfigRpc helper which only knows about
.
- Remove effort/effortMode from sessionConfigRpc types and logic
- runPi.ts: self-register RPC handler with PiThinkingLevel validation
- Reuse resolveSessionConfigPermissionMode from sessionConfigRpc
* refactor: consolidate Pi RPC layer from 36 methods to 3 generics
rpcGateway: 12 methods → callPiRpc<T>
syncEngine: 12 passthroughs → callPiRpc<T> delegate
web client: 12 methods → callPiEndpoint<T>
routes: use engine.callPiRpc with RPC_METHODS constants
hooks: use callPiEndpoint, add missing type imports
* chore: revert unrelated apiMachine test change
* refactor: remove unused ThinkingLevel capability from flavors
Pi's thinking level is an effort variant, not a separate capability.
The ThinkingLevel constant and supportsThinkingLevel() had zero callers
— the frontend uses flavor-based branching for effort option rendering.
* refactor: drop Pi prefix from generic RPC method names
* refactor: remove 13 Pi RPC methods with no UI consumers
Steer: already handled by onUserMessage auto-routing
Follow-up: redundant with HAPI message queue
ListPiCommands/GetMessages/ForkMessages/SessionStats: no UI
Compact/SetAutoCompaction/Fork/Clone/SwitchSession/ExportHtml: no UI
SetSteeringMode/SetFollowUpMode: no UI
Kept: ListPiModels (has UI), SetSessionConfig, ListSlashCommands, Abort, Switch
Deleted: 4 web hooks, 13 RPC handlers, 12 REST routes, 13 rpcMethods entries
Net: -730 lines
* refactor: extract session.ts and loop.ts from runPi.ts
Restructure Pi agent following Codex pattern (without Local/Remote
splitting since Pi only has remote mode):
- session.ts: PiSession class managing state + hub communication
- loop.ts: response parsing, RPC resolver, transport event wiring
- runPi.ts: thin entry (bootstrap, RPC handlers, lifecycle)
Changes from review:
- Encapsulate RPC resolver in PiRpcResolver class (session-scoped,
not module-level singleton)
- Remove unused extractTextFromPiMessage export
- Fix inline import('./types') → top-level import
* refactor: normalize Pi file naming and improve test coverage
- Rename PiTransport.ts → piTransport.ts, PiEventConverter.ts →
piEventConverter.ts, PiMessageAccumulator.ts → piMessageAccumulator.ts
(match project-wide camelCase convention)
- Delete handleResponse.test.ts (tested stale copy of inline function)
- Add loop.test.ts with 20 tests covering parsePiModels,
parsePiCommands, wireTransportEvents integration, and sendPiRpcAndWait
- Total Pi tests: 73 (was 53)
* test: add E2E harness with 4 core helpers and integration specs
Helper functions in e2e/harness.ts capture the four non-obvious
interactions discovered during the 2026-06-09 retest:
- longPress: SessionActionMenu is triggered by 500ms press, not click
- mockOffline: useOnlineStatus hook listens to navigator.onLine +
window offline event, not CDP Network.emulateNetworkConditions
- pollForText: thinking indicator flickers in <1s, 3s polling misses
- isVisible: element.offsetParent returns null for position:fixed
dialogs even when visible; use getBoundingClientRect
Plus Chrome lifecycle (startChrome/stopChrome, never pkill chrome)
and hub API helpers (loginWithToken, listSessions).
5 integration specs (e2e/integration/) cover:
- yolo-permission: toggle + localStorage persistence (4 cases)
- codex-dialog: pre-flight check + dialog render (3 cases)
- stress: 10 concurrent + invalid JWT + malformed + unknown
endpoint (5 cases, all PASS)
All 12 integration cases pass. Full E2E results in
.xzy-harness/2026-06-09-full-e2e-retest/ (67 cases, 0 functional
bugs found).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
* fix: resolve Pi model selection and thinking level issues
- Fix PiModelPanel: use provider+modelId composite for selection check
and React key, preventing duplicate highlights for same-name models
across different providers
- Fix PiThinkingLevelPanel: unify thinkingLevelMap filtering logic by
extracting shared isThinkingLevelSupported utility
- Fix HappyComposer: auto-reset effort to highest supported level when
switching models, update label to reflect effective level
* refactor: remove 29 dead exports from feat-pi-support
Remove unused types, methods, and re-exports identified by dead code audit:
shared/src/apiTypes.ts (19):
- SessionModelIdentifier, ListPiCommandsResponse
- PiSteeringMode, PiFollowUpMode, PiSteerResponse, PiFollowUpResponse
- PiQueueModeResponse, PiMessageEntry, PiMessagesResponse
- PiCompactResponse, PiSetAutoCompactionResponse
- PiForkResponse, PiForkMessageEntry, PiForkMessagesResponse
- PiCloneResponse, PiSwitchSessionResponse
- PiSessionStats, PiSessionStatsResponse, PiExportHtmlResponse
cli/src/pi/types.ts (6):
- PiSessionStats, PiCompactionResult, PiForkMessageEntry (dead local duplicates)
- PiCommandsResponse, PI_THINKING_LEVELS, PI_THINKING_LEVEL_LABELS (dead re-exports)
cli/src/pi/piMessageAccumulator.ts (1):
- flushIfActive() method (comment claimed runPi calls it, but it doesn't)
cli/src/pi/piTransport.ts (1):
- isRunning() method (never called in production code)
web/ (2):
- ProviderGroup, PiThinkingLevelOption (unnecessary exports, made local)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix: resolve 7 PR review issues in Pi support
#3 Remove duplicated PI_THINKING_LEVELS in schemas.ts, import from @hapi/protocol
#2 Add piAvailableModels field to MetadataSchema (schema-runtime consistency)
#6 Replace hardcoded flavor names with supportsEffort() in effort route
#1 Move PiRpcResolver from module-level singleton to PiSession instance
#4 Add piCachedModels fallback in piModelOptions useMemo
#7 Merge message_update dead branch into unified not-converted case
#10 Fix misleading Pi model list comments in modelOptions.ts
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix: normalize Pi model object to string in hub sessionCache (#5), remove extra blank line in rpcGateway (#8)
#5: applySessionConfig now extracts modelId from { provider, modelId }
before passing to setSessionModel / session.model, preventing
[object Object] from being stored in SQLite when Pi switches models.
#8: Remove double blank line before RpcGateway class declaration.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(pi): preserve piAvailableModels on resume, document SetSessionConfig divergence
- sessionFactory: preserve piAvailableModels in pickExistingSessionMetadata
so web shows cached models on inactive-session view without RPC round-trip
- sessionConfigRpc: extend resolveNullableSessionModel to accept
{provider, modelId} object form for schema consistency
- runPi: document why Pi manually registers SetSessionConfig instead of
reusing registerSessionConfigRpc (wire protocol needs separate fields)
- package.json: restore version to 0.20.0
* refactor: remove unused Pi types, extract JsonLineParser, clean up review findings
- Remove 13 unused PiRpcCommand variants and PiStreamingBehavior type (YAGNI)
- Remove unnecessary exports on 3 internal Zod schemas in pi/schemas.ts
- Extract JsonLineParser base class to utils/, shared by PiTransport,
CodexAppServerClient, and AcpStdioTransport (eliminates 3x duplicate
handleStdout buffer logic)
- Remove DEV-only duplicate session ID detection from SessionList.tsx
(debug code unrelated to Pi support scope)
- Add comments explaining key prefix rationale in SessionChat.tsx
* chore: remove unrelated E2E test harness from Pi support PR
E2E harness (codex-dialog, stress, yolo-permission, scratchlist specs)
was introduced in this branch but tests generic HAPI behavior unrelated
to Pi agent support. Should live in a separate PR.
* fix: wrap cursor model change handler for union type compatibility
* fix: apply startup --model to Pi and remove duplicate lockfile entry
1. --model startup bug:
- Add initialModel to PiSession to preserve startup model
- handleGetState preserves initialModel instead of overwriting with Pi default
- get_available_models handler resolves provider from cached models and sends set_model
2. bun.lock duplicate key:
- Remove duplicate @twsxtd/hapi-win32-x64@0.20.0 entry
- Fixes CI lockfile regeneration that caused hono type errors
* fix: update test expectation for effort endpoint error message
* fix(pi): resolve 8 link-review defects + abort session termination
- W1C-D-1: hasSameAgentSessionIds missing piSessionId/kimiSessionId
+ extractAgentSessionId also needs piSessionId recognition
- D-1: dispatchLocalResume pi branch missing effort param
- W1B-1-01: buildCliArgs only passes --effort for claude, not pi
- W2B-D-2: effort=null does not send set_thinking_level to Pi
- D-3: turn_start does not consume pendingLocalIds
- D-7: keep_alive falls into default case in convertPiEvent
- D-9: finally overwrites sessionEndReason set by Switch/Abort
- W2B-D-3: ListPiModels RPC does not update metadata
- Abort handler: remove cleanupAndExit, only cancel current turn
Also: Switch handler returns { success: true } for consistency
Test coverage: 13 new test cases across 5 files
* fix: restore cli version from integration test placeholder
* fix(pi): send restored thinking level to Pi subprocess on startup
opts.effort was stored in piSession.currentThinkingLevel but never
forwarded via set_thinking_level during the startup sequence, causing
runner-spawned and resumed sessions to show the restored effort in
HAPI while Pi kept its default.
* fix: restore cli package version from integration test residue
* fix(pi): switch-to-remote handler preserves session instead of terminating
Replace lifecycle.cleanupAndExit() with createModeChangeHandler + keepAlive
in the Switch RPC handler. Pi runs as a single long-lived subprocess
without BaseLocalLauncher's restart loop, so cleanupAndExit() permanently
destroyed the session on mode switch. The web handoff button now correctly
changes control mode while keeping Pi alive.
* fix(pi): remove permission mode selector (Pi RPC has no runtime switching)
Pi's --mode rpc is non-interactive and auto-approves all tool execution;
there is no set_permission_mode command in the protocol. The selector
reported success without changing Pi's behavior, misleading users.
Remove the concept across all four packages:
- shared: getPermissionModesForFlavor('pi') returns [] (cascades to
hub 400 + web UI auto-hide via length===0 guards); drop
PI_PERMISSION_MODES / PiPermissionMode
- cli: strip permissionMode from PiSession/runPi/pi command/resume;
drop the no-op SetSessionConfig permission branch that stored state
without forwarding to the subprocess
- web: delete PiPermissionPanel.tsx; remove panel block + imports
from HappyComposer
* fix(cli): realpath workspace root in apiMachine test assertion
The handler realpaths the cwd as a symlink-escape guard, so on macOS
/var/folders/... resolves to /private/var/folders/... The test compared
against the un-resolved path and failed on macOS. Use realpathSync on
the expected value for cross-platform consistency (no-op on Linux where
/tmp has no symlink prefix).
* fix(pi): keepalive reads current mode instead of constructor-time startingMode
The Switch handler updated controlledByUser but PiSession.pushKeepAlive()
still emitted the readonly startingMode every 2s, so a runner-started
session switched to local would flip back to remote on the next keepalive.
Replace readonly startingMode with a mutable mode field; add setMode()
that updates it and re-pushes keepAlive immediately. The Switch RPC
handler now calls setMode() before handleModeChange.
* fix(pi): runner no longer passes permission flags to Pi subprocess
After removing the Pi permission selector, the Pi command parser rejects
--permission-mode and ignores --yolo. But the shared buildCliArgs tail in
the runner still appended these flags for Pi sessions, making runner-
spawned Pi children exit before registering a session.
Guard the permission/yolo append with agent !== 'pi'.
* fix(pi): preserve provider identity when persisting selected Pi model
The hub's applySessionConfig normalized Pi's { provider, modelId } object
down to a plain modelId string for the shared session.model field, losing
the provider. On reload or next render, web's selectedPiModel lookup
matched by modelId alone — if two providers share a modelId, the wrong
one was highlighted, and subsequent model/thinking-level changes sent the
wrong provider to the Pi subprocess.
Add a provider-qualified piSelectedModel field to session metadata
(schema + persistPiSelectedModel mirroring persistPreferredPermissionMode).
Web's selectedPiModel now prefers the provider-qualified match and only
falls back to modelId-only matching when absent.
* fix(pi): model picker checkmark follows provider-qualified selection
selectedPiModel already resolves via provider+modelId, but the model
panel's currentPiModel still matched by modelId alone — so with two
providers sharing a modelId the checkmark pointed at the wrong row.
Reuse selectedPiModel directly.
* fix(pi): steer messages consumed immediately, not queued in pendingLocalIds
onUserMessage unconditionally pushed localId into pendingLocalIds, but a
steer (sent while piIsStreaming) does not start a new turn — so the
steer's localId was never drained by turn_start. The next normal prompt's
turn_start would consume the stale steer localId instead, leaving the
new prompt's bubble stuck in the queued bar.
Only queue localId for the prompt path. Steer path emits
messages-consumed immediately.
* fix(pi): clear stale thinking level when switching to non-reasoning model
The model-change effect early-returned when selectedPiModel.reasoning ===
false, leaving the previously-set effort (e.g. 'high') persisted on the
session. The UI hid the thinking picker for the non-reasoning model, but
the hub still forwarded the stale effort as set_thinking_level — with no
visible control to clear it.
Call onEffortChange(null) for non-reasoning models.
* fix(pi): return provider-qualified model in SetSessionConfig applied
The CLI handler returned only currentModel (bare string), so the hub's
applySessionConfig saw a non-object model and cleared
metadata.piSelectedModel via persistPiSelectedModel(session, null) —
undoing the provider that was just stored on the inbound config.
Return { provider, modelId } when both are known so the hub keeps the
provider-qualified metadata intact across active model changes.
* fix(pi): preserve piSelectedModel in bootstrapExistingSession metadata
The metadata whitelist rebuild kept piAvailableModels but omitted
piSelectedModel, so the first resume/local-handoff update dropped the
provider identity — after which web fell back to modelId-only matching
and could select the wrong provider for duplicate modelIds.
* fix(pi): await Pi confirmation before reporting model/effort applied
SetSessionConfig was fire-and-forget — transport.send wrote JSONL to
stdin and returned immediately. If Pi rejected an invalid provider/model
or thinking level, the hub still persisted the new value and the UI
reported success while Pi kept the old runtime state.
Use sendPiRpcAndWait so a failed set_model/set_thinking_level rejects
the web request and leaves the session config unchanged.
* fix(pi): resolve set_model RPC so awaited model switch does not time out
SetSessionConfig awaits sendPiRpcAndWait(set_model) before reporting the
model applied, but handleResponse's set_model branch updated state and
fell through without calling resolvePendingRpc. The pending RPC promise
then waited the full 10s timeout and rejected, making /sessions/:id/model
return 409 even though Pi accepted the change. Mirror every other branch
by resolving the pending RPC after updating currentModel/currentProvider.
* fix(pi): drain pending localId on turn_start only; throw when set_model suppressed
- loop.ts: split agent_start/turn_start branches. Pi emits both per prompt;
draining on both popped the FIFO twice and shipped an undefined localId to
the hub. agent_start now only sets thinking state; turn_start drains.
- runPi.ts: when set_model is suppressed (provider unknown), throw instead of
silently returning applied, so the hub returns 409 rather than persisting a
piSelectedModel Pi never received.
- loop.test.ts: assert agent_start does not drain; add regression test that a
single turn drains exactly one real localId.
* fix(pi): exclude Pi from generic Ctrl/Cmd+M model cycler
SessionChat fed piModelOptions into HappyComposer.availableModelOptions,
so the global Ctrl/Cmd+M shortcut ran getNextModelForFlavor over the Pi
list and called onModelChange with a bare modelId string. Pi needs
{ provider, modelId } to disambiguate duplicate model IDs across
providers; a bare string made runPi fall back to the first cached
provider match (wrong provider) or throw when the provider was unknown.
Drop the piModelOptions useMemo and pass undefined for Pi, mirroring
modelOptions.ts where the Pi branch already returns the current model
unchanged (no-op) when no custom options are supplied. Pi model changes
now go only through the dedicated provider-qualified picker (piModels).
* fix(pi): commit PiSession config only after Pi confirms the RPC
SetSessionConfig previously mutated piSession.currentModel /
currentProvider / currentThinkingLevel BEFORE awaiting
sendPiRpcAndWait(set_model / set_thinking_level). When Pi rejected the
value or the RPC timed out, the handler threw and the route returned
409, but PiSession kept the unconfirmed values; the 2s keepalive then
reported them back to the hub, where handleSessionAlive persisted a
model/effort Pi never accepted.
Resolve the requested model/effort into locals first, send the RPCs,
and only commit to PiSession after each await resolves. The null
(clear-model) path needs no RPC so it still commits immediately; the
unknown-provider path still throws without committing.
* fix(pi): apply startup model only after Pi confirms set_model
Two startup paths persisted the requested --model before Pi confirmed it:
1. handleGetState set session.currentModel = session.initialModel as soon
as get_state returned, using the unconfirmed startup model instead of
Pi's actual default. If the model was unavailable or rejected, the 2s
keepAlive reported it to the hub, which persisted/showed a model Pi
never accepted.
2. get_available_models then sent set_model fire-and-forget, so a Pi
rejection was never observed and currentModel stayed on the bad value.
Fix: handleGetState now reports Pi's real current model (newModel) while
a startup model is merely requested. get_available_models resolves the
provider from the cached list, awaits set_model, and commits
currentModel/currentProvider only on success — on rejection it logs and
keeps Pi's default. The await is fired detached so the
get_available_models RPC itself still resolves for ListPiModels.
* fix(pi): do not persist startup model before Pi confirms set_model
The startup --model still reached the hub unconfirmed via two paths the
previous Fix #13 left open:
1. bootstrapSession({ model: opts.model }) seeded the hub session model
at creation time, and SessionCache.handleSessionAlive persists every
non-undefined keepAlive model — so an unavailable/rejected model was
stored and shown before get_available_models/set_model ran.
2. PiSession constructor set this.currentModel = opts.model, so the very
first keepAlive (sent by startKeepAlive before any RPC confirms the
model) reported the unconfirmed value.
Pass model: undefined to bootstrapSession and start PiSession.currentModel
at null; opts.model is still captured as initialModel and applied/committed
only after get_available_models confirms it exists and set_model succeeds
(Fix #13). The hub now sees Pi's real current model from the first
get_state keepAlive and switches to the requested model only once accepted.
Also add sendPiRpcAndWait contract tests pinning the await<->resolve
symmetry (Fix #10): set_model/set_thinking_level/get_available_models must
resolve before timeout on a success response, and reject on a Pi error.
* fix(pi): apply startup effort only after Pi confirms set_thinking_level
runPi restored opts.effort straight into piSession.currentThinkingLevel
before startKeepAlive ran, and pushKeepAlive persists effort — so a
resumed/runner-spawned session could store/show a thinking level Pi
rejected or ignored. This is the effort analog of the startup-model
confirmation contract (Fix #13/#14).
Capture the requested effort into a local startupThinkingLevel instead of
mutating currentThinkingLevel up front. After transport.start() and the
get_state/get_available_models/get_commands sends, await set_thinking_level
and commit currentThinkingLevel + push a keepAlive only on success; on
rejection keep Pi's default (already reported by get_state). The await is
detached so the run loop is not blocked, and get_state is sent before the
set so its authoritative baseline lands first and cannot clobber the
confirmed value.
* fix(pi): omit unknown runtime config from keepalive, don't clear persisted state
Fix #14 changed PiSession.currentModel to start at null so the startup
--model was not leaked before confirmation. But the hub treats keepAlive
model:null as an explicit clear (sessionCache.ts only skips when the
field is undefined), so the first heartbeat (startKeepAlive runs before
get_state) now erased a resumed Pi session's persisted model/effort
before Pi reported its real state.
Distinguish "unknown" from "clear": currentModel/currentThinkingLevel
start undefined and keepAlive omits undefined fields (via
getKeepAliveRuntime), so the hub leaves persisted values alone until Pi
confirms. null remains an explicit clear and is still forwarded. Once
get_state/set_model/set_thinking_level confirm a value it is set and
reported normally.
* fix(pi): disable Ctrl/Cmd+M model cycler for Pi entirely
Fix #11 removed piModelOptions from availableModelOptions, assuming
getNextModelForFlavor('pi', model, undefined) was a no-op. It is not:
the Pi branch returns normalizeCurrentModel(model), i.e. the current
modelId as a bare string, so the shortcut still called onModelChange with
a bare modelId. That loses the provider and can pick the wrong cached
match, clear the model when session.model is empty, or hit 'provider is
not yet known'. Short-circuit the handler for Pi so model changes go only
through the dedicated provider-qualified PiModelPanel.
* fix(pi): persist piSelectedModel from get_state and startup set_model paths
Pi stores session.model as the bare modelId and relies on
metadata.piSelectedModel ({ provider, modelId }) to disambiguate
duplicate modelId values across providers in the web picker and
thinking-level filtering. But piSelectedModel was only written by the web
/sessions/:id/model path (hub persistPiSelectedModel). The runtime paths
that set currentModel/currentProvider — get_state, the startup
get_available_models set_model, and the set_model response — only
keepAlive'd the bare modelId, so a Pi session on Pi's default model,
resumed from CLI, or started with --model had no provider identity in
metadata and could render/filter against the wrong provider.
Add persistSelectedPiModel(session) (no-op unless both fields are known)
and call it after get_state, after a successful startup set_model, and
after the set_model response updates the fields. This mirrors what the
web picker already does.
* fix(pi): default startingMode to remote — Pi has no local TUI path
A terminal `hapi pi` launch defaulted to startingMode 'local' and marked
the session controlledByUser, but Pi only runs as `pi --mode rpc` with
piped stdio — there is no local terminal/TUI input path like Claude/Codex
have. The terminal user could not drive the session and the web treated
it as local-controlled, so the first terminal Pi session was stuck until
manually switched from the web.
Default to 'remote' so the session is immediately drivable from the web.
An explicit opts.startingMode (runner path) still takes precedence.
* fix(pi): resume with remote startingMode — no local TUI path
The previous Fix #19 changed the `hapi pi` default to remote, but
`hapi resume` still passed startingMode: 'local' into runPi for Pi
sessions, re-introducing the same unsupported local-control state on the
resume path: setControlledByUser publishes controlledByUser while Pi has
no terminal/TUI input, hiding/rejecting remote-only controls until a web
switch. Pass 'remote' here too and update the resume test accordingly.
* fix: restore e2e/scratchlist.spec.ts deleted from main by mistake
The earlier "remove unrelated E2E harness" commit (d1e5b4c) deleted the
whole e2e/ directory this branch had added, but scratchlist.spec.ts is a
main-branch Playwright spec (the only file under playwright testDir
./e2e). Its removal left `bun run test:e2e` with no tests to run while
the script and playwright.config.ts still point at that directory.
Restore scratchlist.spec.ts from main; the unrelated harness files
(HARNESS.md, harness.*, integration/*.mts) that were genuinely
branch-only additions stay removed.
---------
Co-authored-by: pi <pi@local>
Co-authored-by: Claude <noreply@anthropic.com>
|
||
|
|
17439ae02c |
fix(cli): bypass proxy for loopback addresses at CLI entrypoint (#868)
Bun's fetch and node:http honor HTTP_PROXY/HTTPS_PROXY env vars, which can route loopback traffic through a configured proxy (e.g. Surge/Clash). When NO_PROXY doesn't explicitly exclude localhost, this breaks loopback communication: SessionStart hooks fail to arrive (transcripts don't sync, web UI stays empty), runner control client times out, and MCP server connections fail. Normalize NO_PROXY at the CLI entrypoint to always cover loopback (localhost, 127.0.0.1, ::1). Child processes inherit the patched env so their loopback traffic is covered too. Non-loopback traffic continues using the configured proxy. Supersedes the runner control client workaround from #563. |
||
|
|
edc3acc3e2 |
fix(cursor): requeue user message on transient agent exit (auth, rate limit) (#823)
* fix(cursor): requeue user message on transient agent exit (auth, rate limit)
cursorLegacyRemoteLauncher.runMainLoop popped a user message off the queue
before spawning `agent` and silently discarded it whenever `agent` exited
non-zero (auth expiry, rate limit, transient network). The wrapper logged
the failure at debug level only, never surfaced it to the web UI, and
emitted `ready` as if a normal turn had ended.
Capture stderr from the spawned process; classify exit-1 with a transient
signature (Authentication required, rate limit, ETIMEDOUT, ECONNRESET,
EAI_AGAIN) as recoverable; re-head the message via `queue.unshift`, surface
a friendly banner via `sendSessionEvent({type:'message',...})`, and backoff
~2s before the loop picks it up again. Cap at 5 consecutive transient
failures, after which the message is dropped with a clear "resolve and
resend" event so we never spin forever on a genuinely broken auth.
Non-transient non-zero exits also surface the stderr to the UI now (instead
of only the local ring buffer), so a real crash is visible to the operator.
Backoff is overridable via CURSOR_LEGACY_TRANSIENT_BACKOFF_MS for tests.
Tests cover: success path, transient auth requeue + banner, rate-limit
banner, non-transient crash surfaced without requeue, and the 5-failure
drop cap.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cursor): preserve slash-command isolation on requeue; wait for stderr flush
Two findings from the cold-review bot on the requeue path:
1. `enqueueCursorUserMessage` uses `pushIsolated` for pass-through slash
commands (e.g. `/compress`) so they never batch with sibling prompts.
The transient-requeue path used plain `unshift`, which dropped the
isolate bit and allowed the next collected batch to merge the slash
command with a sibling - changing command semantics. Add
`MessageQueue2.unshiftIsolated` and use it when the popped batch was
isolated or when `parseCursorSpecialCommand` recognises the message.
2. `runAgentProcess` resolved on `child.on('exit', ...)`. Node may emit
`exit` while the stderr pipe is still draining, so a fast "auth
required" error printed-and-exited could be classified as
non-transient with empty stderr and silently drop the user message -
the exact bug this PR was supposed to fix. Resolve on `close` instead,
which waits for stdio streams to flush.
Adds a unit test that requeues `/compress` after a transient auth failure
and asserts the second spawn still receives the slash command alone (not
batched with a sibling).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cursor): restrict transient retry to exit code 1 only
Upstream codex review #823 (Minor): the helper treated any non-zero exit
with matching stderr as transient, which could requeue a signal-killed
(SIGTERM 143, SIGKILL 137) or crashed (SIGABRT 134) process whose stderr
happens to contain a keyword like "rate limit". Documented contract is
exit-1-for-transient; tighten the classifier accordingly.
Adds regression test covering exit 143 + rate-limit stderr → no retry.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cursor): clean up transientBackoff abort listener on timer completion
Upstream codex review #823 (Minor): transientBackoff added an abort
listener with { once: true } but only removed it when the abort fired.
Because the launcher reuses one AbortController, repeated transient
retries accumulated stale listeners until the next abort.
Switch to a single completion path that clears the timer AND removes the
abort listener whichever side wins.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cursor): cap in-memory stderr capture at 8 KB
Upstream codex review #823 (Minor): runAgentProcess accumulated every
stderr chunk for the full child lifetime. A noisy `agent` failure could
grow CLI process memory without bound even though only the first 400
chars are ever displayed. Cap the retained copy at 8 KB; debug log of the
full stream is unchanged.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
|
||
|
|
30564601ed |
fix(cli,web): hide Windows spawn windows and show queued attachments (#765)
* fix(cli,web): hide Windows spawn windows and show queued attachments * fix(web): preserve attachment-only queued edit text |
||
|
|
449cf6af0a |
feat(cli): wire Cursor /summarize and /clear slash builtins (#747)
* feat(cursor): wire /summarize and /clear slash builtins for remote sessions Seed cursor builtins for web autocomplete, parse summarize/clear in cursorRemoteLauncher (pass-through to agent -p; reject /clear with args). Fixes tiann/hapi#738 Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor): isolate slash commands before message queue batching Parse summarize/clear at enqueue time (runCursor) with pushIsolateAndClear so waitForMessagesAndGetAsString never merges a slash with the next prompt. Adds queue policy tests for invalid /clear + following message. Addresses PR #747 review. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor): preserve pending messages when isolating slash commands pushIsolateAndClear() wipes the entire queue, so a normal prompt queued before /summarize or /clear would be silently dropped. Add pushIsolated() - isolation without clearing - and route Cursor slash commands through it instead. Adds queue tests covering the preserve-then-isolate path. Addresses PR #747 review. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
df35a8c523 | fix(test): isolate integration tests from production hub via temp hub globalSetup (#734) | ||
|
|
d5a67b717c |
feat(voice): dynamic settings voice picker with safe fallback + preview (#690)
* feat(voice): dynamic settings voice picker with safe fallback + preview * fix(voice): honor picker with configured agent and stop preview on unmount * fix(voice): apply PR review feedback for agent selection and preview cleanup |
||
|
|
0006d04f9e | feat: support multiple workspace roots (#584) | ||
|
|
6df84df756 | fix(hapi): consolidate approved web and Codex recovery fixes (#578) | ||
|
|
8185f0287e | feat(web,hub): cancel queued messages (#568) | ||
|
|
23c0fa4872 | fix(cli): hide Windows taskkill popups during process cleanup (#569) | ||
|
|
0cfc3b4ed2 | fix(cli): preserve codex config args on Windows | ||
|
|
010dc41369 |
feat: workspace browser with --workspace-root opt-in scoping (#526)
* feat(web): add workspace browser for multi-directory navigation Add /browse route with a folder browser that lets users navigate filesystem directories on connected machines and launch sessions from any folder. Supports saved workspace paths and direct path input. The "Start Session" action pre-fills the NewSession form. - CLI: register machine-level `list-directory` RPC handler - Hub: add POST /machines/:id/list-directory route - Web: add WorkspaceBrowser component with git repo detection - Web: add /browse route with navigation from sessions sidebar - Web: support initialDirectory/initialMachineId in NewSession Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add --workspace-root opt-in scoping for /browse and session spawn Adds a single new flag, \`--workspace-root <path>\` (with \`~\` / \`~/foo\` expansion), on \`hapi runner start\` and \`hapi runner start-sync\`. When set: - The runner reports the path in machine metadata. - The list-directory and spawn-session RPC handlers reject paths outside the root, so the web UI can't escape the configured tree even if someone crafts a request manually. - The /browse page in the web UI auto-opens that root, restricts the breadcrumb / go-up to its subtree, and shows directory entries with git-repo annotations. - The /sessions/new form keeps its existing free-text directory input plus autocomplete + recent-paths chips, and gains a small "Browse" button (next to the input) that opens /browse for picking a folder. - Reconnect-time metadata sync ensures stale records get the field filled in (or cleared when the flag is dropped on a later restart), so the hub state matches the CLI's intent. When unset: - Runner behaves like the legacy hapi (no scoping, no browse feature). - /browse renders an informative state pointing at the flag instead of blocking the user. - The /sessions/new form looks identical to the pre-change behavior; the "Browse" button is hidden. Includes a startup banner so \`runner start-sync\` no longer looks like it hung, and surfaces the workspace-root sync result on stdout. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(hub): preserve workspaceRoot when rehydrating machines from store MachineCache.refreshMachine() rebuilt the metadata object from an explicit field allowlist, so any field not in the list (including the new workspaceRoot) was silently dropped on every read — even though it was correctly written to the store. Add workspaceRoot to the zod schema, the Machine interface, and the hand-rolled projection. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(web): friendlier empty state on /sessions When there are zero sessions the page used to be a vast blank rectangle with just the "0 sessions in 0 projects" caption. Render a centered empty state instead: a calendar/agenda icon, a short heading and hint, and two buttons — "Start a session" (→ /sessions/new) and "Browse workspace" (→ /browse). SessionList gains an optional onBrowse prop. Router wires it on the sessions page so the secondary button resolves; other callers can leave it unset to hide that button. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: document --workspace-root flag in cli/README and root README Add a short paragraph under "Runner management" in cli/README.md explaining what \`--workspace-root\` enables (scoped /browse tree, list/spawn enforcement, tilde expansion) and that omitting it keeps the legacy behavior. Mention the workspace browser in the top-level README's Features list. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: address PR #526 review feedback Three findings from the review bot: 1. [Major] Workspace-scope check was lexical only. With workspaceRoot = /safe, a symlink such as /safe/out -> /etc would pass the relative- path test and let list-directory / spawn-happy-session reach paths outside the configured root. realpath the workspaceRoot at construction time, and resolve every incoming path through realpath (walking up to the nearest existing parent for spawn targets that haven't been created yet) before the containment check. 2. [Minor] \`hapi runner start --workspace-root\` with no value used to drop the flag silently and start the runner unscoped. Now treats a missing or flag-shaped next argument as an error. 3. [Minor] /sessions/new's "Browse" button always opened /browse using localStorage's last-used machine, ignoring the user's current selection. NewSession already passes machineId in its callback; forward it through the /browse search params and seed WorkspaceBrowser with it. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(cli): gate list-directory RPC behind --workspace-root opt-in Without a configured workspaceRoot, isWithinWorkspaceRoot() returns true unconditionally, leaving the new list-directory RPC able to enumerate any path on the runner. The Web UI already hides Browse for these machines, but the backend should enforce the opt-in too. Refuse the RPC up front when no workspace root is configured. --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
32755f9056 | feat(web): show queued status for messages pending inference (#492) | ||
|
|
2f61852a9e | refactor: extract local agent spawn helper and unify process tree cleanup (#410) | ||
|
|
b802092bf7 | fix(cli): treat any exit code as expected when abort was requested (#347) | ||
|
|
397ef35f5c | fix(cli): preserve requested cwd for runner-spawned sessions (#315) | ||
|
|
caa76826f4 | fix(cli): preserve invoked cwd for local launcher (#299) | ||
|
|
55f08bd562 | fix(cli): hide windows console windows for runner/claude subprocesses (#242) | ||
|
|
37e10a831b |
feat: rename server package to hub
Rename the `server/` directory to `hub/` and update all references across CLI, docs, web, and workspace configuration. |
||
|
|
1b22fe0f82 |
feat: add CLI-server protocol version mismatch detection
- Define PROTOCOL_VERSION constant in shared/src/version.ts - Server sets X-Hapi-Protocol-Version header on /cli/* responses - Server includes protocolVersion in /health endpoint - CLI extracts serverProtocolVersion from API responses - CLI shows version mismatch hints in both directions - Add tests for error utilities and version extraction close #104 |
||
|
|
442f6765b3 |
fix: prevent Gemini orphan processes when switching modes
Kill entire process tree instead of just the direct child to prevent orphans when Gemini CLI ignores SIGTERM. Implements killProcessTree that collects all PIDs synchronously, signals children first, then waits for termination with auto-escalation to SIGKILL after 2 seconds. Also removes Node.js signal option from spawn since built-in abort handling doesn't handle grandchildren. |
||
|
|
9e335fa305 |
refactor: rename configuration variables for clarity
Standardize naming across CLI and server components: - CLI: serverUrl → apiUrl, HAPI_SERVER_URL → HAPI_API_URL - Server: webapp* → listen*, miniAppUrl → publicUrl, WEBAPP_* → HAPI_LISTEN_*, WEBAPP_URL → HAPI_PUBLIC_URL - Rename serverUrlInit.ts → apiUrlInit.ts with updated logic for backward compatibility - Update all imports, function calls, and documentation accordingly |
||
|
|
0228146b99 | refactor: rename daemon to runner throughout codebase | ||
|
|
3f465cd47d |
fix: escape newlines in shell arguments on Windows
close #70 |
||
|
|
53e4de6684 | feat: add file upload support | ||
|
|
9f2da5f8ae | fix: suppress git stderr when running in non-git directory | ||
|
|
1665c63d95 |
fix: add retry logic to daemon machine registration for transient connection errors
Add exponential backoff retry mechanism to handle ECONNREFUSED errors when the server isn't ready yet during daemon startup. This includes: - New errorUtils module with error classification helpers - withRetry function in time.ts supporting configurable exponential backoff - Machine registration retry with sensible defaults (60 attempts, 1-30s delays) - Error refactoring to consolidate extractErrorInfo utility close #35 |
||
|
|
9dc69d1e80 |
feat: add serverUrl configuration support with settings.json fallback
Implement serverUrl initialization following the cliApiToken design pattern: - Environment variable HAPI_SERVER_URL (highest priority, allows temporary override) - settings.json serverUrl field (user persistent configuration) - Default value 'http://localhost:3006' (fallback) Changes: - Add serverUrl field to Settings interface (persistence.ts) - Convert serverUrl to private property with getter/setter (configuration.ts) - Create initializeServerUrl module to load from settings (serverUrlInit.ts) - Integrate serverUrl initialization in tokenInit flow (tokenInit.ts) - Skip auto-start when serverUrl is configured in settings (autoStartServer.ts) |
||
|
|
94823b7a8b |
feat: add auto-start server feature for CLI
- Added /health endpoint to server for readiness checks (no auth required) - Created autoStartServer module that auto-starts server when: - HAPI_SERVER_URL not set (using default localhost:3006) - cliApiToken exists in settings (server previously used) - Port 3006 is not currently listening - Server runs as child process (not daemon) and exits when CLI exits - Integrated maybeAutoStartServer() into hapi, codex, and gemini commands |
||
|
|
754d9dc0e8 |
feat: auto-detect git worktree context from git commands
When HAPI_WORKTREE_* environment variables are not set, fall back to probing git to detect if running inside a worktree. This enables worktree features to work automatically without explicit env vars. |
||
|
|
ce6234da3f | fix: prevent race condition in MessageQueue2 wait logic | ||
|
|
c35a5ce827 |
feat: add git worktree session support with improved UI
Implement comprehensive worktree session support allowing users to spawn sessions in temporary git worktrees. Includes backend worktree management, full-stack integration, and refined UI for session type selection. Backend: - Add worktree creation/removal utilities with branch management - Track worktree metadata (basePath, branch, name, path) in session metadata - Automatic cleanup of worktrees when sessions fail or exit - Enhanced error handling with stderr tail logging UI improvements: - Redesign session type toggle with improved alignment and spacing - Move worktree description inline with label for cleaner layout - Add branch name input field that appears when worktree mode selected - Auto-focus on worktree input when switching modes - Reduce gap between radio options from gap-3 to gap-1.5 - Update descriptive text and placeholders for clarity Integration: - Thread worktree parameters through API client, RPC handlers, and daemon - Add worktreeEnv utility to read worktree info from environment - Update session spawning to support both simple and worktree modes |
||
|
|
b497abda98 | refactor: extract CLI argument parsing into shared utility | ||
|
|
5d79a3f1ef | refactor: extract spawn abort handling into shared utility | ||
|
|
702072e9ba |
refactor: extract process management utilities for cross-platform support
Consolidate process lifecycle management (kill, check alive) into a new utility module with proper Windows/Unix handling, replacing scattered process.kill() calls with consistent async APIs. |
||
|
|
76b84a0b52 |
refactor: unify bun compiled detection with windows support
- Add shared isBunCompiled() function for consistent runtime detection - Support Windows virtual filesystem paths (/~BUN/) alongside Linux/macOS (/$bunfs/) - Use Bun.main for reliable detection instead of process.argv[1] - Remove redundant $bunfs checks from cli/src/index.ts - Update cli/src/utils/bunRuntime.ts to use shared detection function - Create server/src/utils/bunCompiled.ts for server-side compilation check |
||
|
|
4314aececd |
refactor: migrate from tsx to bun as TypeScript runtime
Remove tsx dependency and update all dev scripts and documentation to use bun as the primary TypeScript runtime for development. Consolidate process detection logic in daemon.ts to check for dev mode via src/index.ts regardless of runtime. |
||
|
|
1a23bfa430 |
refactor: remove custom executable support and simplify Claude CLI resolution
Remove support for custom executable paths and bundled Claude versions, including deprecated environment variables HAPI_USE_BUNDLED_CLAUDE and HAPI_USE_GLOBAL_CLAUDE. This simplifies the codebase to rely only on the global Claude CLI installation. Updates Claude Code spawning logic to remove special handling for .js/.cjs files, adds configurable BUN_BE_BUN environment variable handling, and streamlines path resolution to throw an error when Claude Code CLI is not found on PATH. |
||
|
|
d057daabfe |
chore: migrate cli distribution from npm to bun executable
Migrate HAPI CLI from npm-based distribution to Bun single-executable format: - Remove npm bin wrappers (bin/happy.mjs, bin/happy-mcp.mjs) - Simplify package.json: remove npm publish config (exports, main, module, types, files, publishConfig) - Update bin entry to point to TypeScript source (src/index.ts) - Migrate shebang from Node to Bun (#!/usr/bin/env bun) - Simplify build scripts: remove npm-specific steps (pkgroll, prepublishOnly, release-it) - Update spawnHappyCLI to support compiled binaries and development TypeScript mode - Update daemon/doctor diagnostics for new process detection logic - Production: use `bun build --compile` for single-executable releases - Development: run TypeScript directly via `bun src/index.ts` or `tsx src/index.ts` |
||
|
|
ab06426773 |
feat: add source file execution and fix function name reference
- Add support for running CLI from TypeScript source when using tsx or similar tools - Fix outdated happy__change_title reference to hapi__change_title in codex prompt |
||
|
|
4f03f29ac3 |
docs: rebrand Happy to HAPI and add component documentation
This commit rebrands the project from "Happy" to "HAPI" throughout the codebase, including documentation, comments, logs, and tool references. It also adds comprehensive README files for the server and web components, clarifies the monorepo structure in AGENTS.md and root README.md, and removes the outdated roadmap.md file. Changes include: - Rebrand references from Happy to HAPI in CLI, server, and web components - MCP tool names updated from mcp__happy__ to mcp__hapi__ - Process/service names updated consistently - New server/README.md with deployment and configuration guide - New web/README.md with stack and development instructions - Updated root README.md with quickstart guide - Updated AGENTS.md with cleaner structure documentation - Removed cli/roadmap.md (now superseded by documentation) |
||
|
|
17eeba10d6 |
feat(cli): add Bun single executable binary support
Enables building hapi as standalone Bun-compiled executables for macOS, Linux, and Windows (x64/arm64). Adds build script, bootstrap entry point, runtime asset management, and automatic deployment of bundled tools (ripgrep, difftastic). Includes MCP stdio bridge support and proper environment handling for compiled binaries. Updates documentation with build and installation instructions for single executable distribution. |
||
|
|
80725a2d34 |
feat(cli): add Bun runtime support for ripgrep and CLI spawning
Replace hardcoded 'node' commands with process.execPath to support Bun runtime alongside Node.js. Add runtime detection and entrypoint resolution for Bun. Update documentation to reflect multi-runtime support. |