# Handy SDK demo

A mock partner video site ("Flickbox") with a working demo of the simpler Handy SDK: a partner adds one script tag with their app ID, adds an "Interactive" page to their nav with a Handy banner on top and their scripted videos under it, and puts a small pill on each video. That is the whole integration. Linking with the phone (a QR code), the feed of scripted videos, the connect modal, the clock sync and the video sync all run against a mock of the Handy servers and one mock Handy, so it works with no device or backend.

Made 2026-12-02. A **temporary** Playground project since 2026-12-04, served as it is (plain static files, no build) at `https://playground.handyfeeling.com/handy-sdk-demo/`; `server.js` has its route. Its front page has a short note on what was decided. Remove the folder, its two lines in `server.js` and its row in `public/index.html` when it has done its job.

```bash
cd projects/handy-sdk-demo
npm start            # node serve.mjs, http://localhost:5310/ (no dependencies)
```

The round **DEMO** button in the bottom-right corner opens the demo options: versions and partner options to compare, every visitor state, the script tag for the chosen options, and the count of calls to the (mock) Handy servers. It floats over the page and is not part of the SDK. Any connection key of five or more letters and digits connects; a key with `offline` in it never comes online, to show the warning.

## Contents

1. [The integration](#the-integration)
2. [Partner options](#partner-options)
3. [Staying out of the way](#staying-out-of-the-way)
4. [The demo options panel](#the-demo-options-panel)
5. [The flow](#the-flow) (what the logic has to do, step by step)
6. [Request budget](#request-budget)
7. [What is stored](#what-is-stored)
8. [Where it comes from in the Handyverse app](#where-it-comes-from-in-the-handyverse-app)
9. [Files](#files)
10. [Kit changes wanted](#kit-changes-wanted)
11. [Open questions](#open-questions)

## The integration

```html
<script type="module" src="https://…/handy-sdk.js" data-app-id="demo-partner" data-site-name="Flickbox" data-theme="dark"></script>

<a href="interactive.html">Interactive</a>                        <!-- the partner's own nav link -->
<handy-banner></handy-banner>                                     <!-- top of that page, where the partner's hero goes -->
<video id="player" src="…"></video>
<handy-video-tab video-id="v-neon" for="player"></handy-video-tab> <!-- in the player's box (position: relative): the pill on the video -->
<handy-badge video-id="v-neon"></handy-badge>                      <!-- on a thumbnail -->
```

- The Interactive page is the partner's own page: their nav, their grid, their cards. The SDK gives it the banner and the list: `await HandySDK.scriptedVideos()` returns the feed's videos (`[{ id, script, scriptId }]`), and the page shows those of its videos (`site/site.js`, `interactive()`). The feed is the cached CDN file, so the page costs the Handy servers nothing.
- `data-app-id` is the only required setting. `video-id` is the partner's own ID for the video, the same one the feed uses.
- The look can be tuned per partner with a few more attributes ([Partner options](#partner-options)). `data-feed-url` and `data-kit-base` override where the feed and the kit load from.
- Everything the SDK draws is in shadow roots, styled by the Handy kit (brand-ux's vanilla edition, `vendor/handy-kit/`, v1.16.0 copied from the playground). The partner's CSS can't reach in and the kit can't reach out, so the button, modal and tab look the same on every site.
- `window.HandySDK` exposes the parts (`session`, `clock`, `feed`, `openPanel()`) for a partner who wants their own UI.

## Partner options

A little room to fit each partner, inside one style guide: the components, colours and type are always the Handy kit's. Each option is a `data-` attribute on the script tag, and every one can also change live with `HandySDK.configure({ … })`; each element redraws.

| Attribute | Values (default first) | What it changes |
| --- | --- | --- |
| `data-button-style` | `none` · `icon` · `label` | A Handy button in the header besides the Interactive link (`<handy-button>`; the demo pages leave it out): none; the round "h" icon; or the first draft's pill with the "h", a word and the dot |
| `data-tab-style` | `overlay` · `bar` | On a scripted video: a small pill hovering over its top-left corner that opens the modal, or the first draft's card bar under it with a script chip, the status and a Connect button |
| `data-tab-audience` | `all` · `users` | Who sees that line: everyone, or only visitors who have signed in or used a key on this site |
| `data-badges` | `users` · `all` · `none` | Who sees the "h" on thumbnails |
| `data-script-kinds` | `show` · `hide` | Say "AI script" and "Human script" (in the opened line and the badge's tooltip), or not (Learn then explains scripts without the two kinds) |
| `data-theme` | `auto` · `dark` · `light` | The Handy parts' theme; `auto` follows the system |

Three versions bundle them, to compare (the demo panel's Version row): **Quiet** (the defaults: the Interactive page, no header button), **Minimal** (no badges, no talk of AI), and **First draft** (bar, badges for everyone). A partner can take a version or mix their own.

## The demo options panel

`site/demo-options.js`: a round button with a DEMO tag, fixed in the bottom-right corner, opening a card over the page. Demo only; a partner never ships it.

- **Version** and **Partner options**: every option above, applied live. The version shows as Custom when the options match none.
- **Visitor**: New visitor, Handy user (signed in before, not connected), Connecting, Can't reach (the 10 s warning), Connected. Each goes through the real flow (forget, a remembered key, a key that never answers, a good key); only Can't reach skips the 10 s wait.
- **Partner's site**: the mock site's own look, dark or light, to see the Handy parts on both.
- **Script tag**: the tag for the chosen options, only the attributes that differ from the defaults, with Copy.
- **Handy servers**: the calls this page made, the clock estimate, and Reset visitor (clears what the SDK stored, keeps the options).

The choices are kept in `handy-sdk-demo:options` and applied before the SDK's elements draw, so a reload shows no flash of the defaults.

## Staying out of the way

Handy owners are a small part of a partner's visitors, so for everyone else the SDK is close to invisible (the owner, 2026-12-02: "much less intrusive"). This table is the default, Quiet version; [Partner options](#partner-options) can make it quieter or louder:

| Where | A visitor who never used The Handy here | A Handy user (signed in or a key, on this site) |
| --- | --- | --- |
| Header | the partner's own "Interactive" link among their nav tabs; no Handy branding | the same |
| The Interactive page | a placeholder Handy banner (to become a banner with a video that explains the product), then the partner's grid of scripted videos | the same |
| Thumbnails | nothing | a 24 px "h" in the corner of videos with a script; the kind of script is its tooltip |
| On a scripted video | a small pill over the video's top-left corner, 11 px on a dark glass: The Handy's mark and "This video can move with The Handy". It fades out while the video plays, like the player's own controls, and comes back on a mouse move or a pause. A press opens the modal | connected: just the dot and the state ("Connected", "Playing in sync"); remembered: just the words; connecting: the words, then the state |
| A video with no script | nothing | connected: a pill "No script for this video yet · Request it"; a press sends `scripts/request` (once per video, remembered) and it reads "Requested" |
| Opened (a press on the pill) | the modal: a QR code to scan with the phone, a connection key, What is The Handy? | the modal's controls: Sync offset, Stroke zone, Resync, Disconnect |

Outside the Interactive page, no primary-coloured buttons, cards or Handy copy show until someone presses the pill. The partner's page copy never needs to mention The Handy.

## The flow

The phases are the Handyverse app's device panel's (connected, connecting, offline), with one added: **remembered**, a phone link or key kept from an earlier visit that has not been checked on this page load. That phase is what lets a page load cost the Handy servers nothing.

```
idle ──QR scan / key──▶ connecting ──device answers──▶ connected
  ▲                         │  ▲                           │
  │                    10 s: warning                  Disconnect
  │                         │  │                           ▼
  └──── Forget ◀──── remembered ◀──── Stop waiting ────────┘
                      (page load with a stored link starts here)  
```

### 1. Page load: no Handy servers for new visitors

1. Read the config from the script tag (`data-app-id`, theme, site name).
2. Read localStorage: the session (phone link or key), the clock estimate, the feed cache. Nothing is verified.
3. Phase is **remembered** if a session is stored, else **idle**. Either way the header shows only the partner's "Interactive" link; badges show for remembered visitors.
4. Load the feed (step 2). This is the only request a page load makes, and it goes to a CDN, not the API.
5. Define the elements and load the kit. The kit's CSS is fetched once and rewritten for the shadow roots (`sdk/ui/kit.js`).
6. **Remembered: connect by itself** (the owner, 2026-12-03). With a phone link or key stored, the SDK connects once the page is idle (`requestIdleCallback`), as if Connect had been pressed. This is the one exception to "no Handy servers on load", and only for visitors who already use The Handy here.

Nothing polls. Nothing opens a socket. A visitor who never touches The Handy never reaches the Handy servers.

### 2. The feed: which videos have a script

- One static JSON per app ID: `{ appId, videos: { <partner video id>: { script: "ai" | "human", scriptId } } }` (`sdk/mock/feeds/demo-partner.json`).
- Kept in localStorage for 6 hours, then revalidated with its ETag (a 304 costs nothing). A stale copy is used if the CDN fails.
- It names a script; it never holds one. The script (a script token) is fetched only after someone connects (step 6).
- It drives the badge on thumbnails ("Human script" or "AI script" as its tooltip) and the pill on each video. A video with no script gets neither.

### 3. The button and the panel

- `<handy-banner>`: the top of the Interactive page. For now a placeholder; the real one is a banner with a video that explains the product.
- `<handy-button>` (optional, off by default): the round icon or the labelled pill, with the state dot; a warning icon once connecting has taken more than 10 seconds. A press only opens the panel.
- The panel (`<handy-panel>`) is one shared `<h-modal>`, a bottom sheet under 600 px. Its view follows the phase:

| View | Shows | Actions |
| --- | --- | --- |
| idle | a QR code, "Scan with your phone" (on a phone: **Open the Handyverse app** instead), or a connection key, a placeholder ad that explains The Handy, "Get 20% off today." | Simulate the scan (demo), Connect, Close |
| remembered | the key, "hasn't contacted the Handy servers yet on this visit" | Connect, Forget key, Close |
| connecting | "Reaching your Handy", the key, the clock sync's progress; after 10 s a warning in the same place: light purple, Wi-Fi, check the key, set it up in the Handy app | Stop waiting |
| connected | firmware, key, timing (round trip rated as the app does, when the clock was synced); Sync offset; Stroke zone | Handyverse (a link), More (a menu: Advanced, Resync, Disconnect), Close |
| advanced | a page of its own in the modal, opened from More: a **Labs** subheader with a placeholder, room for more advanced features (Lars's to fill). The way back is an arrow before the title, as brand-ux's page bar has it (design.md 6.8) | ← (back) |
| learn | the basics for the curious: what The Handy is, how scripts follow a video, human vs AI scripts, what you need, sync offset and stroke zone, privacy, how to set one up | ← (back, before the title), Get The Handy |

### 4. Signing in

- **Scan with the phone** (the default; no sign-in form and no Handy account). When the idle view shows, the panel asks for a short-lived link code (`link/start`, 5 minutes) and draws it as a QR code (`sdk/ui/qr.js`, a small encoder with no dependencies, checked with OpenCV's reader). The phone's camera opens the Handyverse app on the link (it must be installed; the panel says so); the visitor picks their Handy there. Meanwhile one long poll (`link/wait`) waits for the phone's answer: a token for this app ID plus the device. Store them; go to connecting. The code is kept across reopenings while it is valid, and the wait stops when the panel closes. On a phone the panel shows **Open the Handyverse app** instead of the code. Mocked in `api.linkStart()`, `api.linkWait()` and `api.demoScan()`; see the open questions.
- **Connection key** (the fallback): the rules are the Handyverse app's `connectionKeyProblem`: letters and digits only, 5 to 64 characters. The error shows on a hint line that is always there, so the button never moves. Stored like a sign-in.
- A stored link or key is "remembered", like a login form's email: Forget key clears it (and revokes a phone link's token).

### 5. Connecting

Started by the person: Connect in the panel, or **play on a scripted video while remembered** (pressing play is their own action, so the session connects then without asking).

1. Phase connecting; start a 10 s patience timer. When it fires, the panel and the button turn into the warning; the wait goes on.
2. Wait for the device to be online: `GET /connected`, then the SSE stream (`/sse`) for the moment it connects. Never a polling loop.
3. `GET /info` (model, firmware) and capabilities (whether it has a slider; the Oh doesn't).
4. Clock: step 6. Uses the stored estimate when it is fresh, so a reconnect within 3 hours costs no `servertime` calls.
5. `PUT /hstp/clocksync` once per connection: online, the servers own the device's clock and keep it synced after this.
6. Read the device's sync offset (`GET /hstp/offset`) and stroke zone (`GET /slider/stroke`), so the sliders start on the truth.
7. Phase connected. If the video is already playing, start The Handy where the video is.

Stop waiting aborts and goes back to remembered. An error goes back to remembered with a card that says what happened.

### 6. The clock: resync timing, kept in localStorage

Synced playback needs `offset = serverTime − Date.now()`. The method is the v3 `/servertime` docs' and the app's (`sampleServerTime`):

- Sequential `GET /servertime` samples; each offset taken at the round trip's midpoint; sort by round trip, keep the fastest two thirds, average.
- **Quick** (8 samples) on a connect with no fresh estimate. **Full** (30) on the Resync button, with "Syncing 12/30" on the button.
- Stored as `handy-sdk:clock` `{ offset, rtd, samples, syncedAt }`, valid for **3 hours** (the app's `SERVER_TIME_MAX_AGE_MS` for `handy-server-clock`). Older than that, the next connect measures again. A run with a round trip over 400 ms (a background tab, a bad network) is used for that page only and never stored, so a bad estimate can't stick for three hours.
- One measurement at a time: a second caller waits for the first (coalesced).
- Shared across tabs: a tab that measures writes storage, and the others follow through the `storage` event.
- `clock.now()` is `Date.now() + offset`: plain local time until measured.
- Resync also re-sends `hstp/clocksync`, so both clocks are fresh.

In the demo the mock servers run 1873 ms ahead; the quick sync estimates 1870 to 1876, and the mock device plays 3 to 4 ms off the video.

### 7. Playing a video (HSSP)

`sdk/core/player-sync.js`, one per `<handy-video-tab>`:

| Video event | Handy call |
| --- | --- |
| `playing` | connect if remembered; `hssp/setup` once per video per connection; `PUT /hssp/play { start_time: video ms, server_time: clock.now(), playback_rate }` |
| `pause`, `waiting` (buffering), `ended` | `PUT /hssp/stop` |
| `seeked` while playing | `hssp/play` again from the new time |
| `ratechange` | `hssp/play` again; the tab warns that The Handy can't follow anything but 1× yet (script tokens can't change speed) |

- One command at a time per video, in order, so a seek never races a play. A resume asked for while a play is already waiting is dropped (one `hssp/play`, not two); a seek or rate change meanwhile plays again once the first is done.
- The script is a **script token**: never parse, sort, draw or measure it. Upload it as it is (`POST scripts01…/api/script/v0/temp/upload`), then `hssp/setup` with the `/partner/v0/token/download` URL it answers. It plays over HSSP only. (The demo's mock uses our own demo funscripts, which are not tokens.)
- "Play on The Handy" in the tab turns it off for this video (stop now, ignore play) and back on (play from where the video is).

### 8. Adjustments

- **Sync offset** (−500 to 500 ms, step 5 in the panel, 10 in the tab): `PUT /hstp/offset`, a device setting, so it follows the person to other sites.
- **Stroke zone** (0 to 100 %, a range with drag-range): `PUT /slider/stroke`. Hidden on a device with no slider.
- Both write 200 ms after the slider settles (the app's debounce), not on every step. The panel and the tab show the same value.

### 9. Stop, disconnect, forget

- **No Stop button** in the panel (the owner, 2026-12-03): pausing the video stops The Handy, and so does Disconnect.
- **Disconnect**: stop, leave connected; the link or key stays (remembered).
- **Forget key**: only from the remembered view (not while connected): disconnect, revoke the token, clear the stored session.

## Request budget

What the demo counted against the mock servers:

| What happened | Calls to the Handy servers |
| --- | --- |
| Any number of page loads, browsing, Learn, as a new visitor | **0** (feed: at most one CDN request per 6 h, 304 after) |
| A page load with a phone link or key saved (connects by itself) | 5: `connected`, `info`, `hstp/clocksync`, `hstp/offset`, `slider/stroke` (+8 `servertime` when the clock is older than 3 h) |
| Opening the panel as a new visitor | 2: `link/start` (once per 5 minutes) and one open `link/wait`, closed with the panel |
| Play on a scripted video, connected | 2: `hssp/setup`, `hssp/play` |
| The same with the clock older than 3 h | +8 `servertime` |
| Pause, seek, play | 1 each (a seek while playing: `stop` while it buffers, then `play`) |
| Resync | 30 `servertime` + 1 `hstp/clocksync` |
| Dragging a slider | 1, when it settles |
| Request it (a video with no script) | 1 `scripts/request`, once per video |

The v3 API answers `X-RateLimit-Limit` (240 per minute in the spec's example) per key. Nothing in this flow comes close.

## What is stored

All under the `handy-sdk:` prefix in localStorage, so a partner can see and clear exactly what is ours:

| Key | What | Kept |
| --- | --- | --- |
| `handy-sdk:session` | `{ method: "phone" \| "key", connectionKey, token?, savedAt }` | until Forget key |
| `handy-sdk:clock` | `{ offset, rtd, samples, syncedAt }` | used for 3 h |
| `handy-sdk:feed:<appId>` | `{ etag, fetchedAt, videos }` | used for 6 h, then revalidated |
| `handy-sdk-mock:device` | the mock device's offset and stroke (demo only) | |
| `handy-sdk-demo:options` | the demo panel's options and site look (demo only) | until changed |

The kit's own `handy-theme` key is the kit's (and never written here, since the partner's `<html>` carries `data-theme`).

## Where it comes from in the Handyverse app

Read on 2026-12-02 in `~/code/handyverse-app`:

| Here | There |
| --- | --- |
| The button (dot, one word, warning in place of the dot) | `src/features/handyverse/components/DeviceButton.vue` (the bar pill) |
| The panel's phases, 10 s patience, the warning in the same box, Stop never disabled, the 200 ms slider debounce, reading the offset and stroke on open | the same file (the device panel), `src/composables/useHandyverseConnect.ts` |
| Key rules | `src/logic/connection-key.ts` |
| Clock sampling, coalescing, 3 h storage | `packages/online-api/src/transport/serverTime.ts`, `packages/rpc-handler/src/transport/serverTime.ts` (`handy-server-clock`) |
| Online: the servers own the device clock (`hstp/clocksync`) | `src/composables/useClockSync.ts` (header comment) |
| Round trip rating (Excellent ≤ 50 ms, Good ≤ 150, Okay ≤ 250) | `src/logic/connection-quality.ts` |
| Script tokens: HSSP only, never sorted, no speed change | the owner's script token rules (global CLAUDE.md) |

Not taken over: Bluetooth, the firmware update nudge, the both-radios card, the firmware 3 (legacy) check, the timeouts card. A web SDK on a partner site is online only; the legacy check (`legacyOnlineVersion`) is worth adding once the real API is wired.

## Files

| Path | What |
| --- | --- |
| `index.html`, `interactive.html`, `watch.html`, `site/` | The mock partner: its own look, its own catalog (`site/catalog.js`, generated thumbnails, our demo clips from the CDN) |
| `site/demo-options.js` | The floating demo options panel (demo only) |
| `sdk/handy-sdk.js` | The entry: config, wiring, the elements, `window.HandySDK` |
| `sdk/core/store.js` | localStorage under one prefix, safe when storage is missing |
| `sdk/core/clock.js` | The server clock (step 6) |
| `sdk/core/feed.js` | The feed (step 2) |
| `sdk/core/session.js` | The state machine (steps 4, 5, 8, 9) |
| `sdk/core/player-sync.js` | Video to HSSP (step 7) |
| `sdk/core/api-mock.js` | The mock servers and device; each method names the real endpoint |
| `sdk/ui/logo.js` | The Handy's logo with its wordmark (the modal's heading), copied from the Vue kit's `handy-logo-art.ts` |
| `sdk/ui/qr.js` | The QR code encoder for the phone link (byte mode, level M, versions 1 to 6) |
| `sdk/ui/kit.js` | Loads the kit into shadow roots (`:root`/`body` → `.hsdk-root`, fonts lifted to the document) |
| `sdk/ui/banner.js`, `button.js`, `panel.js`, `video-tab.js` | `<handy-banner>`, `<handy-button>`, `<handy-panel>`, `<handy-video-tab>` and `<handy-badge>` |
| `sdk/mock/feeds/demo-partner.json` | The demo feed |
| `vendor/handy-kit/` | The vanilla kit, copied from `playground.handyfeeling.com/brandux/vanilla/v1/assets/` |
| `serve.mjs` | A static server with ETags, so the feed's 304 works as on a CDN |

## Kit changes wanted

The vanilla kit works inside shadow roots only with the rewrite in `sdk/ui/kit.js`. For an SDK on other people's sites, brand-ux could ship an embed build:

- **Tokens on `:host` or a class, not `:root`**, and no `body` rules, so the CSS can be adopted into a shadow root as it is.
- **The logo lockups in the vanilla kit**: its `<h-logo>` has only the mark; the SDK copies the horizontal lockup from the Vue kit (`sdk/ui/logo.js`).
- **Fonts as a separate small stylesheet** for the document (Chrome ignores `@font-face` inside a shadow root).
- **Never touch `<html>`**: `handy.js` stamps `data-theme` on it unless the page set one, and `h-modal` toggles `h-modal-gutter`. On a partner site that is their element.
- **`data-h-open` and toasts** work at the document level: `data-h-open` looks its target up with `document.querySelector`, and toasts mount in a layer outside the SDK's shadow roots, where the scoped CSS doesn't reach. The SDK calls `show()` itself and uses no toasts.
- **Global element names** (`h-modal`…) clash if a partner loads another kit version. Scoped custom element registries, or prefixed names in the embed build, would fix it.

## Open questions

1. **The phone link**: the link URL and what the Handy app does with it, the code's lifetime, long poll or SSE for the wait, the token's lifetime and refresh, and whether it is bound to the app ID and the partner's origin. Which device when the visitor has several (the app should let them pick).
2. **The app ID**: does it replace the v3 API key (`X-Api-Key`)? If it is public in the page, the servers must bind it to the partner's origins.
3. **The feed**: who builds it (IVDB?), where it is hosted, how often it changes, and whether it needs the partner's video IDs or a fingerprint.
4. **Script access**: does the script token come from the visitor's purchase on the partner site, the partner's own key, or both?
5. **Speed**: when HSSP can follow a changed playback rate with a token, the tab's warning goes.
6. **Bluetooth**: out of scope for a web SDK on partner sites (Chrome only, needs a chooser). Say so in Learn, or offer it?
