Files
hapi/shared/fixtures
Junmo KimandGitHub 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.
2026-11-09 07:13:58 +08:00
..

Golden protocol fixtures

Machine-generated conformance fixtures for the HAPI client protocol. The web implementation is the source of truth: every expected* value in every file is produced by running the real web implementation over hand-authored wire inputs, then applying the normative projection each suite documents below. Native clients (iOS HapiProtocol, Android :core:protocol) port the same logic and must reproduce the expectations from the inputs exactly.

Three suites:

Suite Pins Web source of truth
chat/ message decode/render pipeline (normalize → reduce → group) web/src/chat/
sse/ session-updated versioned-patch application applySessionDetailPatch in web/src/lib/sessionPatch.ts
pagination/ message window: paging cursors, epoch resets, optimistic sends, trims web/src/lib/message-window-store.ts + web/src/lib/messages.ts

Never edit the JSON by hand — edit the case definitions in web/scripts/fixtures/ (cases/, sse/cases.ts, pagination/cases.ts) and regenerate.

Layout

shared/fixtures/
├── VERSION                  # current fixtureVersion (single integer + \n)
├── chat/<name>.json         # one fixture per case
├── sse/<name>.json
├── pagination/<name>.json
├── catalogs/modes.json      # reference tables (see Catalogs below)
└── README.md

How to consume (all suites)

  • iOS (ios/, SPM test target): resolve the repo checkout from the test file's own location and load every <suite>/*.json, e.g. URL(fileURLWithPath: #filePath) → walk up to the package root → ../../shared/fixtures. Decode the inputs, run the ported implementation, project, and compare against the stored expectations.
  • Android (android/, :core:protocol JVM tests): pass the directory via Gradle — tasks.withType<Test> { systemProperty("hapi.fixtures.dir", rootDir.resolve("../shared/fixtures")) } — and read it with System.getProperty("hapi.fixtures.dir") in the test.
  • Iterate all files in a suite directory (fail on zero files) so newly added fixtures are picked up without native-side changes.

Acceptance bar

Exact match on the normative projection: serialize your computed output and the fixture's stored expectation to canonical JSON (recursively sorted object keys; numbers as JSON numbers; no undefined/absent-key differences) and compare for equality. Field order in the files is already canonical (sorted keys, 4-space indent, LF, trailing newline), so a key-sorted structural deep-compare is equivalent.

fixtureVersion policy

fixtureVersion (mirrored in VERSION, shared by all suites) is bumped when a document schema or a normative projection changes shape. Native suites must fail loudly when the on-disk version is newer than the version they support (do not silently skip), and should tolerate older versions only if they explicitly implement them. Additive new fixture files and new wire cases do not bump the version.


Chat suite (chat/)

Runs the real web pipeline (normalizeDecryptedMessage → reduceChatBlocks → buildVisibleChatBlocks) over wire messages, then projects.

Document schema (fixtureVersion: 1)

{
    "fixtureVersion": 1,
    "name": "claude-assistant-text",        // equals the file name
    "description": "…",
    "input": {
        "messages": [ /* DecryptedMessage[] exactly as GET /sessions/:id/messages returns them */ ],
        "agentState": null,                 // session.agentState (permission requests) or null
        "options": { "hasMoreMessages": false }  // older history exists beyond `messages`
    },
    "expected": {
        "blocks": [ /* projected ChatBlock[] (pre tool-grouping) */ ],
        "hasReadyEvent": false,
        "latestUsage": null,                // or { inputTokens, outputTokens, contextSize, contextWindow }
        "visibleBlocks": [ /* projected blocks after tool-grouping */ ]
    }
}

Per fixture, the acceptance comparison covers blocks, hasReadyEvent, latestUsage, and visibleBlocks.

Normative field contract

The projection keeps structure + semantics and drops web-presentation and advisory detail. Whatever is absent below is intentionally NOT part of the contract — natives may derive their own equivalents but must not expect it in fixtures. Implementation: web/scripts/fixtures/projection.ts (keep in sync with this list).

Optional fields are present only when they carry a value; invokedAt is omitted when null. localId is always present (nullable) on the block kinds that carry it.

Every block

kind, id, createdAt, invokedAt?

Per kind

kind normative fields
user-text localId, text, attachments? — each { id, filename, mimeType, size, path }
agent-text localId, text
agent-reasoning localId, text
cli-output localId, text, source ('user' | 'assistant')
codex-review localId, review (verbatim normalized review object)
generated-image localId, imageId, fileName, mimeType
agent-event event — the normalized AgentEvent object verbatim (type + typed payload fields)
tool-call localId, tool, children? (recursively projected; omitted when empty)
tool-group (visibleBlocks only) firstToolId, lastToolId, tools (projected tool-call blocks in order; membership + order + count)

