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.
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.
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)),}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 })),}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:
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)),}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))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.
| What | Count | Where |
|---|---|---|
Port methods in downloads written as the three-step chain | 7 of 9 | packages/ui/ports/downloads.ts |
| Hand-written "load the module, then call the same method" forwarders | 31 | packages/ui/ports/host-ports-web.ts: 9 downloads, 15 hostShell, 7 cast, back and deepLinks |
| Direct bindings calls outside a port file | 14 | packages/player/src/host.ts (8 are one line each) |
hasKwryHost() checks | 79 in 30 files | 36 in packages/player, 24 in packages/ui, 14 in packages/mweb |
| Copies of "subscribe after the module loads, allow cancel before" | 3 | cast.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.
| Helper | Host has no such operation | Host returned an error |
|---|---|---|
ok in downloads.ts | null | rejects with the typed error |
value in packages/player/src/host.ts | null | null (the error is dropped) |
started in downloads.ts | rejects UNSUPPORTED | rejects with the typed error |
The convention
Seven rules. The first three are already how the code is organised. The last four are new.
| # | Rule | Status today |
|---|---|---|
| 1 | View-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 |
| 2 | A 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 |
| 3 | One 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 |
| 4 | A port method has one of three shapes: hostCall, hostDo, or a named function. See the table below. | New |
| 5 | One 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 |
| 6 | Deferred loading is lazyPort, never a hand-written forwarder. | New |
| 7 | Every port method has one wire-level test: which wire it sends, with exactly which params, and what each outcome becomes for the caller. | New |
| Shape | Use when | Caller gets |
|---|---|---|
hostCall(op) | exactly one host call that returns a value | the value, or null if the host lacks it |
hostDo(op) | exactly one host call that returns nothing | nothing; also resolves when the host lacks it |
| a named function | anything with a decision around the call | whatever 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.
| Check | Result |
|---|---|
Port tests in packages/ui/ports | 41 of 41 pass |
| New wire-level tests | 8 of 8 pass, on the old code and on the new code |
TypeScript on packages/ui and packages/shell-kwry | clean |
| ESLint, host-purity gate, Chromium 53 source gate | pass |
| A wrong argument type or method signature in a port line | fails to compile |
| Size of the change | 5 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.
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)}/** 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({}))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).
onMount(() => { if (hasKwryHost()) onCleanup(addWatchHostStyle()) if (hasKwryHost()) onCleanup(onWatchRoute()) if (hasKwryHost()) onCleanup(coverKeptTabs('player')) setHydrated(true)})onMount(() => { onCleanup(ports.hostShell?.enterWatch()) setHydrated(true)})const [deviceCountry] = createResource(() => (isServer || !hasKwryHost() ? null : true), () => deviceCountryFromHost())const [deviceCountry] = createResource(() => ports.device.country?.())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
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?.() } },}/** 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)) }cast.watch, back.claim, later). Proposed. The right side is not compiled or tested yet.The rest
| Where | What is there | Fit |
|---|---|---|
hostShell in host-ports-web.ts | 15 forwarders; 3 return a cleanup function or nothing | lazyPort 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.ts | 11 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.ts | 7 direct bindings calls | 3 are one line: hostCall or hostDo |
packages/player/src/native/is-downloaded.ts | 3 direct bindings calls | Each has logic around the call; read before changing |
packages/ui/ports/store-purchase.ts | Uses the raw client, not the bindings | Out of scope until it moves to the generated bindings |
What should not change
- A method with real decisions stays a named function.
downloads.startis 40 lines of choices; a helper would hide them. hasKwryHost()inside port files and inhostPorts()is correct. That is the one place allowed to know.- No helper for a shape that appears once.
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.
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})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
// 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).// 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]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
| # | Item | What to build | Size |
|---|---|---|---|
| 1 | Port helpers and lazyPort | Sections 1 to 5 of this page, one port per pull request | small each |
| 2 | Test kit | @hoichoi/shell-kwry/testing, above. Makes rule 7 cheap enough to follow | small |
| 3 | One 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.md | tiny |
| 4 | Running 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 sheets | tiny |
| 5 | A committed navigation index | The 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 pin | medium, in kwry |
| 6 | Generated code that explains itself | A 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 question | medium, in kwry |
| 7 | Calls the tools cannot see | Wires 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 sites | medium |
| 8 | Feedback in the editor | Rule 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 today | small |
| 9 | Fresh worktree | git 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 so | small |
Suggested order
- Pull request 1: the wire-level test file only. No production change.
- Pull request 2: the three helpers, the
downloadsport,lazyPort. - Add the seven rules to
docs/platform/HOST-RULES.md, next to H3.3. - Then one port per pull request, tests first each time:
hostShell,player/src/host.ts,cast-sender,store-purchase. - In parallel: the test kit,
ADD-A-WIRE.mdand the twoAGENTS.mdpointers.
Base branch for all of them: feat/SD/native-platform. Ticket: HOI-4144.