Hoichoi client platform · bridge

kwry bridge

The typed channel between the Solid page and the native islands: what is generated, what crosses the wire, and how an over-the-air shell is stored.

Mapped by Claude (agent) from source at a950df76e · kwry 29b36e1Public · every page in this group shares one access rule

Go deeper

Every mechanism below expands to its rationale, rejected alternatives, a pinned code excerpt and references. Links of the form #dd-<id> open one directly.

Message lifecycle

SequenceOne bridge call, end to endOpen full reader ↗
One bridge call: page → island → resulthostSolid().window.setOrientation({ orientation: 'landscape' })setOrientation(p)advertised v1? fit(p)encode + callJSON-RPC frameorient.lock()result / UNAVAILABLEdecodeEmptyOutcome {ok}Page side (OTA JS)Native side (app binary)ResultSolid page · mweb / player · Sequence participantSolid pagemweb / playergen/solid.ts · operation() + fit() · Sequence participantgen/solid.tsoperation() + fit()gen/client.ts · encode · gate · Sequence participantgen/client.tsencode · gatekwry Bridge · JSON-RPC · WebMessage · Sequence participantkwry BridgeJSON-RPC · WebMessageWindowIsland · generated dispatch · Sequence participantWindowIslandgenerated dispatchOS · orientation lock · Sequence participantOSorientation lockLegendmain requestreturnmessage

Steps 1–8 below follow this diagram.

  1. hostSolid() resolves the one memoised client for this document (host-solid.ts:14-20); connectKwry ran hello with webContract and maxObservations: 10 (client.ts:42-60).
  2. The generated operation checks window.setOrientation.v1 is advertised and fits the params (solid.ts:457-460).
  3. The generated client encodes and calls with a 10 s deadline (client.ts:886-889).
  4. The frame leaves through window.__kwry.postMessage; Android admits it only from an OS-attested allowed origin (A1 WebMessageListener).
  5. The KSP-generated WindowApiDispatch decodes and calls the island.
  6. WindowIsland.setOrientation applies the page's choice: orient.lock(p.orientation) (WindowIsland.kt:35).
  7. The result (or UNAVAILABLE) returns; the page gets Outcome {ok} and never an exception for an unsupported host.

Wire protocol

Envelope
JSON-RPC 2.0. App errors use code -32000 with data {code, retryable, correlationId?, detail?}.
Handshake
Page sends {supportedProtocols:[1], webContract}; host replies with its methods, contract, budgets, update action and capabilities. An island the host does not install comes back null; a method it does not list is a typed unsupported.
Tag range
The page connects to a host on any contract tag (createClient); per-method gating replaces the old exact-tag lockstep. The only range check left is the OTA bundle's minTag..maxTag.
Observations
LATEST: one value in flight plus one pending, ack-paced. LOSSLESS: numbered and buffered, producer suspends when full (used by telemetry.events.v2).
Budgets
kwry defaults: 64 KiB per message, 32 pending requests, 8 observations. Hoichoi raises observations to 10 (Telemetry.kt:262).
Cancellation
An abort or deadline settles the page call as ABORTED/TIMEOUT and sends cancelRequest; the host aborts the work and remembers cancels that arrive early.

Transports

PlatformChannelOrigin checkShell served from
AndroidWebMessageListener (A1) › WebMessagePort with nonce (A2)OS-attested origin against an explicit allow-list, never *shouldInterceptRequest on https://shell.hoichoi.app (Shell.kt)
AppleWKScriptMessageHandlerWithReply in a page content worldframeInfo.securityOrigin + main frame onlykwry://app/ scheme handler
Cast peerGenerated servePeer / createClient over the Cast text channelPeer tiercast-peer.ts

Codegen and compile-time errors

