* test(codex): add web event rendering harness
* fix(codex): surface plan updates in web
* fix(codex): render MCP tool calls in web
* fix(codex): improve terminal and context display
* fix(codex): format token usage events
* fix(codex): show status context in web
* fix(codex): preserve tool result errors
When a user selects a different Gemini model from the Web UI mid-session,
the running `gemini --experimental-acp` process kept using the model it
was launched with. The Web UI reflected the new selection, but the next
response was still produced by the original model.
Changes:
- AcpSdkBackend: add `setModel` wrapping the `session/set_model` RPC.
Errors propagate as standard rejections, matching every other
`sendRequest` call in this file.
- geminiRemoteLauncher: detect model changes between turns and call
`backend.setModel` on the live ACP session — no process restart, no
MCP reload. If the running gemini-cli build returns method-not-found,
the launcher learns once, surfaces a single advisory message, then
silently honors the previous model for the rest of the session.
- AgentSessionBase.pushKeepAlive: small helper used by runGemini to
broadcast new config to the hub immediately after `set-session-config`.
- Both layers serialize the switch — the launcher attempts `setModel`
only between batches, and `AcpSdkBackend.setModel` defensively awaits
`waitForResponseComplete()` before issuing the RPC.
Tests:
- New `geminiRemoteLauncher.test.ts` covers: setModel called between
turns when the model differs; not called when unchanged; the
method-not-found capability latch; transient errors continue with the
previous model; setModel is serialized after the prior prompt.
- `runGemini.test.ts` asserts pushKeepAlive fires from the
`set-session-config` handler.
* 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>
* fix(runner): prevent ghost sessions from orphaned spawn webhooks
spawnSession() registers a tracked session entry before the child's
"Session started" webhook arrives. When the 15s webhook timeout fires,
only pidToAwaiter / pidToErrorAwaiter are cleared; the
pidToTrackedSession entry is left in place and the detached child
keeps running. If the child eventually starts and reports its webhook,
onHappySessionWebhook() still finds the stale tracking entry and
promotes the orphan into a normal runner-managed session, surfacing
a message-less "ghost session" in the web UI.
This is easy to reproduce on opus[1m] --resume: observed real-world
case where four rapid "resume" clicks produced four orphan children
that all reported their webhooks ~60 minutes later, creating four
ghost sessions on the dashboard.
Three-part fix:
1. Make the webhook timeout configurable via
HAPI_RUNNER_WEBHOOK_TIMEOUT_MS (default unchanged at 15_000). Users
on slow models / large resumes can raise the ceiling so the
timeout never fires in the first place.
2. On timeout, also delete the pidToTrackedSession entry and SIGTERM
the child, so a late webhook cannot promote the orphan.
3. Defence in depth: if onHappySessionWebhook() receives a webhook
from a PID that is not tracked but whose payload claims
startedBy: 'runner', ignore it and SIGTERM the child. Genuine
terminal-launched children correctly report
startedBy: 'terminal', so this branch cannot false-positive on
them.
* fix(runner): use tree-kill on timeout and clean up worktree for orphans
Address review feedback on the kill path and worktree cleanup:
1. Timeout handler: replace bare `happyProcess.kill('SIGTERM')` with
`killProcessByChildProcess(happyProcess)` so the entire process tree
(wrapper + detached agent grandchildren) is reaped, matching the
existing `stopSession()` behaviour.
2. Orphan webhook handler: replace bare `process.kill(pid, 'SIGTERM')`
with `killProcess(pid)` for proper SIGTERM → SIGKILL escalation.
A ChildProcess reference is unavailable here (tracking entry already
removed), so tree-kill is not possible — but the timeout handler
should have already tree-killed the group; this is defence-in-depth.
3. Worktree leak: when a worktree session times out, register a
one-shot `exit` listener on the child process to run
`cleanupWorktree()` after the child actually exits. Previously
`maybeCleanupWorktree('spawn-error')` would skip cleanup because
the child was still alive at that point, and `onChildExited()` had
no worktree awareness after the tracking entry was deleted — so the
worktree leaked permanently.
---------
Co-authored-by: fengtian <fengtian@users.noreply.github.com>
* refactor(agent): extend AgentMessage and CodexMessage unions with reasoning variant
Add a reasoning variant to the shared AgentMessage union that flows
out of the ACP backend, and pass it through to CodexMessage so the
existing web reducer (which already renders { type: 'reasoning' }
parts as collapsible blocks) can consume ACP-sourced thoughts
identically to Codex.
No behavior change yet: the ACP handler still drops thought chunks,
and the remote launchers receive the new variant as a no-op. The
behavior is wired up in the following commit.
* feat(acp): forward agent_thought_chunk as reasoning message
Route ACP thought chunks to the session as reasoning AgentMessages so
OpenCode and Gemini thinking output reaches the web UI's Reasoning
block, matching the existing Codex behavior.
Thought chunks are emitted inline without flushing the pending text
buffer — text and thought live on independent interleave lanes, so
splitting a live text segment on every thought arrival would be
wrong. The inline-emit ordering is documented alongside the test
that depends on it.
extractTextContent is not reused for thought content: its
assistant-audience filter is correct for regular message chunks but
would silently drop thoughts annotated with a non-assistant audience,
which have no meaningful audience to filter against. A direct text
block shape check handles the narrower need.
In the remote launchers, reasoning is surfaced to the local terminal
buffer as a truncated system-role hint prefixed with [Thinking],
matching how the Codex flavor already displays reasoning chunks
in-terminal without mixing them into the assistant reply stream.
The skill listing only scanned ~/.agents/skills and ~/.claude/skills
for user-level skills, ignoring ~/.codex/skills where Codex users
commonly store their skills. Add ~/.codex/skills to getUserSkillsRoots()
so these skills appear in the web UI $ autocomplete.
Hidden directories (starting with .) inside the skills root are still
skipped (e.g., .system/).
via [HAPI](https://hapi.run)
Co-authored-by: HAPI <noreply@hapi.run>
* feat(hub,cli): forward permissionMode on session resume
When a session is resumed, the cached permissionMode is now forwarded
through the Hub → Runner → CLI pipeline via a new --permission-mode
flag. Previously the mode was lost on resume, resetting to 'default'.
Each CLI flavor validates the flag value against its own allowed
permission modes (e.g. CLAUDE_PERMISSION_MODES) and rejects unknown
values. The existing --yolo flag is preserved as a shorthand.
* refactor(cli): extract buildCliArgs from startRunner
Extract the CLI argument construction logic into a standalone
exported function so it can be unit-tested independently.
No behavior change.
* test(cli): add buildCliArgs unit tests for --permission-mode
Verify that the runner correctly forwards valid permission modes
via --permission-mode, rejects invalid values, and falls back to
--yolo when no permission mode is set.
* fix(cli): let --permission-mode take precedence over --yolo
When both flags are present, --permission-mode was silently
overwritten by a later --yolo. Guard legacy flag branches with
a hasExplicitPermissionMode check so the explicit flag wins.
* feat(cli): support extra headers for hub requests
* fix(types): normalize missing session fields to null
* refactor(cli): simplify socket extra headers config
extractSDKMetadataAsync() calls query() which sets
CLAUDE_CODE_ENTRYPOINT='sdk-ts' on the current process env.
When claudeLocal() later spawns the claude CLI, the child
inherits this env var, causing Claude Code to treat the
session as SDK-launched. This makes the session invisible
to `claude --resume`.
Strip CLAUDE_CODE_ENTRYPOINT from the child env so the
local spawn uses its own default entrypoint.
Closes#450
The process is spawned with `shell: process.platform === 'win32'` while including dynamic values (e.g., `opts.sessionId`) in `args`. On Windows, shell invocation can introduce command parsing/injection risks if arguments are not strictly validated/escaped.
Affected files: opencodeLocal.ts
Signed-off-by: tuanaiseo <221258316+tuanaiseo@users.noreply.github.com>
* fix(cli,hub): resolve typecheck errors in codex reasoning effort and notification test
- Cast `getModelReasoningEffort()` return (string | null) to
`ReasoningEffort | undefined` at three call sites in
codexLocalLauncher.ts and runCodex.ts where the narrower type is
expected.
- Add missing `modelReasoningEffort: null` default in
notificationHub.test.ts to satisfy the Session type contract.
These errors were introduced in 79a13d2 and have been failing CI on
main since 2026-04-10.
* fix(cli): add missing getModelReasoningEffort to test mock session
The test stub in codexLocalLauncher.test.ts was missing the
getModelReasoningEffort method added in 79a13d2, causing runtime
TypeError in CI.
* fix(cli): filter raw SSE event JSON from leaking into chat messages
Two types of internal JSON were appearing as visible text in Telegram
Mini App and web chat:
1. `rate_limit_event` — the rate limit parser returned `null` for
unknown statuses, causing raw JSON to pass through as assistant text.
Changed to `{ suppress: true }` so all rate_limit_event variants are
handled; new statuses that need display can be added explicitly.
2. `{ type: "output", data: { ... } }` — internal session metadata
envelopes leaked through the ACP text chunk pipeline. Added an
`isInternalEventJson` filter that catches JSON objects with known
internal envelope types (output, event, queue-operation) before they
enter the text buffer.
Closes#386
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(cli): narrow internal event filter to match only leaked metadata shape
Address review feedback: the broad type-based filter could suppress
legitimate assistant JSON with type "event" or "queue-operation".
Narrow the check to only match the specific leaked metadata envelope:
{ type: "output", data: { parentUuid, sessionId, userType } }
Add negative tests confirming other JSON types pass through.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(cli): suppress malformed rate_limit_event without resetsAt
Address review: rate_limit_event payloads missing resetsAt still leaked
as raw JSON because parseRateLimitText returned null before reaching the
unknown-status suppress. Move the allowed check before the resetsAt
guard and suppress malformed payloads instead of passing them through.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(cli): handle parentUuid: null in internal event filter
Root/first-message metadata envelopes have parentUuid: null rather than
a string, so the filter missed them. Accept both string and null.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* test(cli): add e2e regression tests for metadata envelope filtering
Add AcpMessageHandler tests that verify leaked { type: "output", data }
metadata envelopes (both parentUuid string and null) are dropped before
reaching the text buffer.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(cli): clear buffered prefix when cumulative metadata chunk arrives
When a leaked metadata envelope arrives as cumulative streaming chunks
(first an incomplete JSON prefix, then the full blob), the filter
dropped the full chunk but left the prefix in bufferedText. Clear the
buffer when the detected internal JSON starts with the buffered prefix.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(cli): round resetsAt to integer for pipe-delimited format
The web-side regex uses \d+ to parse the timestamp, so a float value
would silently fail to match. Apply Math.round to ensure integer output.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(cli): clear buffered prefix for cumulative rate_limit_event chunks
The prefix-clearing logic only applied to the isInternalEventJson
branch but not to the parseRateLimitText branch, so cumulative
rate_limit_event chunks could leave a raw JSON prefix in the buffer.
Hoist the prefix check before both filters and apply uniformly.
Add regression tests for suppressed and displayable cumulative
rate_limit_event scenarios.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
---------
Co-authored-by: HAPI <noreply@hapi.run>
* fix(cli): continue execution after plan mode in YOLO/bypassPermissions
In YOLO mode (bypassPermissions), exit_plan_mode was auto-approved like
any other tool, skipping the PLAN_FAKE_RESTART injection that tells the
agent to continue. Combined with isAborted() always returning true for
exit_plan_mode, claudeRemote exited the query loop and stalled waiting
for user input.
Fix: in the bypassPermissions branch of handleToolCall, intercept
exit_plan_mode specifically — inject PLAN_FAKE_RESTART into the message
queue and return deny with PLAN_FAKE_REJECT, matching the behavior of
the normal approval flow.
Closes#172
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* test(cli): remove unused isPlanTool helper
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
---------
Co-authored-by: HAPI <noreply@hapi.run>
* refactor(web): extract normalizeTimestamp helper in presentation
Extract the shared seconds-vs-milliseconds normalization logic into
a private `normalizeTimestamp()` helper. No behavior change —
`formatUnixTimestamp()` produces identical output.
* refactor(web): return AgentEvent from parseClaudeUsageLimit
Change return type from `number | null` to `AgentEvent | null` so
the caller doesn't need to construct the event object. No behavior
change — the same `limit-reached` event is produced.
* feat(cli): convert rate_limit_event to standardized text format
Parse undocumented Claude `rate_limit_event` JSON in the CLI adapter
layer (AcpMessageHandler) before it reaches the web.
Converted text format (pipe-delimited):
- "Claude AI usage limit warning|{ts}|{pct}|{rateLimitType}"
- "Claude AI usage limit reached|{ts}|{rateLimitType}"
Status handling:
- `allowed_warning` → warning text with utilization and limit type
- `rejected` → reached text with limit type
- `allowed` → silently suppressed (noise)
- unknown statuses → passed through as-is (forward-compatible)
* feat(web): display rate limit warnings with limit type
Parse standardized pipe-delimited text from the CLI adapter into
`limit-warning` and `limit-reached` events, displaying the rate
limit type (5-hour, 7-day) when available.
- `limit-warning`: "⚠️ Usage limit 90% (5-hour) · resets 2:00 PM"
- `limit-reached`: "⏳ Usage limit reached (5-hour) until 4/2/2026"
- Backward compatible: `limit-reached` without limitType still works
The `reached` regex uses `(?:\|([^|]*))?$` to optionally match the
limitType field, maintaining compatibility with the existing format.
* refactor(cli): move rate limit parsing out of flushText
Remove rate limit detection from flushText() back to plain buffer
flush. The next commit will re-add parsing at the chunk level
(handleUpdate) where it can intercept before buffer merging.
Includes failing tests that demonstrate the mixed-chunk bug:
when a rate_limit_event chunk arrives in the same turn as normal
text, the JSON leaks into the merged buffer.
* fix(cli): intercept rate_limit_event at chunk level, not flush
Move rate limit detection from flushText() to the agentMessageChunk
handler so it fires before the chunk enters the shared text buffer.
Previously, a rate_limit_event chunk arriving in the same turn as
normal text would merge into bufferedText and leak as raw JSON.
Now the chunk is intercepted individually, the existing buffer is
flushed first (preserving prior text), and the converted message
is emitted separately.
* fix(cli): skip flush when suppressing allowed rate_limit_event
Only flush the text buffer when the parsed event will actually be
displayed. Suppressed events (e.g. status: 'allowed') now return
immediately without flushing, preventing a text → allowed → text
sequence from splitting one answer into two agent-text blocks.
* fix(web): include limitType in limit-reached reconcile key
Without this, reprocessing a message from the old format (no
limitType) to the new typed format reuses the stale block and
the (5-hour)/(7-day) suffix never appears.