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
| Module | Targets | Depends on |
|---|---|---|
:contract | jvm (islandgen), android, iOS, macOS | kwry bridge-gen-api, bridge-runtime; KSP bridge-gen |
:host-core | android, iOS, macOS | kwry-core, :log, :contract |
:player-engine (videoplayer-core/) | android, iOS, macOS | :log, Media3, VP9 decoder |
:islands | android, iOS, macOS | :contract, :player-engine, :host-core, kwry-core; Play, Cast, WorkManager on Android |
:hosts:android | app | kwry-android, :islands, billing, Cast, Firebase |
:hosts:androidtv | app | kwry-android, :islands |
:hosts:ios / :hosts:macos | iOS framework / macOS exe | kwry-apple, :islands (iOS), :host-core |
Module list: apps/native/settings.gradle.kts.
Islands per host
| Island | Android phone | iOS | Android TV | Owns |
|---|---|---|---|---|
| app | AppIsland | AppIsland | inline (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 · audioQueue | Media3Engine | AVPlayerEngine | player (Media3) | playback surfaces, MediaSession, PiP |
| downloads | DownloadsEngine | IosDownloadEngine | — | bytes + persistent keys; the page decides what |
| billing / storekit | Play Billing | StoreKit 2 | Play Billing | store purchase sheet; page posts receipts |
| castSender · castPeer | ✓ | ✓ | cast receiver + castPeer | Cast session; typed peer text pipe |
| telemetry | ✓ | ✓ | — | raw facts on one lossless observation |
| auth | SMS consent + phone hint | Sign in with Apple | — | OS credential sheets |
| push · payment | FCM 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
iOS
- Navigation policy
- Main-frame failure → offline URL
- Back: GO_BACK / PORTRAIT only
- First-paint cap timer
- FairPlay licence hook to the broker
Android TV
- No shell bundle, no update gate
- Keep-screen-on, Back key mapping
- Exit = finish()
- Cast Connect receiver
- Launch URL built inline
Player path
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 otherCoroutineScope(…)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 onchild(IO). - Bridge handlers
- Run off main; an island posts to main itself.
assertMainis strict in debuggable builds.
Hosts and floors, in depth
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…
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.
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.
- 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
- 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)
| Option | Why not |
|---|---|
| Tauri/WRY host with Rust shell and Kotlin plugins | Interop 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 Kotlin | Android 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' sheet | H7: 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) |
/**
* 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()- DEEP-DIVE still says the shared host module is 'Not wired ... no host depends on it'
DEEP-DIVE.md:92-95, but PhoneIslands imports tv.hoichoi.host UpdateGate/navigationPolicy/PaymentHandoffGuardPhoneIslands.kt:32-39: doc drift. - DEEP-DIVE says Android 'Host draws a bundled "No Internet" sheet'
DEEP-DIVE.md:80-80; code now loads the seeded shell's offline URL on main-frame failurePhoneIslands.kt:351-352. - Size ratchet: MainActivity.kt is capped at its current 53 lines with a stated goal of 150
host-size-limits.json:2-9;HOST-RULES.md:170-170.
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…
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.
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.
- 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
- 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)
| Option | Why not |
|---|---|
| Swift forwarders / a different host per platform | Proposal goal: 'Nobody writes Rust, JNI, Swift forwarders, or a different host per platform' (kmp-native-host-proposal.md:42-42) |
| tvOS WebView host | tvOS has no public WebView, so Apple TV stays the native KMP app (kmp-native-host-proposal.md:61-61) |
// 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()
}- No APNs: 'APNs registration is not in this app yet'
App.swift:22-23. - DEEP-DIVE says 'iOS always reloads, even though the page listens'
DEEP-DIVE.md:164-164; Host.kt now queues links on intents.events.v1 for the shell to navigateHost.kt:129-133: doc drift. - Host.kt still reads/writes NSUserDefaults for the policy cache
Host.kt:57-61, frozen as 2 H12 debt in the ratchethost-purity-baseline.json:8-8.
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…
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).
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.
- 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
- 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)
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}")
}- 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-166instead 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:
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.
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.
- 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
- 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
| Option | Why not |
|---|---|
| Proposal §9 item 2: lock top-level navigation to the app origin, deny popups | Payment 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 origins | No 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/navigation | The copies had already drifted (navigation, cache-buster, link hosts) (DEEP-DIVE.md:253-256) |
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- host-core.md's origin table lists phone release as hoichoi.tv + www
host-core.md:79-83; code now puts https://mobile.hoichoi.tv firstOrigins.kt:17-20. - Origins.kt uses Regex for DEV_ORIGIN
Origins.kt:27-28, carried as H2.1 debt in the baselinehost-purity-baseline.json:19-19. - Proposal assumed debug 'adds localhost'
kmp-native-host-proposal.md:144-144; code accepts only https://shell-bridge-*-test workers and throws otherwiseOrigins.kt:30-39.
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);
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.
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.
- 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)
- 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
| Option | Why 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) |
/** 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 -> ""
}- FailClosedFloor.DOWNLOADS carries English notification copy ('Downloads', 'Download completed') and a hoichoi.tv tap URL
Mechanics.kt:27-37until 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);
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.
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.
- WebHost.load for the shell entry / offline / gated app.load only
- the purity gate, its baseline JSON, self-test, and host-size ratchet
- 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)
| Option | Why not |
|---|---|
| Inline 'host-purity: allow' escape hatch | Allowed 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 checks | Grep 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) |
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)- apps/native/AGENTS.md still tells agents intents go to 'deeplink.events.v1'
AGENTS.md:20-20, but hosts no longer install it; intents.events.v1 replaced itLinkRouter.kt:15-20. - Baseline at introduction was 271 violations, target 0
HOST-RULES.md:156-159; the current baseline still lists H2.3 in PlayerIsland.kt and H12/H6/H13 in several islandshost-purity-baseline.json:1-60.
Every island, in depth
app islandandroid-phoneiosandroid-tvBoot and store mechanics for the shell:
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.
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.
- splash-gate fact (alreadyReady)
- AppLifecycle foreground/background state flow
- MainFrameFailures ring (newest 8)
- store update/review flow invocation
- choose when to prompt for update or review
- route to an update/offline screen itself (only reports facts and refuses under FORCE)
) : 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())- 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.
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;
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.
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.
- 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
- decide orientation/bars/PiP policy
- decide when to ask for permission
- interpret stored values (except replaying BootSettings/HostConfig at launch)
) : 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- device.setKeepAwake and device.haptic are notInstalled
DeviceIsland.kt:46-48. - window and device both expose setOrientation / setSystemBars
WindowIsland.kt:35-36;DeviceIsland.kt:43-45— overlapping surfaces. - BootSettings is an explicit 'HOI-4132 F5 exception': the host decodes the shell's last player settings before the shell boots
BootSettings.kt:17-26.
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…
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.
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.
- 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
- 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
| Option | Why not |
|---|---|
| Shaka/EME in the WebView inside the app | Widevine 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 rules | H9: logic identical on Android/iOS lives in commonMain (HOST-RULES.md:79-82) |
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())- Effects channel is DROP_OLDEST past 512 while the page is not observing (ponytail note,
SessionCoordinator.kt:76-78. - Android PlayerIsland still uses main.postDelayed for the trailer Back-resume
PlayerIsland.kt:319-325, frozen as H2.3 debthost-purity-baseline.json:31-31. - DEEP-DIVE describes the page polling position every 250 ms
DEEP-DIVE.md:839-852; ACCEPTANCE P4 requires pushed state with zero polling framesACCEPTANCE.md:117-117and AVPlayerEngine says state is 'pushed ... never polled'AVPlayerEngine.kt:122-129: doc drift.
player engines Media3Engine / AVPlayerEngineandroid-phoneandroid-tviosTwo 'dumb' implementations of the common Engine interface, one session each, wrapping production's videoplayer-core controllers (Media3Controller on…
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.
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.
- 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)
- retry on their own ('The controller never retries by itself')
- fetch licences or hold tokens
- carry entitlement, subscription or codec policy (DumbEnvironment)
| Option | Why 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) |
/** 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 }- DEEP-DIVE still says 'The island posts licence requests itself, asking the page for a fresh token'
DEEP-DIVE.md:884-906; both engines now hand the challenge to JSMedia3Engine.kt:623-625;AVPlayerEngine.kt:212-217. - iOS simulator audio device does not start, so smoke tests use a video-only stream
engine-ios.md:68-81. - iOS: no audio-track list or switching; captions from the engine's parser about once a second
DEEP-DIVE.md:922-922.
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…
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.
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.
- pending request map (CAS-swapped immutable snapshot)
- per-request timeout timers
- kwry-licence:// session URL markers
- know the licence server URL, token or headers
- log or store licence bytes
- retry a licence on its own
| Option | Why 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 request | A signed-in header (2470 chars) exceeded the contract's @MaxLength(2048) (player-android.md:95-95) |
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))
}- 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:
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.
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.
- 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
- choose what to download, renditions, limits, or notification copy
- resume at launch or switch owner on a read
- fetch licences (page answers the challenge)
| Option | Why 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) |
/**
* `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) }- releaseLicence on remove is not wired: 'the licence stays (prod)'
Downloads.kt:105-106. - DownloadsEngine still uses SharedPreferences
DownloadsEngine.kt:102-102and iOS indexes in NSUserDefaultsIosDownloadEngine.kt:102-108; both are H12 debthost-purity-baseline.json:10-12. - Player.swift keeps a stale comment 'Downloads are not ported to the kwry app'
Player.swift:44-45, noted in DEEP-DIVEDEEP-DIVE.md:1013-1013.
cast sender / receiver / castPeerandroid-phoneiosandroid-tvcastSender (phone/iOS) runs one common CastSenderMachine over thin Android/Swift Cast SDK adapters;
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.
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.
- 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
- 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
/**
* 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"- CastIsland's hand-off queue is unbounded (ponytail note,
CastIsland.kt:28-30. - CastLoadMapper carries 7 H2.1 (regex) baseline hits
host-purity-baseline.json:24-24. - CAST_CONTROLLER_DELAY_MS = 500 ms after LOAD is an SDK timing workaround kept in Mechanics
Mechanics.kt:128-129.
billing / storekit / payment handoffandroid-phoneandroid-tviosbilling wraps Google Play Billing (SUBS) with a lossless purchase-outcome stream;
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.
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.
- 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
- 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)
| Option | Why not |
|---|---|
| Juspay HyperSDK and SSLCommerz SDK islands | Removed (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 timing | Replaced by an explicit payment.handoff call from the shell on the user's tap (Payment.kt:15-16) |
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())
}- Purchase outcomes outlive the page and may belong to another account; the page must check the account id
BillingIsland.kt:61-64;DEEP-DIVE.md:497-497. - DEEP-DIVE's install table still lists a Juspay island on Android phone
DEEP-DIVE.md:461-461, retired 2026-11-04juspay-native.md:1-2. - Store-policy question (may Play/App Store builds offer web gateways?) is open for business
payments.md:27-40; TalkBack activations have no touch-down and are refusedPaymentHandoff.kt:63-68.
pushandroid-phoneAndroid phone FCM transport:
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.
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.
- 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
- compose titles, bodies or channel copy (H15)
- decide what a tap does (raw tap bubbles up)
- send CleverTap events/profile natively
| Option | Why not |
|---|---|
| Native CleverTap SDK | Removed by owner 2026-11-05: 'CleverTap events and profile are the page's' (Push.kt:41-41) |
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
}- No iOS push: 'APNs registration is not in this app yet'
App.swift:22-23. - Push uses SharedPreferences for mark/referrer flags (H12 debt ×2,
host-purity-baseline.json:7-7; PROMPT_SESSION is declared but unusedPush.kt:259-259. - Picture follows the text notification; a process killed right after onMessageReceived keeps text only (ponytail,
Push.kt:105-105.
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…
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.
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.
- bounded fact channel (64) with drop counting
- log writer applying the page's log policy
- device facts emitted on every open
- name analytics events or pick destinations
- block or throw on produce (any thread)
| Option | Why 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) |
/**
* `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))) }
}- In-memory only; a delivery before any page opens can be lost
Telemetry.kt:14-14. - Not on Android TV: the TV container has no telemetry island
Surfaces.kt:39-47.
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;
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.
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.
- SMS User Consent listener and OS consent sheet
- phone-number hint picker
- ASAuthorizationController and its delegate lifetime
- extract the OTP (shell does)
- store or log the SMS or identity token (logs lengths only)
- decide sign-in flow or session
| Option | Why 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) |
}
// 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),
)- Debug iOS builds have no Sign in with Apple entitlement
AppleAuth.kt:38-38. - e164 uses Regex in the host
AuthHost.kt:228-228, H2.1 debthost-purity-baseline.json:20-20.
caps + voiceandroid-phoneiosandroid-tvcaps reports decoder support (any/secure/hardware per codec) and the Widevine level/CDM properties as facts;
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.
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.
- MediaCodecList / VideoToolbox decoder probes
- MediaDrm open/read/close and cached security level
- SpeechRecognizer / SFSpeechRecognizer and the microphone
- endpoint watchdog ticks and phases
- rank codecs or pick renditions
- choose endpoint thresholds (page sends VoiceEndpoint)
- advertise voice where no recognizer exists (VoiceApiUnsupported)
/**
* 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)- 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-50though the thresholds themselves come from the page's VoiceEndpoint.
homefeed (TV)android-tvAndroid TV home-screen channels and Watch Next:
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.
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.
- TvContract preview channels and programs, Watch Next rows
- HomefeedWorker (periodic + one-shot) and HomefeedReceiver
- catalog fetch bounds (2 MiB, 15 s)
- take the fetch URL from the page
- publish unvalidated items (non-https art, unsafe ids)
/**
* 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)
}- HomeFeed hardcodes product knowledge — catalog path, rail kinds, deep-link URI shapes
HomeFeed.kt:134-172— and carries H2.1 ×9, H13, H12, H6 debthost-purity-baseline.json:11-11;host-purity-baseline.json:15-15;host-purity-baseline.json:25-25;host-purity-baseline.json:55-55. - The INITIALIZE_PROGRAMS receiver is exported; whether the OS protects the action is unverified
HomeFeed.kt:694-699.