Files
hapi/android
Junmo KimandGitHub 523decdf86 fix(hub): fold repeated ACP tool-call updates into one row per callId (#2350)
* feat(shared): read the callId of a supersedable tool-call row

ACP agents re-emit the same tool call under a stable callId on every
state tick, and the timeline folds all of those rows into one card. The
hub and the web both need to recognise the rows that may be superseded,
so add `getToolCallId`, mirroring `getReasoningStreamId`/`getLiveReasoningStreamId`.

Only `codex`/`tool-call` payloads match. The `tool-call-result` that
shares the callId is a different row type that carries completion, so it
never matches and is never dropped. Anything unrecognised reads as null
("keep it").

* fix(hub): fold ACP tool-call updates into one row per callId

ACP agents re-emit a tool_call agent message for the first tool_call and
again for every tool_call_update, all under one callId, and the hub stored
each as its own row. History pages therefore filled with 2-4 duplicate
tool-call rows per call that the web then folded back into a single card
by callId.

Route agent tool-call messages (getToolCallId != null) through an upsert:
scan the session tail for a live tool-call row with the same callId,
stopping at a tool-call-result with that callId or at a user message row
(both mean the incoming message is a new call). On a match, merge the new
payload into the stored row in place — non-null new values win for
name/input/nativeTitle/nativeKind/nativeName/nativeArgs/status so a
status-only tick cannot erase an earlier tick's input — and keep the
row's id, seq, createdAt and localId. The content swap follows the
queued-message edit pattern (no new seq, no content_revision bump).

The post-store broadcast is unchanged (session-room update + web
message-received) and now carries the existing row's id/seq with the
merged content, which the web window store already upserts by id.
Nothing is deleted: result rows, permissions, localId resend handling
and non-tool messages behave exactly as before.

* fix(hub): never regress a merged tool-call row's status

A later tool-call tick that re-emits status pending (agents normalize a
missing/unknown status to pending, so OpenCode permission rounds resend
it after the call already ran) overwrote an earlier in_progress or
terminal status under the plain newest-non-null-wins merge.

Merge status by progression rank instead: pending < in_progress <
completed/failed. The merged row keeps the higher rank, so a running or
finished call never falls back to pending, and a terminal status always
wins over a non-terminal one in either direction. completed/failed share
the terminal tier and ties keep the newer value; unrecognized status
strings rank below every known state so they cannot regress one either.

Also pin the behaviors the upsert relies on with tests: the 200-row
lookback boundary on both sides, a tool-call-result for a different
callId not stopping the scan, nativeName/nativeArgs/progress merging,
and the handler re-broadcasting the existing row id/seq through both the
session-room update and web message-received without storing an extra
row.

* fix(hub): stamp derived tool state at merge time and skip no-op tool-call writes

A merged tool-call row keeps its first snapshot's createdAt for stable
ordering, but the session's derived TodoWrite/team versions gate on
strictly advancing timestamps (todos_updated_at and team_state_updated_at
only accept candidates greater than the stored watermark), so a refined
snapshot arriving on a later tick of the same callId was rejected and the
session's todo list stayed at its first snapshot. Stamp those versions at
merge time instead.

A re-emitted tick whose payload changes nothing now skips the row write
entirely: only observable content changes touch the database.

* fix(web): recover merged tool-call rows after an SSE replay gap

A gap resume (resume: 'gap') cannot prove continuity, and in-place
tool-call merges keep the row's original cursor position, so the
cursor-based tail sync after a gap re-delivered new rows but never the
merged content of rows the window already held. Tool cards could stay
stuck on their first snapshot until a reload.

On the gap path of both connect handlers, reconcile the window from an
authoritative latest page applied as an upsert: rows in the response
replace the held rows by id, while already-loaded rows older than the
latest page and the hasMore/oldest cursor and context survive; an older
load caught in flight is invalidated like on every tail sync and is
re-requested by the user's scroll. Replacing the whole window is not an
option here: a fresh session subscription is always a gap verdict, so
every session switch-back would throw away the user's scrolled-up
history. Rows older than the latest page are not re-fetched; a live
tool-call tick always updates a row inside the newest page, and a
failed recovery fetch leaves the flag set so the next sync retries the
latest page. Cold and structurally invalidated windows keep the plain
reset choreography.

* fix(web): catch up the disconnected interval before the gap-recovery upsert

Gap recovery fetched only the newest page and applied it as an upsert,
so a warm window whose cached tail sat below the page's oldest row kept
a permanent hole: rows that arrived while disconnected between the
cached tail and the page vanished, and the advanced newest cursor never
filled them (cursor syncs only return rows after their cursor).

Run a plain cursor sync first so the window catches up every row it
missed, then apply the authoritative latest page as an upsert to
refresh in-place merged rows. One extra round trip on reconnect; the
upsert alone stays correct for windows that are already contiguous.

* fix(web): replace retained rows when gap recovery observes a different epoch

The recovery upsert requested the latest page without an epoch and the
hub always answers reset:false for latest requests, so rows deleted
while disconnected survived: another client's rewind deletes rows and
bumps the epoch, but the missed messages-invalidated event left the
window's requiresLatestReset false and nothing detected the change.

Compare the response's epoch with the window's epoch in the latest-page
branch and fall back to a full replacement on mismatch. The cursor
catch-up that now precedes the upsert already carries the window epoch
and gets the hub's reset verdict, so this closes the remaining window
where the upsert runs without a preceding successful epoch-carrying
sync.

* fix(web): require a successful catch-up before the gap-recovery upsert

runTailSync resolves normally after catching a request error, so the
recovery continued to the latest-page reconciliation even when the
catch-up failed. With a cached tail at row 10 and the server head at
310, a failed after request followed by a successful latest request
retained row 10 alongside rows 111-310 and advanced the newest cursor
to 310: rows 11-110 became unreachable through ordinary tail or older
paging, and the successful latest response cleared the failure warning.

Fold the recovery into the tail sync itself: the pendingGapRecovery run
catches the window up through the ordinary cursor phase and only
reconciles the latest page once that phase completed without error. A
reset verdict inside the catch-up already replaced the window
authoritatively, so the recovery flag is simply consumed there. On a
catch-up failure the catch skips the reconciliation, keeping the
original cursor, the flag for the next sync's retry, and the visible
warning.

* fix(web): keep the loaded history budget across the gap-recovery upsert

applyLatestResponse always trimmed the merged window to the 400-row
tail budget, even when only refreshing it in place. A reader with 600
loaded history rows therefore lost the oldest rows on a same-epoch
reconnect with no new messages, shifting their reading anchor even
though nothing on the server changed.

Size the recovery upsert's trim to the window's own history budget,
capped at the 800-row older-load ceiling: rows the reader already
loaded are preserved on a no-news recovery instead of being re-evicted.
Full replacements keep the tail budget, since a replaced window holds
only the response rows anyway.

* fix(web): run the catch-up when gap recovery overlaps a cached activation

A cached session's activation asks for a direct latest page
(preferLatestOnActivation), and runTailSync's canIncrement excluded that
flag unconditionally. When gap recovery was requested on top of such an
activation, the recovery therefore took the activation shortcut: a
direct latest-page fetch with no cursor catch-up. With cached rows 1-10
and the server head at 310, the window retained rows 1-10 plus the
latest page 111-310 and advanced its newest cursor to 310, leaving rows
11-110 unreachable through ordinary tail or older paging; the recovery
flag was consumed without ever catching the window up.

Let a pending recovery claim the cursor path even when an activation
shortcut is pending, and defer the activation flag for that run: the
recovery's catch-up + latest-page reconciliation subsumes the
activation's refresh-from-latest, so consuming it there is equivalent.
The flag is also cleared when the recovery finishes through a reset
verdict or its latest-page reconciliation, so a mid-run activation
cannot linger into a later full replacement.

* fix(web): refresh out-of-page tool-call rows during gap recovery

A tool-call row cached before a disconnect can be enriched in place
afterwards; when more than a latest page of newer rows follows before
reconnect, neither the catch-up (newer rows only) nor the latest page
reaches it, and the cached card keeps its stale input/status until the
session is reopened (review finding on hub messages.ts:378, the web
half of the documented jkRY limit).

After the recovery's latest-page reconciliation, sweep the window for
retained non-terminal tool-call rows older than the page bound and
older than the recovery cursor, and refresh each by id through the
existing message-context endpoint. Bounded at 20 (newest first),
best-effort (a failed or epoch-mismatched refresh leaves the row to the
next recovery), and generation-guarded like the rest of the run.

* fix(web): surface gap-recovery refresh failures as the usual sync warning

The out-of-page tool-call refresh sweep swallowed per-row context-fetch
errors, leaving a stale row silently. Let a rejected refresh propagate
to runTailSync's catch so the run's usual warning surfaces; the row
stays as is and the next sync retries the sweep. A refresh answered
under a different epoch, or one that no longer contains the row, stops
the sweep without touching the window. Terminal rows are never swept
(merge status only advances); tests pin the zero-request skip and the
warning on failure.

* fix(android): recover merged tool-call rows through the gap-recovery upsert

The Android window store's gap path recovered through a cursor sync
only: merged tool-call rows keep their original cursor position, so a
row enriched while disconnected kept its stale input/status until a
fresh page happened to include it (the same hole the web recovery
closed).

Port the web choreography: the gap entry point (resume: 'gap' on the
session pipe) flags the window (pendingGapRecovery) and runs
recoverAfterGapResume; the next tail sync catches up the missed
interval with the cursor sync, then fetches an authoritative latest
page and applies it as an upsert — rows present in the page are
replaced by id while rows older than the page, the hasMore/oldest
cursor and the loaded history budget (up to the 800-row older-load
ceiling, mirroring the web trim) survive. An epoch mismatch under the
page falls back to full replacement, a reset verdict during the
catch-up consumes the recovery, and a failed catch-up keeps the flag
and the original cursor so the next sync retries the whole recovery. A
recovery requested while a cached activation's preferLatestOnActivation
is set claims the cursor path and defers the activation shortcut, and
the tail-sync coalescing joins or replaces in-flight runs by their
snapshotted recovery/activation mode like the web does. The queued
-state reconciliation keeps its own ensureAfterCurrent drain and runs
concurrently with the recovery, mirroring the web's two post-gap calls.

The bounded by-id refresh of out-of-page non-terminal rows stays
web-only (Limits follow-up; it needs the message-context endpoint in
the native API seam).

* fix(ios): recover merged tool-call rows through the gap-recovery upsert

Mirror of the Android recovery port for the HapiKit window controller:
the session layer's resume: 'gap' handling now flags the window
(pendingGapRecovery) and runs recoverAfterGapResume alongside the
queued-state reconciliation, and the tail sync catches up the missed
interval with the cursor sync, then fetches an authoritative latest
page and applies it as an upsert — rows present in the page are
replaced by id while rows older than the page, the hasMore/oldest
cursor and the loaded history budget (up to the 800-row older-load
ceiling, mirroring the web trim) survive. An epoch mismatch under the
page falls back to full replacement, a reset verdict during the
catch-up consumes the recovery, and a failed catch-up keeps the flag
and the original cursor so the next sync retries the whole recovery. A
recovery requested while a cached activation's preferLatestOnActivation
is set claims the cursor path and defers the activation shortcut, and
syncTail coalescing joins or replaces in-flight runs by their
snapshotted recovery/activation mode like the web does.

Tests run in CI (Swift toolchain is not available on this machine):
recovery converges the merged row through catch-up + latest page, and a
failed catch-up stops before the latest page and retries on the next
recovery. The bounded by-id refresh of out-of-page non-terminal rows
stays web-only (Limits follow-up).

* test(ios): read the window-message envelope from content, not wire

The new gap-recovery tests compared the merged tool-call row through a
`.wire` accessor that does not exist on WindowMessage (the
role-wrapped envelope lives on the public `content` field; `wire` is
only the convenience initializer's parameter name), which failed to
compile the whole HapiKit test target in CI. Compare the envelope
content values directly — still by value, not by WindowMessage
identity.

* test(ios): read the retry requests off the cumulative request list

provider.requests accumulates across the whole test: the failed first
catch-up stays at index 0, so the retry's catch-up and latest page sit
at indices 1 and 2 — the assertion counted from the retry point and
failed in CI even though the retry behaved exactly as pinned
([after, after, latest]).

* fix(web): keep the reset requirement when the recovery catch-up overflows

A recovery catch-up page can overflow the window's history budget:
history-mode trimming keeps the reading anchor, drops the newer
caught-up rows, and marks the window for a reset
(mergeIntoWindow's prepend trim). The loop breaks on
requiresLatestReset without distinguishing that overflow from a
completed catch-up, and the recovery then reconciled the latest page
on top anyway and consumed the recovery flags — stranding the rows
between the reset-marked window and the page, unreachable from either
cursor (older paging descends from the window edge, the newest cursor
has already passed them).

When the catch-up ends with the window reset-marked, leave the reset
requirement and the recovery flags intact: the next sync's
authoritative replacement closes the hole and consumes the flags, the
same choreography as every other reset-marked window.

* fix(web): finish the sync when the gap-recovery refresh sweep stops early

The out-of-page tool-call refresh sweep early-returned when a context
response no longer contained the row or answered under a different
epoch, bypassing finishTailSync and leaving the window marked syncing
after the controller promise resolved — suppressing tool-history
hydration and read receipts until another sync ran.

Complete the run's bookkeeping on both exits: a missing row finishes
with the usual warning and the row as is; an epoch mismatch marks the
window for the authoritative replacement (server rows may have been
deleted since the page was fetched) and finishes with the warning
instead of reconciling against a stale snapshot.

* fix(android): keep the reset requirement when the recovery catch-up overflows

A recovery catch-up page can overflow the window's history budget: the
history-mode prepend trim keeps the reading anchor, drops the newer
caught-up rows, and marks the window for a reset. The catch-up loop
breaks on requiresLatestReset without distinguishing that overflow from
a completed catch-up, and the recovery then reconciled the latest page
on top anyway and consumed the recovery flags — stranding the rows
between the reset-marked window and the page, unreachable from either
cursor.

When the catch-up ends with the window reset-marked, leave the reset
requirement and the recovery flags intact: the next authoritative
replacement (on returning to the tail view, or on a sync that may reset
history) closes the hole and consumes the flags, the same choreography
as every other reset-marked window. Mirrors the web fix.

* fix(android): keep the earlier older cursor when the recovery upsert retains rows

When the recovery's latest-page upsert retains rows older than the
page (no trim), applyLatestResponse still preferred the response page's
own bound as the older-paging cursor, so an 800-row no-news recovery
re-pointed older loads at the page's oldest row and left the held rows
1-600 unpaged. Keep whichever side is older, like the web has since the
loaded-history-budget fix.

* fix(android): refresh out-of-page tool-call rows during gap recovery

Port the web sweep: after the recovery's latest-page reconciliation, the
window re-reads its retained non-terminal tool-call rows that sit older
than the page bound and were not delivered fresh by the catch-up through
the existing message-context endpoint — bounded at 20 newest-first, with
the same exit semantics the web sweep carries (a missing row finishes
the run with the usual warning and the row as is; a refresh answered
under a different epoch marks the window for the authoritative
replacement and finishes with the warning).

The seam gains getMessageContext (wire types MessageContextPage/
MessageContextResponse; the hub answers a bare null when the message
does not resolve), implemented by HapiApi and scripted null in the
fakes.

* fix(ios): keep the reset requirement when the recovery catch-up overflows

Mirror of the Android/web recovery overflow fix: a recovery catch-up
page can overflow the window's history budget — the history-mode
prepend trim keeps the reading anchor, drops the newer caught-up rows,
and marks the window for a reset — and the recovery then reconciled the
latest page on top anyway and consumed the recovery flags, stranding
the rows between the reset-marked window and the page, unreachable from
either cursor.

When the catch-up ends with the window reset-marked, leave the reset
requirement and the recovery flags intact: the next authoritative
replacement (on returning to the tail view, or on a sync that may reset
history) closes the hole and consumes the flags. Test rides CI — no
Swift toolchain on this machine.

* fix(ios): keep the earlier older cursor when the recovery upsert retains rows

Mirror of the Android/web cursor fix: when the recovery's latest-page
upsert retains rows older than the page (no trim), applyLatestResponse
still preferred the response page's own bound as the older-paging
cursor, so an 800-row no-news recovery re-pointed older loads at the
page's oldest row and left the held rows 1-600 unpaged. Keep whichever
side is older, like the web has since the loaded-history-budget fix.
Test rides CI.

* fix(ios): refresh out-of-page tool-call rows during gap recovery

Port the web sweep: after the recovery's latest-page reconciliation, the
window re-reads its retained non-terminal tool-call rows that sit older
than the page bound and were not delivered fresh by the catch-up through
the message-context endpoint — bounded at 20 newest-first, with the same
exit semantics the web sweep carries (a missing row finishes the run
with the usual warning and the row as is; a refresh answered under a
different epoch marks the window for the authoritative replacement and
finishes with the warning).

The transport gains the endpoint end to end: MessageContextPage/
MessageContextResponse wire types (the hub answers a bare null when the
message does not resolve), APIClient.messageContext, the MessagesProviding
requirement, and the row-swap helper on the window logic. agentMessage-
PayloadType becomes public so the controller can classify rows like the
web does. Tests ride CI — no Swift toolchain on this machine.
2026-11-11 13:05:04 +08:00
..

HAPI Android

Native Android client (Kotlin + Jetpack Compose) for the HAPI hub. Fully independent from the web app; shares the client contract and the web-generated golden fixtures (shared/fixtures/).

End users: install HAPI from Google Play. This README covers development builds.

  • applicationId: run.hapi.companion · minSdk 26 · target/compileSdk 36
  • Toolchain: Gradle 8.14.2 (wrapper) · AGP 8.11.1 · Kotlin 2.1.21 · Compose BOM 2025.05.00 · JDK 17+ (CI uses 21)

Current capabilities

The app provides sessions/chat, approvals and questions, new sessions, attachments, files/Git, Scratchlist, standard dictation, usage/storage, settings and encrypted-relay or direct-FCM notifications. Model and permission controls follow agent/session capabilities; usage/storage require the owner namespace. See the native app guide for platform differences, pairing and features currently available through the web.

  • Session actions: pin/archive plus Rename, Delete and explicit Reopen from the list/chat actions. Delete requires an inactive session. Resume or Reopen can return another session ID: seed its window, move the draft and replace navigation with the returned ID.
  • Composer: optimistic send, queue/steer where supported, drafts and attachments uploaded on selection. Slash suggestions combine session metadata and the slash-command RPC; the skills $ picker has no UI.
  • Incoming shares: Android Share → HAPI accepts single/multiple files, captions, text and links. Choose a session on the current or another paired hub; stopped sessions require explicit restore before upload. Content is added to the existing composer for manual sending. Private, no-backup staging survives pairing and process recreation until handoff, with a 24-hour pending-content lifetime. Once imported, attachments follow the ordinary composer lifecycle (they are not persisted as attachment drafts).
  • Dictation: provider discovery on chat entry picks the first standard-capable provider. The microphone stays hidden until one is available. First use requests RECORD_AUDIO; MediaRecorder records m4a/AAC, multipart transcription inserts text into the draft without sending. DictationController is tested with recorder/API fakes.
  • Background actions: FCM permission Allow/Deny and inline Reply enqueue WorkManager jobs. Workers resolve paired hubs using stored credentials, without requiring a foreground HubGraph. Firebase-free builds skip push.

Building

Native chat scrolling architecture and acceptance checklist: Native transcript scrolling.

Requires an Android SDK for :app/:core:data (set ANDROID_HOME or android/local.properties with sdk.dir=...). :core:protocol alone needs only a JDK.

cd android
./gradlew :core:protocol:test :core:data:testDebugUnitTest :app:testDebugUnitTest
./gradlew :app:assembleDebug :app:lintDebug
./gradlew :app:installDebug                  # connected device
./gradlew :app:connectedDebugAndroidTest     # emulator/device instrumentation

Without an Android SDK you can still run the protocol suite by configuring only the needed projects:

./gradlew --no-configuration-cache --configure-on-demand :core:protocol:test

CI (.github/workflows/android.yml) runs protocol/data/app unit tests, :app:assembleDebug, :app:lintDebug, and Compose instrumentation on API 29 and API 36 for PRs touching android/** or shared/fixtures/**.

Protocol conformance fixtures

:core:protocol is the porting target for web/src/chat/ and is verified against golden fixtures generated from the web implementation. The test task already passes the fixtures location as a system property:

// core/protocol/build.gradle.kts
tasks.test {
    systemProperty("hapi.fixtures.dir", rootDir.parentFile.resolve("shared/fixtures").absolutePath)
}

Fixture-driven tests read System.getProperty("hapi.fixtures.dir") from the checked-in golden fixture set. CI re-runs this suite whenever android/** or shared/fixtures/** change.

Fixtures pin protocol/state semantics, not identical web/native presentation. When changing fixture inputs or generation, run bun run gen:fixtures at the repo root and include generated changes; never hand-edit fixtures. See the fixture guidance.

Pairing

HAPI is self-hosted: the app talks to a hub you run. Pairing = giving the app a hub URL plus that hub's access token; the app verifies the hub (GET /health, requiring the supported protocol version exactly), exchanges the token for a JWT (POST /api/auth), stores the credentials in EncryptedSharedPreferences (keyed per hub — multiple hubs can be paired, one active at a time), and lands on the session UI. Three entry points:

  1. QR scan — the hub prints two QR codes when started with --relay (also under web Settings → Companion pairing). The in-app scanner accepts both: the companion deeplink (hapicompanion://bind?hub=…&code=…) and the web direct-access URL (…?hub=…&token=…).
  2. Deep link — scanning the companion QR with the system camera opens the app directly with a confirm screen (hapicompanion://bind intent filter).
  3. Manual entry — hub URL + access token, for hubs started without --relay.

Pairing against a development hub

# Start a hub with the built-in HTTPS relay (prints the access token + QR codes).
hapi hub --relay

# Use the printed https:// URL. For a source-tree `bun run dev` hub, put an
# HTTPS reverse proxy or tunnel in front of localhost:3006 first.
adb shell am start -a android.intent.action.VIEW \
  -d "hapicompanion://bind?hub=https%3A%2F%2Fhub.example.com&code=<accessToken>"  # optional: exercises the deep link

The app rejects plain-http hub URLs in manual entry, deep links, QR codes, and restored hub state. The manifest also sets android:usesCleartextTraffic="false"; there is no debug or LAN exemption. Sign-out (home → Hubs and settings → Sign out) deletes the stored credentials for that hub and drops it from the roster.

Temporary authentication refresh failures (network/5xx) keep paired credentials. A rejected access token or a second 401 after a successful refresh requires re-pairing. See the auth contract.

Firebase / push

Official Firebase builds: pair an updated hub and allow notifications. The official Firebase client configuration is bundled in the app. Hubs without a private FCM_SERVICE_ACCOUNT_PATH use the official push relay automatically; users do not create Firebase projects or configure service-account keys. Google Play services and FCM connectivity are needed. The push relay also works with hubs accessed through Tailscale or other HTTPS setups; it is independent of hapi hub --relay.

Private builds: create a Firebase project for your application ID, download google-services.json into android/app/, and configure the hub's FCM_SERVICE_ACCOUNT_PATH for that same project. Existing configured hubs keep direct delivery under the default HAPI_ANDROID_PUSH=auto. Use relay, fcm, or off to select explicitly. HAPI_PUSH_RELAY_URL overrides the shared Android/iOS relay URL. One hub cannot mix private-project builds and official-project builds.

Builds without Firebase: the Google services plugin stays conditional. Without app/google-services.json, Firebase does not initialize and push paths no-op; ordinary PR builds require no credentials. Official builds use a separate mandatory configuration check (below).

Encrypted relay: the app registers its FCM token, install ID and random 32-byte pushKey with every paired hub. The ID/key are persisted together in Keystore-encrypted preferences excluded from cloud backup and device transfer. First upgrade replaces the old DataStore identity through the hub's token deduplication; later token rotations reuse the ID/key. On start, pairing, token rotation and worker retries, registrations refresh automatically. Sign-out unregisters before wiping that hub's credentials.

Relay messages carry only hapi_v/hapi_e. AES-256-GCM decryption uses the same golden vector as iOS; notification content is unavailable to the relay and Google. Failed decrypts are dropped. Direct private FCM retains its existing unwrapped data payload. Rendering, foreground-chat suppression, Allow/Deny and Reply workers use the same decoded PushPayload in both paths. input-request notifications instead preview the first question, remaining question count and session name, using the HIGH-importance input_requests channel. They offer no Allow/Deny or message Reply: tap to open the session and answer in the question form. The notification contract still does not name the sending hub: action workers try the active hub first, then other paired hubs on session miss; tapping opens the session against the active hub.

See native companion contract for wire details and relay deployment for maintainer setup.

Official APK/AAB builds

The Android Official Build workflow is manually dispatched on main. It tests and uploads signed APK/AAB workflow artifacts. It does not publish to Google Play itself; the maintainer uploads the AAB to the Play Console. Provide a new positive version_code and the desired version_name.

Repository configuration, set once by the maintainer:

Setting Value
Variable ANDROID_FIREBASE_PROJECT_ID Project used by the deployed relay's FCM service account
Secret ANDROID_GOOGLE_SERVICES_JSON Firebase client config for run.hapi.companion in that project
Secret HAPI_UPLOAD_KEYSTORE_BASE64 Base64-encoded release keystore
Secret HAPI_UPLOAD_KEYSTORE_PASSWORD Keystore password
Secret HAPI_UPLOAD_KEY_ALIAS Optional, defaults to upload
Secret HAPI_UPLOAD_KEY_PASSWORD Optional, defaults to store password

-PhapiOfficialBuild=true -PhapiFirebaseProjectId=<project> requires a matching Firebase project/package and release signing configuration. Missing or mismatched settings fail the build instead of shipping a package without working push. hapiVersionCode and hapiVersionName override the normal version defaults. The Firebase service-account private key belongs only on the relay and must never enter Android build artifacts.

Roll out relay support/credentials first, then the hub, then the app. Verify real background, lock-screen and cold-process notifications using a hub with no Firebase settings; test Allow/Deny/Reply and an iOS push before publishing.

Release signing

Builds do not require signing secrets. :app:bundleRelease produces an unsigned AAB unless an upload key is configured via gradle properties (user-global ~/.gradle/gradle.properties), environment variables (CI secrets), or android/local.properties (gitignored; same property names — the conventional machine-local home, loaded explicitly since it is not part of gradle's own property chain):

gradle property env meaning
hapiUploadKeystore HAPI_UPLOAD_KEYSTORE keystore path (~ ok)
hapiUploadKeystorePassword HAPI_UPLOAD_KEYSTORE_PASSWORD store password
hapiUploadKeyAlias HAPI_UPLOAD_KEY_ALIAS default upload
hapiUploadKeyPassword HAPI_UPLOAD_KEY_PASSWORD default: store password

This is an upload key for Play App Signing (Google holds the actual distribution key, so a lost upload key is resettable in Play Console). Generate one with:

keytool -genkeypair -v -keystore ~/.hapi/upload.keystore -alias upload \
  -keyalg RSA -keysize 2048 -validity 10950

Keystores never live in the repo (*.keystore / *.jks are gitignored).

Modules

Module Type Responsibility
:core:protocol pure Kotlin/JVM (no Android) Hub wire types, chat pipeline, message pagination, versioned patches, agent/mode catalogs, git parsers, pairing links, and golden-fixture conformance tests.
:core:data Android library OkHttp API/SSE transport, per-hub authentication, secure credentials, StateFlow stores and disk snapshots, encrypted push registration/decoding, and background notification actions.
:app Android application Compose screens for pairing, sessions/chat, approvals, new sessions, files, Scratchlist, dictation, usage/storage, and settings; navigation, localization, FCM service, and WorkManager wiring.

Dependency direction: :app → :core:data → :core:protocol.

Internationalization

The app ships English (default) and Simplified Chinese (app/src/main/res/values-zh-rCN/strings.xml). App UI strings live in resources; both files carry the same key set (lint MissingTranslation is the gate).

Adding a string

  1. Add it to app/src/main/res/values/strings.xml with a feature-prefixed key matching the existing convention (chat_, sessions_, files_, scratchlist_, pairing_, settings_, new_session_, notif_, tool_ for tool-card titles). Dynamic values use positional format args (%1$s, %2$d); count-dependent copy uses explicit _one/_many keys (the deliberate house style — no <plurals>).
  2. Add the zh-CN twin to values-zh-rCN/strings.xml. Terminology source of truth is the web corpus web/src/lib/locales/zh-CN.ts — reuse its product terms (会话 session, 机器 machine, 权限模式 permission mode, 工作树 worktree, 草稿夹 scratchlist, 语音输入 dictation, 用量 usage, 智能体/代理 agent). Technical identifiers (model ids, flavor names like Claude/Codex, permission-mode catalog labels, CLI flags) stay untranslated, matching the web's choices.
  3. Reference it: composables via stringResource(R.string...). ViewModels stay string-free — transient notices are semantic sealed types (ChatNotice, ScratchlistNotice, PairingError, DictationErrorKind) resolved at the UI layer; where a ViewModel genuinely composes display text it takes a small Strings seam (FilesStrings, FileViewerStrings, NewSessionStrings) whose defaults are the English values (JVM tests construct without arguments) and whose production instance is resource-resolved in the Navigation holders. Server-provided error text passes through verbatim.

Language switching

Settings → App language offers Follow system (default) / English / 简体中文. The choice persists in LanguagePrefs (DataStore) and applies immediately via AppCompatDelegate.setApplicationLocales:

  • MainActivity extends AppCompatActivity (theme parent Theme.AppCompat.DayNight.NoActionBar) so per-app locales work back to API 26; on API 33+ the framework LocaleManager takes over (the app also declares android:localeConfig for the system App-languages screen).
  • The manifest opts into appcompat's autoStoreLocales (AppLocalesMetadataHolderService meta-data), which re-applies the stored choice synchronously on cold start.
  • Surfaces that resolve strings from the application context — FCM notifications, WorkManager result updates, notification-action receivers — wrap their context with localizedForAppLanguage(AppGraph.appLanguage) (di/LocaleContexts.kt), since per-app locales only retarget activity contexts below API 33.

Out of scope on purpose: :core:protocol presentation strings (getEventPresentation, tool-group activity titles) stay English — the web does not translate them either, and terminology parity with the web wins.

Tool previews

Ordinary chat tools stay compact summaries. Tap a tool or tool group to open a native Navigation Compose page; Back returns one level, Close returns to the chat. Groups start at their latest tool, retain their position when returning from details, and never follow streaming updates automatically. The Latest tool toolbar action scrolls explicitly. Agent processes have their own page with lazy child rows. Approvals remain in the conversation or a live process page; ordinary tool detail pages are read-only.

Plan proposals (ExitPlanMode / exit_plan_mode) start fully expanded in the conversation, rendering the complete input.plan Markdown before approval controls. Tapping the header folds the card. Plan documents are prewarmed in the chat Markdown cache and do not use the ordinary tool-output paging budget; raw input/result remains under Source. Shared Codex proposals also show Implement plan and Continue planning when the active session's agentState.codexPlanProposalId matches the tool-call id. Implementation uses the dedicated plan endpoint, not permission approval; continue hides that proposal’s action menu locally and focuses the composer, preserving its draft and plan mode without sending a message. The plan document remains readable, and a new proposal gets a fresh menu. The menu stays visible when the document is folded; pending/error state survives row recycling. Withdrawn, historical and child proposals remain read-only (an outstanding operation/error can still be shown).

Details recognize namespaced command/script/patch calls, unwrap common nested result envelopes, and keep command exit/status metadata visible. File reads use source-language highlighting; web/agent prose uses Markdown. Source reveals the original input/result, including fields omitted from the preview. Mixed text/media results stay JSON instead of dropping non-text blocks.

Question details show recorded selections, custom answers and notes with Markdown questions/options. Codex choice questions with isOther: true add None of the above and focus optional notes when selected; empty notes are valid. Translations never change the submitted None of the above wire value. Pi/MCP forms without isOther keep their existing choices. Recorded other answers and notes are also shown in question details. request_user_input also restores answers from historical results; live permission answers take precedence. Answered cards avoid duplicate results, but retain errors and the full input/result/answers under Source. Pending questions are answered in the conversation.

Tool inputs/outputs display one part at a time, up to 20,000 Unicode graphemes or 400 source lines. Previous/Next replace the mounted part; visited parts do not accumulate. Large diffs/Markdown use paged source. JSON formatting and output preparation run off the UI thread. File mutation details also offer View current file, distinct from the recorded tool input/result.

Inspectors share the conversation's pipeline and SSE subscription. Opening one freezes tail following, cancels hidden history loading and recording, and hides the keyboard. Returning retains the transcript anchor. Trimmed selections remain readable as labeled snapshots; an epoch reset closes obsolete inspectors.

Long messages and reading layout

User prompts remain inline through 8,000 graphemes and 120 source lines. Larger prompts show a 2,000-grapheme / 24-line preview and View full message opens a reader with one 4,000-grapheme / 80-line part mounted. Pagination preserves whitespace, CRLF, emoji and combining sequences exactly; character counts refer to Unicode graphemes, not UTF-16 offsets.

Copy full content uses the clipboard up to 64 Ki UTF-16 code units. Larger content, or a failed clipboard operation, offers UTF-8 file export through FileProvider and Android's sharesheet; Binder receives a URI, not the text. Exports older than 24 hours are cleaned on the next export.

Body/composer/user text uses 16sp/24sp, code/diff/terminal 14sp/20sp, captions 12sp/16sp. Content and composer share a centered 720dp reading column with 16dp minimum side margins. Bubble widths use actual container constraints, including split-screen; Android font scaling remains enabled.

Connection status and home filters

The chat subtitle reserves its height. Reconnecting · Tap to retry appears after four continuous foreground seconds of outage; retry/backoff transitions do not restart that grace period. Transport state is separate from message events. Default-network/interface/route changes wake reconnect immediately, preserving replay cursors; background retries defer until foreground. A local hub route does not need Android's internet-validation capability.

Home centers the Sessions title between a Hubs and settings icon and a Sort & filter icon, keeping the new-session FAB. The hub menu is the only entry for switching/adding hubs, app settings and sign-out; the active hub is checked. The icon carries a dot for any applied filter or a non-default order and opens one Material 3 sheet that mirrors the web sort and filter menu: machines, activity dates, Show all / active only / archived only and Unread only, then Sort by last message (default) or date created and Active first (on by default: connected sessions lead the pinned and recent sections, below manual pins), both persisted app-wide in hapi_prefs. Status and unread filters keep the open session listed; search ranks by relevance with the base order as tie-break, as on web. Machine choices come from all sessions, including historical machines; names/IDs determine ordering, never counts. Duplicate names include IDs; unnamed and unknown machines are labeled. Reset clears the filters (not the order); filters are transient per home/hub and cleared when no longer valid. The share picker reuses the list model with the base order.

Each row's agent icon carries the web presence badge (one mark per state): solid green pulsing while working, solid blue pulsing when only background tasks run, a green ring when connected and waiting, and a power mark when stopped or archived. A running attached job counts as working even when the agent is idle or disconnected, keeps the session under Active only, and adds a line under the meta line: label · remaining or percent · elapsed with a thin bar (determinate only for an honest fraction), amber with no heartbeat after 15 minutes. Job patches are versioned like web's: a lagged heartbeat cannot resurrect a cleared job. The home holder follows the active connection instance, releasing the previous store and filter even when switching back to a previously used hub URL.

Pairing and Settings both link to the privacy policy. These controls and notices ship in English and Simplified Chinese.

Validation status (2026-09-12)

Protocol/data/app JVM suites: 722 tests passed. Debug APK, instrumentation APK and lint passed. Pixel 6 (Android 17/API 37): installed and visually checked the home toolbar, hub/settings menu, applying/clearing filters, English/Chinese switching and code-copy feedback. Code headers keep an 18dp action icon inside a 48dp touch target, at the trailing edge even with short language labels.

API 36 ARM64 emulator (macOS Hypervisor.Framework): 8 targeted instrumentation tests passed, including 5 new toolbar/code-layout regressions (320dp width, English/Chinese, 2× font scaling), exact clipboard/file export and question details. The full 30-test run was not all green: 3 transcript group-anchor checks and the tool-browser initial-position check also fail with the pre-fix APK. One question-details timeout passed on targeted rerun; the opt-in frame probe was skipped. API 37 instrumentation is blocked by the current Espresso dependency calling the removed InputManager.getInstance() method.

Earlier API 29 checks passed 19 chat/reader regressions. No 60/120 Hz device frame-time, memory, or predictive-back measurements are claimed by these checks.

Unread state uses the hub’s revision read-state contract. List selection and metadata updates never acknowledge reading. The resumed chat acknowledges only its rendered tail, with a durable outbox scoped by hub and namespace.