mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-24 04:47:03 +00:00
38b6540bedee00a1e9e79d12af15a8a9b73f0f80
1794
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
38b6540bed |
feat(agy): show Antigravity's tool calls as the canonical tool cards (#2330)
* docs(agy): say request-review follows agy's toolPermission setting On agy acp, HAPI's request-review is agy's default mode, which asks only as agy's own toolPermission setting says. With toolPermission set to always-proceed, agy runs commands and edits without asking, so HAPI shows no approval prompts, and HAPI cannot override that per session. The guide now says so, and says what acceptEdits and plan do on agy. It also notes that always-proceed approves a request a PreToolUse hook marks force_ask: agy sends it as an ordinary approval request, with nothing that says it came from a hook. * feat(acp): carry the agent's own tool name and args on tool calls Some ACP agents send their own tool name and args next to the standard title, kind and rawInput (agy: name, args). Pass them through as nativeName and nativeArgs so a launcher can pick a card by the real tool instead of a free-text title. Agents that send no name are unaffected. * feat(agy): show agy ACP tool calls as the canonical tool cards Map agy's own tool names to the cards the other flavors use: run_command to Bash (with a clean stdout result), read_file to Read, edit_file to an Edit diff, write_file to Write, search_web to WebSearch, invoke_subagent to Task and call_mcp_tool to the mcp card. A write_file artifact (plan or task list) is shown as a plan instead of a hidden brain-directory path. A command agy moves to the background gets no further update after end_turn, so its card spun until the next message. Show it as running in the background at end_turn; the real result replaces that when agy reports it in a later prompt's stream. |
||
|
|
89eb8868dd | fix(web): collect and dismiss optional async questions above composer (#2322) | ||
|
|
5ed3d14f88 |
test(ios): capture intermittent transcript layout diagnostics (#2325)
* test(ios): capture intermittent transcript layout diagnostics * fix(ci): keep iPad diagnostics running after failures * ci: retry iOS diagnostics after transient simulator failures |
||
|
|
fdea9432a6 |
fix(mcp): shrink duplicated peer identity prompt strings (#2326)
SESSION_ID_PREFIX_PARAM_DESCRIPTION and PEER_IDENTITY_UUID_RULE are embedded verbatim into multiple MCP tool schemas, so each trimmed token is paid N times per turn. Keep the load-bearing rules (prefer full UUID from a citation; UUID is identity; never invent titles; rename is a non-event) and drop scaffolding examples / Copy-reference restatement. Verified before cutting: the soup-only "agentSessionId survives hub-row churn" clause is not on upstream/main (durable resolve is still open in tiann/hapi#2251); PEER_IDENTITY_UUID_RULE comes from rename-proof Parent stamps (#1922 / #175) where agents invented titles after parent rename. AI disclosure (CONTRIBUTING.md): drafted and verified by Composer (Cursor) running as a HAPI peer agent from the MCP context-cost audit. via HAPI (https://hapi.run) Co-authored-by: HAPI <noreply@hapi.run> Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
f75109ce07 |
fix(cli): keep LAN access for sessions that outlive their runner on macOS (#2328)
* fix(cli): keep LAN access for sessions that outlive their runner on macOS macOS attributes Local Network decisions to a process's responsible process, which a child inherits from its spawner. Sessions spawned by a runner that launchd started (directly, or through the npm launcher bin/hapi.cjs) inherit the runner's or the launcher's pid. Once that process exits (upgrade, version handoff) while the sessions are kept, every new process in their trees that connects to a LAN address fails with EHOSTUNREACH. When the spawner may hand its responsibility on, detached spawnHappyCLI children (sessions, runner handoff, runner start) are started with HAPI_DISCLAIM_RESPONSIBILITY=<spawner pid>. In a direct child of that pid, the entry hook removes the variable from the libc environment and re-executes process.execPath in place via posix_spawn(POSIX_SPAWN_SETEXEC) with responsibility_spawnattrs_setdisclaim, so the child becomes its own responsible process. The pid, stdio, process group, cwd and the rest of the environment are unchanged, so the runner's ChildProcess tracking keeps working. The spawner may hand its responsibility on when it is its own responsible process, or when its responsible process is its direct parent, is the npm launcher (which now passes HAPI_LAUNCHER_PID) and is itself its own responsible process. A spawner started from Terminal or over SSH keeps the inherited responsibility and with it the implicit LAN allowance macOS grants there. The lookup uses responsibility_get_pid_responsible_for_pid through bun:ffi; when it is unavailable the spawn is not disclaimed and this is logged once. Binaries without the hook ignore the variable, and a copy that leaks into a rolled-back tree is ignored because its parent is not the spawner. The private disclaim symbol may disappear: the hook then execs without it, and any other failure continues in-process; the reason is written to the hapi log. * fix(cli): print --help and --version when HAPI_HOME cannot be created The entry point imported runtime/responsibility to read the npm launcher's pid. That module imports the logger, whose configuration creates HAPI_HOME, so `hapi --help` and `hapi --version` failed before printing when that directory could not be created. Move the launcher pid into a dependency-free module, read it from there, and make the optional disclaim fallback note best effort. Add an entry point test that runs both flags with an unwritable HAPI_HOME. |
||
|
|
2524f81615 |
fix(web): render OpenCode tool names and shell cards like their canonical cards (#2310)
* refactor(web): share the tool-name alias table across presentation paths OpenCode reports built-in tools by lowercase ACP id (bash, write, edit, ...), and #2299 resolved them to the canonical result views with a local table in _results.tsx. Lift that table into toolNameAliases.ts with a resolveToolNameAlias helper so the upcoming presentation paths (card title/icon, input renderer, terminal detection) resolve through the same module instead of growing their own tables. No behavior change: getToolResultViewComponent keeps the exact-name lookup first and only falls back to the resolved alias. OpenCode ids whose dedicated views read Claude-shaped fields (skill, todowrite, patch, question) stay unresolved, as before. * fix(web): render OpenCode lowercase tool names like their canonical cards OpenCode v2 tool calls arrive with lowercase ACP ids (bash, write, edit, glob, grep, list, webfetch, websearch, task). The result views resolved them since #2299, but the card title/icon, the detail dialog's Input section and terminal-card detection still treated them as unknown tools: the bash card showed a wrench icon, a literal "bash" title, and its dialog dumped raw input JSON ({command, cwd, description}). Resolve every presentation path through the shared toolNameAliases module: - getToolPresentation resolves the alias before the knownTools lookup, so lowercase ids get the canonical icon/title/subtitle. - The terminal title prefers the invocation's own description field (OpenCode bash carries the model's command summary there) over an ACP title that merely repeats the tool name, then falls back to the formatted command and, for complex commands, the localized tool.semanticTitle.runShell label. Cards without any command keep the plain Terminal fallback. - The ToolCard input renderer renders the Command code block for the resolved Bash/CodexBash names, matching how Codex already hides the cwd and description keys from the input display. - TERMINAL_RELATED_TOOL_NAMES lists canonical names only; the display helpers resolve the incoming name first (OpenCode bash -> Bash). Exact-name lookups still win everywhere, so Claude, Codex, Gemini, agy and the v1 lowercase read alias render exactly as before. * fix(web): render shell-shaped unknown-tool cards like the terminal cards Live wire capture of OpenCode v2.2.5 shows running updates carry the raw command as the ACP title, so the final tool-call name is the command string ("ls") rather than the bash id — and Gemini ACP names shell calls after the command too. Those names never match the alias table, so they fell through to the generic wrench card and dumped raw input JSON ({command, description, cwd}) in the dialog. Route shell-shaped cards through the terminal presentation: - getToolPresentation falls back to the Bash presentation (TerminalIcon, description-first title, command subtitle) when the input carries a command, so an ACP title that merely repeats the command no longer promotes to the generic 'Run shell' label — the formatted command (or the invocation description) becomes the title instead. - renderToolInput switches from the canonical-name comparison to the existing isTerminalToolBlock predicate, which classifies these cards as 'command' via their execute native kind. Their input renders as the same Command code block as Codex, with cwd/description omitted. The transient pending card OpenCode emits before the command is known (name 'shell', input {cwd} only) keeps the generic fallback: it has no command to show yet and is replaced by the command-name card once the running update arrives. * fix(web): route shell-shaped card results through the terminal result view OpenCode command-name cards ("ls") resolved to GenericResultView: their result text rendered as generic markdown, collapsing the output onto one line and autolinking file names, while the canonical Bash card shows the same output in the terminal code block with line breaks preserved. getToolResultViewComponent takes the block now and, after the exact-name and alias lookups miss, falls back to the Bash result view when the block is terminal-shaped (isTerminalToolBlock). The predicate itself moves to chat/toolGroups.ts next to getToolGroupActionKind, which drives it, so the result registry can import it without a component cycle; ToolCard.tsx re-exports it for its existing consumers. Call sites (card, detail dialog, trace child rows) pass their block. Cards whose name already resolves to a dedicated view (OpenCode grep/glob/list via the alias table, CodexBash, exact names) keep that view; only unknown shell-shaped names change. |
||
|
|
d784f1f7bd |
feat(agy): run Antigravity over agy acp with mid-turn Steer (#2319)
* refactor(agy): isolate the stream-json transport in its own module
Move everything only the stream-json driver uses into
cli/src/agy/legacyStreamJson/: the driver and stream process, the NDJSON
parser, the conversation-DB model and title readers, the transcript entry
types, and the agy transcript producer that lived on ApiSessionClient as
sendAgySessionMessage. The driver now registers its own queued-message
cancel handler for batches held in its retry backoff instead of reaching
through AgySession.
The loop runs the remote session through agyRemoteLauncher, the one place
that picks a transport; it is the only importer of the new module. No
behavior change.
* feat(acp): report soft-steer usage and prompt timing to the caller
Antigravity ends a steered session/prompt request early and reports each
request's share of the turn in its own response. Let soft-steer callers
receive that usage so they can total it for the turn.
prompt() waits for earlier output before it sends and for late output
after the answer. Callers can now learn when the request was sent and
answered, and a soft steer exposes when it was answered, so they can time
the agent itself and run their own timers on its answers.
* fix(acp): keep the JSON-RPC error code on failed requests
A rejected request lost the agent's error code, and the soft-steer failure
log printed the Error as {}. The rejection now carries code and data, and
the log keeps the message and code.
* feat(agy): run Antigravity on agy acp when agy supports it
agy 1.5.0 added an ACP server. When `agy --version` reports 1.5.0 or
newer, agyRemoteLauncher runs the session on a new ACP launcher over the
shared AcpSdkBackend; older agy, or a version that cannot be read
(pre-release of 1.5.0, missing binary, no answer), keeps the stream-json
driver and says why in the session. The check and the stream-json
launcher live in legacyStreamJson/, behind one call.
On ACP, one agy acp process serves the session. The agy conversation id is
the ACP session id, so stored agySessionId values resume through
session/resume without replay, whichever transport started them. The
launcher marks the session with agyProtocol 'acp' in metadata; the
stream-json launcher removes a stale marker.
- Model and effort apply per turn through session/set_model with agy's
<model>-<effort> ids; clearing the model returns to agy's default. The
mode is sent every turn, since agy can change it on its own.
- A queued message counts as delivered once agy takes it (its echo,
output, or answer), or when it goes back to the composer.
- Permission modes map to ACP session modes. agy approval requests reach
HAPI through the shared ACP permission handler. agy titles a
run_command request with the command line, so the handler's name hints
for HAPI's own MCP tools (change_title, think, ...) are turned off for
agy; otherwise a command such as `grep think notes.md` would skip the
approval prompt. Automatic approvals pick a one-time option, because the
agy process outlives mode switches, and agy question requests always
wait for the user.
- Titles come from session_info_update, and each turn reports one usage
total built from the prompt responses.
- If the agy process dies, the next turn restarts it and resumes the
conversation (the transport now reports whether its process is alive).
A restart that fails part way leaves no half-started process in use;
the next turn tries again. A prompt agy never started is restored to
the composer.
* feat(agy): add accept-edits and plan permission modes
agy has default, accept-edits, and plan execution modes. Expose
accept-edits and plan as acceptEdits and plan next to request-review
(agy's default mode) and always-proceed. On agy acp they switch per turn
through session/set_mode without restarting agy; the stream-json driver
passes them as --mode, so a change restarts its process like other
launch settings. The iOS and Android catalogs mirror the new list.
* feat(agy): steer queued messages into the running turn
agy acp folds a second session/prompt into the running turn. Register the
SteerQueuedMessage handler in the agy ACP launcher and open the steering
gate for agy sessions whose metadata says agyProtocol 'acp'; stream-json
sessions stay queue-only. The launcher publishes the marker and registers
the handler before it starts agy, so the hub knows the protocol before any
turn can take a steer; until then the hub tells a steer on an agy session
that Steer is not available yet, rather than listing other flavors.
agy answers the request a steer interrupts at once (end_turn) while the
turn continues under the steer, and it lets a running tool call finish.
So the launcher keeps the turn, its steeringActive state, and thinking
until every open prompt request settles, and totals usage across them;
usage from a steer answered after its turn ended is not reported again.
agy echoes a steer as a user_message_chunk when it folds it in. The ACP
backend now reports those echoes after flushing the output before them,
and the launcher commits the steer when the echo text that follows the
prompt's own echo matches it (whitespace-insensitive; the longest steer
text wins when one contains another), so the message lands in the transcript where
it entered the turn rather than after the final answer. Each steer
resolves once (echoed or answered, held, or put back). agy rejects a
prompt while an approval is open, so a steer is refused then and the
message stays queued.
Stop applies to the whole turn lifetime. It withdraws Steer at once and
refuses steers that arrive after it. The turn is registered before agy
restarts or switches settings, so a Stop before the prompt is sent puts
it back in the composer, and a prompt still waiting to send is cancelled
as soon as it reaches agy. agy answers a cancelled prompt with a normal
`cancelled` result; when it produced no output, the prompt also goes back
to the composer. agy answers open requests with `cancelled` and
ends open tool calls; the turn's handler stays active so those final tool
updates still render. A steer cancelled before its echo is held for an
explicit Retry or Cancel, as for Cursor. A steer agy never answers is
dropped after a grace period: its row is held the same way and the agy
process is stopped (late permission requests are cancelled, not
approved), and the next turn restarts it. If agy ignores the cancel, its
process is stopped after a timeout in the same way.
* feat(agy): report and fall back when agy acp fails to start
An agy older than 1.5.0 never reaches this path: the version check in the
selection seam already runs it on stream-json. On 1.5.0 or newer, agy acp
can still fail to start or to open the conversation, for example when agy
is not signed in, the ACP install is broken, or the process exits during
start-up. The session used to end as crashed, without the reason.
The launcher now sends the reason to the chat, and the selection seam runs
the session on the stream-json driver instead, saying in the session that
Steer is not available. Only start failures fall back: errors after agy
acp is up end the session as before, and a kill during start-up is
neither reported as a failure nor falls back. The fallback stays in the
selection seam and legacyStreamJson/.
* feat(agy): show per-turn usage in the response footer
On agy acp each turn ends with a round summary: input, output, thinking,
cache-read and total tokens (summed across the requests of a steered
turn), the model, and agy's own time from sending the prompt to its last answer
(HAPI's waits before sending and for late output are left out), and
tok/s. agy reports no per-step timing, so generation time is that round
time minus the spans spent running tools or waiting for the user
(overlaps counted once), and generated tokens are output plus thinking,
as for OpenCode. The web footer renders it like the
other round summaries.
agy's usage adds up every model call of a request and agy sends no
usage_update, so it is not a context size. The turn's usage therefore no
longer goes out as a token_count for the context indicator, which stays
empty as it is for agy on stream-json.
* fix(agy): keep the session when Stop arrives while no turn is running
Stop aborts the queue wait and replaces the abort controller. The main
loop then checked the new controller's signal, found it not aborted, and
left the loop, so a late or repeated Stop after a turn had ended closed
the session and disconnected agy. The loop now checks the signal its
wait used and keeps waiting for the next message.
* fix(agy): confirm a steer only at its echo
A later steer makes agy answer an earlier steer's request at once
(end_turn) while the tool call and the turn go on, before agy has folded
the earlier steer in. Taking that answer as delivery marked the message
consumed, so a Stop before its echo left it without Retry or Cancel.
A steer is now confirmed when agy echoes it. An answer without an echo
counts only when the turn ends: confirmed if the turn ended without a
Stop, held for Retry or Cancel after one.
* fix(agy): hold unechoed steers when agy is lost mid-turn
An early-answered steer was confirmed when its turn ended without a Stop.
If agy exited before echoing it (for example when a later steer answered
its request and then the process died), the turn still ended without a
Stop, so the steer was marked consumed although agy may never have folded
it in, and Retry or Cancel was gone.
A steer request that fails with a lost transport now marks agy as lost
for the turn, and an early-answered steer without an echo is confirmed
only when the turn ends cleanly: no Stop and no lost agy process.
Otherwise it is held for Retry or Cancel.
* test(agy): pin how each steer outcome is decided
Cover the steer paths that had no test: a control command or a message
that left the queue is refused; a steer whose delivery state cannot be
recorded, or whose request agy loses while starting or writing it, is
held for Retry or Cancel; a steer sent while agy restarts stays queued
and runs next; an early-answered steer echoed before a Stop stays
confirmed; a steer agy rejects after a Stop goes back to the queue; the
main prompt stays delivered when Stop leaves a steer agy may have taken;
and an open steer is held when agy ignores the cancel or the session is
killed.
* fix(agy): confirm every steer that one echo chunk carries
When agy echoed two pending steers in one user_message_chunk, the first
match cleared every steer's echo text, so the other steer was not
confirmed at its echo. It was confirmed only when the turn ended, and a
Stop before then held it for Retry although agy had taken it. A match now
uses up only its own text, and the remaining steers keep matching.
* fix(agy): keep matching the prompt's echo after a stray echo
An echo chunk that did not continue the prompt (for example a late echo
from the previous turn) ended the wait for the prompt's own echo. The
prompt's echo that followed was then matched against the steers, so a
steer whose text the prompt contains could be confirmed before agy took
it. Such a chunk is now checked against the steers only, and the prompt's
echo is still recognized when it comes.
* fix(agy): settle the running turn before a kill returns
The runner ends the session and closes the client as soon as kill()
returns. kill() only cancelled the turn and disconnected agy, so a prompt
that was still waiting to send, or whose cancelled answer was still
draining, put itself back in the composer (or was confirmed) only after
that, and those events were lost; the session end could then record the
prompt as delivered without restoring it.
kill() now waits for the running turn to settle after disconnecting agy,
bounded to a few seconds so an agy that never settles cannot hold the
session end. Archive and runner stop both end the session through kill();
leaving remote mode does not apply to agy, and a normal exit waits for
the turn in the main loop.
* fix(web): choose the Antigravity permission mode when creating a session
The create form still showed Antigravity's old YOLO toggle, so a new
session could only start in request-review or always-proceed, although
the session mode picker offers request-review, acceptEdits, plan and
always-proceed. Antigravity now uses the same native permission select
as the other agents, filled from the shared mode catalog, and the chosen
mode is sent with the spawn.
The default stays as before: a stored YOLO toggle carries over
(on → always-proceed, off → request-review), otherwise the hub's default
applies, mapped onto agy's modes. Fallbacks that used the literal
'default' mode, which agy does not have, now ask the shared catalog for
the flavor's default instead.
|
||
|
|
ee1e6ae7c2 | feat(opencode): show round usage and tokens per second (#1668) | ||
|
|
df96b3b8fb | fix(opencode): surface v2 scheduled retries (#2300) | ||
|
|
3caa3f9e84 |
feat(web): add setting to keep unread sessions visible (#2292)
Since
|
||
|
|
5ce30b20c9 |
feat(cli): auto-steer ping-peer messages into active peer turns (#2298)
* refactor(shared): describe steering support with a per-flavor capability table Replace the flavor comparison chains in isSteeringSupportedForFlavor and isSteeringSupportedForSession with a table keyed by flavor, so a protocol restriction such as legacy Cursor sessions sits next to the flavor it applies to. Results are unchanged for every flavor and Cursor session shape. * feat(cli): auto-steer ping-peer messages into active peer turns Peer messages in auto mode only steered Codex turns. Record each flavor's active-turn signal in the steering capability table, expose it as hasActiveSteeringTurn(), and use it in both the peer sender and the waiting queue's Steer gate, so remote Claude, Pi, OpenCode and Cursor ACP targets with an active, steerable turn also get the queued message steered into it. Auto still stores one ordinary queued message first and attempts the existing steer action at most once. A steer that the hub rejects or that stays unconfirmed keeps the accepted message without resending, and the receipt now says which of "not attempted", "rejected by hub" or "not confirmed" applied. Inactive targets, --wake, explicit steer and explicit queue are unchanged. * fix(cli): keep ping-peer steer notes accurate when delivery is unresolved Auto receipts reported every unsuccessful steer response as "rejected by hub" and promised the message stays queued. Only a refusal before any native steer is dispatched (an HTTP 4xx, or a Hub failure without a localId) is definitive. A failure that carries a localId, such as an RPC timeout or an OpenCode steer that is still being reconciled, now reads "steer not confirmed; delivery unresolved" without promising queued delivery. Auto notes for a skipped steer used the explicit-steer refusal text, so an accepted receipt could say "no message sent". They now use separate reasons (for example "target is idle"); explicit steer wording is unchanged. |
||
|
|
0b82bd7658 |
fix(acp): use content as tool output when rawOutput has only metadata (#2299)
* refactor(acp): extract tool result output selection * fix(acp): use content as tool output when rawOutput has only metadata OpenCode v2 sends the real tool output in the ACP content array and puts only metadata in rawOutput. rawOutput won unconditionally, so every tool result card showed just the metadata or no output. When rawOutput is an object whose only key is metadata and content normalizes, report the normalized content as the output and keep the metadata next to it. rawOutput that carries a body is left untouched. * fix(web): render OpenCode lowercase tool names with their dedicated result views OpenCode reports built-in tools by lowercase id (bash, glob, grep, ...), but the result view registry is keyed by Claude-style names. Only read had an alias, so the rest fell back to the generic markdown view: shell output lost its line breaks and file names rendered like links. Resolve a small set of OpenCode ids to the matching registered view after the exact-name lookup, so exact names keep their current views. Tools whose dedicated view reads Claude-shaped fields (skill, todowrite, patch, question) stay on the generic view. |
||
|
|
e360c88e68 |
feat(hub): cache model-list RPCs with single-flight + stale-while-revalidate (#2301)
Model-list endpoints (claude/pi/agy/dsh, machine- and session-scoped) round-trip an RPC to the runner on every picker open. Even healthy engines answer in ~1s; a busy one serializes them for 3-13s and a stalled one stretches past the web server's 30s request cap, surfacing as opaque gateway timeouts. Catalogs change rarely, so route these fetches through the same SessionEnumerationCache treatment the enumeration RPCs already use (#2032): - concurrent callers share one in-flight fetch; TTL hits answer with no RPC; stale values serve immediately while revalidating - an 8s cold cap returns a typed error long before the request cap - error bodies and RPC failures propagate — never pinned as last-good - agy refresh=true bypasses the cache; the machine-agy-models-updated realtime event invalidates the entry so event-driven refetches see the new catalog cold - entries are released when a session leaves the active set Also aligns the dsh/agy/agy-session routes with the existing rpc_target_missing contract (503 + stable code instead of 500) so the web can stop hammering dead targets, and moves the pi-models session route onto the engine wrapper. Co-authored-by: Claude Code <noreply@anthropic.com> |
||
|
|
671fc8fced | fix(web): preserve notification opt-out during recovery (#2308) | ||
|
|
2741217b89 |
feat(web): add push notification controls and unread dots (#2303)
* feat(web): expose push controls and unread session dots * fix(web): synchronize push subscription controls |
||
|
|
a1fdb78405 | fix(web): show queued steer delivery feedback (#2306) | ||
|
|
b9880693a7 |
fix(opencode): describe display tools via Code Mode execute for OpenCode v2 (#2307)
* fix(opencode): describe display tools via Code Mode execute for OpenCode v2
OpenCode v2 can list MCP tools only in a Code Mode catalog whose entries
are callable as JavaScript inside the execute tool, so the hapi_display_*
names and aliases HAPI advertised may not exist there. Replace the three
per-tool display hints used by the OpenCode instructions with one block
that prefers a direct tool and otherwise calls tools.hapi.<tool>({ path })
through execute. The block appears once in both the ACP first prompt and
the local hapi-instructions.md. Hints for other agents are unchanged.
* fix(opencode): do not re-display user-provided files unless asked
Agents sometimes called the display tools on a file the user had just
attached or asked them to read, which only echoes it back. Say in the
display tools block that the tools are for files the user has not been
shown, and that files the user attached, pasted, or pointed to are not
displayed again unless the user asks.
|
||
|
|
810aab72fc | fix(web): keep jump-to-bottom visible in history (#2304) | ||
|
|
3ce46a9b13 |
feat(acp): re-enable change_title for ACP launchers with manual title precedence (#1672)
* feat(acp): re-enable change_title for ACP launchers with manual title precedence opencode/cursor/kimi disabled the hapi change_title MCP tool (#1028), relying solely on native ACP session-title sync. When the agent never generates a native title there was no way to set one short of hub API calls. Re-enable change_title on those launchers. The shared title-sync controller marks manual titles, so later native sessionInfoUpdate titles no longer overwrite them. * fix(acp): include copilot in change_title re-enable and harden tests Copilot has the same ACP title-sync shape as opencode/cursor/kimi, so it gets the same shared controller wiring. Add a cursor regression test asserting one controller instance is shared across backend (re)creation paths and cover the onChangeTitle failure path. * fix(acp): persist manual title precedence in session metadata The manual flag lived only in one controller closure, so a recreated remote launcher or a resumed session started fresh and let the next native ACP sessionInfoUpdate overwrite a change_title rename. Store acpManualTitle in session metadata and initialize new controllers from it. * fix(agent): preserve acpManualTitle through existing-session bootstrap bootstrapExistingSession rebuilds metadata through an allowlist, so the manual-title marker was dropped on process resume and native ACP title sync could overwrite a change_title rename. * fix(cursor): preserve manual title precedence across live relaunch |
||
|
|
893260ac9b | Release version 0.34.3 | ||
|
|
4e0e1788aa |
feat(web): add an Unread-only option to the session list filter (#2294)
Unread sessions are always visible since 0.34.1, but there was no way to narrow the list down to just them. Add an off-by-default "Unread only" checkbox to the sort/filter menu, persisted with the other view prefs. The open session stays visible (same rule as the status filter), and groups are not collapsed while the filter is on so no unread row is hidden. Default behaviour is unchanged. Co-authored-by: Ian Stevenson <is@lockhouse.systems> Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> |
||
|
|
003f5237db |
fix(web): avoid re-parsing session read state for every sidebar row (#2290)
The session list asks for read state once per row on each render, and each call re-read and re-parsed the whole persisted store. With about 1.7k sessions that kept the main thread busy for tens of seconds when loading the list or opening a session. Keep the parsed store and compare it with the raw stored value on the first read after a microtask checkpoint, then trust it for the rest of that synchronous pass. localStorage stays the source of truth, so writes from other tabs or code are picked up by the next read after the checkpoint. If a save fails the cached copy is dropped so unsaved changes are not kept. |
||
|
|
6712e19dfa | Release version 0.34.2 | ||
|
|
5a5731f938 |
fix(cli): stop peer pings from waking or broadcasting to unrelated sessions
ping_peer resumed any inactive target by default, and list_peers returned the whole namespace (including offline sessions) with no machine or cwd, so agents re-woke finished collaborators and broadcast exclusive-work notices to every listed peer. - ping_peer refuses inactive targets unless wake=true (CLI --wake, exit 5); spawn_peer keeps waking its own fresh child. - list_peers lists active sessions only (hub GET /api/sessions?active=true) unless includeInactive (CLI --list --all); rows show busy/idle, machine, cwd, and same-machine/same-cwd marks relative to the caller. - inspect_peer reports the peer's machine. - Prompts and tool descriptions: message only task-related peers, inspect unfamiliar peers first, never broadcast, never wake for FYI/status. |
||
|
|
7688a4f13a |
ci(ios): bound and isolate Mac regression test hangs (#2287)
* ci(ios): bound Mac regression test hangs * test(ios): adapt Mac Catalyst split visibility assertion * test(ios): keep compact split coverage iPad-only |
||
|
|
9710a664e0 | test(ios): wait for pairing fields to disable (#2288) | ||
|
|
d3f700c88e | fix(android): publish tool-card async state on main thread (#2289) | ||
|
|
f95dcee05e |
fix(web): preserve blob-backed images in shared exports (#2282)
* fix(web): preserve blob-backed images in shared exports * test(web): include blob export spec in CI |
||
|
|
ec414ce474 | fix(web): keep Fast toggle legible in dark mode (#2286) | ||
|
|
b81a043fd2 |
fix(web): drop empty reasoning blocks so tool calls group together
Claude Code stores thinking with an empty body when the content is not displayed. Each one became an agent-reasoning block that rendered nothing but still sat between tool calls, so consecutive tools no longer counted as adjacent and stayed ungrouped. Skip creating a reasoning block for blank text. A streamed reasoning block is still created once its first non-empty snapshot arrives. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3f54ea53bd |
feat(web): add a concise chat view
Long tasks bury the conversation under hours of tool calls, reasoning, and progress narration. The concise view hides that work and keeps only what the user said and each round's final reply. - A round runs from one user input to the next; agent text after the round's last tool call or reasoning is its reply. While a round runs, its latest narration reads as live progress until the next tool call. - Blocks that need the user stay visible: pending permissions (including inside subagents), questions, plan proposals, user shell commands, errors, terminal API failures, and recaps. - Toggle from the session header or Settings > Chat; the preference is per device and syncs across tabs. Off by default. - A search jump can target hidden messages, so the full thread shows while a search target is active. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
13541a1928 | Release version 0.34.1 | ||
|
|
49c22d73a1 |
feat(web): group and collapse inactive session mentions (#2271)
* feat(web): filter session mentions to active sessions * feat(web): group and collapse inactive session mentions |
||
|
|
7b20218c40 |
feat(web): keep unread sessions visible and drop the date and unread filters
With sort and filter in place, two toolbar filters no longer earned their space. The date range filtered on updatedAt while the list orders by the user's last message, and sort plus search already cover finding older sessions. The unread toggle was a transient lens that compensated for unread rows hiding in auto-collapsed projects. - Remove the date range picker from the session list search and the share-target picker. - Remove the Unread only toggle. Instead, a collapsed project still lists its unread sessions under its header, and the preview limit never hides an unread row. - Reorder the toolbar by purpose: list controls next to search, then New, then browse and settings. Mark all as read only appears with unread sessions, so it moves last and no longer shifts the other controls when it comes and goes. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
e2b2af695b |
feat(codex): support explicit local model catalog configuration (#2266)
* fix(codex): reuse local model catalogs by default * fix(codex): verify catalog provenance and native schema before reuse * fix(codex): keep refresh credentials out of discovery homes * refactor(codex): reduce catalog support to explicit configuration * fix(codex): invalidate selected catalogs and resolve shim names |
||
|
|
db7ace3dc3 |
feat(web): sort and filter the session list (#2263)
* feat(web): sort and filter the session list The session list had one fixed order, the user's last message, and active and archived sessions were interleaved inside each project. With in-progress pinning off by default, a connected session could sit below a stack of archived ones, and archived sessions could not be listed on their own. A sort and filter button in the list toolbar now sets: - Sort by: last message (the existing default), date created, or recent activity including agent output. - Active first (on by default): connected sessions lead each project, and projects with one lead the list. Manual pins still come first. - Show: all sessions, active only, or archived only. The open session stays visible, and archived-only keeps projects expanded instead of auto-collapsing them. Choices persist and stay in sync across consumers and tabs. The Display setting "Show active sessions only" is now the Active status, and an existing true value carries over. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): keep the default project order while searching Relevance ranking keeps the incoming project order for equal scores, so passing the list view into grouping let Active first and the chosen sort reorder equally relevant search results. Group with the default last-message order while a text query is active, as before. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): drop the Recent activity session sort The Hub advances updatedAt only for human messages; agent output moves an in-memory progress clock that clients never see. Recent activity therefore ordered like Last message. Ordering by user input is the agreed contract across clients (see #1512), so remove the option rather than add a new activity clock. A stored "activity" value falls back to the default. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: HAPI <noreply@hapi.run> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
631e38faaf |
feat(web): archive a session from its row on hover (#2264)
* feat(web): archive a session from its row on hover Archiving a session took a right-click or long-press, a menu item and a confirmation. On pointer devices, hovering a connected session's row now swaps its time/progress cluster for an archive button, the way chat apps tidy their history. Keyboard focus reveals it too; touch devices keep the long-press menu. Archiving stops the session's agent, so the button only skips the confirmation for an idle session: it archives at once and shows a toast with Reopen. A session that is replying, waiting on approval or running background tasks still opens the existing confirmation. Failures are reported in a toast. Toasts gain an optional inline action for this, and the archive icon moves into the shared icon set. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): keep the hover archive spinner until archiving settles The hub can report a session inactive while the archive request is still confirming cleanup. The row's archive button rendered only for active sessions, so its spinner vanished early and a slow or failing cleanup looked finished. Keep the button, and the hidden time cluster, while the request is pending. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): keep archive progress across session list regrouping The hover archive spinner lived in row state. With in-progress pinning on, a session that turns inactive mid-archive moves out of the Active section and remounts, which reset that state and hid the spinner while cleanup was still being confirmed. Read the pending state from the shared archive mutation key instead, as the session header and delete dialog already do. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: HAPI <noreply@hapi.run> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3affdd92c9 |
fix(cli): silence Cursor post-done harness Briefly inform turns (#2268)
* fix(cli): silence Cursor post-done harness "Briefly inform" turns After AGENT_NOTIFY_SUMMARY status:done, drop notify_on_output resume speech/tools/thinking until the next HAPI user prompt so the competing finished-shell system ping cannot force a second user-visible reply. Fixes #2267 Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): narrow post-done silence to speech; keep soft-steer active Address cold review + Codex P2: suppress only text/reasoning after status:done, treat outstanding soft-steer as an active turn, and add a launcher regression for harness-resume drops. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): discard suppressed harness buffers before next prompt After a done close, idle-flushed harness speech stays buffered. Clear it before reopening the silence gate so prompt()'s pre-swap drain cannot resurrect the redundant reply (Codex P2 on #307). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): keep post-done silence through drain and handler swap Address upstream bot Minors on #2268: suppress speech after done even during promptInFlight drain windows, and reopen the gate only once when promptGeneration advances after the handler swap (not before prompt()). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): seal done footer before quiet-drain harness coalescing Address #2268 Minor: Cursor can append finished-shell speech during the post-prompt quiet window onto the same buffer as AGENT_NOTIFY_SUMMARY done, which hid the end-anchored footer. Seal the done segment when flavor=cursor at native response return, and truncate buried harness prose in the launcher as defense in depth. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): harden post-done seal against queue race and false closes Await sessionUpdateQueue before sealing a Cursor done footer; keep note() end-anchored; fence-aware truncate with soft-steer exemption and same-line glue handling so examples and steered speech are not cut (#2268 Minors). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): keep seal end-anchored; harden footer scan edges Seal only flushes end-anchored done footers (soft-steer truncate stays in the launcher). Footer scan skips inline-code examples and tracks JSON string/escape state so braces inside summary values do not break glue detection (#2268 Minors). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): ignore tilde-fenced done-footer documentation examples Recognize ~~~ fences with matching opener length alongside ``` so truncate/seal defense does not treat tilde-fenced footer examples as a real post-close (#2268 Minor). Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
306d2821f7 |
feat(web): remember and toggle Codex fast mode in the composer (#2276)
* feat(web): remember Codex fast mode and add it to model picker * feat(web): add Codex fast toggle to composer toolbar |
||
|
|
8e2b7ab80c |
fix(ios): unblock Mac Catalyst builds (#2275)
* fix(ios): mark attachment localization key manual * fix(ios): guard hinge probe on Mac Catalyst |
||
|
|
bd58f23bb1 |
fix(hub): align alive/steer tests with post-#1981 metadata (#2273)
* fix(hub): align alive/steer tests with post-#1981 metadata aliveEvents was matching a full session snapshot (or by-ref refresh) that includes activeAt, not the markMessageQueued patch. steerDeliveryLifecycle used a stale metadataVersion after titleSuggestionTurn advanced the DB. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): type steer metadata from engine session cache Store getSession metadata typing dropped required path/host on the realtime event value; use the refreshed engine session instead. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
c4847b241e |
feat(opencode): support mid-turn steering (#1981)
* feat(opencode): support mid-turn steering Register the per-message Queue/Steer RPC on the OpenCode remote launcher so a waiting-queue row can be delivered into the active turn as a concurrent ACP session/prompt (soft inject, no cancel, no mode/model/effort mutation), reusing the existing reservation/delivery-state protocol shared with Codex and Cursor ACP. The steer gate is closed synchronously by every cancelling or terminal path (normal-prompt finally, abort, switch/exit, teardown, stderr stall cancel), each steer operation is tracked from the moment its reservation is taken until completion plus all restore/consumed bookkeeping settles, and the foreground prompt drains those operations — abort-aware through the original turn signal — before ready, thinking=false or the next batch. steerability is published through the existing agentState.steeringActive flag so the web's queued Steer button is reachable. Gate the feature on the shared steering flavors (now including opencode) and update the hub's supported-flavor wording. * fix(opencode): acknowledge native steering acceptance * fix(opencode): preserve steering delivery outcomes * docs(opencode): remove obsolete abort-race comment * fix(opencode): preserve steering resolution ownership * fix(opencode): isolate ambiguous steering attempts * fix(opencode): compare resolved steering settings * fix(opencode): reconcile steering receipts after dispatch * fix(opencode): distinguish pending steering delivery outcomes * fix(opencode): restore receipts after successful native responses Track native input requests separately from detached steer operations. Resume receipt correlation after inputs quarantined by cancellation return their own successful responses, while keeping uncertain writes on completion-based confirmation. * fix(opencode): bound receipt proof to unambiguous native inputs * feat(opencode): steer v2 inputs through native inbox * fix(opencode): preserve v2 restoration and cancellation ownership * docs(opencode): describe v2 inbox steering confirmation * fix(steer): expire Claude confirmation with its owning worker |
||
|
|
fa02830a60 |
fix(ios): show the chat title in the Mac toolbar
The Mac window's NSToolbar drops the custom .principal header, and the hidden titlebar title also hid the navigation title. Use the system title on Mac (as on the folded Duo) with a unified toolbar instead. |
||
|
|
e1093466c9 |
feat(ios): support macOS through Mac Catalyst
Build the app and notification extension for Mac Catalyst with the Mac idiom, so Macs get a 1:1 native window instead of the scaled iPad app. The Mac build keeps the run.hapi.app bundle ID and adds Mac entitlements (sandbox, network, microphone, user-selected files, Mac APNs). - Always use the split on Mac with a sidebar list style, denser rows, 14pt reading text, a hidden duplicate titlebar title, a minimum window size and page-sized sheets; open web links in the default browser and hide the unavailable live QR scanner. - Add menu bar / hardware-keyboard commands: New Session, Settings, Toggle Sidebar, a Session menu (settings, files, rename, export, stop, previous/next session) and a guide link. - Composer: Return sends on Mac (Shift/Option-Return for a newline, IME untouched, first suggestion picked); dropped files and pasted images or copied files become attachments on all platforms. - CI builds Mac Catalyst and runs the navigation, split and transcript geometry tests there; README documents the Mac build. |
||
|
|
82c5c00a38 |
feat(web,hub): add opt-in search for session message content (#1598)
Adds an opt-in content search over session messages, alongside the existing metadata search. An FTS5 index covers visible user and assistant prose; the sidebar gains a scope toggle, and selecting a result opens the matching message rather than the session tail. Search scope is a two-state toggle rather than a dropdown: a 48x48 target matching the clear endcap, distinct glyphs for session details vs message text, tooltips naming the real scopes, and the active mode kept on the collapsed chip (tiann/hapi#2081). Dogfooded on a live 1178-session fleet. The scope toggle and reading forward from a search result were both click-tested on that install — the latter walking six bounded pages through a 1,507-message session and stopping correctly at the session head. The per-commit history does not survive this squash; the review trail — including which commit closed which finding — is on the PR threads. Fixes #1554 Fixes #2081 |
||
|
|
1f4518df20 | Release version 0.34.0 | ||
|
|
b4fcddee2f |
feat(android): offer web-parity color theme presets in appearance settings (#2228)
* feat(android): offer web-parity color theme presets in appearance settings Bring the web client's color-theme catalog (Default plus 16 named palettes) to Android as an appearance choice. Each preset carries five seed colors per scheme and derives every other tone with the web client's exact math — per-channel elevation mixes, the WCAG-luminance dark/light call, and tie-up rounding — so a preset renders the same on both clients. A selected preset overrides the dynamic and OLED schemes (OLED renders the preset's dark seeds, like the web layering), while Default keeps Material You and the built-in light/dark/OLED schemes. The picker reuses the expressive choice dialog: every card shows the preset's light/dark canvas split plus its accent strip, and longer catalogs scroll inside the dialog so they stay usable on small screens. Material You switches off with an explanatory note while a preset is active, since presets pin their own palettes. Persistence is one DataStore key over the existing theme prefs, with unknown ids degrading to Default. Strings land in en/ru/zh in matching order; the proper-noun preset names stay untranslated, matching the web locales. Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> * test(android): pin the HapiTheme scheme resolution order with a matrix The preset > oled > dynamic > static ordering and the OLED-yields-to-dark- seeds rule (preset.palette(dark = darkTheme || oled)) lived inline in the HapiTheme composable where no JVM test could reach them -- reordering the when (a stack-conflict surgery hazard) would pass every gate silently. Extract the order into a pure resolver (resolveThemeSchemeSource returns a descriptor; the composable maps it to schemes, with a local SDK guard lint can see) and pin it with an exhaustive matrix: all 16 named presets x every darkTheme/oled/dynamicColor/sdk combination resolve to the preset palette, DEFAULT+oled beats dynamic color, dynamic color only fires on S+ when enabled, and Nord-under-OLED-with-light-system asserts concrete dark-seed hexes. Verified discriminating by mutation: dropping `|| oled` fails 2 tests, hoisting dynamic above oled fails 1. Co-Authored-By: Claude Code <noreply@anthropic.com> --------- Co-authored-by: Claude Code <noreply@anthropic.com> Co-authored-by: HAPI <noreply@hapi.run> |
||
|
|
3fc15e92cf |
fix(dsh): resume DSH ACP sessions after HAPI restart (#1926)
* fix(dsh): resume DSH ACP sessions after HAPI restart * fix(dsh): register active session handoff * fix(dsh): preserve native id in summaries * fix(dsh): keep native resume on recorded machine * test: refresh CI checks |
||
|
|
0de50e6abc |
feat(android): composer scheduled send with preset and specific picks (#2156)
* feat(android): composer @ mentions with session chips and file hits Mirror the web composer @-mention autocomplete: an active `@word` at the composer tail opens a dropdown that merges two sources like the web's `[...sessionHits, ...fileHits]`: - Session rows from the cached session list via `matchSessionsForMention` (web `sessionReference.ts` port): sidebar dedupe by `flavor:agentSessionId`, `hasConversationContent == true` gate so empty stubs are never reference targets, current session excluded, score tiers (title exact/prefix/contains, id prefix/contains, other-field) with active +50 / archived -25, Long-scored with updatedAt as tiebreak, limit 20. Insert text is Copy-reference prose (`See session "<title>" (/sessions/<id>) for context.` + steer suffix) with JSON-quote escaping, whitespace normalization, and 120-grapheme truncation via BreakIterator. - File rows via `GET /api/sessions/:id/files` (limit 50) for codex / copilot flavors only: copilot inserts `@<fullPath>`, codex inserts `@"<fullPath>"` with quote/backslash escaping; RPC failure degrades silently to session-only rows (web parity), CancellationException rethrown. Trigger detection ports `findActiveWord.ts` byte-for-byte (hard-stop scan, `@` boundary rule, `/`+`.` path continuation forward-only, bare `@` popup, no code-fence exemption), evaluated at the end of the text (the Android composer is a cursor-less String field - full cursor-aware mirror kept as `Mentions.findActiveWord`). Selection swaps the whole word and appends a trailing space (`applySuggestion.ts`). The `hasConversationContent` gate field already exists on this lineage as a non-nullable Boolean (absent / JSON null decodes to `false` via HapiJson coercion, asserted in a new SessionDecodingTest case); the `searchSessionFiles` seam moves onto `ChatSessionApi` with a defaulted `limit` parameter. MentionDropdown reuses the SlashCommandDropdown chrome; new string `chat_mention_suggestions` lands at identical key positions in en/zh-rCN/ru, and three zh keys a prior merge had parked at the file tail move back to their en-mirrored positions so all three locales key-sync exactly. Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> * Align mention prefix scan and title whitespace with the web - findActiveWord default prefixes now mirror the web trigger set ['@', '/', '$'] (HappyComposer.tsx): a boundary-legal '/' or '$' tail word stops the backward scan, so "@ref /tmp" yields the "/tmp" word (routed to the slash/skill domain) instead of joining a multi-word mention query whose whole-word swap would swallow the typed "/tmp" on selection. - sanitizeSessionReferenceTitle now collapses the JS /\s+/ Unicode whitespace set (NBSP, U+3000, U+2028/2029, U+FEFF, ...) so CJK titles normalize byte-identically to the web. Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> * Mentions: caret-aware detection + stale-row invalidation (review fixes) Consolidates the two review fixes from #2155 into this implementation: caret-position — detection and insertion now evaluate at the composer caret instead of the text tail. Mentions.mentionQueryOf gains a selection-aware overload; the VM tracks text + caret as one atomic ComposerDraft (mirroring the field's TextFieldValue), ChatComposer reports text/selection in a single callback and adopts external text at the reported caret, and applySuggestion rests the cursor after the insertion. A selected range suppresses suggestions (web rule). stale-suggestion — the file leg emits an empty batch before awaiting each RPC, so the previous query's rows never linger while a new query's request is in flight (delayed-response regression test included). Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> * Fix androidTest lambda arity after composer callback consolidation CodexPlanActionsTest renders ChatComposer with onTextChange = {}, which no longer compiles now that the callback reports (text, selectionStart, selectionEnd) atomically. Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> * feat(android): composer scheduled send with preset and specific picks The composer clock entry (web ScheduleTimePicker twin): the exact web preset set (+5m/+30m/+1h/+4h, resolved at the send instant) plus a specific-datetime tab with the web's 30 s past-grace and 7-day ceiling (ScheduleSend pure-logic object). A pending pick arms ChatViewModel.pendingSchedule, expires absolute picks on the clock, downgrades steer long-presses to queue (the wire forbids scheduledAt + steer), rides the send RPC as epoch-millis scheduledAt, and the queued bar's Edit re-arms a future fire time as an absolute pick (computeEditPendingSchedule). Queue rows now label with the web formatScheduledTime ("Oct 25, 2:30 PM", the year only when it differs from the current one). Declared divergences from web/src (all also in KDoc): - Paste gate: the web drops file pastes while a schedule is pending; the Android composer has no clipboard-file paste path, so the illegal combination is made unreachable instead — the attach button disables while a pick is pending and the clock button disables with attachments on the tray (the same mutual exclusion the web enforces). - Pending-pick lifetime: the web clears the pick only after the send mutation is accepted and restores it on failure; Android clears at dispatch because the failed row already carries wire scheduledAt and retryFailedMessage re-fires with it — the retry is the restore. - Panel chrome: the web anchors a fixed panel above the clock button (bottom sheet on touch viewports) and closes on outside-pointer-down; Android renders the panel above the input card like the slash/mention dropdown precedent and closes on the clock toggle or a selection. The specific tab splits the web's single datetime-local box into date + time fields for touch keyboards; the web's min/max input attributes are browser affordances, not mirrored — the pure validator is the gate, as on the web. Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> * Guard scheduled-send edge paths found in adversarial review - editQueuedMessage no longer re-arms the schedule restore while the attachment tray is non-empty: the wire forbids scheduledAt + attachments and the clock button is disabled with attachments, so an armed pick would be invisible, un-clearable, and crash the send on the invariant check. The drop surfaces a notice instead. - The restore is now guarded by a pick snapshot taken at tap time: a schedule re-picked during the cancel round-trip wins over the restore (web snapshots text + pendingSchedule together in onEdit). - The /clear|/new concurrent shortcut now requires scheduledAt == null like the web — a scheduled clear queues as a scheduled message. - The pending-schedule expiry job is an AtomicReference: set/clear raced across the main thread and the edit-restore coroutine could leak a stale job that clears a newer pick at its deadline. - formatScheduledTime follows the locale's hour cycle and date order like web Intl ("25 окт., 14:30" / "10月25日 14:30" / "Oct 25, 2:30 PM"); the zh queued-scheduled label drops its full-width colon. Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> * Fix preview lambda arity after composer callback consolidation Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> * Reject scheduled sends over attachments and serialize schedule transitions The wire contract excludes attachments from scheduled sends, but only the clock button's enabled state enforced it — the picker panel stays open across an attachment add and the share-import path can drop a file into the tray while a pick is armed. Three layers now hold: - ViewModel transition gate: arming a pick over a non-empty tray is rejected in applyPendingScheduleLocked (clears always allowed); the open picker panel also closes the moment a chip appears (ChatComposer). - Send guard: sendMessage resolves the schedule BEFORE the draft clears or the tray consumes and bails with a ScheduleAttachmentConflict notice, so both sides stay recoverable in the UI. - performSend's invariant tripwire stays as the last net. Same commit, the two flagged Minors from review: - Replacement/expiry serialization: the pick value swap and the expiry registration become one critical section (scheduleMutex), replacing the AtomicReference job handle whose getAndSet still left a window where a restore published A, a callback picked B, and A's timer cleared B at A's deadline. Uncontended transitions stay synchronous via tryLock; the timer body re-checks the revision inside the lock so an obsolete timer can never clear a newer pick. - Queued-edit restore now snapshots the schedule revision (web pendingScheduleRevisionAtEdit) instead of value equality, so a pick - or a pick plus explicit clear - re-made while the cancel round-trip is in flight wins over the restore even when the slot's value lands back where it started. Interaction tests: rejection while chips sit in the tray, pre-consume send guard, consecutive absolute picks keeping only the newest expiry, a preset surviving a restored pick's deadline, and edit-restore losing to both a mid-flight pick+clear and a clear+same-preset reselection. Co-Authored-By: Claude Code <noreply@anthropic.com> * Mask specific date/time entry for digit keyboards The Specific-tab fields kept KeyboardType.Number, but a numeric soft keyboard has no `-` or `:` key, so the required YYYY-MM-DD / HH:mm shapes were literally untypeable. The fields now auto-insert the separators as digits arrive (maskDateInput / maskTimeInput): digits only, capped at the wire shape, idempotent on already-formatted text (a pasted "2026-11-05" stays put; deleting just re-masks the rest). A half-typed pair (non-blank, so Submit is tappable) used to fail the tap silently: parseSpecificInput returns null and onSubmit did nothing. It now surfaces an inline invalid-shape error (SpecificError.Invalid, Android-only — the web's datetime-local box cannot hold a malformed shape), joining Past/TooFar and clearing on the next edit like them. Pure-logic tests cover keystroke-by-keystroke separator growth for both fields, mask idempotence, non-digit/overflow capping, and that mask output feeds the strict parser unchanged (partial masks parse to null, never a silently wrong instant). Test tags (schedule-date-input / schedule-time-input / schedule-submit) added for the instrumentation tests. Co-Authored-By: Claude Code <noreply@anthropic.com> * Add schedule composer instrumentation tests Device-level state transitions for the two review-flagged surfaces, one setContent per test against the 320dp CI viewport: - Mutual exclusion: an open picker panel dismisses the moment an attachment chip lands, and the clock button reports disabled with the non-empty tray. - Preset flow: tapping +30m delivers Preset("+30m") and closes the panel. - Digit-IME entry: performTextInput injects through the IME channel (the soft keyboard's path), so raw digits typed into the Specific fields must come back masked ("20261105"→"2026-11-05", "1430"→"14:30") and the submitted pick resolves to the typed wall time in the device zone, asserted against the exact epoch ms. - Partial input ("20261"/"143") submits to the inline invalid error string, not a silent no-op. Co-Authored-By: Claude Code <noreply@anthropic.com> --------- Co-authored-by: Claude Code <noreply@anthropic.com> Co-authored-by: HAPI <noreply@hapi.run> |
||
|
|
218d99cddf |
feat(android): render mermaid fences as offline diagrams (#2161)
* feat(android): render chat markdown math with offline KaTeX Port the web math pipeline to Android chat markdown. A new MarkdownMath pre-pass in :core:protocol extracts math with web semantics (remark-math singleDollarTextMath:false + remark-latex- bracket-math): $$ display flows, $$ text math only when the closer run equals the opener and stays inside the paragraph, single $ never triggers math (currency stays prose), \(..\)/\[..\] bracket pairs, backslash-escaped delimiters stay literal, and code spans, fences, links and link reference definitions are fully protected. Matches are lifted behind private-use placeholder tokens and re-inserted as MathInlineNode/MathBlockNode custom nodes, hoisting display math out of paragraphs while blockquote/list containers survive the reparse. 37 JVM tests mirror the web suite's cases. Rendering is a shared offline WebView (ui/markdown/MathWebView.kt) fed a self-built HTML document (MathDocument.kt) against bundled assets/katex/ (KaTeX 0.16.45, same version as web). The view is network-blocked (blockNetworkLoads + shouldInterceptRequest refuses http/https/ws/wss) with file/content access disabled; asset URLs still resolve through the file:///android_asset/katex/ base URL. Theme color and font size are injected per render and the document reports its height through a JS bridge (ResizeObserver + onPageFinished re-measure). KaTeX failures follow the web's three-tier semantics, degrading to monospace raw TeX. Inline \(..\) and single-paragraph $$ math degrades to monospace TeX for v1: AnnotatedString cannot host a WebView and one WebView per fragment is too costly in chat lists. The parser still emits MathInlineNode so a future renderer can upgrade inline rendering without touching the extraction layer. Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> * fix(android): convert CSS pixels correctly at the math WebView boundary The JS bridge reports scrollHeight in CSS pixels, but KaTeXMathBlock treated the value as Android physical pixels and divided it by the screen density when sizing the modifier: on a density-3 device a reported 90 CSS px block collapsed to 30dp instead of ~90dp. The font conversion had the opposite mismatch — 16sp chat text went through TextUnit.toPx() (physical pixels) and was injected as `font-size: 48px` CSS, making formulas render ~3x too large on the same screen. Define the two boundary conversions explicitly as pure functions next to the document builder and unit-test them: - spFontToCssPx: CSS px and sp are both density-independent, so only the user's font-scale preference crosses the boundary; density never enters (16sp stays 16 CSS px at any density, 21 at fontScale 1.3). - cssPxToDp: reported CSS px map 1:1 to dp at the default WebView scale, multiplied by WebView.scale when the view is zoomed. The document now also pins the viewport with `width=device-width, initial-scale=1`, making the 1 CSS px = 1 dp default scale an explicit property of the document rather than a WebView default, with a regression test asserting the meta tag. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix(android): refresh the math WebView height callback across spec changes KaTeXMathBlock keyed its height state with remember(spec) but assigned MathWebView.onHeightChanged inside AndroidView.factory, which runs only when the Android view is created. The callback therefore captured the initial spec's state object: when LaTeX, theme color or font size changed, remember(spec) minted a new state while AndroidView retained the existing view and its stale callback, so every measurement from the reloaded document updated the orphaned state and the current block stayed at its 22dp minimum. Keep one stable holder (MathViewHeightState) remembered unkeyed for the mounted view, reset it explicitly in onRender when the spec changes, and re-point the view's callback plus reset the height inside AndroidView.update before rendering — the creation-time callback then always feeds live state. JVM tests drive the holder through spec changes on one mounted view (the pre-fix wiring cannot compile against this shape: the factory-captured remember(spec) state is exactly the orphan the holder removes). Co-Authored-By: Claude Code <noreply@anthropic.com> * fix(protocol): bound dollar flow math closing to the enclosing container findFlowClose kept scanning after the opening line left its container and accepted an unprefixed closing run, so `> $$\n> x\n\nOrdinary prose\n\n$$\ny\n$$` paired the quoted opener with the later top-level `$$`: the prose was swallowed into the formula and the final `$$` lost its own opener. remark-math (verified against micromark-extension-math, whose math flow is `concrete` and dies with its container) renders the quote's math, the prose and a separate top-level equation instead. Bound matching to the opening container, distinguishing container shapes: a closer is only accepted from a line that still carries the container prefix; a blank line ends a blockquote (a following `> $$` opens a NEW quote, while a `>`-only line is an in-quote blank the container survives); a list item may resume after blank lines (loose lists), so blanks are skipped and the next content line decides; an unrecognized prefix is plain <= 3 space indentation, not a container, and keeps the unbounded scan (blank lines and fences stay math content). Regression tests: the quoted example (prose stays prose, the later equation keeps its own opener), a list-container variant, a blank-line/new-quote guard, plus two in-container close locks — the first three fail on the pre-fix scan. Co-Authored-By: Claude Code <noreply@anthropic.com> * feat(android): render mermaid fences as offline diagrams Port the web MermaidDiagram component to Android chat markdown. A fence whose language is exactly `mermaid` (case-sensitive, like the web's MARKDOWN_COMPONENTS_BY_LANGUAGE key) now dispatches to MermaidDiagramView instead of the plain code block; every other fence keeps the CodeBlock path. Rendering runs in a hardened offline WebView fed a self-built HTML document against bundled assets/mermaid/mermaid.min.js (Mermaid 11.14.0, curl-fetched, sha256-identical to the web app's locked dependency). That dist file is a self-contained classic script assigning globalThis mermaid - no imports, no runtime fetches - so no ES-module/CORS workaround is needed. The view shares the KaTeX skeleton: network stack blocked, file/content access off, asset URLs through the file:///android_asset/mermaid/ base URL (OfflineMathWebViewClient generalized to OfflineMarkdownWebViewClient, no behavior change). Behavior mirrors the web component line by line: initialize with startOnLoad:false, securityLevel:'strict', suppressErrorRendering:true and the web's dark/light themeVariables palettes verbatim (theme flips re-render); the validate-then-render gate parses with suppressErrors first and never calls render() after a failed validation, re-parsing once without suppression only to surface a human-readable reason; svg element ids are per-instance (`mermaid-<n>`, web useId) so the scoped styles mermaid emits cannot collide across diagrams in one message; wide diagrams scroll horizontally inside the document while the svg is centered at max-width:100% and height:auto. The code header (language chip + copy) stays above the body like the web's retained DefaultCodeBlock header; until the diagram renders - and on failure - the raw source is shown below it (the block's source exit), with the failure notice appearing only for actual errors so the loading window never flashes a render-error line. mermaidFallbackUi maps state to those surfaces as a pure function. 15 JVM tests cover dispatch, offline-ness, palettes, security flags, the validation gate structure, id uniqueness, generation filtering, script-breakout safety and the fallback mapping; the driver's runtime semantics were additionally validated against the real bundle in jsdom (flowchart/sequence render, invalid source surfaces the parse reason, hostile labels are rejected/sanitized under strict). Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> * fix(android): convert CSS pixel heights correctly in the mermaid WebView Both height reporters feeding MermaidDiagramView — the document bridge's report() (documentElement/body scrollHeight) and OfflineMarkdownWebViewClient's onPageFinished re-measure — return CSS pixels, but the rendered branch ran the value through with(density) { heightPx.toDp() }, which treats it as Android physical pixels and divides by display density: on a 3x display a diagram measuring 180 CSS px received a 60dp box and was clipped into an unnecessarily scrolling WebView. Fix it exactly like the KaTeX base now does: the document pins `width=device-width, initial-scale=1` (making 1 CSS px = 1 dp at the default WebView scale an explicit property of the document rather than a WebView default), and the reported value crosses the boundary through the shared density-independent cssPxToDp helper — extracted as the pure mermaidRenderedHeightDp so the composable no longer holds any density conversion at all, keeping both markdown renderers on one boundary contract. (The KaTeXMathBlock repeat of the same bug is fixed by the rebased base; MathWebView.kt arrives converted already.) JVM tests: the viewport pin is asserted against the built document (demonstrated failing on the pre-fix template) and the conversion math is driven through the pure helper — 180 CSS px stays 180dp because the boundary carries no density parameter, mirroring the base's MathDocumentTest contract. Co-Authored-By: Claude Code <noreply@anthropic.com> --------- Co-authored-by: Claude Code <noreply@anthropic.com> Co-authored-by: HAPI <noreply@hapi.run> |