Data flowOne contract, two languagesOpen full reader ↗
One contract, generated into both languagesKotlin @Island interfaces → KSP + islandgen → Kotlin dispatch and TS client; CI fails on drift01 / Author02 / Generate03 / Artifacts04 / Consumers@Island interfaces · 24 islands · 01 / Author@Island interfaces24 islandsKSP processor · kwry bridge-gen · 02 / GenerateKSP processorkwry bridge-genislandgen · schema + TS · 02 / Generateislandgenschema + TSKotlin dispatch · *Dispatch · Containers · 03 / ArtifactsKotlin dispatch*Dispatch · Containersschema + lock · releases · breaking.toml · 03 / Artifactsschema + lockreleases · breaking.tomlTS client · shell-kwry/src/gen · 03 / ArtifactsTS clientshell-kwry/src/genNative hosts · install islands · 04 / ConsumersNative hostsinstall islandsCI checks · islandgenCheck · tsc · 04 / ConsumersCI checksislandgenCheck · tscPage code · hostSolid() ops · 04 / ConsumersPage codehostSolid() opsannotationswalk schemaKotlin coderelease JSONTS codecompileevolution checkimportLegendprimary datapolicy / PIIdata storedata flow
CheckFails whenWhere
@Since on every wireA method or observation has no release tagKSP processor
Version ladderA changed row has no defaulted @Capability field or @Frozen dateKSP processor
@Frozen(removeAfter)The removal date has passedKSP processor (uses build date)
Evolution vs every releaseA breaking change is not listed in breaking.tomlbreaking.toml
Stale TS clientgen/ differs from a fresh generationpnpm typecheck = gen:check && tsc in shell-kwry
Release immutabilityA frozen schema/releases/*.json changesislandgen lock (contract/build.gradle.kts)

OTA bundle store

Slots
Seed (embedded in the app) plus two OTA slots. A shell that dies before bridge.ready() rolls back on the next boot; a rolled-back version is never installed again.
Verification
Signature (when a trust key is set), format, expiry, channel, contract range, total and per-file size, SHA-256 of every file, no unlisted files.
Hoichoi today
Unsigned by design: trust = null, the app's own HTTPS origin is the trust (Shell.store). Hashes, sizes, range and channel are still checked.
Fetch
Android stages $ORIGIN/shell/<contract>/ after start (refreshShell); the update policy is /.well-known/shell-policy.json (Policy.kt).
Published by
deploy-mobile.yml stages the unsigned shell into the phone Worker and probes it with a HoichoiShell user agent (deploy-mobile.yml).

Every bridge mechanism, in depth

11 items · click any row
kwry: OS WebView + typed bridge as the native hostkwry is a Kotlin Multiplatform library that wraps each platform's own WebView (Android WebView, WKWebView) and gives the hosted Hoichoi web page a…
What

kwry is a Kotlin Multiplatform library that wraps each platform's own WebView (Android WebView, WKWebView) and gives the hosted Hoichoi web page a typed JSON-RPC 2.0 channel to native 'islands'. All UI stays web; native only provides capabilities and surfaces.

Why this way

The proposal wants 'one Kotlin contract' and 'one protocol (JSON-RPC 2.0)' so that 'Nobody writes Rust, JNI, Swift forwarders, or a different host per platform' kmp-native-host-proposal.md:11-42. It found 'no maintained "wry for Kotlin" exists' on GitHub, so kwry is built in-house (kmp-native-host-proposal.md:82). Binding WRY would mean 'Kotlin -> JNI -> Rust -> JNI -> android.webkit.WebView: two hops for nothing', while Kotlin already reaches the platform WebViews directly (kmp-native-host-proposal.md:88-97). The target plan keeps 'One Solid/web UI everywhere' because it gives the 'Same layout, text and focus behaviour on every platform; one ecosystem; everything deploys remotely' (zipline-bridge-and-player-mvi.md:104).

Alternatives considered
OptionWhy not
Tauri / WRY (Rust host)No C API, needs its own event loop, and adds Rust + UniFFI/Gobley layers; the Kotlin host is 'Kotlin end to end' with direct calls into existing KMP engines. Tauri is better at desktop packaging, its permission system and Windows, and stays a fallback for Windows only. (kmp-native-host-proposal.md:86-97)
Tauri host (comparison table)JS -> Rust -> UniFFI -> Kotlin interop and a fragile Gobley dependency; Tauri keeps Windows only if the mingwX64 spike fails. (kmp-native-host-proposal.md:319-340)
React Native JSI / Nitro-style host objectsA system WebView exposes 'No public API' to put native objects inside the page's engine, only message channels; the only synchronous route (addJavascriptInterface) is ruled out for security reasons. (zipline-bridge-and-player-mvi.md:1904-1911)
Lynx / Valdi (TS compiled to native views)'Not our model (we keep DOM UI)'. Only relevant to a future Apple TV renderer. (zipline-bridge-and-player-mvi.md:1498)
CapacitorNot rejected outright. It 'Confirms our A1-first ladder and main-frame rule' and its app-ready rollback is adopted. Its runtime Proxy plugin objects are rejected because 'Generated classes give stack traces, go-to-definition and tree-shaking'. (zipline-bridge-and-player-mvi.md:1489)
Zipline (Kotlin/JS in an embedded engine)The docs take its developer model (services, close() ownership, function IDs), not its runtime. The docs give no reason for not adopting Zipline's runtime. (zipline-bridge-and-player-mvi.md:1496)
compose-webview-multiplatformBuilt for Compose screens. Desktop bundles a whole Chromium and there is no origin or permission model, so it is 'Wrong shape for a host'. (kmp-native-host-proposal.md:77)
In the code
export async function connectKwry(log: (line: string) => void = (l) => console.log(l)): Promise<Client | null> {
  const s = selectTransport()
  if (!s) {
    if (typeof window !== 'undefined' && (window as unknown as { __kwry?: unknown }).__kwry != null) {
      throw new KwryConnectError('kwry bootstrap present but no transport for its tier')
    }
    return null
  }
  const bridge = await Bridge.connect(s.transport, {
    webContract: CONTRACT,
    // NS-8 (plan §2.2): the hosts' KwryApp budgets (contract MAX_OBSERVATIONS): the measured 8, telemetry.events.v2, one spare.
    budgets: { maxObservations: MAX_OBSERVATIONS },
    onSpan: (span) => { try { spanSink?.(span) } catch { /* telemetry never breaks a call */ } },
  }).catch((e: unknown) => { throw e instanceof KwryConnectError ? e : new KwryConnectError('kwry handshake failed', { cause: e }) })
  const client = createClient(bridge)
  const h = client.bridge.hello
  log('KWRY-HOICHOI hello ok ' + JSON.stringify({ tier: h.tier, engineVersion: h.caps.engineVersion, contract: h.contract, hash: CONTRACT_HASH }))
  return client
