- HapiProtocol/Pairing/BindLink: parses the companion deeplink
(hapicompanion://bind?hub=&code=) and the web direct-access QR
(?hub=&token=) with URLSearchParams form-decoding semantics, in
lockstep with the Android port (tests mirror BindLinkTest.kt).
- HapiClient/Auth/HubPairingService: normalize -> GET /health
(reachability + protocolVersion) -> POST /api/auth -> persist
Keychain + registry + active hub; unpair with fallback. Covered by
PairingLogicTests through the HTTPPerforming seam.
- App layer: AppModel (@Observable @MainActor pairing state machine:
restore, pair, switch, sign out, deep-link routing, scenePhase,
terminal-auth-failure banner) + HubSession (per-active-hub APIClient/
AuthManager/global SSEClient with suspend-resume and a connection
state for the UI; store routing is TODO(M2)).
- Pairing UI: welcome flow, VisionKit QR scanner (with Simulator/
permission fallbacks), manual entry (paste-friendly), shared confirm
sheet with per-PairingFailure error states.
- HapiApp routes hapicompanion:// through AppModel (paired hubs switch
with a notice, never log the token); RootView switches unpaired/
paired and hosts the deep-link confirm sheet; HomePlaceholderView
shows hub, connection dot, hub switcher (M2a replaces it with the
session list).
- Info.plist: NSCameraUsageDescription; README: pairing guide + manual
test pass.
:core:data app.hapi.data.sse — the /api/events transport per
docs/api/client-contract/sse.md (reference web/src/hooks/useSSE.ts):
- SseConnection: SseTransport seam (Connected/Event/Failure flow) with the
okhttp-sse implementation on a dedicated client (readTimeout=0, no cache,
own dispatcher), buildEventsUrl, Last-Event-ID header on resume, and an
acceptEncodingIdentity fallback flag for the gzip escape hatch.
- ReconnectPolicy: normative constants + pure backoff schedule (immediate
first retry, 1s..30s exponential, 300s ceiling after 8 attempts, 0..500ms
injected jitter).
- SseEngine: per-key (global / session:<id>) connection loops — handshake
gate on connection-changed{status:connected} with ok/gap resume verdict,
per-key cursors advanced only after the downstream hand-off
(at-least-once), 10s connect deadline, 90s staleness watchdog ticking 10s,
one silent 401 re-auth per cycle costing no backoff attempt, background
retry deferral + 45s foreground stale check; all timing via injected
delay/clock for virtual-time tests.
- SyncEventRouter: 13-type union fan-out to the SyncTargets seam (M2 wires
stores), handshake gap -> requestFullResync, Unknown ignored.
Tests (32): virtual-time engine suite (fake transport + turbine), policy
schedule with seeded jitter, router mapping, and MockWebServer integration
through the real okhttp transport — including proof that gzip SSE frames
surface incrementally (flush-per-event body withheld behind a throttle).
Gzip also verified against a live local hub (Content-Encoding: gzip,
handshake decoded instantly, heartbeat +30.0s mid-stream).
Two new golden-fixture suites, expectations machine-generated from the web
implementation (same source-of-truth principle as the chat suite):
- shared/fixtures/sse/ (12 cases): session-updated versioned-patch
application via applySessionDetailPatch — strict version gates for
metadata/agentState/todos/teamState, out-of-order arrival, teamState:null
clear, max-monotonic updatedAt, flat last-write-wins fields, sub-minute
activeAt keep-alive drop, scratchlistUpdatedAt trigger, and the pinned
actual behavior that activeTurnStartedAt is NOT applied by the patch path.
Inputs are stored schema-normalized and validated against SessionSchema /
strict SessionPatchSchema at generation time; per-patch applied/unchanged
verdicts are part of the contract.
- shared/fixtures/pagination/ (11 cases): op scripts driving the real
message-window store with a scripted ApiClient — latest page + SSE ingest,
before-cursor older pages, epoch-mismatch reset (window discard + recorded
internal latest request), reset:true replace preserving optimistic rows,
localId echo reconciliation, messages-consumed invokedAt stamping (no
cursor advance), message-cancelled removal, cancel-too-late invoked-row
ingest, hidden-row cursor advance, 400-row trim preserving queued rows,
and queued-state gap recovery. Documents pin the exact requests the store
issued, older-load outcomes, reconcile candidates, and a minimal window
projection (ids/order, queued/optimistic flags, hasMore, epoch, viewMode,
compound cursors).
Generator: web/scripts/fixtures/{sse,pagination}/ extend the K5 framework
(canonical serialization reused; suites pruned of stale files). Web
self-conformance tests replay every fixture against the real implementation
in bun run test:web. README documents schemas, projections, replay
contracts, and native consumption for both suites.
No time injection needed: the store's only Date.now() reads gate
notification throttling, which never reaches persisted or projected state.
* feat(config): add agent config descriptor protocol and advertise via runner capability
Introduce shared agent configuration descriptors covering model, effort,
permission, and secondary settings per agent flavor, plus the canonical
HAPI YOLO -> native permission mode mapping. Runners advertise the
builtin descriptors through the runner-state capability so hubs and web
can render configuration without hardcoded flavor branches.
Migrate the OpenCode create-session model picker from a bespoke radio
list to the shared SelectControl combobox.
* feat(web): render create-session permission from agent config descriptor
Replace the flavor-branched Grok/Codex-family/YOLO permission block with
a descriptor-driven PermissionField. Pi now reports permission as managed
instead of silently ignoring the YOLO toggle, and YOLO-only flavors show
the native permission mode the preference maps to.
Removes the superseded GrokPermissionModeSelector and
CodexFamilyPermissionModeSelector components.
* ci: retry flaky claudeRemote 5s-timeout failure
* fix(web): persist explicit OpenCode Default selection instead of restoring a concrete model
The parent initialization effect treated every null selected model as
'uninitialized' and auto-picked a concrete advertised model, clobbering
the user's explicit Default choice (and a restored Default preference).
null now means explicit Default and is preserved; only undefined (no
choice made yet) triggers probe-based initialization. Add parent-level
regression tests for Default persistence and remembered-model restore.
* fix(web): accept undefined selected model in OpencodeModelSelector props
* feat(web+cli+hub): unify create-session model/effort fields and add Pi model/effort support
Pi's agent config descriptor now advertises model (machine) and effort
(static thinking levels) for create AND session availability:
- cli: ListPiModelsForMachine RPC runs 'pi --list-models' (cached, inflight
deduped) and parses the provider/model table; startup model match accepts
provider-qualified ids
- hub: GET /api/machines/:id/pi-models route + rpcGateway/syncEngine passthrough
- web: NewSession renders Pi models grouped by provider through the generic
ModelSelector and a new descriptor-driven EffortField (replaces the
per-flavor LaunchEffortSelector/ReasoningEffortSelector pair); launch payload
forwards Pi model + thinking-level effort (runner already supported --model/
--effort for pi)
* fix(web): render Pi provider groups in ModelSelector and scope Grok availability warning
- ModelSelector now renders grouped options as <optgroup> (Pi models are
provider-grouped; identical modelIds from different providers stay distinct)
- PermissionField only receives autoPermissionModeSupported for Grok — a
cached Grok probe result no longer leaks the Grok warning onto other agents
Addresses HAPI Bot Minor findings on #1469.
* fix(web): drop Object.groupBy from ModelSelector; revalidate restored Pi models against the catalog
- ModelSelector buckets options with a reduce instead of Object.groupBy
(Safari < 17.4 has no polyfill — New Session would throw on those clients)
- Pi restored model/effort are cleared when the value is absent from the live
machine catalog, and Create waits for the catalog while a non-default Pi
choice is being validated (mirrors Codex/Grok/Copilot handling)
Addresses HAPI Bot findings on #1469.
* fix(pi+web): serialize startup model before thinking level; hide Pi launch controls during history import
- PiSession gains startupModelSettled; the startup set_thinking_level waits for
the requested model's set_model attempt to settle first, so a level the
default model rejects is not lost before the requested model is confirmed
(set_model and set_thinking_level were already serialized by the runtime
mutation lock; this pins the model-first ordering)
- Create Session hides Pi model/effort controls while a Pi history import is
selected — the import reopens the native session as-is and would silently
ignore launch-only model/effort values
Addresses HAPI Bot findings on #1469.
* fix(pi): settle startup-model gate when model discovery fails or returns no models
A failed or empty get_available_models response would leave the
startupModelSettled gate unresolved, stranding a requested startup effort
indefinitely. Resolve the gate on the error path and the empty-models path;
adds regression tests for both.
* feat(web): composer model/effort value buttons and settings order
Wide composers now show [model] and [effort] value buttons for non-Pi
flavors (labels from the current session values), opening the settings
sheet on click. Narrow viewports collapse to the settings button only
via a new useNarrowViewport hook. The settings sheet reorders to
Model -> Effort -> Permission -> other settings (Fast mode,
collaboration, Copilot agent mode) so permission is first-class.
Toolbar customization gains 'model'/'effort' items with settings labels.
Pi keeps its dedicated model/thinking panels unchanged (unified
descriptor-driven sheet is a follow-up).
* fix(web): satisfy strict types in composer value-button test harness
* fix(web): address review findings on composer model/effort value buttons
- Normalize null/'auto'/'default' model wire values onto the value:null
option so default-model sessions keep a localized label button (Major)
- Exempt model/effort value buttons from the settings outside-click
dismissal so a second click closes the sheet instead of reopening it
- Read matchMedia synchronously in useNarrowViewport so narrow first
paints never flash the wide toolbar
- Add regression tests: model=null/'auto' labels, toggle-close behavior,
and initial narrow-viewport render
* feat(web): fold Pi into the generic composer model/effort value buttons
Pi sessions previously exposed model/effort twice: dedicated 'Pi model' /
'Pi thinking level' toolbar buttons (PiModelPanel/PiThinkingLevelPanel)
AND the settings sheet's generic Model/Effort sections. Consolidate so Pi
looks exactly like every other flavor:
- Pi now uses the generic model/effort value buttons; labels resolve from
the provider-qualified piModels catalog (name -> modelId -> session id).
- The settings sheet's Model section already renders provider-grouped Pi
rows and Effort renders Pi thinking levels, so the dedicated panels and
their toolbar slots are deleted.
- Keep Pi's mid-turn control affordance (#1442): Pi turns hold
thread.isDisabled for minutes, so Pi model/effort controls stay enabled
while a turn is running (configurationControlsDisabled instead of
controlsDisabled), including the sheet rows.
- Drop 'piModel'/'piThinking' toolbar layout items; persisted layouts
normalize them away automatically.
Tests: pi value-button label/sheet tests, mid-turn model selection via the
unified sheet, toolbar layout defaults.
* fix(web): keep a session-settings trigger on narrow viewports and mid-turn Pi
Address the HAPI review bot's two Minor findings on the Pi consolidation:
- Narrow viewports collapse the model/effort value buttons into the
settings sheet, so a persisted toolbar layout hiding the gear left no
session-settings trigger at all. ComposerButtons now forces the gear
back into the rendered layout on narrow viewports (wide layouts keep
honoring the user's hidden choice).
- The Pi mid-turn live-control rule only reached the value buttons and
sheet rows; with those buttons gone on narrow, the gear was still
disabled by controlsDisabled for the whole (minutes-long) Pi turn.
HappyComposer now passes settingsDisabled={modelEffortControlsDisabled}
so the gear stays clickable mid-turn for Pi exactly like the buttons.
Tests: narrow + hidden-gear layout keeps Settings; narrow Pi mid-turn
gear stays enabled and opens the provider-grouped sheet.
* fix(web): address HAPI Bot Pi settings-sheet findings
Three Minor findings from the review bot on the unified Pi sheet:
- Provider-qualified selection: rows compared only modelId, so duplicate
model IDs across providers all looked selected. Compare against
piSelectedModel's provider+modelId when available.
- Thinking-level reset: the removed Pi panel toggled the current level
back to null; the unified effort rows only submitted concrete values.
Re-clicking the selected effort row now clears it for Pi.
- Memo staleness: the settings-sheet memo did not depend on
modelEffortControlsDisabled, so a Pi disabled-state transition while
the sheet was open left rows enabled from the prior render.
Tests: colliding model IDs highlight only the matching provider row,
re-clicking the selected effort row sends null, and a rerender with
active=false disables the open sheet's rows.
* fix(web): include piSelectedModel in settings-sheet memo deps
The overlays memo reads piSelectedModel for provider-qualified row
highlighting but only declared the derived selectedPiModel. When
piSelectedModel hydrates from absent to a qualifier that resolves to
the same catalog object, the memo is reused and duplicate model IDs
stay highlighted across providers. Add the raw prop to the dep array.
* fix(web): gate Pi model rows on catalog; reset drill-down via value button
Address the HAPI Bot review on the unified composer settings sheet:
- Pi no longer falls back to the generic synthesized modelOptions rows
when its provider catalog is empty/loading. Selecting one of those
would post a bare model id that runPi cannot resolve to a provider
(first cached match or 409). The Model section now only renders for
Pi when piModelGroups exists, and renders grouped rows exclusively.
- Closing the sheet through the model/effort value button now goes
through handleSettingsToggle, so a Cursor variant drill-down resets
to the base model list on reopen (previously only the gear and
outside-click paths cleared it).
Tests: empty Pi catalog hides Model section; value-button close resets
Cursor drill-down.
* fix(web): hide Pi effort controls until the selected model resolves
Address the HAPI Bot review: with the catalog still loading/failed there
is no selectedPiModel to derive a capability map from, but the unified
effort control stayed enabled (mid-turn Pi controls are intentionally
live). Selecting a level would send set_thinking_level for a model that
may not support reasoning, and the RPC can be rejected after the sheet
closed. The old dedicated panel guarded this state.
showEffortSettings now requires a resolved, reasoning-capable Pi model;
the effort value button hides the same way. With an empty catalog Pi
exposes no settings trigger at all, matching the old control states.
Tests: unresolved Pi catalog mid-turn exposes no effort action.
* fix(web): hide the Pi model trigger until the catalog resolves
Address the HAPI Bot Minor finding: with an empty/loading Pi catalog the
model value button fell back to the bare session model id and rendered
an enabled trigger that opens no Model section. Show the button only
once the provider-qualified catalog entry resolves.
* fix(web): prevent replaying historical assistant output
* fix(web): handle history pagination during typing handoff
* fix(web): preserve streaming handoff across history windows
* fix(web): distinguish hydrated active runs from new output
* fix(web): preserve handoff across tail hydration
* fix(web): preserve first output in user-only turns
* fix(pi): settle autonomous agent lifecycles instead of swallowing them
When Pi starts an agent lifecycle on its own — a subagent completion
wake-up, scheduled work — no HAPI prompt is in flight, so the previous
prompt lifecycle has already delivered its settlement and
deliveredSettlement is still true. agent_start unconditionally set
thinking=true, but every settlement path (agent_settled delivery, the
legacy agent_end grace, the prompt-lifecycle fallback) was gated shut by
that stale flag, so the autonomous turn's completion was swallowed:
thinking stayed true forever, the FIFO pump stayed blocked
(piIsStreaming), new messages queued without ever being sent, and abort
waited on a settlement that could never arrive. The only escape was
killing the session.
Open a fresh settlement cycle when agent_start/turn_start arrives with
deliveredSettlement still true: reset deliveredSettlement,
agentEndObserved and activeAgentSettledSeen so the existing settlement
paths (direct agent_settled, legacy agent_end grace) apply to the
autonomous lifecycle. Prompt-driven lifecycles are unaffected because
beginPromptLifecycle has already reset the flag before their agent_start
arrives; mid-cycle retries are unaffected because their cycle has not
settled yet.
Evidence: hapi log 2026-08-13-18-39-10-pid-85758.log — 19:24:07
agent_start (no prompt accepted) → 19:25:40 agent_end + agent_settled
both swallowed → session stuck thinking=true for 27+ minutes until
killed.
* fix(pi): generation-scope the settled callback against autonomous lifecycle races
Review follow-up (HAPI Bot, Major): deliverSettlement() notifies
onAgentSettled only after an async conversationHistory.syncEntries().
An autonomous lifecycle can begin in that window; the stale finally
callback would then mark the new lifecycle's abort boundary as settled
before it emits agent_settled.
Capture lifecycleGeneration at settlement time and skip the
notification when it no longer matches, and advance the generation when
agent_start reopens a settlement cycle for an autonomous lifecycle so
the in-flight callback turns stale.
New regression test holds syncEntries open across the autonomous
agent_start and asserts the stale callback does not settle the new
boundary (fails without the fix).
* fix(codex): cache codex model list to avoid spawning app-server per request
listCodexModels() spawned a fresh `codex app-server` subprocess on every
request: exec a version probe, boot the app-server, validate the ChatGPT
session (token refresh over the network when needed), list models, then
kill the process. Fleet measurement showed 0.5-4.4s per call on healthy
machines and 33s (initialize timeout) on a machine with a slow OpenAI
network path, and the web refetches on every session open / dialog mount
(staleTime 30s).
Mirror the opencode model cache: cache successful non-empty lists for 5
minutes and coalesce concurrent requests into a single app-server spawn.
Failures and empty results are never cached, so a broken machine retries
on the next request.
Fixes#1533
* test(codex): cover TTL expiration of the model list cache
* fix(hub): retry Cursor SQLite cleanup on Windows
* test(hub): keep cleanup retry regression Windows-specific
* test(hub): exercise Windows cleanup retry in CI
* fix(codex): preserve native instructions
Keep HAPI guidance in the developer layer so app-server retains Codex persistence rules. Align long-running goal states with the Codex 0.147 protocol.
* fix(codex): filter new goal statuses
* fix(web): preserve current Fork action while reading history
* fix(web): invalidate stale Fork boundary during history updates
* fix(web): invalidate Fork boundary after message consumption