Hoichoi client platform · native

Native hosts and islands

What each host installs, what it still owns, and the KMP modules underneath. Hosts are wiring; islands are OS capabilities that apply what the page decided.

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

Go deeper

Every host and island below expands to what it owns, what it must never decide, the rationale, a pinned code excerpt, gotchas and references.

Module graph

ModuleTargetsDepends on
:contractjvm (islandgen), android, iOS, macOSkwry bridge-gen-api, bridge-runtime; KSP bridge-gen
:host-coreandroid, iOS, macOSkwry-core, :log, :contract
:player-engine (videoplayer-core/)android, iOS, macOS:log, Media3, VP9 decoder
:islandsandroid, iOS, macOS:contract, :player-engine, :host-core, kwry-core; Play, Cast, WorkManager on Android
:hosts:androidappkwry-android, :islands, billing, Cast, Firebase
:hosts:androidtvappkwry-android, :islands
:hosts:ios / :hosts:macosiOS framework / macOS exekwry-apple, :islands (iOS), :host-core

Module list: apps/native/settings.gradle.kts.

Islands per host

IslandAndroid phoneiOSAndroid TVOwns
appAppIslandAppIslandinline (configure + ready)splash gate, store update/review, HostConfig persist
nav · intents✓✓✓Back presses as facts, raw OS intents buffer
window · device · storage✓✓—orientation, bars, PiP policy, permissions, atomic files
player · audioQueueMedia3EngineAVPlayerEngineplayer (Media3)playback surfaces, MediaSession, PiP
downloadsDownloadsEngineIosDownloadEngine—bytes + persistent keys; the page decides what
billing / storekitPlay BillingStoreKit 2Play Billingstore purchase sheet; page posts receipts
castSender · castPeer✓✓cast receiver + castPeerCast session; typed peer text pipe
telemetry✓✓—raw facts on one lossless observation
authSMS consent + phone hintSign in with Apple—OS credential sheets
push · paymentFCM render, payment handoff——transport and scheme allow-list only
caps · voice✓✓✓decoder/DRM facts, speech
homefeed——✓Android TV home channel

Sources: phone PhoneIslands.kt, iOS Islands.kt, TV TvActivity.kt. Each host passes a KSP-generated <Surface>Container with one required argument per island, so a missing island is a compile error (Surfaces.kt).

What each host still owns

Android phone

  • FORCE refusal in UpdateGate
  • Navigation floor + payment guard
  • IME inset into device.state
  • Offline 204 hold, main-frame fallback to shell /offline
  • Back floor: pop, else background

PhoneIslands.kt

iOS

  • Navigation policy
  • Main-frame failure → offline URL
  • Back: GO_BACK / PORTRAIT only
  • First-paint cap timer
  • FairPlay licence hook to the broker

Islands.kt

Android TV

  • No shell bundle, no update gate
  • Keep-screen-on, Back key mapping
  • Exit = finish()
  • Cast Connect receiver
  • Launch URL built inline

TvActivity.kt

Player path

SequencePlayback and DRM licenceOpen full reader ↗
Playback + DRM licence: the page answers every key requestAndroid Media3 path; iOS FairPlay uses the same brokersession.open(Open)coordinator.openprepare(manifest)challenge bytesEffect.LicenseRequestPOST challenge + tokenlicenceCommand.ProvideLicenseprovide(id)state · QoS effectsOpen (JS chose rendition + DRM)Key request round-tripPlayingPlayer (JS) · native-main.ts · Sequence participantPlayer (JS)native-main.tsSessionWire · contract ↔ engine · Sequence participantSessionWirecontract ↔ engineSessionCoordinator · one surface · retry · Sequence participantSessionCoordinatorone surface · retryMedia3Engine · ExoPlayer + CDM · Sequence participantMedia3EngineExoPlayer + CDMLicenceBroker · timeout → NO_ANSWER · Sequence participantLicenceBrokertimeout → NO_ANSWERLicence server · Hoichoi contents API · Sequence participantLicence serverHoichoi contents APILegendmain requestreturnsecurityasync tracemessage

SessionWire maps contract types to engine types; SessionCoordinator owns the one-surface rule, generation fencing and retries (SessionCoordinator.kt).

Threading and scopes

Root
ProcessScope = SupervisorJob + Default, never cancelled; everything shorter-lived is a .child() and no other CoroutineScope(…) may exist (Lifetimes.kt).
Islands
Phone/TV: lifecycleScope + Default; iOS host and TV process: ProcessScope.child().
Engines
Media3/AVPlayer each run on ProcessScope.child(main); downloads queries on child(IO).
Bridge handlers
Run off main; an island posts to main itself. assertMain is strict in debuggable builds.

Hosts and floors, in depth

6 items · click any row
Android phone host (MainActivity / PhoneIslands / Page.kt phoneConfig)android-phoneA KwryActivity 'socket' that boots the seeded, signed JS shell in kwry's WebView, wires every phone island through the generated…
What

A KwryActivity 'socket' that boots the seeded, signed JS shell in kwry's WebView, wires every phone island through the generated AndroidPhoneContainer, and forwards OS facts (intents, kwry events, Back, PiP, Home, touches) without deciding anything.

Why this way

KDoc calls MainActivity 'a socket (HOI-4132)': it 'forwards OS facts ... and decides nothing. The shell decides the boot (FORCE / offline / app.load), the window and the prompts' MainActivity.kt:11-16. PhoneIslands keeps only the H0 residue: 'the UpdateGate refusal, the main-frame fallback to the shell, the offline hold, the payment-scheme navigation policy and the OS Back default' PhoneIslands.kt:62-69. The generated container means 'forgetting one does not compile' PhoneIslands.kt:137-141. The overall rationale is that 'a UI change ships with a worker deploy, not an app store release, as long as the contract does not change' ARCHITECTURE.md:48-48.

Owns
  • the Activity / task lifecycle and edge-to-edge window (phoneEdgeToEdge)
  • kwry WebView config: admitted ORIGINS + seeded shell bundle origin, readyTimeoutMs splash cap, UA suffix, PROTECTED_MEDIA permission
  • WebViewClient mechanics: OfflineHold 204 answer, main-frame-error fallback to the shell's offline URL
  • IME/safe-area inset plumbing for WebView 113
  • OS Back default when no page listens (goBack or moveTaskToBack)
  • per-foreground update-policy refresh and OTA shell refresh
Never decides
  • route, read extras or pre-route an intent (H11.1, H11.3)
  • load a URL outside ShellLoader (H11.2)
  • draw native product UI or copy (H4.3, H4.4)
  • decide FLEXIBLE update prompts or which screen shows (H1.1)
  • store product state in SharedPreferences (H12)
Alternatives considered
OptionWhy not
Tauri/WRY host with Rust shell and Kotlin pluginsInterop JS → Rust → (UniFFI) → Kotlin vs JS → Kotlin; Gobley is a fragile dependency; team is Kotlin end to end (kmp-native-host-proposal.md:319-340)
Bind WRY from KotlinAndroid path would be 'Kotlin → JNI → Rust → JNI → android.webkit.WebView: two hops for nothing' (kmp-native-host-proposal.md:86-97)
Host-drawn bundled 'No Internet' sheetH7: splash, offline, downloads list and update screen are shell screens seeded in the bundle; host offline behaviour is mechanical only (HOST-RULES.md:71-73)
In the code
/**
 * The Hoichoi phone app on kwry: a socket (HOI-4132). kwry boots the seeded shell ([phoneConfig]); [PhoneIslands] wires
 * the islands and the WebView mechanics; this activity forwards OS facts (intents, kwry events, Back, configuration,
 * PiP, Home, touches) and decides nothing. The shell decides the boot (FORCE / offline / app.load), the window and the
 * prompts; intents reach it raw (HOI-4127).
 */
class MainActivity : KwryActivity() {
    private var islands: PhoneIslands? = null
    private var admitted: Bundle? = null