Talks to
Android System WebView (androidx.webkit)WKWebViewHoichoi page (packages/shell-kwry)Hoichoi islands (apps/native/islands)kwry bridge-runtime (Kotlin + TS)
Gotchas
  • The page runtime is vendored as a copy (kwry-version.md:10 says 'diff -r clean'). At this pin src/runtime is clean, but src/solid/call.ts differs from kwry packages/solid/src/call.ts (Hoichoi's operation() tries the next version on UNSUPPORTED, upstream returns unsupported). See call.ts:51-53 vs call.ts:51-53
  • KWRY-DEEP-DIVE.md cites kwry commit 55f37d4 KWRY-DEEP-DIVE.md:5, but the pin is now 29b36e1 kwry-version.md:5. Line numbers and some behaviour in it are stale.
  • kwry has no CI of its own ('There is no CI: everything is run here', README.md:17. In Hoichoi, CI runs islandgenCheck only when KWRY_TOKEN is set ci.yml:275-279.
Kotlin contract and its annotations (@Island/@Method/@Observation/@Since/@Frozen/@Surface)Every island is a Kotlin interface annotated in apps/native/contract.
What

Every island is a Kotlin interface annotated in apps/native/contract. KSP reads wire-shaping annotations (names, kinds, versions, grants, surfaces), and the walker reads @SerialInfo bounds (@MaxLength, @Range, ...) from kotlinx descriptors.

Why this way

The vocabulary follows plan §10: 'Kotlin declarations -> KSP + serialization descriptors -> canonical schema'. Type-level bounds are @SerialInfo 'so every type-level annotation below is @SerialInfo and sits on the property it bounds' Annotations.kt:7-10. @Since is 'Required on every wire name' (Annotations.kt:165-167). @Frozen keeps 'an older method version kept for installed peers until [removeAfter]' (Annotations.kt:178-183). @Surface makes KSP generate a container with 'no defaults (a host that forgets one does not compile)' (Annotations.kt:55-65). Hoichoi adopted @Surface (review R9) so there are 'no name sets, no host-side filters' Contract.kt:103-104.

Alternatives considered
OptionWhy not
Proposal-era annotations (@Timeout, @IslandHandle(survivesReload), @IslandErrors, EventSink params)Superseded by the @Method/@Observation vocabulary. The repo does not document why each was dropped. Sessions moved to explicit sessions/attachments/leases (plan §7). (kmp-native-host-proposal.md:161-201)
Host-side name filters (NOT_YET_INSTALLED sets)Replaced by @Surface + @InstalledOn per review R9: 'Per-method / per-field availability is declared on the island interfaces, never filtered by name in a host.' (Surfaces.kt:5-9)
Expo Modules @Record/@SharedObject/@Event vocabularyCited as 'Strong validation of our direction (annotations -> generated TS)'. The vocabulary was taken as inspiration, not as a dependency. (zipline-bridge-and-player-mvi.md:1492)
In the code
    @Observation(
        Mode.LATEST,
        push = "app.lifecycleChanged.v1",
        ack = "app.ackLifecycle.v1",
        doc = "Foreground / background of the app (Android Activity onStart/onStop, iOS scene active/background). The open result is the state now; later snapshots replace each other (latest), and `resumes` counts every background -> foreground, so a page that sees it grow knows it resumed even when the background snapshot was conflated.",
    )
    @InstalledOn(AndroidPhone::class, Ios::class)
    @Since(R2026_10_C)
    suspend fun lifecycle(): Flow<AppLifecycle> = throw BridgeException(ErrorCode.UNSUPPORTED, "app.lifecycle.v1 is not installed")
Talks to
bridge-gen KSP processorWalker (bridge-gen-api)hoichoi.schema.jsongenerated <Surface>Container
Gotchas
  • KSP drops omitted arguments of library annotations, so the processor restates every default in a DEFAULTS map; a new annotation field needs an entry there KWRY-DEEP-DIVE.md:1293.
  • @Frozen(removeAfter) fails the build once the date passes: 'has passed ... delete <wire>' Processor.kt:432-438. Hoichoi's superseded versions carry removeAfter 2027-02-02 (Contract.kt:62).
  • Surfaces are host-side only (surfacesInSchema = false), so they never enter the schema or its hash Contract.kt:111.
Codegen: KSP -> canonical schema -> islandgen (lock/check) -> TS clientThe bridge-gen KSP processor emits a Spec plus per-island Dispatch/Fake/Sender.
What

The bridge-gen KSP processor emits a Spec plus per-island Dispatch/Fake/Sender. islandgen write/lock/check walks the spec into the committed schema/hoichoi.schema.json plus immutable releases and contract.lock.json. 'islandgen ts' generates packages/shell-kwry/src/gen (client, types, validators, fakes, lock, solid, serve) from the committed JSON.

Why this way

Principle 1: 'Typed end to end, generated from one source ... Nobody hand-writes wire code' zipline-bridge-and-player-mvi.md:85. Codegen goes 'KSP -> canonical schema -> Kotlin adapters, plain TS clients/validators ... locks, fixtures, fakes, docs' for 'One source of truth; idiomatic output on both sides' (zipline-bridge-and-player-mvi.md:118). Against tauri-specta: 'We generate from Kotlin, and also emit runtime validators, release locks and a skew matrix, because our web and binaries ship on different schedules' (zipline-bridge-and-player-mvi.md:700). The schema is embedded in the spec 'so every target's startup walk is checked against it' build.gradle.kts:38-41.

Alternatives considered
OptionWhy not
tauri-specta (Rust -> TS types)Generates types only. kwry also needs validators, locks and a skew matrix because web and binaries ship separately. (zipline-bridge-and-player-mvi.md:700)
kxs-ts-genListed as 'a candidate, not validated'. (zipline-bridge-and-player-mvi.md:695)
Zipline-style Kotlin compiler plugin'Study. We use KSP (source generation), but Zipline shows the adapter shape.' (zipline-bridge-and-player-mvi.md:1701)
Runtime Proxy objects (Capacitor registerPlugin<T>)'Generated classes give stack traces, go-to-definition and tree-shaking.' (zipline-bridge-and-player-mvi.md:1750)
Method IDs as signature hashes (proposal §5.2)The plan ports the hashing idea into the lock but names methods name.vN: 'We name methods name.vN and keep hashes in the lock'. (zipline-bridge-and-player-mvi.md:1689)
In the code
// kwry islandgen (plan §10.2, §17.10): write = rewrite schema/hoichoi.schema.json; lock = release the current tag;
// check = schema, releases and lock all match the Kotlin declarations. Runs in CI (ci.yml android job) and in the
// pre-push hook when the pushed range touches apps/native/contract/.
listOf("check" to "islandgenCheck", "write" to "islandgenWrite", "lock" to "islandgenLock").forEach { (mode, task) ->
    tasks.register<JavaExec>(task) {
        group = "verification"
        val jvm = kotlin.jvm()
        dependsOn("jvmMainClasses")
        classpath = files(jvm.compilations["main"].output.allOutputs, jvm.compilations["main"].runtimeDependencyFiles)
        mainClass.set("dev.kwry.gen.api.IslandGenKt")
        workingDir = projectDir
        args(mode, "tv.hoichoi.contract.HoichoiSpec", "schema")
    }
}
Talks to
bridge-gen (KSP)bridge-gen-api IslandGen/TsGenapps/native/contract/schema/releasespackages/shell-kwry/src/genCI android job
Gotchas
  • kwryTsGen reads the committed schema JSON, not the Kotlin, so the TS lags until islandgenWrite runs KWRY-DEEP-DIVE.md:1263, :1509).
  • A stale schema crashes the host at startup, not at build time (Schema(HoichoiSpec) startup proof) KWRY-DEEP-DIVE.md:1455, :1510).
  • The evolution check does not compare changes to errors, deadlineMs or since on a released name; review those by hand KWRY-DEEP-DIVE.md:1418, :1513).