tool object

{ id, name, state, input?, result?, permission? }

  • state: 'pending' | 'running' | 'completed' | 'error'
  • input: verbatim wire value (may be null when only the result was seen)
  • result: verbatim wire value, present once a result/progress landed — including hub truncation markers (…[hapi: truncated N chars]…) byte-for-byte
  • permission?: { status, mode?, decision?, allowedTools?, answers?, reason? } — status: 'pending' | 'approved' | 'denied' | 'canceled'

Top level

  • hasReadyEvent: boolean (a ready event is consumed, never a block)
  • latestUsage: null or { inputTokens, outputTokens, contextSize, contextWindow } (contextWindow nullable; contextSize already folds cache tokens in)

Dropped (web-presentation / advisory — not in fixtures)

Block level: meta, usage (per-block), model, durationMs, status (optimistic-send state), originalText, streamId, uuid/parentUUID, agentTimestamp. Tool level: createdAt/startedAt/completedAt/ execStartedAt/execCompletedAt (timing), description, nativeTitle, nativeKind, progress. Permission level: id, date, createdAt, completedAt. Attachments: previewUrl. Generated image: source. Tool group: defaultOpen, historyState, needsOlderHistory, activityTitle, presentationMode, summary. Top level: latestGoal, latestUsage.cacheCreation/cacheRead/model/timestamp.


SSE session-patch suite (sse/)

Pins the versioned-patch algorithm for session-updated events carrying a SessionPatch (contract: docs/api/client-contract/sse.md, "Versioned patch algorithm"). Expectations are computed by the real web fold — applySessionDetailPatch in web/src/lib/sessionPatch.ts.

Document schema (fixtureVersion: 1)

{
    "fixtureVersion": 1,
    "name": "metadata-newer-version-applied",   // equals the file name
    "description": "…",
    "initialSession": { /* full Session as cached before the first patch */ },
    "patches": [ /* SessionPatch payloads in arrival order */ ],
    "expectedPatchResults": [ "applied" | "unchanged", … ],  // aligned with patches
    "expectedSession": { /* Session after folding all patches */ }
}

Replay contract

Fold over patches in order:

next = applySessionDetailPatch(session, patch)   // your port
results[i] = next == null ? "unchanged" : "applied"
session = next ?? session

Compare results against expectedPatchResults and the final session against expectedSession (canonical-JSON equality). unchanged is normative: it means the call reported "nothing changed — keep the previous object identity" (version-gated wrapper, sub-minute activeAt keep-alive, no-op assignment). A port that applies a stale wrapper, or that treats a keep-alive as a change, fails on the verdict even when the final session happens to match.

Both inputs are stored schema-normalized: initialSession is the parse output of SessionSchema and every patch is the parse output of the strict SessionPatchSchema (zod defaults applied, e.g. TodoItem.priority), so consumers decode the JSON verbatim — no schema re-run needed. The generator validates every authored patch against the wire schema, and the web self-check re-validates on every test run, so fixtures cannot drift from shared/src/schemas.ts.

Behavior deliberately pinned (see the individual descriptions):

  • versioned wrappers (metadata/agentState/todos/teamState) apply only when version is strictly greater than the cached watermark; equal and older versions are dropped regardless of value; absent todosUpdatedAt/ teamStateUpdatedAt watermarks count as 0
  • teamState wrapper with value: null clears the field (absent in expectedSession) and still stores the watermark
  • updatedAt is max-monotonic; an older updatedAt alone is unchanged
  • flat fields are last-write-wins; a serviceTier key explicitly present as null clears it
  • activeTurnStartedAt is not applied by the patch path (web behavior: no assignment branch) — a patch carrying only it is unchanged
  • a patch whose only effective change is an activeAt delta < 60s is unchanged and the cached activeAt does not move
  • scratchlistUpdatedAt is a refetch trigger only: unchanged, no session mutation

Pagination suite (pagination/)

Pins the message-window store: paging requests it must issue, epoch-reset handling, optimistic-send reconciliation, queued-row lifecycle, and window trimming (contract: docs/api/client-contract/pagination.md). Expectations are recorded from the real web store (web/src/lib/message-window-store.ts) driven by a scripted ApiClient.

Document schema (fixtureVersion: 1)

{
    "fixtureVersion": 1,
    "name": "older-page-epoch-mismatch-resets",   // equals the file name
    "description": "…",
    "ops": [ /* operation script, in order; see below */ ],
    "expectedState": { /* final window projection, see below */ }
}

Operations