    override val peakRefresh = PeakRefresh.SAME_RESOLUTION // without it WebView rAF is capped at 60

    override fun edgeToEdge() = phoneEdgeToEdge(this)

    override fun kwryConfig() = phoneConfig(this) { islands?.open(it) }
    override fun app(host: KwryHost) = PhoneIslands(this, host).also { islands = it }.app()
Talks to
kwry KwryActivity/KwryHosthost-core (appOrigins, UpdateGate, navigationPolicy, PaymentHandoffGuard)PhoneIslands → AndroidPhoneContainer islandsShell (seeded bundle)Push.admitHostConfigStore
Gotchas
iOS host (Swift App → Kotlin HoichoiHost, Islands.kt)iosA thin Swift scene shell (App.swift) builds one Kotlin HoichoiHost from Swift-only SDK adapters (AVPlayer interop, FairPlay, Cast, Speech, StoreKit…
What

A thin Swift scene shell (App.swift) builds one Kotlin HoichoiHost from Swift-only SDK adapters (AVPlayer interop, FairPlay, Cast, Speech, StoreKit 2, Crashlytics); the Kotlin framework owns the KwryViewController, all islands (IosIslands/IosContainer), update gate and launch.

Why this way

App.swift: 'a thin scene shell. All behaviour is in the KMP framework HoichoiHost' App.swift:1-2; 'The one host (HOI-4132 I1): built once ... owns every island' App.swift:7-10. Swift exists only where the API is Swift-only: StoreKit 2 'is a Swift-only API, so Swift drives it and answers with plain data; the island ... stays here' StoreKit.kt:67-71; DEEP-DIVE: 'Swift gets no generated code' and 'implements small hand-written Kotlin interfaces' DEEP-DIVE.md:342-342. Every iOS island is required except voice, whose 'presence is the page's mic decision' Islands.kt:154-160.

Owns
  • UIApplication/scene lifecycle, supported orientations mask
  • UNUserNotificationCenter delegate (taps forwarded raw)
  • WKWebView via KwryViewController, launch screen until app-ready
  • service-worker registration sweep before first load
  • last-good shell-policy text (NSUserDefaults)
  • AVPlayerLayer under the web view and the native Cast button above it
Never decides
  • interpret notification payloads or link paths (H11.1)
  • run injected scripts (H2.2; Islands.kt notes 'No script runs in this host')
  • background itself (QA1561)
  • native payment SDKs other than StoreKit (H5)
Alternatives considered
OptionWhy not
Swift forwarders / a different host per platformProposal goal: 'Nobody writes Rust, JNI, Swift forwarders, or a different host per platform' (kmp-native-host-proposal.md:42-42)
tvOS WebView hosttvOS has no public WebView, so Apple TV stays the native KMP app (kmp-native-host-proposal.md:61-61)
In the code
        // The first load waits for the update policy and the service-worker sweep (caches, cookies, storage kept).
        var waiting = 2
        val ready = {
            if (--waiting == 0) {
                link?.let { l -> islands.intents.accept(IntentSource.LINK, l, coldStart = true) } // the shell navigates once it subscribes
                log.i("host.load_start", mapOf(LogKey.ON to LogValue.Bool(link != null)))
                if (deps.debug?.ownsLaunch(this) != true) launch.firstLoad()
            }
        }
        update.resolve(ready)
        h.webView.configuration.websiteDataStore.removeDataOfTypes(setOf(WKWebsiteDataTypeServiceWorkerRegistrations), NSDate.distantPast) {
            ready()
        }
Talks to
App.swift / SceneDelegateAppleDeps (Player.swift, Cast.swift, Voice.swift, StoreKit.swift, Crash.swift)kwry-apple KwryViewController/AppleWebHosthost-core (navigationPolicy, launchUrl, ProcessScope)IosIslands → IosContainerUpdate / Shell
Gotchas
Android TV host (TvActivity, no shell bundle)android-tvA KwryActivity that loads the hosted TV build from one exact origin (no seeded shell bundle, no update gate), sets the AndroidTV UA and…
What

A KwryActivity that loads the hosted TV build from one exact origin (no seeded shell bundle, no update gate), sets the AndroidTV UA and keep-screen-on, and installs the TV island set (player, billing, homefeed, Cast receiver, caps, voice, intents, castPeer).

Why this way

KDoc: 'configuration + ports over KwryActivity ... The hosted TV web app owns every screen and every key. Host duties: AndroidTV user agent, keep-screen-on, the fastest panel mode, the TV islands' TvActivity.kt:45-52. Process-wide buffers live in TvApp because 'a sender's LAUNCH/LOAD can cold-start the app' TvApp.kt:16-20. The surface's contract note says 'owner: no TV work' Surfaces.kt:38-38. Why no seeded shell bundle: not documented in repo; inferred from code: kwryConfig passes only origins=setOf(origin) and no bundle TvActivity.kt:68-78.

Owns
  • FLAG_KEEP_SCREEN_ON, PeakRefresh.ANY panel mode
  • TV UA string (AndroidTV token + HoichoiShell token)
  • remote BACK key → one nav.back press
  • Cast Connect receiver attach/detach, LOAD intents
  • splash watchdog (TV_SPLASH_WATCHDOG_MS) and splash-probe log vocabulary
  • microphone release onPause
Never decides
  • read the intent beyond action/data (VIEW → LINK, SEARCH → VOICE with opaque extras)
  • let Cast intent strings or sender credentials reach JS
  • decide what Back does beyond running nav.exit (finish)
In the code
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        log.i("splash.armed", mapOf(LogKey.DURATION to LogValue.Duration(Mechanics.TV_SPLASH_WATCHDOG_MS.milliseconds)))
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        val i = islands!!
        i.player.attach(host.view) // native SurfaceView beneath the transparent WebView
        // Cast Connect: LOAD intent data is parsed into typed values by CastLoadMapper; nothing from the intent reaches JS.
        // A re-created activity (savedInstanceState) never replays its launch intent: not the LOAD, not the link.
        val launch = intent.takeIf { savedInstanceState == null }
        val loads = object : CastLoads {
            override suspend fun decoders() = safeRunCatching { i.caps.decoders() }.getOrNull()
            override fun play(request: CastPlayback, level: WidevineLevel) = i.player.playCast(request, level)
        }
        CastConnect.attach(this, tvApp.cast, tvApp.scope, loads, launch)
        forward(launch, coldStart = true)
        host.loadShell("$origin/?platform=androidtv&appVersion=${BuildConfig.VERSION_NAME}")
    }
Talks to
kwry KwryActivityTvApp (CastIsland, IntentsIsland, HomeFeed worker)HostIslands (nav, caps, billing, voice, player)CastConnectHostConfigStore
Gotchas
  • No FORCE update gate on TV: the transcript passes update 'NONE' TvActivity.kt:141-148; host-core.md ledgers 'Android TV FORCE gate not added' (D7, host-core.md:166-166.
  • TV keeps kwry's exact-origin lock, so other http(s) pages go to the system browser DEEP-DIVE.md:203-203; it does not use host-core navigationPolicy like phone/iOS.
  • The launch URL is built inline ('$origin/?platform=androidtv&appVersion=...', TvActivity.kt:166-166 instead of host-core launchUrl used by phone/iOS.
host-core (Origins, Policy/UpdateGate, Navigation table, PaymentHandoffGuard, Lifetimes/ProcessScope)android-phoneiosandroid-tvA commonMain-only KMP module holding the one copy of host security/mechanics rules:
What

A commonMain-only KMP module holding the one copy of host security/mechanics rules: which exact origins a build admits, the shell-policy update decider and FORCE gate, the main-frame navigation table, the payment-app hand-off guard, and the process-rooted coroutine scope.

Why this way

It replaces drifted per-host copies: Navigation 'Replaces three drifted rules: phone MainActivity isWeb ..., iOS Policy.kt navigationPolicy ..., TV kwry's exactOriginPolicy' Navigation.kt:9-13; Policy is 'one copy for every host (was hosts/android Policy.kt:13-37 = hosts/ios Policy.kt:17-41...)' Policy.kt:9-11. HOST-RULES H9: 'Two platform copies of the same rule is a violation' HOST-RULES.md:79-82. UpdateGate: 'load is the only way an app document loads: refused off the app origins, refused while FORCE' UpdateGate.kt:11-16. ProcessScope is 'The one root of every coroutine ... No other CoroutineScope(…) exists in hosts/ or islands/' Lifetimes.kt:10-14.

Owns
  • origin table per Surface/build type and DEV_ORIGIN override validation (fails closed)
  • update-policy parse/decide/last-known-good resolution (FORCE/FLEXIBLE/NONE)
  • UpdateGate: the FORCE refusal of app.load
  • navigate(): ALLOW / OPEN_EXTERNAL / DENY floor + page policy
  • PAYMENT_SCHEMES / GATEWAY_DOMAINS deny floor
  • ProcessScope + child() supervisor scopes
Never decides
  • do I/O (hosts fetch the policy and store last-good; 'this decides')
  • own the FLEXIBLE prompt ('The page reads the action ... and owns the FLEXIBLE prompt; the host only gates FORCE')
  • let a page policy add to the app trust anchor or widen the payment floor
Alternatives considered
OptionWhy not
Proposal §9 item 2: lock top-level navigation to the app origin, deny popupsPayment and SSO pages must load and return in the WebView; locking them out 'would break the in-WebView return' (host-core.md:167-167)
Empty compiled NAV_ALLOW list of payment/SSO originsNo payment/SSO origin is a literal in the repo (they come from backend answers); floor became 'scripted https stays' (host-core.md:91-91)
Keep per-host copies of origins/policy/navigationThe copies had already drifted (navigation, cache-buster, link hosts) (DEEP-DIVE.md:253-256)
In the code
    if (!r.isMainFrame) return NavigationDecision.ALLOW
    if (r.url == "about:blank") return if (forced) NavigationDecision.ALLOW else NavigationDecision.DENY
    val o = Origin.of(r.url) ?: return NavigationDecision.DENY
    val allow = p?.allowInApp.orEmpty().mapNotNull(Origin::of)
    val https = o.scheme == "https"
    return when {
        o in app || o in allow -> NavigationDecision.ALLOW

        https && !r.hasUserGesture && (p?.scriptedStay ?: true) -> NavigationDecision.ALLOW

        https && r.hasUserGesture && (p?.tappedStay ?: tappedStay) -> NavigationDecision.ALLOW

        o.scheme == "https" || o.scheme == "http" -> if (p?.openExternal
            ?: true
        ) {
            NavigationDecision.OPEN_EXTERNAL
        } else {
            NavigationDecision.DENY
Talks to
kwry-core NavigationPolicy/OriginPhoneIslands, iOS Host.kt, AppIslandHostConfigStore (CurrentNavigation/CurrentPayment)contract HostNavigationPolicy/HostPaymentPolicy
Gotchas
Mechanics + FailClosedFloor + HostConfigStore (floors the page can only narrow)android-phoneiosandroid-tvMechanics.kt is the only place island numeric constants may live (each marked KEEP with an OS/wire reason);
What

Mechanics.kt is the only place island numeric constants may live (each marked KEEP with an OS/wire reason); FailClosedFloor holds the page's own values used only until its first config call; HostConfigStore persists the page's app.configure blob and refuses anything that would widen a host security floor.

Why this way

H1.4: 'A host may hold mechanism constants only ... They live in a Mechanics.kt per module and each has a one-line reason' HOST-RULES.md:40-44. Mechanics.kt header: two kinds only; 'a product value ... never lives here: it is a contract field the page sends' Mechanics.kt:10-16. HostConfigStore: generated validators already bound fields; 'check refuses what would WIDEN a host security floor' and is 'The ONE path a host reads the blob through ... a host never branches on HostConfig fields itself' HostConfigStore.kt:22-33.

Owns
  • KEEP constants: wire bounds, OS ids, buffer sizes, transport timeouts
  • pre-config floors: DOWNLOAD_LIMITS, DOWNLOADS notification config, VOICE_ENDPOINT
  • persisted HostConfig (storage boot/hostConfig) replayed before the first page
  • HostOverrides (splash cap, store URL, cast receiver id, push channel names, UA suffix, HTTP bounds)
Never decides
  • hold product thresholds, retry counts or UX timings outside the contract (H1.1, ACCEPTANCE P3)
  • accept a page blob that adds payment schemes/gateways, a non-store storeUrl, a forged HoichoiShell/contract UA token, or below-minimum splash/HTTP bounds
  • let the blob touch the bridge origin allowlist, OTA verify or push spoof stripping
Alternatives considered
OptionWhy not
Gate on a grep of '0.9x' literals'Catches 0.95 but not 95, 19/20 or a constant from another file'; replaced by property P3 (constants only in Mechanics.kt with a reason) (ACCEPTANCE.md:74-74)
In the code
        /** The first field that would widen a floor or break the host, or "" when [c] is acceptable. */
        fun check(c: HostConfig): String = when {
            c.splashMaxMs < Mechanics.CONFIG_SPLASH_MIN_MS -> "splashMaxMs"
            c.storeUrl.removePrefix("https://").substringBefore('/') !in STORE_HOSTS -> "storeUrl"
            !PAYMENT_SCHEMES.containsAll(c.payment.schemes) -> "payment.schemes"
            !GATEWAY_DOMAINS.containsAll(c.payment.gatewayDomains) -> "payment.gatewayDomains"
            "HoichoiShell" in c.userAgentSuffix || "contract/" in c.userAgentSuffix -> "userAgentSuffix"
            c.httpTimeoutMs < Mechanics.CONFIG_HTTP_MIN_TIMEOUT_MS -> "httpTimeoutMs"
            c.httpMaxBytes < Mechanics.CONFIG_HTTP_MIN_BYTES -> "httpMaxBytes"
            else -> ""
        }
Talks to
StorageIsland (persistence)host-core HostOverrides, CurrentNavigation, CurrentPaymentAppIsland (app.configure.v1)Downloads/Voice islands (floors)scripts/check-island-literals.mjs
Gotchas
  • FailClosedFloor.DOWNLOADS carries English notification copy ('Downloads', 'Download completed') and a hoichoi.tv tap URL Mechanics.kt:27-37 until the page's downloads.configure arrives.
  • HostConfigStore's own storage key needs a 'host-purity: allow H1.2' comment HostConfigStore.kt:74-75.
  • apply() silently clamps splashMaxMs to the TV watchdog ceiling HostConfigStore.kt:62-63, so the phone's soft cap can never exceed 10 s.
ShellLoader + Gate H host purity rulesandroid-phoneiosandroid-tvShellLoader.loadShell is the single permitted web-view navigation (boot, retry, offline fallback);
What

ShellLoader.loadShell is the single permitted web-view navigation (boot, retry, offline fallback); Gate H (HOST-RULES.md + scripts/check-host-purity.mjs ratchet) bans decisions, workarounds, glue, native UI and product state in hosts.

Why this way

Principle: 'The host exposes state and methods. The shell decides.' HOST-RULES.md:7-19. ShellLoader: 'The only place a host navigates its web view (HOI-4127, Gate H H11.2)... A link, a notification tap or any other intent never loads a URL' ShellLoader.kt:5-10. The gate ratchets debt down: 'CI fails if any count rises ... Debt only goes down' HOST-RULES.md:111-121. ACCEPTANCE v2 restates the end goal as 'a single OTA seam ... no product change is ever blocked on a store release' ACCEPTANCE.md:78-79.

Owns
  • WebHost.load for the shell entry / offline / gated app.load only
  • the purity gate, its baseline JSON, self-test, and host-size ratchet
Never decides
  • loadUrl/host.load outside ShellLoader (H11.2)
  • evaluateJavascript / user scripts (H2.2)
  • addJavascriptInterface / WKScriptMessageHandler (H3.2)
  • AlertDialog/Toast/UIAlertController product UI (H4.3)
  • raise the baseline or add allow comments to pass (LLM accountability)
Alternatives considered
OptionWhy not
Inline 'host-purity: allow' escape hatchAllowed only with a HOI ticket and counted; agents may not add one to make a change pass (HOST-RULES.md:118-120)
Grep-only gate checksGrep for one API name misses loadData, postWebMessage, WebMessagePort; v2 moves to Konsist/detekt/Gradle tasks, grep stays a fast pre-check (ACCEPTANCE.md:72-72)
In the code
package tv.hoichoi.islands

import dev.kwry.core.WebHost

/**
 * The only place a host navigates its web view (HOI-4127, Gate H H11.2). Every caller is a mechanical (re)load of the
 * shell: the launch URL, a Retry / network-back / relaunch of the URL that never admitted, the offline Downloads copy.
 * A link, a notification tap or any other intent never loads a URL: it goes to the shell on `intents.events.v1` and
 * the shell navigates.
 */
fun WebHost.loadShell(url: String) = load(url)
Talks to
PhoneIslands.open, iOS Host/Update/Shell, TvActivity.onCreateUpdateGate (gated app.load)scripts/check-host-purity.mjs, host-purity-baseline.json, check-host-size.mjs
Gotchas

Every island, in depth

14 items · click any row
app islandandroid-phoneiosandroid-tvBoot and store mechanics for the shell:
What

Boot and store mechanics for the shell: app.ready (splash release), app.load / app.update over UpdateGate, app.configure (HostConfigStore), in-app update/review flows, lifecycle state and drained main-frame failures.

Why this way

KDoc: 'platform capabilities in, pure logic here ... the plugin runs the flow, the page decides when; boot = app.load / app.update (HOI-4132: the shell decides the boot; the gate keeps the origin and FORCE checks)' AppIsland.kt:69-75. Main-frame failures are recorded so 'the shell reads why it booted instead of the host naming a route' AppIsland.kt:100-104.

Owns
  • splash-gate fact (alreadyReady)
  • AppLifecycle foreground/background state flow
  • MainFrameFailures ring (newest 8)
  • store update/review flow invocation
Never decides
  • choose when to prompt for update or review
  • route to an update/offline screen itself (only reports facts and refuses under FORCE)
In the code
) : AppApi {
    override suspend fun ready() = AppReadyResult(ready.alreadyReady())
    override suspend fun lifecycle(): Flow<AppLifecycle> = lifecycle
    override suspend fun startUpdate(p: AppStartUpdateParams) = AppStartUpdateResult(store.update(p.mode))
    override suspend fun requestReview() = AppReviewResult(store.review())
    override suspend fun load(p: AppLoad): AppLoadResult = AppLoadResult(
        when (boot.load(p.url)) {
            LoadGate.LOADING -> AppLoadOutcome.LOADING
            LoadGate.REFUSED -> AppLoadOutcome.REFUSED
            LoadGate.FORCE -> AppLoadOutcome.UPDATE_REQUIRED
        },
    )
    override suspend fun update(): Flow<AppUpdateState> = boot.action.map { AppUpdateState(it.wire(), boot.storeUrl) }
    override suspend fun configure(p: HostConfig): HostConfigResult = config?.accept(p) ?: super.configure(p)
    override suspend fun mainFrameFailed() = AppMainFrameFailures(failures.drain())
Talks to
host-core UpdateGateHostConfigStorekwry withReady / splashAndroid HostClient / iOS Shell.MainFrameFailure
Gotchas
  • Android TV does not use AppIsland: it passes an inline AppApi with only configure/ready TvActivity.kt:104-124.
  • DEEP-DIVE says 'A foreground stream is declared, not installed' for App DEEP-DIVE.md:447-447; AppIsland now implements lifecycle() AppIsland.kt:85-85 — whether each surface installs that row is per @InstalledOn, unverified here.
nav + intents islandsandroid-phoneiosandroid-tvnav reports each system Back press with raw facts (canGoBack, hiddenHistory, landscape, canBackground) on a lossless stream and runs the page's…
What

nav reports each system Back press with raw facts (canGoBack, hiddenHistory, landscape, canBackground) on a lossless stream and runs the page's chosen nav.exit action; intents forwards every OS intent (links, push taps, search) raw on intents.events.v1 with a host-owned buffer for cold start.

Why this way

NavIsland: 'the host keeps no Back chain of its own' — the page picks the action from the press's facts (NS-4, plan B4) NavIsland.kt:25-33. IntentsIsland: 'every OS intent goes to the shell raw ... nothing here reads a path, a route or a payload key'; the queue is 'the observation's host-owned buffer: a cold-start intent waits there' IntentsIsland.kt:24-33. HOST-RULES H11 requires exactly this HOST-RULES.md:89-92.

Owns
  • per-document lossless Back-press log (window 8)
  • process-lifetime lossless intents buffer
  • page-absent Back floor (browser default)
  • wire-bound filtering of URLs and extras
Never decides
  • parse paths/queries or switch on scheme/host (H11.1)
  • navigate the page for a link (H11.2)
  • keep its own Back cascade
Alternatives considered
OptionWhy not
deeplink.events.v1 with a host-side link parser/renamesFrozen for shells before 2026-12-d; its parser moved to core/intents/link-path.ts so the shell parses and routes (Intents.kt:22-26)
Old TV shell's injected synthetic Escape keydown for BackReplaced by nav.back.v1 items (no script injection) (NavIsland.kt:25-29)
In the code
class IntentsIsland(scope: CoroutineScope, private val clock: Clock) : IntentsApi {
    val out = LosslessOut(HostIntent.serializer(), INTENTS_WINDOW)
    private val queue = Channel<HostIntent>(INTENTS_WINDOW) // bounded, in front of the buffer
    private val n = AtomicLong(0L)

    init {
        scope.launch { for (i in queue) out.emit(i) }
    }

    /** Queues one intent; false when the shell is [INTENTS_WINDOW] × 2 behind (the OS intent is then dropped, logged by the host). */
    fun accept(source: IntentSource, url: String?, extras: Map<String, String?> = emptyMap(), coldStart: Boolean = false): Boolean {
        val id = "i-${n.incrementAndFetch()}"
        return queue.trySend(HostIntent(id, source, url?.takeIf(::wireSafe), boundExtras(extras), coldStart, clock.nowMs())).isSuccess
    }
Talks to
LinkRouter / Push.hostIntent (Android phone)TvActivity.forward / TvAppiOS Links + App.swift scene callbackshost NavHost (facts/exit)
Gotchas
window / device / storage islandsandroid-phoneiosandroid-tvwindow applies the shell's orientation, system bars, brightness and PiP auto-enter policy and reports size/orientation/PiP facts;
What

window applies the shell's orientation, system bars, brightness and PiP auto-enter policy and reports size/orientation/PiP facts; device exposes state (network, insets), share sheet, levels, permission prompts and country facts; storage is a capped namespaced key/value file store for the shell.

Why this way

WindowIsland: 'No rule of its own: the shell decides the orientation, the bars, the brightness and whether Home enters picture-in-picture' WindowIsland.kt:18-23. DeviceIsland: requestPermission is 'the OS prompt; the shell decides when to ask' DeviceIsland.kt:38-39. Storage: 'mechanics only' with caps checked under one lock StorageIsland.kt:36-39; H12 says persisted shell state 'goes through a generated StoreIsland key/value capability' HOST-RULES.md:94-95.

Owns
  • orientation lock, system bars, window brightness override
  • PiP auto-enter flag on Home
  • device state flow, share sheet, OS permission prompt
  • files under <root>/<namespace>/<key>, atomic temp+rename writes, 8 MiB/namespace cap
Never decides
  • decide orientation/bars/PiP policy
  • decide when to ask for permission
  • interpret stored values (except replaying BootSettings/HostConfig at launch)
In the code
) : WindowApi {
    private val facts = MutableStateFlow(initial)

    @Volatile private var autoEnter = false

    override suspend fun setOrientation(p: WindowOrientationParams) = orient.lock(p.orientation)
    override suspend fun setSystemBars(p: WindowBars) = bars.show(p.visible)
    override suspend fun setBrightness(p: WindowBrightness) = brightness.set(p.level)
    override suspend fun setPip(p: WindowPip) {
        autoEnter = p.autoEnter
    }
    override suspend fun state(): Flow<WindowState> = facts
Talks to
MainActivity.onUserLeaveHint → window.userLeaving → player PiPPlayerIsland (PlayerOwnsPip on iOS)BootSettings.replayBootSettings → player.configureHostConfigStore
Gotchas
player island + SessionWire + SessionCoordinatorandroid-phoneiosandroid-tvplayer.session.* is served on every platform by one commonMain SessionWire (contract ↔ engine type mapping) over one SessionCoordinator (one-surface…
What

player.session.* is served on every platform by one commonMain SessionWire (contract ↔ engine type mapping) over one SessionCoordinator (one-surface rule, generation fencing, parked/preloaded engines, effect fan-out); platform PlayerIslands keep only the surface, window, PiP, MediaSession and clip surfaces.

Why this way

SessionCoordinator: 'the one session rule set every platform shares (Gate H9). Media3 / AVPlayer only implement Engine ... No product rule (Gate H10): heartbeat and QoS periods, close timing and every window come from the page' SessionCoordinator.kt:34-43. SessionWire: 'Both PlayerIslands ... delegate their six session methods here, so the same page drives either engine through one mapping' SessionWire.kt:18-22. Android PlayerIsland: 'The page owns every rule (entitlement, licence, analytics, resume, close timing); this keeps the OS bindings' PlayerIsland.kt:75-81. DEEP-DIVE: native for 'Secure playback' (Widevine L1/FairPlay) and 'Production parity' DEEP-DIVE.md:783-788.

Owns
  • the single video surface and its placement under the transparent web view
  • generation counter and per-session slots (MAX_SESSIONS=4)
  • window flags (transparent, FLAG_SECURE, keep-screen-on), PiP, MediaSession / Now Playing
  • lossless effects buffer and session state snapshots
  • the native audio queue
Never decides
  • entitlement, resume/skip/next, controls visibility (H10)
  • heartbeat/QoS periods or retry policy (page sends Open.retry, heartbeatMs, qos)
  • choose renditions or rank codecs (ACCEPTANCE: 'Native never ranks codecs')
  • fall back to the web player inside a host
Alternatives considered
OptionWhy not
Shaka/EME in the WebView inside the appWidevine L1 / FairPlay run through platform players, not the web view; any Shaka load inside a host is rejected (DEEP-DIVE.md:783-788)
Fall back to the web player when the island is missing'there is no fallback from native to Shaka inside an app; a missing island is an error, by design' (ARCHITECTURE.md:161-161)
Two platform copies of the session rulesH9: logic identical on Android/iOS lives in commonMain (HOST-RULES.md:79-82)
In the code
    suspend fun open(o: Open, admitted: (live: Set<String>) -> Unit = {}): Opened = lock.withLock {
        val liveMain = owner?.let { slots[it] }?.takeIf { it.kind == SessionKind.MAIN && owner != o.sessionId }
        if (o.kind == SessionKind.TRAILER && liveMain != null) return Opened(o.sessionId, generation, Failure(FailureCode.SURFACE_BUSY))
        val gen = ++generation
        // A session waiting out the page's close (Release.afterMs) lets go of its decoders before this one's init (legacy flush).
        slots.filter { it.value.release != null && it.key != o.sessionId }.keys.toList().forEach(::drop)
        val old = slots.remove(o.sessionId)
        old?.let { cancel(it) }
        val engine = old?.engine ?: newEngine.create()
        val slot = Slot(engine, o.kind, gen, Trace.parse(o.traceparent, o.sessionId), o.retry)
        slots[o.sessionId] = slot
        evictParked()
        admitted(slots.keys.toSet())
Talks to
Media3Engine / AVPlayerEngine (Engine)LicenceBrokerDownloadsIsland (offline licence + local assets)CastSender (castHandoff/mainLive)WindowIsland (PiP)page adapter packages/player/src/native
Gotchas
player engines Media3Engine / AVPlayerEngineandroid-phoneandroid-tviosTwo 'dumb' implementations of the common Engine interface, one session each, wrapping production's videoplayer-core controllers (Media3Controller on…
What

Two 'dumb' implementations of the common Engine interface, one session each, wrapping production's videoplayer-core controllers (Media3Controller on Android, AVPlayerController on iOS) with environments that carry no product inputs.

Why this way

Media3Engine: 'the dumb Media3 engine (H10) ... over the production engine ... No product rules ... No licence fetch (HOI-4138 O2): every key request is an Effect.LicenseRequest' Media3Engine.kt:75-82. AVPlayerEngine: 'No product rules: no thresholds, windows, entitlement, licence URLs or analytics names; JS ... owns those. State is pushed' AVPlayerEngine.kt:122-129. Engine.kt: 'Both reply only after the change applied (no fire-and-forget)' Engine.kt:8-16. Production engine was chosen because a from-scratch Media3 player 'lacks prod's retry strategies ... rendition fallback ... auto Widevine L3 fallback' videoplayer-core-extraction.md:5-7.

Owns
  • decode, ABR, buffers, CDM session at the page's security level
  • the page-requested retry modes (SAME / SAFE_DECODER / SOFTWARE_DECODER / CLEAR_CACHE)
  • QoS counters (sampled on request)
  • offline recovery / network-restore resume (Android)
  • AVAudioSession, Now Playing, FairPlay plumbing via Swift interop (iOS)
Never decides
  • retry on their own ('The controller never retries by itself')
  • fetch licences or hold tokens
  • carry entitlement, subscription or codec policy (DumbEnvironment)
Alternatives considered
OptionWhy not
From-scratch Media3 1.5.1 player (Android TV Tauri prototype NativeVideoSurface.kt)Lacks prod's retries, rendition fallback, key-policy refresh, L3 fallback, LimitTrackSelection, HttpEngine→Cronet path and QoS (videoplayer-core-extraction.md:7-7)
In the code
/** The engine's inputs with no product state: no entitlement, no subscription, no codec policy, no licence fetch. */
internal class DumbEnvironment(
    context: Context,
    private val cdn: Map<String, String>,
    private val engine: Media3Engine,
    /** The page's level for this session's CDM (PlayerDrm.securityLevel); fixed: the engine never changes it. */
    override val widevineSecurityLevel: String? = null,
) : EngineEnvironment {
    private val network = NetworkMonitor(context)
    override val networkAvailable: StateFlow<Boolean> = network.available
    fun close() = network.close()

    /** The CDM's challenge goes to the page as [Effect.LicenseRequest]; [url] is the [VIA_JS] marker, never fetched. */
    override suspend fun fetchLicense(url: String, body: ByteArray, action: LicenseAction, codec: String?, mode: String?): ByteArray =
        engine.licenceViaJs(body, codec.orEmpty())
    override val keyPolicy = KeyPolicyProvider { _, _ -> null to null }
Talks to
SessionCoordinatorvideoplayer-core Media3Controller / AVPlayerControllerLicenceBrokerHoichoiFairPlay (Player.swift interop)DownloadsEngine / IosDownloadEngine (offline sources)
Gotchas
LicenceBroker / DRM via JSandroid-phoneandroid-tviosA thread-safe broker that turns each CDM challenge (Widevine) or FairPlay SPC into an Effect.LicenseRequest for the page and completes the waiting…
What

A thread-safe broker that turns each CDM challenge (Widevine) or FairPlay SPC into an Effect.LicenseRequest for the page and completes the waiting key request exactly once with the page's ProvideLicense answer, null on release, or null after a 30 s liveness timeout.

Why this way

KDoc: 'The JS-owned licence round-trip (FairPlay SPC on Apple, Widevine challenge on Android, HOI-4134 S3) ... Every request completes exactly once' LicenceBroker.kt:27-33. ACCEPTANCE's single OTA seam: native hands 'the opaque challenge bytes to JS, take the opaque licence bytes back'; JS owns 'Licence server URL, headers, auth token ... the shell makes the HTTP call' ACCEPTANCE.md:81-85; 'That is the whole DRM surface' ACCEPTANCE.md:100-100. The timeout is a 'liveness backstop so a dead page fails as DRM, never hangs' Mechanics.kt:71-73.

Owns
  • pending request map (CAS-swapped immutable snapshot)
  • per-request timeout timers
  • kwry-licence:// session URL markers
Never decides
  • know the licence server URL, token or headers
  • log or store licence bytes
  • retry a licence on its own
Alternatives considered
OptionWhy not
Island POSTs the licence itself with a pulled token (PlayerAuthSource / PlayerAuth, 401 retry)Superseded: Gate A v2 says the player loses PlayerAuth (token cache, credentials refresh, licenceHeaders) and licence/entitlement handling (ACCEPTANCE.md:93-97)
Token as a field on player.open'a field on player.open would need a new open version for each DRM path ... and a fresh page registration on every open' (player-token.md:15-15)
authHeader inside the open requestA signed-in header (2470 chars) exceeded the contract's @MaxLength(2048) (player-android.md:95-95)
In the code
        val id = "lic-${seq.incrementAndFetch()}"
        // Started only once registered: a timer that fired first would find nothing and the request would wait forever.
        val timer = scope?.launch(start = CoroutineStart.LAZY) {
            delay(timeoutMs)
            finish(id, null)
        }
        while (true) {
            val cur = pending.load()
            if (pending.compareAndSet(cur, cur + (id to (completion to timer)))) break
        }
        timer?.start()
        emit.send(Effect.LicenseRequest(sessionId, id, challengeB64, keySystem, codec))
    }
Talks to
Media3Engine.licenceViaJs / DumbEnvironment.fetchLicenseAVPlayerEngine.fetchLicence ← Swift IslandLicenseFetcher (Player.swift)SessionWire offline broker (downloads, sessionId dl-<contentId>)page player.session.effects / command ProvideLicense
Gotchas
  • An unanswered request surfaces as detail AUTH_UNAVAILABLE, a wire string kept from 2026-10-f pages LicenceBroker.kt:91-92.
  • DEEP-DIVE's 'Native DRM' section (credential order, 401 force-refresh) describes the retired native-fetch design DEEP-DIVE.md:884-908.
downloads (DownloadsIsland + engines)android-phoneiosOne common DownloadsIsland maps the contract onto a DownloadEngine:
What

One common DownloadsIsland maps the contract onto a DownloadEngine: Media3 DownloadManager + a dataSync foreground service on Android, AVAssetDownloadURLSession with FairPlay persistable keys on iOS; persistent licences come from the page via the player's licenceRequest pair.

Why this way

KDoc: 'NS-3 (R11/R14): the host holds no download policy. The owner is downloads.setOwner's ..., nothing resumes unless the page says so, and the free-space rule is the page's' Downloads.kt:90-94; the engine 'indexes, downloads and stores what the page sent; every decision ... is the page's' Downloads.kt:44-47. HOST-RULES H0: 'Background transfer must survive the page; Android requires a foreground-service notification' HOST-RULES.md:32-32.

Owns
  • OS download engines and on-disk files/index
  • Android foreground service, JobScheduler resume, terminal notifications (page copy)
  • iOS background session and FairPlay persistable keys
  • owner key, Wi-Fi-only flag, limits held for the process
Never decides
  • choose what to download, renditions, limits, or notification copy
  • resume at launch or switch owner on a read
  • fetch licences (page answers the challenge)
Alternatives considered
OptionWhy not
KMP owns downloads, licences and storage as source of truth (proposal §8.4)Gate A v2: 'The shell resolves URLs, the licence and the persistent key. Native only moves bytes and stores the key in the CDM' (ACCEPTANCE.md:104-104)
In the code
/**
 * `downloads` island, once for every host: the contract over a [DownloadEngine]. NS-3 (R11/R14): the host holds no
 * download policy. The owner is downloads.setOwner's (a list reads only), nothing resumes unless the page says so, and
 * the free-space rule is the page's (it reads settings().freeBytes before a resume).
 */
class DownloadsIsland(private val engine: DownloadEngine, private val licence: OfflineLicence) : DownloadsApi {
    /** The last owner the page set (the offline shell's boot URL replays it, §6b). */
    val owner: String get() = engine.owner

    override suspend fun start(p: DownloadStartParams): DownloadStartResult = engine.service { engine.start(p, licence) }

    override suspend fun pause(p: DownloadIdParams) = engine.service { engine.pause(p.contentId, p.owner) }

    override suspend fun resume(p: DownloadResumeParams) = engine.service { engine.resume(p) }

    // NS-3 (plan H10) releaseLicence is not wired yet: the licence stays (prod).
    override suspend fun remove(p: DownloadRemoveParams) = engine.service { engine.remove(p.contentId, p.owner) }
Talks to
PlayerIsland / SessionWire.offlineLicenceAndroidDownloadEngine → DownloadsEngine (Media3) → HoichoiDownloadServiceIosDownloadEngine → FairPlayDownloads (Player.swift)HostTelemetry (download facts)FailClosedFloor
Gotchas
cast sender / receiver / castPeerandroid-phoneiosandroid-tvcastSender (phone/iOS) runs one common CastSenderMachine over thin Android/Swift Cast SDK adapters;
What

castSender (phone/iOS) runs one common CastSenderMachine over thin Android/Swift Cast SDK adapters; cast (Android TV) is the Cast Connect receiver that plays LOADs natively and reports page-safe events; castPeer moves opaque kwry frames over the Hoichoi Cast namespace between phone and TV shells.

Why this way

CastSenderMachine: 'Every castSender rule both senders share ... The adapters only drive [sdk]' CastSenderMachine.kt:88-94. HOST-RULES H0: 'Google Cast SDK / AirPlay own the session and the system picker'; the shell owns 'When to show the button, LOAD metadata ... every control decision' HOST-RULES.md:30-30. CastConnect: 'No intent string and no sender credential ever reaches the page, and nothing here evaluates script' CastConnect.kt:60-70. CastPeer 'Knows no message in the pipe' CastPeer.kt:36-41.

Owns
  • CastContext / GCKCastContext session, discovery and picker
  • the native Cast button inside the page's rect
  • TV CastReceiverContext, MediaSession for host Cast sessions
  • lossless cast.events buffer (process lifetime on TV)
  • castPeer transports per connected peer
Never decides
  • decide LOAD metadata or when to show the button
  • pass sender credentials or licence URLs to the TV page (DRM challenge goes via CAST-B castLicence to the sender page)
  • interpret castPeer frames
In the code
/**
 * CAST-B (review 2026-11-05 Part 2, approach B): the Hoichoi Cast namespace to one peer device as a kwry
 * [dev.kwry.bridge.Transport]. kwry's [PortCore] keeps the handler slots, the early-frame buffer, the closed latch and the
 * onClose replay; this adds only how a frame leaves. Main thread, like every Cast SDK call ([CastPeerIsland] asserts it).
 * Knows no message in the pipe.
 */
class CastNamespaceTransport(private val ch: CastChannel, val peer: String) :
    PortCore(DocumentIdentity("cast:$peer", ORIGIN, isMainFrame = true)) {
    override fun out(text: String) {
        if (!ch.send(peer, text)) end(CloseReason.SEND_FAILED)
    }

    companion object {
        /** The Hoichoi namespace (receiver options, sender channel). One kwry frame per Cast message. */
        const val NAMESPACE = "urn:x-cast:tv.hoichoi.peer"
Talks to
Android CastSender (hosts/android cast)iOS CastSender.kt ↔ Cast.swift (AppCast)TV CastConnect + CastLoadMapper → PlayerIsland.playCastCastIsland (TvApp)kwry PortCore
Gotchas
billing / storekit / payment handoffandroid-phoneandroid-tviosbilling wraps Google Play Billing (SUBS) with a lossless purchase-outcome stream;
What

billing wraps Google Play Billing (SUBS) with a lossless purchase-outcome stream; storekit wraps StoreKit 2 via Swift (AppStoreKit) with Transaction.updates; payment.handoff opens allow-listed UPI/wallet links in the OS app on a real touch, for web gateway flows.

Why this way

H5: 'Only Google Play Billing and StoreKit. No Juspay, SSLCommerz or other gateway SDKs ... They run through their web flows in the shell' HOST-RULES.md:65-66. BillingIsland: 'The page owns every decision (which plan, which offer, when to restore, the server calls, every message); this only talks to Play' BillingIsland.kt:54-65. payments.md: 'Both islands are dumb ... They carry no copy and choose no offer' payments.md:3-9. Payment contract: 'the shell calls this on the user's tap instead of the host guessing from tap / hop timing' Payment.kt:15-16.

Owns
  • Play BillingClient connection and purchase sheet
  • StoreKit 2 purchase sheet, Transaction.updates listener
  • outcome buffers (window 8) that survive a document
  • payment-scheme allow-list, intent:// sanitising, touch-down gesture fact
Never decides
  • choose plan/offer or write copy
  • verify receipts or post them to the backend (page does)
  • log or persist purchase tokens / transaction ids
  • embed gateway SDKs (H5)
Alternatives considered
OptionWhy not
Juspay HyperSDK and SSLCommerz SDK islandsRemoved (contract 2026-12-b, HOI-4121); Gate H5 forbids other payment SDKs; Juspay/SSLCommerz run as web flows (payments.md:22-25)
HandoffGuard inferring payment intent from tap/hop timingReplaced by an explicit payment.handoff call from the shell on the user's tap (Payment.kt:15-16)
In the code
class HandoffIsland(private val activity: Activity, private val openWeb: Browser) : PaymentApi {
    private val touch = AtomicBoolean(false)

    /** A touch-down reached the activity (main thread): the gesture fact. */
    fun touched(ev: MotionEvent) {
        if (ev.actionMasked == MotionEvent.ACTION_DOWN) touch.set(true)
    }

    override suspend fun handoff(p: PaymentHandoffParams): PaymentHandoffResult {
        val r = if (!touch.getAndSet(false)) Handoff.REFUSED else openPaymentLink(activity, p.url, openWeb) // startActivity: any thread
        // never the link
        log.i("payment.handoff", mapOf(LogKey.CODE to LogValue.Id(paymentScheme(p.url) ?: "none"), LogKey.REASON to LogValue.Enum(r)))
        return PaymentHandoffResult(r.wire())
    }
Talks to
HostIslands (billing for phone + TV)iOS StoreKitIsland ↔ StoreKit.swifthost-core PaymentHandoffGuard / paymentSchemepage store-purchase.ts / plans.tsx
Gotchas
pushandroid-phoneAndroid phone FCM transport:
What

Android phone FCM transport: the token (logged by length only), rendering a data payload as sent while the app may be dead, stripping spoofed CleverTap wzrk_* extras from launch intents (Push.admit), forwarding taps raw, push.configure for channel copy, and the install referrer.

Why this way

KDoc: 'Transport only (HOI-4127, HOI-4132 A13): the token, the origin check on a tap (admit), and the tap itself read raw into one HostIntent ... a data message is rendered as sent while the app is dead (no page to do it)' Push.kt:36-44. H0: 'Page is not alive when the push arrives; OS requires a native service' HOST-RULES.md:29-29. admit exists because 'MainActivity is exported, so any app could start it with --es wzrk_pn true ...' Push.kt:142-146.

Owns
  • FirebaseMessagingService (HoichoiFCM)
  • notification channels (ids; names from the shell)
  • per-install notification mark (SharedPreferences)
  • intent extra sanitising before anything reads it
  • install-referrer once-per-install flags
Never decides
  • compose titles, bodies or channel copy (H15)
  • decide what a tap does (raw tap bubbles up)
  • send CleverTap events/profile natively
Alternatives considered
OptionWhy not
Native CleverTap SDKRemoved by owner 2026-11-05: 'CleverTap events and profile are the page's' (Push.kt:41-41)
In the code
    fun admit(context: Context, intent: Intent): Bundle? {
        // host-purity: allow H11.1 H0: Push.admit origin check (strips spoofed wzrk_*), the security boundary the ticket keeps HOI-4127
        val extras = safeRunCatching { intent.extras?.apply { keySet() } }
            .getOrElse {
                intent.replaceExtras(null as Bundle?)
                return null
            } ?: return null // unreadable extras (foreign Parcelable): none
        val keys = extras.keySet().toSet()
        if (keys.none { it.startsWith("wzrk_") || it == MARK }) return extras
        val drop = pushKeysToDrop(keys, safeRunCatching { extras.getString(MARK) }.getOrNull(), mark(context))
        drop.forEach {
            intent.removeExtra(it)
            extras.remove(it)
        }
        log.i("push.intent", mapOf(LogKey.ON to LogValue.Bool("wzrk_pn" in keys - drop), LogKey.COUNT to LogValue.Count(drop.size)))
        return extras
    }
Talks to
MainActivity.onCreate/onNewIntentLinkRouter → IntentsIslandHostTelemetry (push/install facts)Http (image fetch)HostOverrides.pushChannelNames
Gotchas
telemetry islandandroid-phoneiosOne lossless observation (telemetry.events.v2) carrying raw host facts (device, install, push, download, warn+ log lines) for the page to name and…
What

One lossless observation (telemetry.events.v2) carrying raw host facts (device, install, push, download, warn+ log lines) for the page to name and send, plus telemetry.log.v2 to write page lines into the native logger.

Why this way

KDoc: 'the host's raw facts as one LOSSLESS observation ... Nothing is named or filtered here beyond that' TelemetryIsland.kt:44-50. HOST-RULES H0 media row puts 'analytics, heartbeat, QoS reporting' with the shell HOST-RULES.md:31-31; the phone keeps one per process because 'the FCM service reports a delivery in a process that may never start MainActivity' Telemetry.kt:11-15.

Owns
  • bounded fact channel (64) with drop counting
  • log writer applying the page's log policy
  • device facts emitted on every open
Never decides
  • name analytics events or pick destinations
  • block or throw on produce (any thread)
Alternatives considered
OptionWhy not
Durable native analytics batch queue with retry (proposal §8.7)Not built: facts are in memory and a delivery in a process that dies before any page opens is lost (ponytail) (Telemetry.kt:14-14)
In the code
/**
 * `telemetry` island (NS-8, review R10/R11): the host's raw facts as one LOSSLESS observation, `telemetry.events.v2`.
 * Producers on any thread ([install], [push], [download], the [logWriter]) only `trySend` into a bounded channel; one
 * coroutine in [scope] moves each fact into kwry's [LosslessOut] (ordering, window, acks, backpressure are kwry's). A full
 * channel drops the fact and counts it; the count rides the next fact that gets through as `dropped`. Every open emits the
 * `factDevice` first and applies the page's log policy (the open params). Nothing is named or filtered here beyond that.
 */
class TelemetryIsland(scope: CoroutineScope, private val device: DeviceFacts) : TelemetryApi {
    val out = LosslessOut(TelemetryFact.serializer(), TELEMETRY_BUFFER)
    private val queue = Channel<TelemetryFact>(TELEMETRY_BUFFER)
    private val dropped = AtomicLong(0L)
    private val writer = TelemetryLogWriter(LogSink { offer(TelemetryFactLog(it.item())) })

    init {
        scope.launch { for (f in queue) out.emit(f.withDropped(dropped.exchange(0L))) }
    }
Talks to
Push.render / installReferrerDownloadsEngine.telemetrytv.hoichoi.log Logger writersiOS IosIslands (Crashlytics writer alongside)
Gotchas
auth (SMS consent, Sign in with Apple)android-phoneiosAndroid phone auth island reads one OTP SMS via Play services SMS User Consent and offers the phone-number hint;
What

Android phone auth island reads one OTP SMS via Play services SMS User Consent and offers the phone-number hint; iOS appleAuth runs native Sign in with Apple and returns the identity token / authorization code to the page.

Why this way

AuthHost: prod's SMS Retriever 'only delivers an SMS that ends in the app's 11-char hash, and the backend's template carries com.viewlift.hoichoi's ... so this host uses SMS User Consent' and lives in the host because 'Play services auth is a phone-only dependency' AuthHost.kt:53-60. auth.sms.v1 returns 'the SMS as the user allowed it; the shell extracts the code' AuthHost.kt:70-73. AppleAuth mirrors prod's ASAuthorizationAppleIDProvider flow AppleAuth.kt:35-39.

Owns
  • SMS User Consent listener and OS consent sheet
  • phone-number hint picker
  • ASAuthorizationController and its delegate lifetime
Never decides
  • extract the OTP (shell does)
  • store or log the SMS or identity token (logs lengths only)
  • decide sign-in flow or session
Alternatives considered
OptionWhy not
SMS Retriever API (prod)Requires the app's 11-char hash in the SMS; backend template carries a different package's hash (AuthHost.kt:54-57)
auth.smsCode.v1 (host extracts the code)Retired for auth.sms.v1 (HOI-4132 A11); not installed (AuthHost.kt:66-68)
In the code
            }
            // The sheet must be Play services' own activity and must not grant URI access (nested-intent hardening).
            val grants = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
            if (consent.resolveActivity(activity.packageManager)?.packageName != GMS || consent.flags and grants != 0) {
                throw BridgeException(ErrorCode.UNAVAILABLE, "unexpected consent intent")
            }
            val r = launch(ActivityResultContracts.StartActivityForResult(), consent)
            if (r.resultCode != Activity.RESULT_OK) return AuthSmsResult(AuthSmsMessageOutcome.DENIED, "")
            return AuthSmsResult(
                AuthSmsMessageOutcome.RECEIVED,
                // host-purity: allow H11.1 H0: Play services SMS User Consent result (an OS auth reply, not an intent to route) HOI-4127
                r.data?.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE).orEmpty().take(Mechanics.SMS_MAX),
            )
Talks to
Play services SmsRetriever / IdentityAuthenticationServicesPhoneIslands / IosContainer
Gotchas
caps + voiceandroid-phoneiosandroid-tvcaps reports decoder support (any/secure/hardware per codec) and the Widevine level/CDM properties as facts;
What

caps reports decoder support (any/secure/hardware per codec) and the Widevine level/CDM properties as facts; voice runs one utterance through the platform recognizer (inline state/start/stop on phone+iOS, one-shot recognize on TV) using the page's endpoint parameters.

Why this way

Caps contract: 'Device playback capabilities the page cannot feature-check' Caps.kt:16-19; Gate A v2: 'native reports caps.decoders() as a fact. The shell picks the rendition. Native never ranks codecs' ACCEPTANCE.md:102-102. VoiceIsland follows 'Flutter speech_to_text / @react-native-voice/voice (one module per OS behind one API)' VoiceIsland.kt:47-51; its endpoint starts at FailClosedFloor until voice.setEndpoint VoiceIsland.kt:91-93.

Owns
  • MediaCodecList / VideoToolbox decoder probes
  • MediaDrm open/read/close and cached security level
  • SpeechRecognizer / SFSpeechRecognizer and the microphone
  • endpoint watchdog ticks and phases
Never decides
  • rank codecs or pick renditions
  • choose endpoint thresholds (page sends VoiceEndpoint)
  • advertise voice where no recognizer exists (VoiceApiUnsupported)
In the code
/**
 * One platform's speech SDK (Android SpeechRecognizer, iOS SFSpeechRecognizer through the app's Swift). The island owns
 * every rule: endpointing, the processing wait, phases, outcomes. Shape: Flutter speech_to_text / @react-native-voice/voice
 * (one module per OS behind one API). Main thread, every call.
 */
interface SpeechEngine {
    /** [SpeechEndpoint]'s speech level in this engine's unit, from the page's [VoiceEndpoint]. */
    fun loud(e: VoiceEndpoint): Float
    fun amplitude(rms: Float): Double
    fun available(): Boolean

    /** True: the microphone may be used now without asking. */
    fun granted(): Boolean

    /** Asks the user; cancelling the call withdraws the request. */
    suspend fun ask(): Boolean
    fun start(sink: SpeechSink)
Talks to
Android CapsIsland / Apple CapsIslandCastConnect (decoders for LOAD)AndroidSpeech / iOS IosSpeech ← Voice.swiftHostIslands
Gotchas
  • iOS caps reports hardware decode only (software-only decoders read absent) and its comment still says the page 'plays through WKWebView FairPlay' CapsIsland.kt:16-21, while playback is native AVPlayer.
  • VoiceIsland KDoc says 'The island owns every rule: endpointing...' VoiceIsland.kt:47-50 though the thresholds themselves come from the page's VoiceEndpoint.
homefeed (TV)android-tvAndroid TV home-screen channels and Watch Next:
What

Android TV home-screen channels and Watch Next: the page publishes rails and watch-next items; an hourly WorkManager job (and INITIALIZE_PROGRAMS broadcast) refreshes channels from the app origin's catalog with no WebView alive.

Why this way

HomefeedIsland re-validates what the generated dispatch already bounded 'before anything reaches the TV provider' HomefeedIsland.kt:16-20. H0 lists 'TV channels / watch-next publishing' as an OS integration where the shell owns 'Everything the shell sends to them and every decision about when' HOST-RULES.md:34-34. The worker's app URL is 'Never taken from the page, so no page can point the background fetch elsewhere' HomeFeed.kt:147-151.

Owns
  • TvContract preview channels and programs, Watch Next rows
  • HomefeedWorker (periodic + one-shot) and HomefeedReceiver
  • catalog fetch bounds (2 MiB, 15 s)
Never decides
  • take the fetch URL from the page
  • publish unvalidated items (non-https art, unsafe ids)
In the code
/**
 * The system sends INITIALIZE_PROGRAMS after install from the Play Store (the launcher may send it again). Test with:
 *   adb shell am broadcast -a android.media.tv.action.INITIALIZE_PROGRAMS -n <applicationId>/tv.hoichoi.islands.homefeed.HomefeedReceiver
 * The receiver is exported, so any app may send this action (whether the OS protects it is unverified). It reads no intent
 * data: the worst a spoofed broadcast does is enqueue one refresh from the host's fixed app origin (REPLACE policy).
 */
class HomefeedReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action != TvContractCompat.ACTION_INITIALIZE_PROGRAMS) return
        log.i("homefeed.initialize_programs")
        HomeFeed.enqueueNow(context, "initialize-programs")
        HomeFeed.schedulePeriodic(context)
    }
Talks to
TvActivity (AndroidTvContainer)TvApp (appUrl, schedulePeriodic)WorkManagerAndroid TV provider (TvContractCompat)
Gotchas