Hoichoi client platform · proposal

Port glue convention

How code that runs with or without the kwry bridge should be written: seven rules, three small helpers, before and after from a tested spike, and where else the same cleanup applies.

Proposal by Claude (agent) from Hoichoi.SharedClientPlatform 10d1bc325 and a local spike branchPublic · every page in this group shares one access rule

In one paragraph

The same view-model code runs in a browser, on a TV, and inside a phone app that answers calls over the kwry bridge. The layer that hides the difference is a port. Today most port code is the same three steps typed out by hand for every method, plus a second copy of every method only to delay loading. This page proposes seven rules and three small helpers that remove the repetition, shows the code before and after, and lists where else the same shapes appear. Sections 1 to 4 are tested on one port. Sections 5 and 6 are proposals.

31
Hand-written load-then-call forwarders
79 in 30 files
Host checks outside one place
3
Different rules for a failed host answer
41 of 41 pass
Port tests after the change

The problem

A port is an interface the view-model calls (packages/interfaces/ports/vm-ports.ts), with one implementation per environment in packages/ui/ports/. Inside a kwry host the implementation calls the generated bridge bindings. Each method does three things, and only the middle one differs: wait for the bindings, make one call, turn the host answer into what the caller gets.

Beforepackages/ui/ports/downloads.ts22 lines
const ok = <T>(r: Out<T>): T | null => {  if (r.ok) return r.value  if (r.unsupported) return null  throw r.error}export const downloads: Downloads = {  start: (a) => hostSolid().then((s) => start(s.downloads, a)),  list: (owner) => hostSolid().then((s) => s.downloads.list({ owner, limit: DOWNLOAD_LIMITS.maxItems })).then((r) => ok(r)?.items ?? []),  progress: () => hostSolid().then((s) => s.downloads.state()).then(mapped),  pause: (contentId, owner) => hostSolid().then((s) => s.downloads.pause({ contentId, owner })).then((r) => void ok(r)),  // [] keeps the stored rules; fresh keys replace them for the row's own manifest origin (the host knows it).  resume: (contentId, owner, fresh) => hostSolid().then(async (s) => {    const headers = keyHeaders(fresh)    const row = Object.keys(headers).length ? (ok(await s.downloads.list({ owner, limit: DOWNLOAD_LIMITS.maxItems }))?.items ?? []).find((i) => i.contentId === contentId) : undefined    return s.downloads.resume({ contentId, owner, headerRules: row ? headerRulesOf(row.manifestUrl, headers) : [] })  }).then((r) => void ok(r)),  // Prod keeps the offline licence on remove (DownloadTracker); NS-1 makes that the page's choice.  remove: (contentId, owner) => hostSolid().then((s) => s.downloads.remove({ contentId, owner, releaseLicence: false })).then((r) => void ok(r)),  removeAll: () => hostSolid().then((s) => s.downloads.removeAll({})).then((r) => void ok(r)),  settings: () => hostSolid().then((s) => s.downloads.settings({})).then((r) => ok(r)),  setWifiOnly: (wifiOnly) => hostSolid().then((s) => s.downloads.setSettings({ wifiOnly })).then((r) => void ok(r)),}
Afterthe same port, with the helpers18 lines
const listed = hostCall((s, owner: string) => s.downloads.list({ owner, limit: DOWNLOAD_LIMITS.maxItems }))export const downloads: Downloads = {  start: (a) => hostSolid().then((s) => start(s.downloads, a)),  list: (owner) => listed(owner).then((r) => r?.items ?? []),  progress: () => hostSolid().then((s) => s.downloads.state()).then(mapped),  pause: hostDo((s, contentId, owner) => s.downloads.pause({ contentId, owner })),  // [] keeps the stored rules; fresh keys replace them for the row's own manifest origin (the host knows it).  resume: hostDo(async (s, contentId, owner, fresh) => {    const headers = keyHeaders(fresh)    const row = Object.keys(headers).length ? (await listed(owner))?.items.find((i) => i.contentId === contentId) : undefined    return s.downloads.resume({ contentId, owner, headerRules: row ? headerRulesOf(row.manifestUrl, headers) : [] })  }),  // Prod keeps the offline licence on remove (DownloadTracker); NS-1 makes that the page's choice.  remove: hostDo((s, contentId, owner) => s.downloads.remove({ contentId, owner, releaseLicence: false })),  removeAll: hostDo((s) => s.downloads.removeAll({})),  settings: hostCall((s) => s.downloads.settings({})),  setWifiOnly: hostDo((s, wifiOnly) => s.downloads.setSettings({ wifiOnly })),}
Seven of the nine methods were the three-step chain. After: each line is the port method and the one host call it makes, with the page's own choices (releaseLicence: false). Argument types come from the Downloads interface, so nothing is cast and nothing is typed twice. Tested: the 8 wire-level tests pass on both sides.

A second file then repeated every method again, only so the first file loads on first use and browsers never download it:

Beforepackages/ui/ports/host-ports-web.ts12 lines
const dl = (): Promise<Downloads> => import('./downloads.ts').then((m) => m.downloads)const downloads: Downloads = {  start: (a) => dl().then((d) => d.start(a)),  list: (userId) => dl().then((d) => d.list(userId)),  progress: () => dl().then((d) => d.progress()),  pause: (id, userId) => dl().then((d) => d.pause(id, userId)),  resume: (id, userId, fresh) => dl().then((d) => d.resume(id, userId, fresh)),  remove: (id, userId) => dl().then((d) => d.remove(id, userId)),  removeAll: () => dl().then((d) => d.removeAll()),  settings: () => dl().then((d) => d.settings()),  setWifiOnly: (wifiOnly) => dl().then((d) => d.setWifiOnly(wifiOnly)),}
Afterone helper, one line per port6 lines
function lazyPort<P extends object>(load: () => Promise<P>): P {  return new Proxy({} as P, {    get: (_, method) => (...args: unknown[]) => load().then((port) => (port[method as keyof P] as (...a: unknown[]) => unknown)(...args)),  })}const downloads = lazyPort<Downloads>(() => import('./downloads.ts').then((m) => m.downloads))
Adding a method to Downloads no longer needs an edit here. Tested: the 8 wire-level tests pass on both sides.

How much of it there is

Counted on the PR #516 branch at 10d1bc325, excluding tests and generated code.

WhatCountWhere
Port methods in downloads written as the three-step chain7 of 9packages/ui/ports/downloads.ts
Hand-written "load the module, then call the same method" forwarders31packages/ui/ports/host-ports-web.ts: 9 downloads, 15 hostShell, 7 cast, back and deepLinks
Direct bindings calls outside a port file14packages/player/src/host.ts (8 are one line each)
hasKwryHost() checks79 in 30 files36 in packages/player, 24 in packages/ui, 14 in packages/mweb
Copies of "subscribe after the module loads, allow cancel before"3cast.watch, back.claim, later in host-ports-web.ts

Three rules for one question

The larger risk is not the line count. It is that "what does a failed host answer become" has three different answers, and a reader cannot tell from a call site which one applies.

HelperHost has no such operationHost returned an error
ok in downloads.tsnullrejects with the typed error
value in packages/player/src/host.tsnullnull (the error is dropped)
started in downloads.tsrejects UNSUPPORTEDrejects with the typed error

The convention

Seven rules. The first three are already how the code is organised. The last four are new.

#RuleStatus today
1View-models use port interfaces only. No bridge import and no hasKwryHost() in a view-model or a view.Gate rule H3.3 in docs/platform/HOST-RULES.md, with 37 allowed exceptions
2A capability some environments lack is an optional port. The caller writes ports.downloads?.pause(...). One function, hostPorts(), decides which ports exist.VmPorts has 10 required and 9 optional ports
3One file per port, named after it, in packages/ui/ports/. Decisions that belong to the page (which rendition, which headers, keep or release a licence) live in that file.In place
4A port method has one of three shapes: hostCall, hostDo, or a named function. See the table below.New
5One answer rule, valueOf: the value on success, null when the host lacks the operation, reject with the typed error otherwise. A method that needs another rule is a named function and says so in its comment.New
6Deferred loading is lazyPort, never a hand-written forwarder.New
7Every port method has one wire-level test: which wire it sends, with exactly which params, and what each outcome becomes for the caller.New
ShapeUse whenCaller gets
hostCall(op)exactly one host call that returns a valuethe value, or null if the host lacks it
hostDo(op)exactly one host call that returns nothingnothing; also resolves when the host lacks it
a named functionanything with a decision around the callwhatever it declares

The helpers

All of the shared code, in packages/shell-kwry/src/ports/host-solid.ts (the file exists at that commit; these three functions are added by the spike):

export function valueOf<R, C extends string, D>(r: Outcome<R, C, D>): R | null {
  if (r.ok) return r.value
  if (r.unsupported) return null
  throw r.error
}

export function hostCall<A extends unknown[], R, C extends string, D>(
  op: (s: HostSolid, ...args: A) => Promise<Outcome<R, C, D>>,
): (...args: A) => Promise<R | null> {
  return (...args) => hostSolid().then((s) => op(s, ...args)).then(valueOf)
}

export function hostDo<A extends unknown[], C extends string, D>(
  op: (s: HostSolid, ...args: A) => Promise<Outcome<unknown, C, D>>,
): (...args: A) => Promise<void> {
  return (...args) => hostSolid().then((s) => op(s, ...args)).then((r) => void valueOf(r))
}

The test shape

Written first, against the generated fake host, so they pass on the old code and on the new code. That is what shows the refactor changed no behaviour.

it('each sends its one wire with exactly these params and resolves as the port promises', async () => {
  const { seen, downloads } = await connect()
  await expect(downloads.pause('c1', 'u1')).resolves.toBeUndefined()
  await expect(downloads.remove('c1', 'u1')).resolves.toBeUndefined()
  expect(seen).toEqual([
    { wire: 'downloads.pause.v1', params: { contentId: 'c1', owner: 'u1' } },
    // The page's choice: the offline licence is kept on remove.
    { wire: 'downloads.remove.v1', params: { contentId: 'c1', owner: 'u1', releaseLicence: false } },
  ])
})

What was verified

On a local branch, spike/HOI-4144-port-binder, two commits on top of 10d1bc325: tests first, then the refactor. The branch is not pushed, so it has no link yet.

CheckResult
Port tests in packages/ui/ports41 of 41 pass
New wire-level tests8 of 8 pass, on the old code and on the new code
TypeScript on packages/ui and packages/shell-kwryclean
ESLint, host-purity gate, Chromium 53 source gatepass
A wrong argument type or method signature in a port linefails to compile
Size of the change5 files, +188 −30; 129 of the added lines are the new test file

Not verified

No run on a device. Nothing in the change touches the wire format, and the fake host validates each call against the contract.

Is Proxy safe on TV?

lazyPort uses Proxy. That is safe on every TV the project supports. AGENTS.md on main sets the floor at Chromium 53 (LG webOS 4.x), drops Tizen 4.0 because it has no Proxy, and allows Solid stores for that reason. The TV bundle built from main at bd8a522db already contains 7 new Proxy( sites; 4 are unconditional (Solid store and the router) and run at boot. The port file is also outside the TV build: the host check compiles to false there.

Where else the same pattern applies

The target

Code above the port line reads as if there is only one environment: no host check, no waiting for bindings, no unwrapping of answers, in a view-model, a view or packages/core. packages/core already meets this (it has no bridge import and no host check). The work is in packages/player, packages/ui and packages/mweb. Every "after" in this section is a proposal.

Host functions that views call directly

packages/player/src/host.ts exports 12 host functions, and 17 files outside ports and the player import them. The file has 23 host checks. The check has a real job here: it stops a browser from downloading the bridge code. So it belongs inside the helper, once.

Beforepackages/player/src/host.ts16 lines
export async function deviceCountryFromHost(): Promise<{ network: string; sim: string; locale: string } | null> {  if (!hasKwryHost()) return null  return (await solid()).device.country({}).then(value, () => null)}export async function hostLevels(p: { brightness?: number; volume?: number } = {}): Promise<{ brightness: number; volume: number } | null> {  if (!hasKwryHost()) return null  return (await solid()).device.setLevels(p).then(value, () => null)}export async function shareFromHost(params: { title: string; url: string }): Promise<boolean> {  if (!hasKwryHost()) return false  return (await solid()).device.share(params).then((r) => r.ok, () => false)}export async function clearHostHistory(): Promise<boolean> {  if (!hasKwryHost()) return false  return (await solid()).nav.clearHistory({}).then((r) => r.ok, () => false)}
Aftertwo helpers, then one line each10 lines
/** A host value, or null: no host, the host lacks the operation, or the call failed. */const hostValue = <A extends unknown[], R>(op: (s: HostSolid, ...a: A) => Promise<Outcome<R, string, unknown>>) =>  async (...a: A): Promise<R | null> => (hasKwryHost() ? op(await solid(), ...a).then((r) => (r.ok ? r.value : null), () => null) : null)/** True when the host did it. */const hostDid = <A extends unknown[]>(op: (s: HostSolid, ...a: A) => Promise<Outcome<unknown, string, unknown>>) =>  async (...a: A): Promise<boolean> => (hasKwryHost() ? op(await solid(), ...a).then((r) => r.ok, () => false) : false)export const deviceCountryFromHost = hostValue((s) => s.device.country({}))export const hostLevels = hostValue((s, p: { brightness?: number; volume?: number } = {}) => s.device.setLevels(p))export const shareFromHost = hostDid((s, p: { title: string; url: string }) => s.device.share(p))export const clearHostHistory = hostDid((s) => s.nav.clearHistory({}))
Covers 8 of the 12 functions. The answer rule differs from valueOf on purpose: these are "try the host, else fall back" calls, so an error becomes null. Naming the helper hostValue, not hostCall, keeps the two rules visibly apart. The other 4 functions have decisions around the call and stay written out. Proposed. The right side is not compiled or tested yet.

Views that ask "am I in a host?"

35 of the 79 host checks are in .tsx files. Heaviest: Player.tsx (6), plans.tsx (5), WatchRoute.tsx, LoginDialog.tsx and IosAccount.tsx (3 each).

Beforepackages/ui/routes/WatchRoute.tsx6 lines
onMount(() => {  if (hasKwryHost()) onCleanup(addWatchHostStyle())  if (hasKwryHost()) onCleanup(onWatchRoute())  if (hasKwryHost()) onCleanup(coverKeptTabs('player'))  setHydrated(true)})
Afterone port method that returns one cleanup4 lines
onMount(() => {  onCleanup(ports.hostShell?.enterWatch())  setHydrated(true)})
A host-only side effect moves behind one port method. In a browser the port is absent and nothing runs. Proposed. The right side is not compiled or tested yet.
Beforepackages/ui/auth/LoginDialog.tsx1 line
const [deviceCountry] = createResource(() => (isServer || !hasKwryHost() ? null : true), () => deviceCountryFromHost())
Afteran optional port method1 line
const [deviceCountry] = createResource(() => ports.device.country?.())
A capability becomes an optional method. packages/core/vm already reads optional ports this way (11 guards or ?. calls there). Proposed. The right side is not compiled or tested yet.

Subscribe once the module has loaded

Beforepackages/ui/ports/host-ports-web.ts13 lines
const back: Back = {  claim(handle) {    let off: (() => void) | undefined    let gone = false    void host().then((m) => {      if (!gone) off = m.claimHostBack(handle)    })    return () => {      gone = true      off?.()    }  },}
Afterthe block written once, then one line per use13 lines
/** A subscription on a module that loads on first use; the returned cancel works before and after the load. */function subscribeLater<M>(load: () => Promise<M>, subscribe: (m: M) => () => void): () => void {  let off: (() => void) | undefined  let gone = false  void load().then((m) => {    if (!gone) off = subscribe(m)  })  return () => {    gone = true    off?.()  }}const back: Back = { claim: (handle) => subscribeLater(host, (m) => m.claimHostBack(handle)) }
The same 9 lines appear three times today (cast.watch, back.claim, later). Proposed. The right side is not compiled or tested yet.

The rest

WhereWhat is thereFit
hostShell in host-ports-web.ts15 forwarders; 3 return a cleanup function or nothinglazyPort for the 12 promise methods, the 3 others written out. Needs a lazyPort form that takes the method names; decide when spiked
packages/ui/ports/host-shell.ts11 wires listed as strings, 5 called through a private call(wire, params)Generated members, then hostDo lines. The file records one bug from this: requestPermission got the default 10 s deadline and aborted with the iOS prompt still open
packages/player/src/native/cast-sender.ts7 direct bindings calls3 are one line: hostCall or hostDo
packages/player/src/native/is-downloaded.ts3 direct bindings callsEach has logic around the call; read before changing
packages/ui/ports/store-purchase.tsUses the raw client, not the bindingsOut of scope until it moves to the generated bindings

What should not change

Developer and agent experience

The same question from the other side: what does a person or an agent have to know, type or look up to add or change one bridge call? All items are proposals.

One test setup instead of 34

34 test files mock the bridge by hand: 50 vi.mock lines and 105 vi.resetModules() calls. The same two mock lines appear verbatim in 7 files.

Beforetop of a port test file today16 lines
let fake: Fake | null = nullvi.mock('@hoichoi/shell-kwry/detect', () => ({ hasKwryHost: () => true, isAppleHost: () => false }))vi.mock('@hoichoi/shell-kwry', () => ({ kwryClient: async () => fake?.client ?? null }))async function connect(methods?: string[]) {  vi.resetModules()  fake = await connectFake(methods ? { methods } : {})  const seen: Array<{ wire: Wire; params: unknown }> = []  const record = (wire: Wire, result: unknown) => fake!.fake.on(wire, ((params: unknown) => (seen.push({ wire, params }), result)) as never)  record('downloads.pause.v1', {})  record('downloads.settings.v1', SETTINGS)  const { downloads } = await import('./downloads.ts')  return { seen, downloads, record }}afterEach(() => {  fake = null})
Afterone test entry point, '@hoichoi/shell-kwry/testing'6 lines
const host = await fakeHost({ apple: false })host.answer('downloads.pause.v1', {})host.answer('downloads.settings.v1', SETTINGS)const { downloads } = await host.load(() => import('./downloads.ts'))await downloads.pause('c1', 'u1')expect(host.calls).toEqual([{ wire: 'downloads.pause.v1', params: { contentId: 'c1', owner: 'u1' } }])
host.calls is what every wire-level test needs and each file builds by hand. Vitest hoists vi.mock per file, so how the kit installs its mocks is unverified until spiked. Proposed. The right side is not compiled or tested yet.

Comments a newcomer can read

Beforepackages/ui/ports/downloads.ts2 lines
// NS-1 (plan H7/H8): the page's track choice (prod quality ceiling, the manifest's default languages) and repeat rule// (a failed row restarts, any other is kept: prod DownloadTracker).
Afterreason in plain words, ticket last2 lines
// The page, not the host, picks the tracks (quality ceiling, the manifest's default languages) and decides what a// repeat start does: a failed row restarts, any other is kept. Same as the production app. [HOI-4138]
Glue comments lean on internal codes: 8 in downloads.ts, 8 in player/src/host.ts, 5 in host-shell.ts. A reader without the plan documents cannot decode them. Proposed. The right side is not compiled or tested yet.

The rest, in priority order

#ItemWhat to buildSize
1Port helpers and lazyPortSections 1 to 5 of this page, one port per pull requestsmall each
2Test kit@hoichoi/shell-kwry/testing, above. Makes rule 7 cheap enough to followsmall
3One page for "add a bridge call"The steps exist inside docs/architecture/KWRY-DEEP-DIVE.md, a file of over 1,400 lines. Write a one-screen ADD-A-WIRE.md: contract method, generate, host island, one port line and its test, use from the view-model. Link it from AGENTS.mdtiny
4Running a host screen without a phone?shell=fake already runs a dev build against the generated fake host in a plain browser (packages/shell-kwry/src/dev-fake.ts). AGENTS.md does not mention it (0 matches). Document it: it is the cheapest way for an agent to drive downloads, the cast sheet or the store sheetstiny
5A committed navigation indexThe IDE plugin and the MCP tools read kwry-index.json (wire to Kotlin contract, TS member, host implementation). The app has none committed; the generator is not on kwry main yet. Land it and move the pinmedium, in kwry
6Generated code that explains itselfA generated member says only "the highest advertised version that can carry the request". Copy the contract's doc comment, error codes and deadline into it, so hover answers the questionmedium, in kwry
7Calls the tools cannot seeWires called by string, the raw client in store-purchase.ts, and islands held in a local before the call. Measured with the IDE plugin: Cmd+click to Kotlin resolved 128 of 149 call sitesmedium
8Feedback in the editorRule 1 runs as a script with a baseline. Add the same import ban as an ESLint no-restricted-imports rule for view-models and views; the root ESLint config has none todaysmall
9Fresh worktreegit worktree add leaves the kwry submodule empty, so generation fails until pnpm kwry:sync. Fall back to the committed generated code automatically and print one line saying sosmall

Suggested order

  1. Pull request 1: the wire-level test file only. No production change.
  2. Pull request 2: the three helpers, the downloads port, lazyPort.
  3. Add the seven rules to docs/platform/HOST-RULES.md, next to H3.3.
  4. Then one port per pull request, tests first each time: hostShell, player/src/host.ts, cast-sender, store-purchase.
  5. In parallel: the test kit, ADD-A-WIRE.md and the two AGENTS.md pointers.

Base branch for all of them: feat/SD/native-platform. Ticket: HOI-4144.