Replay each op strictly sequentially against your ported store. Ops that hit the server carry responses — the scripted GET /messages replies, consumed FIFO — and the machine-recorded expectedRequests: the exact query objects the web store sent (limit only for a latest page; beforeAt+beforeSeq+ limit for older pages; afterAt+afterSeq+untilAt+untilSeq+epoch+ limit for tail catch-up, where untilAt/untilSeq are null on the first loop request). Your port must issue the same requests in the same order and consume every scripted response.

op Store operation (web name) Notes
sync-tail syncTailMessages Full tail sync; latest page when no usable cursor, else the after-cursor loop.
fetch-older fetchOlderMessages One older page. expectedOutcome is {kind:'applied', hasMore, addedRenderableCount} or {kind:'stopped', reason}. On an epoch mismatch the store runs an internal tail sync — its request/response belong to this same op and the outcome is stopped/epoch-reset.
sse-messages ingestIncomingMessages SSE message-received delivery (also advances the newest cursor when an epoch is cached — even past rows the pipeline hides).
append-optimistic appendOptimisticMessage Local optimistic row (id === localId). Does not advance the newest cursor.
update-status updateMessageStatus Client send-state transition by localId.
messages-consumed markMessagesConsumed SSE event: stamp invokedAt, flip status to sent (skip failed), re-sort by position; never advances the newest cursor.
message-cancelled removeOptimisticMessage SSE event / optimistic DELETE removal; matches localId or id; idempotent.
cancel-invoked remove + append DELETE answered {"status":"invoked"}: remove by localId, then ingest the returned message with client status sent (the harness adds the status).
set-view-mode setMessageViewMode tail re-entry trims to the visible window and, after a history overflow, forces a latest reset.
queued-state reconcile round trip Collect candidates (user rows with invokedAt === null, pinned in expectedCandidates, window order), apply invoked entries like messages-consumed, then drop candidates in neither queuedLocalIds nor invoked.

expectedState projection (normative)

{
    "messages": [ { "id", "localId", "seq", "createdAt",
                    "invokedAt"?,     // wire tri-state: absent / null / number
                    "scheduledAt"?,   // wire tri-state
                    "status"?,        // client send state when present
                    "queued": bool,   // user row ∧ invokedAt === null ∧ status ≠ 'failed'
                    "optimistic": bool } ],   // localId ∧ id === localId
    "hasMore": bool,                  // older history exists (server flag ∨ trim)
    "epoch": number | null,
    "viewMode": "tail" | "history",
    "olderCursor": { "at", "seq" } | null,   // next before-request position
    "newestCursor": { "at", "seq" } | null   // next after-request position
}

messages order is normative (position order: at = invokedAt ?? createdAt, ties by seq). The cursors are the store's compound paging positions (web internals oldestPosition* / newestPosition*); everything else that is web-internal (render/version counters, notification throttling, persistence) is intentionally NOT part of the contract.

Determinism notes: the web store's only wall-clock reads gate notification throttling and never touch this projection, so no time injection is needed — replays are exact. Fixtures keep every position pair distinct (no (at, seq) ties), so the web's id tie-break (localeCompare) never decides an order; native ports should still break full ties with an ASCII id comparison.


Catalogs

catalogs/ holds reference tables generated from shared/src modules (not from the chat pipeline) by the same generator, with the same canonical serialization and drift gate. Never edit them by hand.

  • catalogs/modes.json — generated from shared/src/modes.ts (web/scripts/fixtures/modesCatalog.ts imports the module directly, like the chat pipeline):

    • permissionModesByFlavor: for every AGENT_FLAVORS entry, the permission modes offered for that flavor in offer order, each as { mode, label, tone } (tone: 'neutral' | 'info' | 'warning' | 'danger'). An empty array means the flavor exposes no runtime permission switching (e.g. pi).
    • codexCollaborationModes: the codex-only collaboration axis as { mode, label } pairs.

    Natives port this table (mode ids, order, labels, tones) and should compare their port against the file in tests the same way as the chat fixtures: canonical-JSON equality.


Regeneration & drift gate

bun run gen:fixtures        # from the repo root (runs web/scripts/generate-fixtures.ts)

Output is byte-deterministic (canonical serialization), so git status after a regeneration is the drift signal: when web/src/chat/**, web/src/lib/sessionPatch.ts, web/src/lib/message-window-store.ts or web/src/lib/messages.ts change behavior, regenerated fixtures differ, the diff gets committed, and the native conformance suites go red until the ports catch up. The web-side self-checks (all in bun run test:web) re-run every stored input against the live implementation and fail on any divergence from the stored expectations or from canonical serialization:

  • web/src/chat/fixtures.test.ts — chat suite (also rebuilds catalogs/modes.json from shared/src/modes.ts and compares)
  • web/src/lib/sessionPatch.fixtures.test.ts — sse suite
  • web/src/lib/message-window-store.fixtures.test.ts — pagination suite