Hoichoi client platform · JavaScript

JS layers and ports

The apps, the packages they share, the one-way dependency direction, and where each decision lives. This is the part that ships on every web deploy.

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

Go deeper

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

Apps

AppWhat it isBuilt / deployed as
webSolidStart (vinxi) SSR on Cloudflare Workers. The same app builds the phone target and the OTA shellhoichoi-web (hoichoi.tv), hoichoi-mobile (mobile.hoichoi.tv) — app.config.ts
tvSolidTV DOM renderer for LG / Samsung / Vidaavite build → dist/tv — main.ts
androidtvtv-kit with the WebGL renderer, fixed to Android TV, plus kwry gluemain.ts
vidaa-tvPlain Worker: serves the TV build and /api/catalog at the edgeworker.js
mobileProbes and docs only; all phone UI is in web—
tv-kit-devtv-kit harness (webgl + dom)dev only

Package layering

interfaces types only

Ports and VM types; no runtime code. VmPorts lists every capability a view model may use; host-only ports (cast, back, deepLinks, hostShell) are optional (vm-ports.ts).

↓

core the brain

Pure decisions, ~60 view models, navigation, intents, the player protocol and flows. Depends only on interfaces.

↓

adapters: platform · player · shell-kwry · api · auth · analytics

I/O and device facts. shell-kwry depends on nothing but config; player brings Shaka for the web and the native session bridge.

↓

views: ui · mweb · tv-kit

Solid components plus the port bindings per platform: one web set for browser, phone host and DOM TV (create-ports.ts), host extras only when a kwry host is present (host-ports-web.ts), and a TV set (tv-kit ports).

↓

apps

Entry points only.

Where decisions live

DecisionFunctionSource
Boot: update / offline / loadbootStep()host-shell.ts
Deep link / push tap → routeintentEffect(), handleIntent()intents.ts
Download limits, grouping, entry CTAdownloads.ts, download-entry.tsdownloads.ts
Store offer and copychooseOffer, chooseApplePromostore-billing.ts
Rendition, DRM, offline licenceopenFor()open.ts
Licence URL, credentials, 401/403 refreshsessionLicence()license.ts
Playback policy, DRM retryplayback.tsplayback.ts
Cast load metadata and hand-offcast.tscast.ts

Player: one switch

createPlayer() takes the host player inside a kwry host and Shaka everywhere else (createPlayer.ts). Inside a host, createNativeSessionEngine drives the native session and answers every licence request from the page (native-main.ts).

Telemetry

AppRoot starts host telemetry only inside a native app (AppRoot.tsx). One lossless telemetry.events.v2 observation carries raw host facts; nameHostFact turns them into PostHog, SigNoz and CleverTap events (host-telemetry.ts). On Android TV and browsers the island is absent and this path is a no-op.

Deploy and CI

WorkflowDoesSource
deploy-webbuild:web → hoichoi-web on push to maindeploy-web.yml
deploy-mobilebuild:phone, same-origin FairPlay cert, stage unsigned OTA shell, assetlinks/AASA, deploy hoichoi-mobile, probe shelldeploy-mobile.yml
citypecheck, lint, tests (also under Hermes), TV/web budgets, Gate H host purity, host-boundary ratchet, Gate A (informational), Android + iOS native buildsci.yml

Every JS layer, in depth

15 items · click any row
apps/web: SolidStart on Cloudflare Workers + phone build targetOne SolidStart (SSR + hydration) app built with the cloudflare_module Nitro preset serves desktop/mobile browsers;
What

One SolidStart (SSR + hydration) app built with the cloudflare_module Nitro preset serves desktop/mobile browsers; the same source built with HOICHOI_BUILD_TARGET=phone (__PHONE__=true) emits .output-phone, deployed as the hoichoi-mobile worker the Android/iOS hosts load.

Why this way

ARCHITECTURE.md: "a UI change ships with a worker deploy, not an app store release, as long as the contract does not change" ARCHITECTURE.md:48, and browsers stay untouched because "the bridge code is never downloaded" (:49). app.config.ts says apps/web is "the MODERN web build only" because "Vinxi/SSR cannot emit an ESM-free Cr53 client", so "the build pipeline forks into two thin shells over one shared packages/* source" app.config.ts:101-104. The phone target "removes desktop presentation branches, and preserves existing API/auth/stores/loaders/native player implementations" phone-build.md:5.