Hello handshake and per-method gating (exact-tag lockstep dropped)The page sends bridge.hello.v1 {supportedProtocols:[1], webContract}.
What

The page sends bridge.hello.v1 {supportedProtocols:[1], webContract}. The host checks only shape and protocol, then returns documentId, tier, the sorted list of granted methods, capabilities and its contract name. The generated createClient makes an island null when none of its members are advertised, and rejects an unadvertised member with API_MISMATCH before sending.

Why this way

Since kwry d5be46b, 'generated createClient connects a host on any contract tag (HOI-4156 R-RANGE)' kwry-version.md:5. The template's reason: 'an installed app keeps every island it has against a newer page): what it lacks is told apart per island (null) and per method (API_MISMATCH / an operation's unsupported), never by the tag' client.tmpl:253-257. The owner's rule is quoted as 'allow everything to work on everything' older-host.test.ts:1-5. STORE-BUILD.md states the outcome: 'a missing island is null, a missing method is a typed unsupported' STORE-BUILD.md:15-17.

Alternatives considered
OptionWhy not
Exact contract-tag lockstep (page refuses a host on another tag)'a page on a new tag cuts off older apps: no islands, player "unavailable", splash waits for its cap'. Dropped by HOI-4156. (DEEP-DIVE.md:494)
Host-side contract comparisonThe host 'never compares webContract with its own contract' and validates the format only. Skew handling is the client's job. (KWRY-DEEP-DIVE.md:946)
In the code
/**
 * Wraps a connected lane R2 `Bridge` (`Bridge.connect(transport, { webContract: CONTRACT })`). A host on any contract tag
 * connects (HOI-4156: an installed app keeps every island it has against a newer page): what it lacks is told apart per
 * island (`null`) and per method (`API_MISMATCH` / an operation's `unsupported`), never by the tag.
 */
export function createClient(b: Bridge): Client {
  const adv: { [w: string]: 1 } = {}
  for (const m of b.hello.methods) adv[m] = 1
  const installed = (i: string) => {
    const ms = ISLANDS[i] || []
    return !ms.length || ms.some((m) => { const w = WIRE[m]; return w !== undefined && adv[w] === 1 })
  }
Talks to
Bridge.connect (page runtime)Bridge.hello (Kotlin runtime)generated client.ts _gate@kwry/solid operation()
Gotchas
  • DEEP-DIVE.md (:291, :355, :494) and ARCHITECTURE.md (:280) still describe the old exact-tag rule. The code at this pin connects on any tag.
  • Hello is not a gate on the host: request() serves contract calls whether or not hello ran, and 'no-hello' is declared but never emitted KWRY-DEEP-DIVE.md:963.
  • Platform and app version travel in the user-agent suffix, not in the hello DEEP-DIVE.md:725.
Observations: LATEST (conflated) vs LOSSLESS (windowed) with ack pacingA latest observation returns the first snapshot as the open result, then keeps 1 value in flight plus 1 pending (a newer value replaces the pending…
What

A latest observation returns the first snapshot as the open result, then keeps 1 value in flight plus 1 pending (a newer value replaces the pending one) until the page acks. A lossless observation numbers items, sends at most window unacked items, suspends the producer at its buffer capacity, and can resume from a cursor. Ten seconds without an ack closes either kind.

Why this way

The plan picks 'Credit-based observations with two modes' for 'Bounded memory and no silent loss where loss matters' zipline-bridge-and-player-mvi.md:110. Latest gives 'Delivery is "eventually the latest", not every transition' (zipline-bridge-and-player-mvi.md:604-608). Lossless 'exists for streams where every item matters', and 'If the buffer bound is reached, the producer is suspended. Items are never dropped' (zipline-bridge-and-player-mvi.md:670-678). Hoichoi's app.lifecycle explains its choice: a lossless producer would stall 'behind a frozen page', and 'a reloaded page needs the state now, not a backlog' App.kt:32-42.

Alternatives considered
OptionWhy not
Tauri channels (ordered by index, no flow control)'no backpressure'. kwry's streams are credit-based instead. (zipline-bridge-and-player-mvi.md:1042)
Generic Zipline Flow backpressureReview item R03: notification emit differs from Zipline's suspending collector, so the plan states an 'Explicit latest-state protocol, no generic Flow claim'. (zipline-bridge-and-player-mvi.md:2679)
Lossless for app lifecycleThe WebView is paused while lifecycle changes, so it cannot ack and the host callback would stall. The host-owned buffer would also replay stale transitions to the next document. (App.kt:32-42)
In the code
    fun offer(item: Versioned<T>) {
        if (closed) return
        validate(item.revision)
        if (item.revision <= newestRevision) return
        newestRevision = item.revision
        if (inFlight != null) pending = item // Replace, never append.
        else transmit(item)
    }

    /** Returns true when the ACK released credit (it matched the revision in flight). */
    fun ack(revision: Long): Boolean {
        if (closed) return false
        validate(revision)
        if (revision > sentRevision) throw IllegalStateException("ACK_NOT_SENT")
        if (revision != inFlight) return false // Duplicate or stale.
        inFlight = null
        val next = pending
        pending = null
Talks to
Bridge.kt openLatest/pump/ackStreamLosslessStreampage bridge.ts (install + ack)@kwry/solid latest()/events
Gotchas
  • Latest revisions skip numbers (conflated values still use up a revision), so never treat a revision gap as loss KWRY-DEEP-DIVE.md:1053, :1205).
  • A lossless buffer is in memory only and outlives the document: a reload resumes, but process death loses it KWRY-DEEP-DIVE.md:1088.
  • KWRY-DEEP-DIVE says the page is not told about an ack-timeout close (:874, :1094, :1204). That is stale: at this pin the host sends bridge.observationClosed.v1 (HOI-4116), and the page ends the handle as host-closed Bridge.kt:808-816; bridge.ts:511-529.
Budgets: message size, pending requests, observations (maxObservations 8 -> 10 in Hoichoi)Every queue has a number in kwry's Budgets:
What

Every queue has a number in kwry's Budgets: 64 KiB per frame (16 KiB target), 256 KiB per batch, 32 pending requests plus 4 reserved for cleanup methods, 8 observations, rate buckets, a 10 s ack timeout, and blob routing above 64 KiB. Hoichoi overrides maxObservations to 10 on every host and on the page.

Why this way

Plan principle 6: 'Backpressure everywhere. Every stream has credit. No unbounded queue exists in any layer' zipline-bridge-and-player-mvi.md:93. Cleanup gets reserved capacity 'so a seek flood can't block revocation' (zipline-bridge-and-player-mvi.md:627). The starting values are plan §9.3 rows, marked 'runtime choice: tune under device tests' Contract.kt:108-111. Hoichoi's 10 is documented as: 'The measured peak is 8 distinct wires; telemetry.events.v2 is the 9th, plus one spare' Telemetry.kt:258-262.

Alternatives considered
OptionWhy not
Rate overflow: silent drop (a) or answer every refused request (b)(b) is out because 'a 1 000-call flood would be answered 1 000 times'. (a) gives the page no typed error. kwry picked (c), capped typed answers, with the owner decision still pending. (budgets.md:7-52)
Raise kwry's default maxObservationsThe handoff says 'Do NOT raise kwry's maxObservations (native release)'. Hoichoi instead fixed leaks (ref-counted observeHostState) and overrides Budgets per host. (HANDOFF-2026-11-04-2315-kwry-arch.md:95-107)
In the code
data class Budgets(
    /** §9.3 "Normal control target ≤16 KiB; diagnostic above target". */
    val targetMessageBytes: Int = 16 * 1024,
    /** §9.3 "Absolute inbound message: 64 KiB per frame"; checked before parsing. */
    val maxMessageBytes: Int = 64 * 1024,
    /** §9.3 "total batch ≤ 256 KiB". */
    val maxBatchBytes: Int = 256 * 1024,
    /** §9.3 "Snapshot: 32 KiB target ceiling inside absolute envelope cap". */
    val maxSnapshotBytes: Int = 32 * 1024,
    /** §9.3 "Pending finite requests: 32 per document; excess rejected". */
    val maxPendingRequests: Int = 32,
    /** §9.3 "Observations: 8 per document". */
    val maxObservations: Int = 8,
    /** §9.3 "Provisional sessions: 2 per document; 10 s activation expiry". */
    val maxProvisionalSessions: Int = 2,
    val provisionalExpiryMs: Long = 10_000,
Talks to
Bridge.kt admission/request ladderpage runtime wire.ts BUDGETSHoichoi hosts (PhoneIslands.kt, TvActivity.kt, HostWiring.kt)packages/shell-kwry connectKwry
Gotchas
Transports: Android A1/A2, Apple WKScriptMessageHandlerWithReply, exact-origin allow-listOn Android, kwry probes androidx.webkit features and picks A1 (addWebMessageListener, engine-attested sourceOrigin/isMainFrame;
What

On Android, kwry probes androidx.webkit features and picks A1 (addWebMessageListener, engine-attested sourceOrigin/isMainFrame; the reply proxy is the document fence), else A2 (a WebMessagePort posted to the exact origin plus a nonce handshake). A3 is a MAC'd JavascriptInterface for debug builds only. On Apple, kwry uses a page-world script message handler with reply plus callAsyncJavaScript(arguments:) back. Only top-level documents on an exact allowed origin are admitted.

Why this way

Principle 8: 'Origin and frame admission come from the platform, never from message content' zipline-bridge-and-player-mvi.md:95. Against WRY, which 'uses addJavascriptInterface for every app, with origin taken from the tracked URL', kwry will 'prefer OS-attested channels, and scope injection to our origin' (zipline-bridge-and-player-mvi.md:783). Principle 4: 'The best path is automatic ... App code never writes feature checks' (zipline-bridge-and-player-mvi.md:91). On Apple the text is 'passed as an argument, never interpolated' AppleWebHost.kt:305-311, because splicing it 'turns any escaping bug into script injection' KWRY-DEEP-DIVE.md:696. Origins are exact, with 'no wildcard' Origin.kt:3-9.

Alternatives considered
OptionWhy not
addJavascriptInterface as the default path (Capacitor legacy, WRY)'Exposed to all frames'. It is kept only as the hardened A3 tier (debug-only until external review). (zipline-bridge-and-player-mvi.md:1749)
Admission by tracked page URL (WRY/Tauri)'Can't fence documents or frames'. (zipline-bridge-and-player-mvi.md:1748)
WebSocket transport to localhost (Electrobun)'Adds a network surface; platform message channels are available on our targets'. (zipline-bridge-and-player-mvi.md:1752)
webview_bind on Windows'carries no origin', so kwry uses ICoreWebView2 WebMessageReceived instead. (kmp-native-host-proposal.md:127)
Isolated content world on AppleNot documented. The page world is used so page scripts see window.__kwry, and 'No doc in the tree states the reason'. (KWRY-DEEP-DIVE.md:638)
In the code
    // ---- A1 (plan §12.2): OS-attested sourceOrigin + isMainFrame per message; the reply proxy is the document's fence key.
    private fun onA1(v: WebView, msg: WebMessageCompat, sourceOrigin: Uri, isMainFrame: Boolean, reply: androidx.webkit.JavaScriptReplyProxy) = onMain {
        val origin = sourceOrigin.toString()
        if (Origin.of(origin)?.let { it in config.origins } != true) { docs.reject(origin, isMainFrame, RefusalReason.ORIGIN); return@onMain }
        val binary = caps.arrayBuffer
        val p = docs.admit(reply, origin, isMainFrame) { id -> port(id, binary, reply::postMessage, reply::postMessage) }
        val frame: Any? = if (msg.type == WebMessageCompat.TYPE_ARRAY_BUFFER) msg.arrayBuffer.takeIf { binary } else msg.data
        deliver(p, frame, origin)
    }
Talks to
androidx.webkit WebViewCompatWKUserContentControllerDocuments/Fence (Android), KeyFence (Apple)page runtime select.tsHoichoi MainActivity / iOS Host
Gotchas
  • forceTier and enableA3 throw in non-debuggable builds before the WebView exists Tier.kt:35-44. Hoichoi passes neither, so it gets A1, A2 or no bridge.
  • Same-origin sub-frames still see __kwry on A1/A2; only their frames are refused as sub-frame KWRY-DEEP-DIVE.md:434.
  • Apple has no binary frames ('ArrayBuffer body arrives as {}'), and that was measured on macOS, not iOS KWRY-DEEP-DIVE.md:685-687.
BundleStore OTA: two slots, ready-handshake rollback, verify-before-activate (unsigned in Hoichoi)kwry's BundleStore keeps current and previous slots plus an embedded seed.
What

kwry's BundleStore keeps current and previous slots plus an embedded seed. install() verifies the bundle and stages it as unconfirmed current. It activates only at the next entry document and must call bridge.ready() within the timeout, or it is rolled back and its version is rejected for good. Hoichoi uses it for the seeded JS shell (splash, offline, downloads, update) on its own origin https://shell.hoichoi.app, in unsigned mode.

Why this way

Store.kt: activation waits for the next top-level load 'so one document never mixes assets of two versions', and 'previous is always known-good' Store.kt:69-82. The ready rollback is plan §19.4 item 5, the 'Capacitor/Capgo pattern' zipline-bridge-and-player-mvi.md:1558. Unsigned: 'the bundle comes over HTTPS from the app's own origin, so there is no signature and no expiry (both only make sense with a key). Every other check below still runs' Verify.kt:68-69. Hoichoi echoes this: 'hashes, sizes, range and channel are still checked' Shell.kt:65.

Alternatives considered
OptionWhy not
Ed25519-signed manifest with expiry and key rotation (plan §19.4 item 3)Supported by kwry. Hoichoi passes trust = null (HOI-4156) because the bundle is fetched over HTTPS from its own origin. (zipline-bridge-and-player-mvi.md:1556)
Serve the shell from an app originThe shell gets its own exact origin because its 'extensionless-path answer (every route = the entry) must never take over the online app's origin'. (Shell.kt:21-30)
In the code
    fun store(open: SeedFiles, storage: BundleStorage, contract: String, tag: String, clock: Clock): BundleStore? {
        val seed = safeRunCatching { read(open) }.getOrNull() ?: return null
        return BundleStore(
            storage,
            null, // unsigned (HOI-4156): the bundle is the app's own origin over HTTPS; hashes, sizes, range and channel are still checked
            InstalledContract(contract, tag),
            clock = clock::nowMs,
            embedded = seed,
            channel = AcceptedChannel.Only(CHANNEL),
        ).also {
            it.boot()
        } // ponytail: on main in kwryConfig (one slot read + verify, ~1 MB); move to LaunchFiles' off-main read if it shows in cold start
    }
Talks to
kwry-android intercept / kwry-apple kwry:// schemeVerify.kt verifyBundleHoichoi Shell.kt (Android, iOS)scripts/native/shell-bundle.mjs seed stepapp.load.v1 boot decision
Gotchas
  • ARCHITECTURE.md:141 and DEEP-DIVE.md:664 say signed bundles are 'Not used'. That is stale: Hoichoi's shell runs on BundleStore (HOI-4119) Shell.kt:21-27.
  • Only entry documents can activate or confirm an install. A static page that never calls ready() cannot roll back a good bundle bundle.md:18-23.
  • BundleStore is not thread-safe. Hoichoi wraps install in synchronized(store), and slot files are not fsynced one by one (a torn slot falls back one slot) Shell.kt:81-89, :102-109).
@kwry/solid operation()/Outcome/useLatest and Hoichoi's shell-kwry wrappingGenerated Solid bindings (gen/solid.ts) expose one operation per method, versions listed newest first.
What

Generated Solid bindings (gen/solid.ts) expose one operation per method, versions listed newest first. operation() picks the highest version the host advertised that can express the request and returns a typed Outcome (ok | unsupported+needs | error), never a throw. useLatest/latest() bind a latest observation to a reconciled Solid store. Hoichoi's ports/host-solid.ts binds them once per document to the single kwry client.

Why this way

From call.ts: 'App code never writes start/startV2/startV3 or hostHas()', and '"The host can't do this" is an ordinary typed result, never a throw ... the compiler forces the caller to handle unsupported and each declared error code' call.ts:1-6. latest.ts uses reconcile 'keyed by the contract's @SolidStore(key), so one item's progress tick re-runs only the readers of that item' latest.ts:1-3. Hoichoi wraps them 'so a wire observation is opened once per document whoever reads it' host-solid.ts:1-2, which matters under the per-document observation cap.

Alternatives considered
OptionWhy not
Hand-written version picking (startV2 / hostHas)Removed by the generator: 'at call time the highest version the host advertised in hello that can express the request wins'. (call.ts:1-3)
Throwing on an unsupported hostOutcome forces callers to handle unsupported at compile time. (call.ts:5-6)
In the code
  return async (p, o) => {
    let needs = versions[0].wire
    for (const v of versions) {
      if (!advertised().has(v.wire)) continue
      const a = v.adapt(p)
      if ('needs' in a) { needs = a.needs; continue }
      try {
        return { ok: true, value: (await v.send(a.params, o)) as R }
      } catch (e) {
        const err = toBridgeError<C, D>(e)
        // A capability-gated field (HOI-4124) the host does not advertise: the generated client rejects UNSUPPORTED with
        // the capability as the message before anything is sent. Same meaning as an unadvertised version: try the next.
        if ((err.code as string) === ErrorCode.UNSUPPORTED) { needs = err.message; continue }
        return { ok: false, unsupported: false, error: err }
      }
    }
    return { ok: false, unsupported: true, needs }
  }
Talks to
gen/solid.ts (SolidGen)generated client.tssolid-js/store reconcilepackages/ui ports, player
Gotchas
  • The vendored copy is not verbatim. Hoichoi's call.ts:51-53 continues to the next version on UNSUPPORTED (commit f362cb5bd, HOI-4134 K1, tested in operation.test.ts:1-25. The pinned kwry returns unsupported at once call.ts:51-53. That breaks kwry-version.md:10's 'also verbatim' claim, and a re-copy on the next bump would silently revert it.
  • latest() keeps a store for the whole document once read and never frees its observation slot ('ponytail' note, latest.ts:44-50. The handoff flags downloads.state leaking this way HANDOFF-2026-11-04-2315-kwry-arch.md:105-106.
  • A null client answers every operation as unsupported, never a throw host-solid.ts:14-20.
Cast peer bridge: servePeer / castPeer between phone and TV shellsThe castPeer island turns the Hoichoi Cast custom namespace into a text-frame pipe;
What

The castPeer island turns the Hoichoi Cast custom namespace into a text-frame pipe; native knows no message types. In JS, each peer device becomes a kwry Transport (an InMemoryPair). The phone shell serves castLicence over it with the generated servePeer, and the TV shell calls it with the ordinary generated client (Bridge.connect + createClient).

Why this way

Contract comment (CAST-B, review 'Part 2: Cast licence', approach B): 'Native moves text frames only: no licence type, no codec, no session prefix' CastPeer.kt:16-19. servePeer is described as 'the production twin of fakes.ts' with 'Deny by default ... params are decoded and results encoded with the generated validators, always checked, so a peer cannot answer what a real host could not', and 'one traceparent spans both devices' serve.tmpl:7-13. CastPeerServers makes castLicence required because 'The generated Servers is all-optional, which would let a shell serve nothing' cast-peer.ts:11-15.

Alternatives considered
OptionWhy not
Native licence relay (CastLicence.kt, cast- session prefix)Removed in 2026-12-o: 'The native licence relay (CastLicence.kt, the cast- session prefix) is gone'. The review document behind approach B is not in this repo. (Contract.kt:97-98)
In the code
  private accept(peer: string): Link {
    const t = this.transport(peer)
    servePeer(t, this.serving!, { budgets: { maxMessageBytes: CAST_FRAME_MAX } })
    return this.links.get(peer)!
  }

  /** [peer] as a Transport: what the runtime sends goes out on castPeer.send; a refused send ends the link (send-failed). */
  private transport(peer: string): Transport {
    this.links.get(peer)?.end()
    const [mine, theirs] = InMemoryPair()
    theirs.onMessage((f) => {
      if (typeof f !== 'string') return
      void this.pipe.send({ peer, text: ascii(f) }).catch(() => theirs.close(CloseReason.SEND_FAILED))
    })
    const link: Link = { deliver: (text) => theirs.send(text), end: () => theirs.close(CloseReason.TRANSPORT_LOST) }
    this.links.set(peer, link)
    theirs.onClose(() => { if (this.links.get(peer) === link) this.links.delete(peer) })
    return mine
Talks to
castPeer island (native CastNamespaceTransport)generated serve.ts servePeergenerated client.tsGoogle Cast custom namespace
Gotchas
  • Frames are capped at CAST_FRAME_MAX = 30 000 and must be printable ASCII. Non-ASCII is escaped to \uXXXX so it stays JSON CastPeer.kt:24-36; cast-peer.ts:20-24.
  • servePeer serves requests only. 'observations and callbacks stay host-served' serve.tmpl:9.
  • A peer leaving ends its link as transport-lost, and in-flight calls settle with it cast-peer.ts:28-32.
Error model: ErrorCode list, UNSUPPORTED vs API_MISMATCH, cancellationStandard JSON-RPC codes (-32700..-32603) keep their meaning.
What

Standard JSON-RPC codes (-32700..-32603) keep their meaning. App errors are -32000 with data.code from a fixed list (UNAVAILABLE, STALE_ATTACHMENT, NOT_ENTITLED, DRM, UNSUPPORTED, ABORTED, TIMEOUT, RESOURCE_LIMIT, OPERATION_ID_REUSED). API_MISMATCH (an unadvertised member) and transport-lost are page-only settlements and never go on the wire. A cancel settles ABORTED at once and cancels the handler cooperatively; operation records answer 'did it happen?'.

Why this way

'The codes are a fixed list. A contract cannot add codes' canonical-schema.md:288. API_MISMATCH is listed as 'settlements the generated client raises locally, never a wire code' protocol.json:53-56. On cancellation: 'Cancellation is cooperative, so the side effect may already be durable when the cancel lands', so handlers mark ctx.committed() runtime-cancel.md:6-17. The immediate ABORTED reply is kept 'because a cancel never waits on the handler' runtime-cancel.md:34-39. UNSUPPORTED for a capability-gated field is raised client-side 'before sending: the field asks for behaviour, so it is never silently stripped' canonical-schema.md:127.

Alternatives considered
OptionWhy not
Tauri core IPC (no cancellation)Tauri has 'None in core IPC'. kwry adds bridge.cancelRequest.v1 and outcome records. (zipline-bridge-and-player-mvi.md:1046)
Reply with the real result after a committed cancel (plan §17.7 example)A deliberate departure: the runtime keeps the immediate ABORTED, and the committed outcome is read through bridge.operationStatus.v1 or a duplicate operationId. (runtime-cancel.md:34-39)
Contract-defined error codesNot allowed: 'A contract cannot add codes'. Typed detail goes in errorDetail (a closed sealed type or enum). (canonical-schema.md:286-288)
In the code
    /** Plan §9.2 cancel: cancels in admission order map to coroutine cancellation (§17.7); the reply is `ABORTED`. */
    private fun cancel(id: FrameId) {
        val p = pending[id]
        if (p == null) {
            early += id
            if (early.size > b.earlyCancels) early.remove(early.first())
            return
        }
        p.cancelWork()
        settle(p, Outcome.App(ErrorCode.ABORTED, RuntimeMessage.ABORTED.text))
    }

    private fun settle(p: Pending, o: Outcome) {
        if (p.settled) return
        p.settled = true
        if (pending[p.id] === p) pending.remove(p.id)
        p.timer?.cancel()
Talks to
RuntimeMessage.ktOperations.ktpage peer.ts deadlinesgenerated client _gate/_unsupported@kwry/solid Outcome
Gotchas
  • Docs and code disagree: canonical-schema.md:296 says UNSUPPORTED covers 'flag/capability/grant off', but an ungranted name is answered -32601 KWRY-DEEP-DIVE.md:1186; Bridge.kt:454.
  • There are two TIMEOUTs: the page's own deadline gives retryable:true, the host's reply gives retryable:false KWRY-DEEP-DIVE.md:1207.
  • Malformed replies are dropped and never answered, so two peers cannot ping-pong errors KWRY-DEEP-DIVE.md:898.