Alternatives considered
OptionWhy not
Serve the Cr53 TV client from the same SolidStart/Vinxi buildVinxi hard-injects <script type=module>, so it cannot emit an ESM-free Cr53 client; TV is a separate Vite/IIFE shell (app.config.ts:101-104)
Bundle the UI into the APK/IPAPhone apps load the hosted web build; "nothing of the UI is bundled in the APK or IPA" so UI ships with a worker deploy (ARCHITECTURE.md:38-48)
In the code
    // apps/web is the MODERN web build only. The Cr53 TV web app is apps/tv —
    // Vinxi/SSR cannot emit an ESM-free Cr53 client (hard-injects
    // <script type=module>), so the build pipeline forks into two thin shells
    // over one shared packages/* source. Values MUST be strings or DCE no-ops.
    define: { __TV__: 'false', __WEB__: 'true', __KWRY__: 'true', __PHONE__: String(phoneBuild) },
    resolve: {
      alias: [
        ...(phoneBuild ? [{ find: /^\.\/styles\.css$/, replacement: fileURLToPath(new URL('./src/phone.css', import.meta.url)) }] : []),
Talks to
packages/ui AppRootpackages/mwebCloudflare Workers (wrangler.jsonc hoichoi-web, wrangler.mobile.jsonc hoichoi-mobile)native phone hosts (kwry)apps/web/shell
Gotchas
  • Build web and phone sequentially: "Nitro still shares .vinxi scratch state" phone-build.md:7; AGENTS.md:765).
  • ARCHITECTURE.md says the phone hosts' release origin is hoichoi.tv ARCHITECTURE.md:73, but the production phone worker is mobile.hoichoi.tv per apps/web/wrangler.mobile.jsonc:2-5; the doc lags the code.
  • eslint max-lines keeps apps thin: app.tsx <= 80 lines, route files <= 30 (AGENTS.md:331).
OTA shell (apps/web/shell, shell-bundle.mjs, shell-ota.mjs; /boot /offline /update /downloads)A separate client-only Vite build of a tiny Solid app (splash, boot, update, offline, downloads screens) is packed by kwry's bridge-bundle CLI into…
What

A separate client-only Vite build of a tiny Solid app (splash, boot, update, offline, downloads screens) is packed by kwry's bridge-bundle CLI into an unsigned manifest+files bundle, seeded in the APK/IPA and republished over the air at the tag-free /shell/<id>/ path on mobile.hoichoi.tv.

Why this way

Gate H rule H7: "Splash, offline/no-internet, the downloads list and the update screen are shell screens, seeded in the app bundle (kwry BundleStore) and updated over the air" and the host's only offline behaviour is mechanical HOST-RULES.md:71-73. main.tsx: "every decision (FORCE, offline, app.load, Retry) is this page's" main.tsx:1-4. It is a plain Vite build because SolidStart "cannot" add a server-less SPA router and "a plain Vite build is smaller and has no server at all" vite.config.ts:1-3. The bundle is UNSIGNED: "the origin it is served from is the trust; the hosts check hashes, sizes, contract range and channel" shell-bundle.mjs:3-4, and ONE copy covers "every installed app" ("allow everything to work on everything", shell-ota.mjs:4-5.

Alternatives considered
OptionWhy not
An spa router inside the SolidStart (vinxi) appEvery vinxi router is SSR-or-SPA over one route tree and still goes through Nitro's output; plain Vite is smaller and serverless (vite.config.ts:1-3)
Host-drawn native offline sheet / update screen (old assets/offline, OfflineSurface, policySwap)Ported into the shell so the page decides when it shows and what Retry does; H7.2 flags assets/offline and OfflineSurface (ShellScreens.tsx:1-3)
Signed bundle / per-tag copiesOwner chose unsigned with origin-as-trust and one tag-free copy whose range spans oldest release..current (shell-ota.mjs:2-5)
In the code
render(
  () => (
    <AppRoot hint="web" offlineShell>
      <Router>
        <Route path="/splash" component={SplashScreen} />
        <Route path="/boot" component={BootScreen} />
        <Route path="/update" component={UpdateScreen} />
        <Route path="/offline" component={OfflineScreen} />
        <Route path="/downloads" component={() => <Downloads />} />
        <Route path="/downloads/settings" component={() => <Downloads section="settings" />} />
        <Route path="*" component={OfflineScreen} />
      </Router>
    </AppRoot>
  ),
  document.getElementById('app')!,
)
Talks to
kwry BundleStore / bridge-bundle CLIpackages/mweb/pages/ShellScreens.tsxpackages/ui/ports/host-ports-web.ts (bootHost, hostShell)deploy-mobile.yml (stage + probe)apps/native/contract/schema
Gotchas
  • The shell origin has no session (localStorage is per origin): the host passes the user in ?user= for the downloads screen main.tsx:21-24.
  • shell-bundle.mjs fails the build if a CSS url() is not in the bundle ("MSIM-2: /fonts 404") or Tailwind utilities are missing shell-bundle.mjs:36-46.
  • deploy-mobile.yml's header comment still says /shell/<id>-<tag>/ deploy-mobile.yml:4 while the code publishes tag-free /shell/<id>/ deploy-mobile.yml:89-93.
TV apps: apps/tv (SolidTV DOM), apps/androidtv (WebGL tv-kit), apps/vidaa-tv workerEvery TV is a thin host over packages/tv-kit:
What

Every TV is a thin host over packages/tv-kit: apps/tv calls startTvKitApp() on the SolidTV DOM renderer as a Cr53 IIFE (LG/Samsung/Vidaa), apps/androidtv runs the same kit on WebGL with kind fixed to TvAndroid plus kwry glue, and apps/vidaa-tv is a Cloudflare worker serving the built TV bundle and an edge /api/catalog.

Why this way

AGENTS.md: "The TV hosts are configuration over the kit"; "A host differs only in its port configuration (kind) and build options; module swaps (vite alias overrides) are not allowed" (AGENTS.md:213). Renderer choice was measured: on Docker Chromium 53 "WebGL cannot create a context (3/3), DOM PASS 3/3", so "LG and Samsung ship the DOM renderer ... WebGL stays for Android TV and Apple TV" DESIGN-tv-kit.md:79-83; apps/tv/vite.config.ts cites "WebGL texture budgets on 1-1.5 GB sets" vite.config.ts:4. The Vidaa worker does not re-implement catalog logic: it "calls the SAME shared aggregateCatalogRails core that web SSR uses" worker.js:11-18.

Alternatives considered
OptionWhy not
WebGL renderer on LG/SamsungWebGL could not create a context on the Cr53 rig; re-open for LG only with the gate on a real panel (DESIGN-tv-kit.md:79-83)
@lightningjs/solid-ui primitives"unusable with this pair" (@solidtv/solid 1.6.6 + renderer 1.10.2), so primitives are in-house (DESIGN-tv-kit.md:23-26)
Retired DOM TV app (packages/ui/pages/tv, tv-boot.ts)Deleted in C4; the TV kit is the only TV renderer (DESIGN-tv-kit.md:3-6)
Vite alias module swaps per host (old ATV override createPlayer)Platform behaviour in a Vite swap is invisible to shared tests; swaps are banned (zipline-bridge-and-player-mvi.md:44-49)
In the code
// Android TV: the same TV kit as apps/tv, WebGL renderer, kind fixed to Android TV (the one port difference,
// ports/port-differences.test.ts). The kwry glue below (splash hand-off, deep links, Back, voice, Cast) is
// the host's native surface, not a module swap.
import '@hoichoi/tv-kit/polyfills'
import { PlatformKind } from '@hoichoi/interfaces/enums'
import { startTvKitApp } from '@hoichoi/tv-kit/app'
import './androidtv.css'
import { startDeepLinks } from './native/deeplinks'
import { startSplashHandoff } from './native/splash'
import { mountCastBadge, startCastReceiverBridge } from './native/cast'
import { startNavBack } from './native/nav'
import { startVoiceSearch } from './native/voice'
import { READY_CLASS } from './native/app-ready'
import { sendHostPolicy } from '@hoichoi/player/native/host-policy'

startSplashHandoff()
Talks to
packages/tv-kit (startTvKitApp, tvBuildConfig, createTvPorts)packages/core VMsShaka via classic-script shaka.js (DOM TV)kwry Android TV host (androidtv glue)apps/vidaa-tv worker + packages/api catalog-core
Gotchas
  • Polyfills must be the first import of a JSX-free main.ts; a .tsx entry hoists the JSX runtime above it (AGENTS.md:215; DESIGN-tv-kit.md:36-39.
  • Roboto MSDF atlas has no Bengali glyphs (Bengali renders blank on WebGL) DESIGN-tv-kit.md:84-85.
  • Packaging requires HOICHOI_TV_APP_URL and rejects the production reference vidaa.hoichoi.tv README.md:19-31.
packages/interfaces ports + VmPortsZero-runtime type contracts:
What

Zero-runtime type contracts: Ports (loader, device, i18n, session, nav, storage, clock) is how core reaches any host, and VmPorts extends it with everything a screen VM needs (commands, analytics, player engine, caps) plus optional host-only ports (downloads, payments, cast, back, deepLinks, hostShell).

Why this way

vm-ports.ts: "Hosts implement them ... tests pass fakes. Nothing here names a surface: a host differs only in what it implements and in the PlatformUiCapabilities it declares" vm-ports.ts:1-3. AGENTS.md mental model: ports are "how core reaches the host" (AGENTS.md:297). DESIGN-core-ports explains LoaderKey is a name not a fetcher because "the fetchers are query() wrappers in packages/ui ... core may import neither" DESIGN-core-ports.md:21-22. Optional members mean "an island the host did not install is simply absent. The page degrades, it never feature-sniffs" ARCHITECTURE.md:110.

Alternatives considered
OptionWhy not
Loader keys carrying a fetch functionFetchers are query() wrappers in packages/ui / @hoichoi/store; core may import neither (DESIGN-core-ports.md:21-22)
seed and persist as one memberA persist that also seeded would hand a later refresh the stale page; a redirect that also persisted would leave the seed unused (DESIGN-core-ports.md:25-26)
In the code
export interface VmPorts extends Ports {
  session: SessionState
  nav: VmNavigation
  command: Commands
  analytics: AnalyticsSink
  feedback: Feedback
  share: ShareSheet
  /** FLOWS' timer dep, the same function every flow takes: VMs pass it straight into their flows. */
  schedule: Schedule
  caps: PlatformUiCapabilities
  player: PlayerEngine
  support: Support
  /** Present only where the host has them (caps.screens() has 'audio' / 'downloads'; caps.storeBilling; voiceSearch). */
  audio?: AudioSession
  downloads?: Downloads
  payments?: Payments
  voice?: Voice
  phoneHint?: PhoneHint
Talks to
packages/core (consumer)packages/ui/ports (web/phone impl)packages/tv-kit/src/ports (TV impl)packages/core/vm/testing/fake-ports.ts
Gotchas
  • host-shell.ts is "HAND-TYPED from the ticket's Kotlin/TS sketch while the CONTRACT lane cuts the tag" pending generated bindings host-shell.ts:1-4.
  • interfaces/{vm,ports,nav} is held to the same Hermes floor as core: imports solid-js and relative paths only (eslint.config.mjs:103, :453).
packages/core: decisions, VMs, intents ("JS is the brain")All product decisions live once in packages/core as pure functions (decisions/), screen VMs over ports (vm/), flows, nav, intents and player policy,…
What

All product decisions live once in packages/core as pure functions (decisions/), screen VMs over ports (vm/), flows, nav, intents and player policy, with no rendering and no platform globals, so every kit and host runs identical logic.

Why this way

The exact phrase "JS is the brain" is not in the repo; the documented equivalents are "The host exposes state and methods. The shell decides." HOST-RULES.md:9 and the shell "owns every decision, all UI, all copy, every route, every threshold, all analytics naming and all product policy" HOST-RULES.md:15-16. ARCHITECTURE.md: "One core, two kits. Every screen's decisions live once in packages/core (VMs over ports)" ARCHITECTURE.md:4. AGENTS.md: "A TV-vs-web fork in logic is a defect, never the fix" (AGENTS.md:209). Core is lint-gated to "Hermes is the floor" and tests also run under Hermes ("the Roku floor") (eslint.config.mjs:451-452; test-hermes.mjs:1-2.

Alternatives considered
OptionWhy not
Tv*-prefixed logic modules or __TV__ ? : behavioural branchesOnly polyfills or version pins may differ by platform; logic forks are defects (AGENTS.md:208-209)
Decisions in native hosts (thresholds, routes, offer choice)Gate H1: hosts never decide (HOST-RULES.md:40-44)
In the code
        { selector: 'FunctionDeclaration[generator=true]', message: 'Proposal rule 2: generators are off the Hermes floor.' },
        { selector: 'FunctionExpression[generator=true]', message: 'Proposal rule 2: generators are off the Hermes floor.' },
        {
          selector:
            "ImportDeclaration[source.value='solid-js'] > ImportSpecifier[imported.name='lazy'], ExportNamedDeclaration[source.value='solid-js'] > ExportSpecifier[local.name='lazy'], ExportAllDeclaration[source.value=/^solid-js/]",
          message: 'Proposal rule 2: no lazy in core.',
        },
        { selector: 'JSXElement, JSXFragment', message: 'Proposal rule 1: core never renders.' },
        // Hermes 0.12 does not parse these, and the es2016 test bundle keeps them as written.
        { selector: 'ArrowFunctionExpression[async=true]', message: 'Proposal rule 2: Hermes has no async arrows; use an async function or .then.' },
        { selector: 'ClassDeclaration, ClassExpression', message: 'Proposal rule 2: Hermes has no class syntax; use functions and object literals.' },
        {
          selector: `ImportExpression > Literal[value=/${deny}/], ImportExpression[source.type!='Literal']`,
          message: CORE_IMPORT_MESSAGE,
        },
Talks to
packages/interfaces (types)@hoichoi/api, errors, media (allowed imports)packages/ui + mweb (web kit)packages/tv-kit (TV kit)packages/player/src/native (player policy consumer)
Gotchas
  • Core may import only solid-js, solid-js/store, @hoichoi/interfaces|api|errors|media and relative paths (eslint.config.mjs:99-105).
  • No async arrows, classes or generators in core: Hermes 0.12 does not parse them (eslint.config.mjs:181-191).
  • Solid-2-removed APIs (on, batch, createComputed, mergeProps, splitProps) are banned in core (eslint.config.mjs:161-166).
Per-platform port bindings (ui/ports create-ports, host-ports-web, tv-kit ports)Web, mobile web and the phone hosts share one binding set in packages/ui/ports (createPorts for base Ports, createVmPorts adds VM ports, hostPorts…
What

Web, mobile web and the phone hosts share one binding set in packages/ui/ports (createPorts for base Ports, createVmPorts adds VM ports, hostPorts adds lazy kwry-only ports); every TV uses createTvPorts in packages/tv-kit/src/ports with kind as the only per-host difference.

Why this way

create-ports.ts: "One implementation set serves web, the phone hosts and the TV DOM app" create-ports.ts:15 and it is "Called as a function, never as <PortsContext.Provider>: a component layer re-keys every data-hk below it" (:29). host-ports-web.ts: host-only ports are "present only inside a KWRY host ... Each method loads its module on first use ... so browsers and boot carry none of it" host-ports-web.ts:8-9. createVmPorts is built lazily "so the VM ports reach only the chunks of pages that run a VM: boot carries none of it" vm-ports-web.ts:17-19. Since C4, "the TV kit's one ports module ... implements every port for LG/Samsung/Vidaa/Android TV" DESIGN-core-ports.md:47-49.

Alternatives considered
OptionWhy not
<PortsContext.Provider> JSXA JSX provider is a component layer and re-keys every data-hk below it (hydration mismatch) (DESIGN-core-ports.md:3-5)
TV mounting AppRoot / ui portsRetired in C4; TV uses createTvPorts (DESIGN-core-ports.md:37-49)
In the code
// Inside PlatformProvider and I18nProvider. One implementation set serves web, the phone hosts and the TV DOM app.
export function createPorts(initialLocale: Locale): Ports {
  return {
    loader: webLoader,
    device: createDeviceWeb(usePlatform()),
    i18n: createI18nWeb(useI18n(), initialLocale),
    session: webSession,
    nav: webNavigation,
    storage: webStorage,
    sessionStorage: webSessionStorage,
    clock: systemClock,
  }
}
Talks to
packages/ui/AppRoot.tsx@hoichoi/player/host + shell-kwry (lazy)packages/ui/ports/host-shell.tspackages/tv-kit/src/app.tsx@hoichoi/platform capabilitiesForKind
Gotchas
  • Route VMs must redirect via useRouteNavigation(ports.nav), never ports.nav.replace: a hidden kept tab could redirect the visible one DESIGN-core-ports.md:50-54.
  • ports.audio is attached asynchronously; a VM reading it on a cold start to the audio page sees none host-ports-web.ts:136-148.
  • TV ports drop analytics and echo i18n keys for now (ponytail notes) index.ts:105-107, :174-176).
Boot decision: bootStep + ShellScreensThe seeded shell's /boot screen asks the pure core function bootStep(update, connectivity) whether to show /update (FORCE), /offline (no validated…
What

The seeded shell's /boot screen asks the pure core function bootStep(update, connectivity) whether to show /update (FORCE), /offline (no validated network) or app.load the hosted app; ShellScreens also renders the in-app offline sheet and the running-app FORCE gate.

Why this way

host-shell.ts: "the decisions the Android/iOS hosts made and the shell makes now. Pure; the host only applies them" host-shell.ts:1-2; undefined inputs mean "null = wait, never guess" (:11). BootScreen replaced "MainActivity loadApp/openShell/showUpdate. Decided once." ShellScreens.tsx:151-154. It waits for the host's device.state.v1 snapshot, not navigator.onLine, because "an offline boot loaded the app" (SHELL-OFF-3) (:164-165). Grounded in H7 HOST-RULES.md:71-73.

Alternatives considered
OptionWhy not
Host decides boot (MainActivity loadApp/openShell/showUpdate, host-core Page.kt updateHtml)Moved to the shell under HOI-4132; host only applies (ShellScreens.tsx:137,151-154)
navigator.onLine for the boot network checkAn offline boot loaded the app (SHELL-OFF-3); host snapshot used, with a 1500 ms fallback (ShellScreens.tsx:127-128,164-171)
A held app.update observation in the running appkwry's 8 observations per document are full on /watch; read once at mount and on foreground (ShellScreens.tsx:205-209)
In the code
export type BootStep = 'update' | 'offline' | 'load'

/**
 * The seeded shell's launch: FORCE -> the update screen; no validated network -> offline/downloads; else app.load.
 * Undefined = not answered yet (the host's app.update / device.state.v1 snapshot): null = wait, never guess.
 */
export function bootStep(update: UpdateMode | undefined, net: Connectivity | undefined): BootStep | null {
  if (update === 'FORCE') return 'update'
  if (!update || !net) return null
  return net.validated ? 'load' : 'offline'
}
Talks to
HostShell port (app.load, app.update, lastMainFrameFailure)Device port connectivity (device.state.v1)apps/web/shell routesapps/web/src/app.tsx (AppOfflineSheet, AppForceUpdate)
Gotchas
  • Offline screen returns to the app only on the validated edge; otherwise a reachable network with a dead server would bounce app -> shell -> app forever ShellScreens.tsx:69-77.
  • AppOfflineSheet never mounts while hydrating (Safari R1: root reconcile dropped [data-app-root]) ShellScreens.tsx:110-113.
  • The host's UpdateGate still refuses app.load under FORCE ShellScreens.tsx:206-208.
Player switch: createPlayer + web Shaka pathcreatePlayer is the single engine switch:
What

createPlayer is the single engine switch: __PHONE__ or a kwry host -> the native player island (createHostPlayer), otherwise createWebPlayer (Shaka 4.12.4, or Safari native HLS/FairPlay); createPlayerEngine wraps it as the VmPorts PlayerEngine.

Why this way

createPlayer.ts: "The one player switch ... Inside a kwry host ... every player, main and trailer, is the native player island's ... a host without the island, or an island failure, ends in a typed error, never Shaka / EME" createPlayer.ts:1329-1337. DEEP-DIVE: "there is no native-to-web fallback; a host without the island shows an error" DEEP-DIVE.md:1055. AGENTS.md requires one implementation: "one TrailerPlayer, one Player, one createPlayer" for web and TV (AGENTS.md:209). On TV, Shaka loads by script tag because inlining would put "~600 KB into app.js and its boot eval" createPlayer.ts:170-173.

Alternatives considered
OptionWhy not
Fall back to Shaka/EME inside a hostBy design a missing island is an error ("please update the app"); loadShaka rejects inside a host as a backstop (createPlayer.ts:197-199)
Fake <video> override via Vite swap (old ATV path)Two state machines must agree, behaviour hidden from shared tests, untyped calls (zipline-bridge-and-player-mvi.md:34-49)
Warm Shaka on Safari/WebKitThey play via native HLS and never construct Shaka, so the ~240 KB chunk cannot improve first frame (createPlayer.ts:152-155)
In the code
/**
 * The one player switch (plan §16.9). Inside a kwry host (phone, Android TV,
 * iOS) every player, main and trailer, is the native player island's
 * (./native/native-main.ts). There is no web playback there: a host without
 * the island, or an island failure, ends in a typed error, never Shaka / EME.
 * Plain browsers and the TV web apps (no kwry host) keep the web player
 * (Shaka, or Safari native HLS). `__KWRY__` is false only in builds that never
 * run in a kwry host (LG / Tizen, apps/tv), keeping the bridge out of them.
 */
export function createPlayer(video: HTMLVideoElement, options: CreatePlayerOptions): PlayerHandle {
  if (__PHONE__) return createHostPlayer(video, options)
  if (__KWRY__ && hasKwryHost()) return createHostPlayer(video, options)
  return createWebPlayer(video, options)
}
Talks to
packages/player/src/native/native-main.tsshaka-player 4.12.4@hoichoi/shell-kwry hostIslandpackages/core/vm/player.ts via PlayerEnginepackages/tv-kit video/engine.ts
Gotchas
  • AGENTS.md still documents shaka-player "^4.11.11" with lockfile 4.16.30 (AGENTS.md:520), but package.json:42 pins exactly 4.12.4 (matching DEEP-DIVE.md:1034.
  • "Native player unavailable" is almost always a page/app contract mismatch, not a player bug DEEP-DIVE.md:252.
  • Never reuse main-title Shaka instances; one Shaka instance per role DEEP-DIVE.md:1210; AGENTS.md:166).
Native player bridge: native-main.ts + core/player open/license/sessionInside a kwry host, native-main.ts builds a core PlayerSession over the dumb player island:
What

Inside a kwry host, native-main.ts builds a core PlayerSession over the dumb player island: core/player/open.ts decides the Open (one rendition, DRM level, FairPlay inputs, captions), license.ts runs the licence protocol in JS, and session.ts turns the island's LATEST snapshots and LOSSLESS effects into session state.

Why this way

native-main.ts: "a @hoichoi/core/player PlayerSession over the player island (HOI-4120); JS owns the policy (HOI-4138)" native-main.ts:1-2. license.ts: "the licence protocol, OTA-updatable ... Native never sees a URL, a token or the platform= parameter" license.ts:1-4. session.ts: "JS owns everything with a name (licence protocol, analytics, heartbeat, windows)" session.ts:20-22. Native is used for "Secure playback: Widevine L1 on Android and FairPlay on iOS ... not the web view" and production parity DEEP-DIVE.md:783-788; H10 "Engines are dumb" HOST-RULES.md:84-87.

Alternatives considered
OptionWhy not
Fake <video> element over Media3 (old ATV)Two state machines, untyped calls, a fake per shell; replaced by a session store (zipline-bridge-and-player-mvi.md:34-53)
Request the WIDEVINE_L1 licence platformServer then demands hardware security for audio keys and audio decryption fails (license.ts:36-38)
Native chrome for player controlsTarget is web chrome; native only where spike M4 fails (zipline-bridge-and-player-mvi.md:172)
In the code
/** One licence exchange: challenge (base64) in, licence (base64) out. A 401/403 refreshes the credentials once. */
export async function requestLicense(deps: LicenseDeps, url: string, challengeB64: string): Promise<string> {
  const post = async (force: boolean) => deps.post(url, headersFor(await deps.credentials(force)), challengeB64)
  let res = await post(false)
  if (refused(res.status)) res = await post(true)
  // The entitlement licence answers `{data: base64}` (createPlayer.ts registerResponseFilter) or raw bytes.
  if (res.text.trim().startsWith('{')) {
    const parsed = JSON.parse(res.text) as { data?: unknown; message?: unknown }
    if (typeof parsed.data === 'string' && parsed.data) return parsed.data
    throw new Error(typeof parsed.message === 'string' ? parsed.message : 'Licence denied (' + res.status + ')')
  }
  if (res.status < 200 || res.status > 299) throw new Error('Licence request failed (' + res.status + ')')
  return res.bodyB64
}
Talks to
player island (kwry, Media3 / AVPlayer)packages/core/decisions/playback.ts (drmLevel, sessionPolicy)entitlement licence APIpackages/player/src/analyticscast-sender, downloads (is-downloaded)
Gotchas
  • Never send a token inside the open request: a signed-in token exceeds its size limit DEEP-DIVE.md:1008.
  • Always compare the session number, or a late event from a stopped trailer can end the new player DEEP-DIVE.md:1010.
  • The CDN's FairPlay cert CORS allows hoichoi.tv only, so the phone build mirrors /fairplay.cer and sets VITE_FAIRPLAY_CERT_URL open.ts:14-21; deploy-mobile.yml:67-87.
Downloads decisions (core/decisions/downloads, download-entry)Pure functions decide the download CTA per movie/season, what a tap does (start/pause/resume/ignore), row metadata bounds, entitlement mapping, My…
What

Pure functions decide the download CTA per movie/season, what a tap does (start/pause/resume/ignore), row metadata bounds, entitlement mapping, My Downloads grouping/tabs/filters, limits and the headless service's notification copy; the native download engine just executes.

Why this way

download-entry.ts: decisions "moved from mweb/lib/download-{entry,states,action,entitlement} ... One copy for every kit" download-entry.ts:4-5. downloads.ts: "No DOM, no island: DownloadsVM ... feeds it the island's list + progress snapshots" downloads.ts:1-4, and DOWNLOADS_CONFIG equals the host's compiled floor "so a copy or deep-link change is a JS-only release" (:18-22). H0 keeps only the download engine native; "What to download, rendition list, limits, copy shown in the service notification (passed as params)" stay with the shell HOST-RULES.md:32.

Alternatives considered
OptionWhy not
Decisions in mweb lib modulesMoved into core so every kit shares one copy (download-entry.ts:4-5)
Notification copy compiled into nativeShell passes it via downloads.configure.v1; host floor only until first call (downloads.ts:18-33)
In the code
/**
 * What a tap does to titles that already have downloads. One title (prod downloadContent :1486-1510): downloading
 * pauses; queued / paused / failed resume; loading / completed / removing do nothing. A season (downloadSeason
 * :1416-1421): every episode downloading or queued pauses them all, every one paused or queued resumes them all.
 * Otherwise `start` the ones with no download (:1422).
 */
export function existingAction(states: readonly DownloadStatus[]): 'start' | 'pause' | 'resume' | 'ignore' {
  if (states.length === 1) {
    const s = states[0]
    if (s === 'none') return 'start'
    if (s === 'downloading') return 'pause'
    if (s === 'queued' || s === 'paused' || s === 'failed') return 'resume'
    return 'ignore'
  }
  if (every(states, 'downloading', 'queued')) return 'pause'
  if (every(states, 'paused', 'queued')) return 'resume'
  return 'start'
}
Talks to
Downloads port (host-ports-web.ts -> generated downloads bindings)packages/core/vm/downloads.ts, vm/download-entry.tsdownload engine islandtelemetry factDownload (analytics)
Gotchas
  • Newest list call wins: overlapping list calls resolve out of order (a season delete: 24 list calls, 217 ms to 4.5 s) downloads.ts:100-110.
  • A season emptied pops back once only; popping again would leave My Downloads too downloads.ts:87-98.
  • Row images are kept only if https and <= 512 chars (generated validator bounds) download-entry.ts:58-71.
Store billing decisions (store-billing.ts, ui/ports/store-purchase.ts)Native keeps only Play Billing / StoreKit 2 islands that return codes, offers and receipts;
What

Native keeps only Play Billing / StoreKit 2 islands that return codes, offers and receipts; core/decisions/store-billing.ts chooses the offer/promo and the copy, and ui/ports/store-purchase.ts (phone) picks the payment route per country and syncs receipts with the backend.

Why this way

store-billing.ts: "the page's decisions over the dumb billing / storekit islands ... which offer to buy and every message the viewer reads live here" store-billing.ts:1-5. payments.md: "Only the store-mandated rails stay in native code"; "Gate H5 forbids any other payment SDK in a host" and both islands "carry no copy and choose no offer" payments.md:5-9. store-purchase.ts: "The hosts never talk to the backend; nothing here logs a purchase token or a transaction id" store-purchase.ts:11. If a store forbids a gateway, "the page drops it in store-purchase.ts paymentRoute ... (no native change)" payments.md:41.

Alternatives considered
OptionWhy not
Juspay / SSLCommerz native SDK islandsRemoved in contract 2026-12-b; H5 allows only Play Billing and StoreKit, gateways run as web flows (payments.md:22-25)
In the code
/** The fields an offer decision needs (BillingOffer on the wire). */
export interface StoreOffer {
  offerToken: string
  tags: readonly string[]
  freeTrial: boolean
}

/**
 * prod BillingHelper.processNewPurchase: a free trial applicable -> the free-trial offer, else a non-trial offer; either
 * way Play's first offer as the fallback. null = the product has no offer (the page fails the purchase).
 */
export function chooseOffer<T extends StoreOffer>(offers: readonly T[], freeTrial: boolean): T | null {
  return (freeTrial ? offers.find((o) => o.freeTrial) : offers.find((o) => !o.freeTrial)) ?? offers[0] ?? null
}
Talks to
billing / storekit islands via kwryClientbackend /plan/subscribe/iap and /subscription/restorepackages/ui/pages/plans.tsxapps/androidtv/web/src/iappackages/i18n plans.billing*/store* keys
Gotchas
  • Store-policy question (user choice billing, iOS BD external link) is OWNER-VERIFY; code assumes web flows are allowed where prod offers them payments.md:27-41.
  • Purchase outcomes can reach the next page load, possibly for another account; the page filters by account id ARCHITECTURE.md:282.
  • payments.md names packages/player/src/native/store-purchase.ts as the phone consumer payments.md:13, but the file is packages/ui/ports/store-purchase.ts at this commit.
Host telemetry + analytics (startHostTelemetry, nameHostFact, apm/PostHog/SigNoz)Phone hosts emit raw facts (device, install referrer, push data, download transitions, warn+ log lines) on one lossless telemetry.events.v2…
What

Phone hosts emit raw facts (device, install referrer, push data, download transitions, warn+ log lines) on one lossless telemetry.events.v2 observation; startHostTelemetry subscribes after apm init, and nameHostFact turns facts into prod's PostHog/SigNoz/CleverTap events, with player.* bridge calls exported as host spans.

Why this way

host-telemetry.ts (player): what only the host sees "arrives as raw facts on ONE lossless observation ... the page names them and sends prod's PostHog / SigNoz events (owner 2026-10-25: the web layer sends all logging and analytics)" host-telemetry.ts:1-4. analytics/host-telemetry.ts: utm/organic and wzrk id rules "moved here from the host" host-telemetry.ts:1-4. H0/H1 put "all analytics naming" in the shell HOST-RULES.md:16. AppRoot defers telemetry until first interaction because tracer/posthog/otel chunks downloading before LCP were "charged ... to the LCP graph" AppRoot.tsx:303-306.

Alternatives considered
OptionWhy not
Host names and sends analytics (host bridgeSpan, TRACED_INFO_*, host prefs for App_Updated)Moved to the page under NS-8 / HOI-4132 (host-telemetry.ts:193-197)
Start telemetry at load + idleOn fast pages idle came ~10 ms after load and chunks hit Lighthouse's LCP graph; gated on first interaction (AppRoot.tsx:303-306)
In the code
/** Which host lines leave the host (was the host's TRACED_INFO_*): warn+, and the first 8 info lines per event in a traced playback. */
export const TELEMETRY_POLICY: Omit<TelemetryPolicy, 'afterSeq'> = { minLevel: 'warn', tracedInfoAreas: ['player.', 'cast.', 'download'], perEventInfo: 8 }

/**
 * Subscribes to telemetry.events.v2 for the document's life (reopened from its cursor after a background suspension); a
 * no-op where the host has no `telemetry` island (Android TV, browsers). Never throws; returns the stop function.
 */
export async function startHostTelemetry(sink: HostTelemetrySink, policy = TELEMETRY_POLICY): Promise<() => void> {
  const island = await hostIsland('telemetry').catch(() => null)
  if (!island) return () => undefined
  onKwrySpan(sink.span?.bind(sink))
  const sub = await keepOpen((afterSeq) => telemetryFacts(island, { ...policy, afterSeq }, (f) => safe(() => sink.fact(f)))).catch(() => null)
  return () => {
    onKwrySpan(undefined)
    sub?.close()
  }
}
Talks to
kwry telemetry island (telemetry.events.v2, telemetry.log.v2)packages/analytics (apm/OTel -> SigNoz, PostHog, CleverTap)packages/ui/AppRoot.tsxQoE beacons (/qoss)
Gotchas
Tab deck / mweb page owner modelOn phone hosts (VITE_TAB_DECK=1) each kept tab page lives in its own host box beside <main>, shown by inline-style writes on pointerup with the…
What

On phone hosts (VITE_TAB_DECK=1) each kept tab page lives in its own host box beside <main>, shown by inline-style writes on pointerup with the router a frame later; tab-deck.ts is the single owner of the visible page (pageLayer resolver, coverPage, onDeckPark).

Why this way

Measured speed: the deck's switch is "1-4 ms and touch -> presented p50 72 ms (min 40), against 112-160 ms for the router switch" tab-deck.ts:12-16. The design doc names the defect class: "two sources of truth about the visible page" and "Patching each intersection does not converge ... The fix is ownership" DESIGN-tab-deck-page-owner.md:12-20. Principle 1: "A single module, the page owner, answers 'which element is the page on screen'" (:24-25); covers use translateY(100vh) because it "freed 85-100 MB compositor-only" (:59-63). Web and TV are unchanged: "__PHONE__ false compiles the owner out" (:42-43).

Alternatives considered
OptionWhy not
Drop the deck or patch its edgesOwner decision 2026-10-31: keep it and make it the real owner (DESIGN-tab-deck-page-owner.md:3-4)
A separate page-owner module / custom routertab-deck.ts already owns hosts, shown tab, scroll; router untouched (DESIGN-tab-deck-page-owner.md:47-50,71)
opacity:0 / visibility:hidden to hide covered pagesopacity freed nothing; visibility restyles every descendant (DESIGN-tab-deck-page-owner.md:61-63)
Adopt the hydrated Home DOM into the deckRe-parenting a hydrating Solid tree shifts hydration ids (DESIGN-tab-deck-page-owner.md:71-74)
In the code
/*
 * Phone hosts, VITE_TAB_DECK=1 (experiment): every kept tab page lives in its own host box beside <main> and is never
 * taken off the document, so it stays styled, laid out, painted and rastered while another tab is on screen. A bottom
 * bar tap shows a tab already in the deck on its pointerup, in one task that writes inline styles only, and the router
 * follows after that frame (installTabDeck's [navigate]); the route's keeper then finds the page here and leaves it.
 *
 * Measured on a Realme 8 Pro (60 Hz, WebView 156) with a cloned Home/Search deck (scripts/measure/android-smoothness
 * deck-floor.mjs + bench.mjs): the switch's own main-thread work is 1-4 ms and touch -> presented p50 72 ms (min 40),
 * against 112-160 ms for the router switch. Only z-index/position/height change here: pointer-events, inert or
 * visibility are inherited and restyle every descendant (22-78 ms on ~1,000 nodes), and a class or a deck attribute
 * matched by a descendant selector restyles the whole subtree too (13-72 ms).
 */
export const tabDeckEnabled = __PHONE__ && import.meta.env.VITE_TAB_DECK === '1'
Talks to
packages/ui/lib/kept-tab.ts registry seamscroll-keep.tsdetails motion (shared-detail-motion)ArtistRoute / WatchRoute coversSolid Router
Gotchas
  • Never toggle attributes (aria-hidden) on hosts: Blink invalidates by attribute name, costing 20-24 ms in the tap tab-deck.ts:879-881.
  • pointer-events/inert/visibility are inherited and restyle every descendant (22-78 ms on ~1,000 nodes); only z-index/position/height change tab-deck.ts:14-16.
  • The clips host is never moved: its clip draws through it DESIGN-tab-deck-page-owner.md:63.
CI + deploy (ci.yml gates H/A, deploy-web, deploy-mobile, budgets)ci.yml runs typecheck/lint/test plus core-under-Hermes, TV/web/TV-kit bundle builds with purity, Cr53 compat and perf-budgets.json size gates, Gate H…
What

ci.yml runs typecheck/lint/test plus core-under-Hermes, TV/web/TV-kit bundle builds with purity, Cr53 compat and perf-budgets.json size gates, Gate H host purity ratchets, an informational Gate A, a separate phone budget job and Android/iOS host builds; deploy-web.yml ships hoichoi-web and deploy-mobile.yml ships hoichoi-mobile plus the OTA shell, then probes it.

Why this way

Gate H: "CI runs pnpm check:host:purity. A violation fails the build" HOST-RULES.md:4-5, a ratchet that "may only go down" ci.yml:122. Gate A is "Informational until the programme is done (HOI-4113); then drop continue-on-error so it blocks" ci.yml:137-141. Budgets: "A change that improves the UI but drops the Lighthouse or PageSpeed score is a regression and does not ship" and "perf-budgets.json is the gate" (AGENTS.md:526, :543). The phone budget is "its own job so a phone regression fails CI without touching the shared bundles job" ci.yml:152-154. deploy-mobile publishes the shell "so a shell change reaches installed apps with no store build" deploy-mobile.yml:3-5.

Alternatives considered
OptionWhy not
bundle-size.yml alone as the perf guard"it is a proxy, not a substitute — passing it does not mean the score held" (AGENTS.md:541)
gzip CLI for budget measurementApple/GNU gzip and zlib differ by more than the 512 B tolerance across machines; Node zlib gives the same number on Mac and Ubuntu (check-budgets.mjs:7-10)
Phone budget built without .env~1.9 KB gz smaller, which would hide a regression of that size (ci.yml:152-154)
In the code
      # HOI-4125: UI reaches the host through ports only (tools/eslint/host-boundary-allow.json may only shrink).
      - name: Host boundary ratchet
        run: pnpm check:host-boundary

      # Gate A (docs/platform/ACCEPTANCE.md): every KWRY-ARCH acceptance criterion as a number from the code.
      # Informational until the programme is done (HOI-4113); then drop continue-on-error so it blocks.
      - name: KWRY-ARCH acceptance (Gate A)
        id: arch
        continue-on-error: true
        run: |
          node scripts/check-arch-acceptance.mjs --json > arch-acceptance.json || true   # report first, so the artifact exists on failure
          pnpm -s check:arch
Talks to
Cloudflare Workers (wrangler deploy)kwry private submodule (KWRY_TOKEN)scripts/check-*.mjs gatesperf-budgets.jsonpr-preview.yml (Lighthouse, goldens)
Gotchas
  • Raising a budget is an owner decision with before/after numbers in the PR body (AGENTS.md:545; perf-budgets.json phone.note).
  • No CI job runs the web-first contract check; contract mismatch cuts off older apps ARCHITECTURE.md:229, :280).
  • Golden pixel breaches are report-only until the Linux re-take (AGENTS.md:543).