@joiner-platform/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/README.md +30 -2
  2. package/bundled-resources/poe-tile-templates/base/CLAUDE.md +72 -0
  3. package/bundled-resources/poe-tile-templates/base/README.md +7 -0
  4. package/bundled-resources/poe-tile-templates/base/_bunfig.toml +8 -0
  5. package/bundled-resources/poe-tile-templates/base/_gitignore +18 -0
  6. package/bundled-resources/poe-tile-templates/base/client.ts +12 -0
  7. package/bundled-resources/poe-tile-templates/base/package.json +36 -0
  8. package/bundled-resources/poe-tile-templates/base/playwright.config.ts +38 -0
  9. package/bundled-resources/poe-tile-templates/base/scripts/check-source.ts +148 -0
  10. package/bundled-resources/poe-tile-templates/base/scripts/dev.ts +19 -0
  11. package/bundled-resources/poe-tile-templates/base/scripts/doctor.sh +29 -0
  12. package/bundled-resources/poe-tile-templates/base/scripts/visual-check.ts +64 -0
  13. package/bundled-resources/poe-tile-templates/base/synced-store/backend-config.ts +9 -0
  14. package/bundled-resources/poe-tile-templates/base/synced-store/client-config.ts +8 -0
  15. package/bundled-resources/poe-tile-templates/base/synced-store/data/items.ts +16 -0
  16. package/bundled-resources/poe-tile-templates/base/synced-store/mutators/index.ts +10 -0
  17. package/bundled-resources/poe-tile-templates/base/synced-store/mutators/remove-todo.ts +5 -0
  18. package/bundled-resources/poe-tile-templates/base/synced-store/mutators/set-todo.ts +20 -0
  19. package/bundled-resources/poe-tile-templates/base/synced-store/mutators/types.ts +5 -0
  20. package/bundled-resources/poe-tile-templates/base/synced-store/mutators.test.ts +138 -0
  21. package/bundled-resources/poe-tile-templates/base/synced-store/schema.ts +40 -0
  22. package/bundled-resources/poe-tile-templates/base/tests/e2e.test.playwright.ts +92 -0
  23. package/bundled-resources/poe-tile-templates/base/tests/mobile-viewport.test.playwright.ts +111 -0
  24. package/bundled-resources/poe-tile-templates/base/tests/render-check.test.playwright.ts +128 -0
  25. package/bundled-resources/poe-tile-templates/base/tests/screenshot.test.playwright.ts +86 -0
  26. package/bundled-resources/poe-tile-templates/base/tests/setup-dom.ts +70 -0
  27. package/bundled-resources/poe-tile-templates/base/tile/src/backend.ts +3 -0
  28. package/bundled-resources/poe-tile-templates/base/tile/styles.css +47 -0
  29. package/bundled-resources/poe-tile-templates/base/tsconfig.json +13 -0
  30. package/bundled-resources/poe-tile-templates/coverage.config.json +6 -0
  31. package/bundled-resources/poe-tile-templates/index.ts +27 -0
  32. package/bundled-resources/poe-tile-templates/package.json +31 -0
  33. package/bundled-resources/poe-tile-templates/phaserjs/package.partial.json +6 -0
  34. package/bundled-resources/poe-tile-templates/phaserjs/tile/index.html +14 -0
  35. package/bundled-resources/poe-tile-templates/phaserjs/tile/src/entry.ts +35 -0
  36. package/bundled-resources/poe-tile-templates/phaserjs/ui/App.test.happydom.tsx +98 -0
  37. package/bundled-resources/poe-tile-templates/phaserjs/ui/App.ts +180 -0
  38. package/bundled-resources/poe-tile-templates/phaserjs/ui/phaser-scene.ts +174 -0
  39. package/bundled-resources/poe-tile-templates/phaserjs/vite.config.ts +28 -0
  40. package/bundled-resources/poe-tile-templates/preact/package.partial.json +9 -0
  41. package/bundled-resources/poe-tile-templates/preact/postcss.config.js +5 -0
  42. package/bundled-resources/poe-tile-templates/preact/tile/index.html +14 -0
  43. package/bundled-resources/poe-tile-templates/preact/tile/src/entry.tsx +36 -0
  44. package/bundled-resources/poe-tile-templates/preact/tile/styles.css +51 -0
  45. package/bundled-resources/poe-tile-templates/preact/tsconfig.json +15 -0
  46. package/bundled-resources/poe-tile-templates/preact/ui/App.test.happydom.tsx +69 -0
  47. package/bundled-resources/poe-tile-templates/preact/ui/App.tsx +116 -0
  48. package/bundled-resources/poe-tile-templates/preact/vite.config.ts +18 -0
  49. package/bundled-resources/poe-tile-templates/react/package.partial.json +12 -0
  50. package/bundled-resources/poe-tile-templates/react/postcss.config.js +5 -0
  51. package/bundled-resources/poe-tile-templates/react/tile/index.html +14 -0
  52. package/bundled-resources/poe-tile-templates/react/tile/src/entry.tsx +38 -0
  53. package/bundled-resources/poe-tile-templates/react/tile/styles.css +51 -0
  54. package/bundled-resources/poe-tile-templates/react/tsconfig.json +14 -0
  55. package/bundled-resources/poe-tile-templates/react/ui/App.test.happydom.tsx +71 -0
  56. package/bundled-resources/poe-tile-templates/react/ui/App.tsx +110 -0
  57. package/bundled-resources/poe-tile-templates/react/vite.config.ts +21 -0
  58. package/bundled-resources/poe-tile-templates/scripts/cleanup.ts +10 -0
  59. package/bundled-resources/poe-tile-templates/scripts/generate.ts +57 -0
  60. package/bundled-resources/poe-tile-templates/scripts/install-diagnostics.ts +52 -0
  61. package/bundled-resources/poe-tile-templates/scripts/paths.ts +7 -0
  62. package/bundled-resources/poe-tile-templates/scripts/sdk-dependency-key.ts +288 -0
  63. package/bundled-resources/poe-tile-templates/scripts/verify-all-sdks.ts +132 -0
  64. package/bundled-resources/poe-tile-templates/scripts/verify-local-sdk-command.ts +30 -0
  65. package/bundled-resources/poe-tile-templates/scripts/verify-local-sdk-tarball.ts +397 -0
  66. package/bundled-resources/poe-tile-templates/solidjs/_bunfig.toml +14 -0
  67. package/bundled-resources/poe-tile-templates/solidjs/package.partial.json +13 -0
  68. package/bundled-resources/poe-tile-templates/solidjs/postcss.config.js +5 -0
  69. package/bundled-resources/poe-tile-templates/solidjs/tests/solid-plugin.ts +49 -0
  70. package/bundled-resources/poe-tile-templates/solidjs/tile/index.html +14 -0
  71. package/bundled-resources/poe-tile-templates/solidjs/tile/src/entry.tsx +36 -0
  72. package/bundled-resources/poe-tile-templates/solidjs/tile/styles.css +51 -0
  73. package/bundled-resources/poe-tile-templates/solidjs/tsconfig.json +15 -0
  74. package/bundled-resources/poe-tile-templates/solidjs/ui/App.test.happydom.tsx +70 -0
  75. package/bundled-resources/poe-tile-templates/solidjs/ui/App.tsx +129 -0
  76. package/bundled-resources/poe-tile-templates/solidjs/vite.config.ts +18 -0
  77. package/bundled-resources/poe-tile-templates/tests/check-source.test.ts +131 -0
  78. package/bundled-resources/poe-tile-templates/tests/dev-script.test.slow.ts +166 -0
  79. package/bundled-resources/poe-tile-templates/tests/fixtures/customized-manager.ts +67 -0
  80. package/bundled-resources/poe-tile-templates/tests/fixtures/extended-mutators.ts.txt +106 -0
  81. package/bundled-resources/poe-tile-templates/tests/fixtures/multiplayer-verification.test.playwright.ts.txt +103 -0
  82. package/bundled-resources/poe-tile-templates/tests/fixtures/replace-starter-schema.ts +67 -0
  83. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/phaserjs.tsx.txt +85 -0
  84. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/preact.tsx.txt +69 -0
  85. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/react.tsx.txt +73 -0
  86. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/seating.ts.txt +54 -0
  87. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/solidjs.tsx.txt +70 -0
  88. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/vanilla-js.tsx.txt +85 -0
  89. package/bundled-resources/poe-tile-templates/tests/generated-templates.test.ts +278 -0
  90. package/bundled-resources/poe-tile-templates/tests/happy-dom-version.test.ts +27 -0
  91. package/bundled-resources/poe-tile-templates/tests/install-diagnostics.test.ts +99 -0
  92. package/bundled-resources/poe-tile-templates/tests/native-gesture-defaults.test.ts +23 -0
  93. package/bundled-resources/poe-tile-templates/tests/playwright-version.test.ts +84 -0
  94. package/bundled-resources/poe-tile-templates/tests/render-check-scaffold.test.ts +56 -0
  95. package/bundled-resources/poe-tile-templates/tests/sdk-dependency-key.test.ts +129 -0
  96. package/bundled-resources/poe-tile-templates/tests/visual-check.test.ts +90 -0
  97. package/bundled-resources/poe-tile-templates/vanilla-js/package.partial.json +3 -0
  98. package/bundled-resources/poe-tile-templates/vanilla-js/tile/index.html +14 -0
  99. package/bundled-resources/poe-tile-templates/vanilla-js/tile/src/entry.ts +35 -0
  100. package/bundled-resources/poe-tile-templates/vanilla-js/ui/App.test.happydom.tsx +96 -0
  101. package/bundled-resources/poe-tile-templates/vanilla-js/ui/App.ts +113 -0
  102. package/bundled-resources/poe-tile-templates/vanilla-js/vite.config.ts +17 -0
  103. package/cli.ts +134 -0
  104. package/index.ts +96 -0
  105. package/package.json +48 -5
  106. package/skills/audio-generation/.generated-by-poe-templated-docs +0 -0
  107. package/skills/audio-generation/SKILL.md +125 -0
  108. package/skills/finish-prototype/.generated-by-poe-templated-docs +0 -0
  109. package/skills/finish-prototype/SKILL.md +22 -0
  110. package/skills/help-me-build/.generated-by-poe-templated-docs +0 -0
  111. package/skills/help-me-build/SKILL.md +56 -0
  112. package/skills/image-generation/.generated-by-poe-templated-docs +0 -0
  113. package/skills/image-generation/SKILL.md +128 -0
  114. package/skills/one-shot/.generated-by-poe-templated-docs +0 -0
  115. package/skills/one-shot/SKILL.md +22 -0
  116. package/skills/platform-prototype/.generated-by-poe-templated-docs +0 -0
  117. package/skills/platform-prototype/SKILL.md +60 -0
  118. package/skills/platform-subagent/.generated-by-poe-templated-docs +0 -0
  119. package/skills/platform-subagent/SKILL.md +16 -0
  120. package/skills/poe-tiles-cli/.generated-by-poe-templated-docs +0 -0
  121. package/skills/poe-tiles-cli/SKILL.md +609 -0
  122. package/skills/poe-tiles-cli/references/device-motion.md +40 -0
  123. package/skills/poe-tiles-cli/references/player-updates.md +41 -0
  124. package/skills/prototype/.generated-by-poe-templated-docs +0 -0
  125. package/skills/prototype/SKILL.md +149 -0
  126. package/skills/publish/.generated-by-poe-templated-docs +0 -0
  127. package/skills/publish/SKILL.md +73 -0
  128. package/skills/synced-store/.generated-by-poe-templated-docs +0 -0
  129. package/skills/synced-store/SKILL.md +583 -0
  130. package/skills/synced-store/references/actions.md +85 -0
  131. package/skills/synced-store/references/api-patterns.md +245 -0
  132. package/skills/synced-store/references/architecture-scaling-and-performance.md +280 -0
  133. package/skills/synced-store/references/client-api-reference.md +263 -0
  134. package/skills/synced-store/references/data-visibility.md +95 -0
  135. package/skills/synced-store/references/external-stores.md +162 -0
  136. package/skills/synced-store/references/file-uploads.md +216 -0
  137. package/skills/synced-store/references/getting-user-info-of-members.md +228 -0
  138. package/skills/synced-store/references/limitations.md +72 -0
  139. package/skills/synced-store/references/live-data-limit-hook.md +131 -0
  140. package/skills/synced-store/references/mutator-rules.md +169 -0
  141. package/skills/synced-store/references/platform.md +49 -0
  142. package/skills/synced-store/references/schema-and-bindings.md +85 -0
  143. package/skills/synced-store/references/schema-libraries.md +57 -0
  144. package/skills/synced-store/references/schema-migrations.md +119 -0
  145. package/skills/synced-store/references/searchable-tables.md +27 -0
  146. package/skills/synced-store/references/server-forking.md +115 -0
  147. package/skills/synced-store/references/singleton-tables.md +61 -0
  148. package/skills/synced-store/references/sort-keys.md +253 -0
  149. package/skills/synced-store/references/ui-patterns.md +95 -0
  150. package/skills/tile-creator/.generated-by-poe-templated-docs +0 -0
  151. package/skills/tile-creator/SKILL.md +197 -0
  152. package/skills/tile-creator/references/assets.md +124 -0
  153. package/skills/tile-creator/references/backend-api.md +354 -0
  154. package/skills/tile-creator/references/cli-limitations.md +64 -0
  155. package/skills/tile-creator/references/cli.md +604 -0
  156. package/skills/tile-creator/references/client-api.md +2407 -0
  157. package/skills/tile-creator/references/composing-apps.md +166 -0
  158. package/skills/tile-creator/references/e2e-tests.md +55 -0
  159. package/skills/tile-creator/references/game-ux-best-practices.md +57 -0
  160. package/skills/tile-creator/references/migrating-pre-rename-tiles.md +79 -0
  161. package/skills/tile-creator/references/multiplayer-api-recipe.md +205 -0
  162. package/skills/tile-creator/references/native-results.md +100 -0
  163. package/skills/tile-creator/references/platform-integration.md +201 -0
  164. package/skills/tile-creator/references/power-report.md +199 -0
  165. package/skills/tile-creator/references/publish-rollout.md +166 -0
  166. package/skills/tile-creator/references/publishing.md +33 -0
  167. package/skills/tile-creator/references/push-notification-guidelines.md +58 -0
  168. package/skills/tile-creator/references/render-check.md +266 -0
  169. package/skills/tile-creator/references/running-the-client-api-on-a-server-owned-by-the-user.md +95 -0
  170. package/skills/tile-creator/references/safe-area-insets.md +79 -0
  171. package/skills/tile-creator/references/sandbox-limitations.md +32 -0
  172. package/skills/tile-creator/references/scaffolded-tile-folder-structure.md +48 -0
  173. package/skills/tile-creator/references/scaffolding-a-new-app.md +202 -0
  174. package/skills/tile-creator/references/simulations.md +125 -0
  175. package/skills/tile-creator/references/synced-store-client-reference.md +92 -0
  176. package/skills/tile-creator/references/troubleshooting.md +22 -0
  177. package/skills/tile-creator/references/turn-based-mutator.md +43 -0
  178. package/skills/tile-creator/references/user-erasure.md +14 -0
  179. package/skills/tile-creator/references/vite-plugin.md +166 -0
  180. package/skills/tile-creator/references/workspace-retention.md +72 -0
  181. package/src/admin-conversions-client.ts +28 -0
  182. package/src/admin-reviews-client.ts +36 -0
  183. package/src/api.generated.ts +1527 -0
  184. package/src/auth-token.ts +198 -0
  185. package/src/bounded-read.ts +35 -0
  186. package/src/bun-version.ts +33 -0
  187. package/src/checkout-base.ts +207 -0
  188. package/src/cli-bun-version.ts +16 -0
  189. package/src/cli-env.ts +28 -0
  190. package/src/cli-name.ts +23 -0
  191. package/src/client.ts +2474 -0
  192. package/src/collect-files.ts +226 -0
  193. package/src/commands/accounts.ts +55 -0
  194. package/src/commands/admin-abandon-conversion.ts +60 -0
  195. package/src/commands/admin-reviews.ts +66 -0
  196. package/src/commands/admin.ts +219 -0
  197. package/src/commands/auth.ts +89 -0
  198. package/src/commands/checkout-prototype.ts +67 -0
  199. package/src/commands/creator-source-capability.ts +11 -0
  200. package/src/commands/doctor-bun.ts +145 -0
  201. package/src/commands/doctor-command.ts +64 -0
  202. package/src/commands/doctor-package-json.ts +47 -0
  203. package/src/commands/doctor-sdk-pin.ts +156 -0
  204. package/src/commands/doctor-store-keys-lexer.ts +213 -0
  205. package/src/commands/doctor-store-keys-scan.ts +262 -0
  206. package/src/commands/doctor-store-keys.ts +196 -0
  207. package/src/commands/doctor.ts +371 -0
  208. package/src/commands/init/blank-scaffold-templates.ts +397 -0
  209. package/src/commands/init/index.ts +170 -0
  210. package/src/commands/init/internal-toolchain.ts +49 -0
  211. package/src/commands/init/manager-test-template.ts +107 -0
  212. package/src/commands/init/multiplayer-test-template.ts +217 -0
  213. package/src/commands/init/name-input.tsx +167 -0
  214. package/src/commands/init/no-store-scaffold-templates.ts +281 -0
  215. package/src/commands/init/no-store-scaffold.ts +134 -0
  216. package/src/commands/init/package-json-scripts.ts +72 -0
  217. package/src/commands/init/scaffold.ts +960 -0
  218. package/src/commands/init/sdk-tarball-url.generated.ts +4 -0
  219. package/src/commands/init/sdk-tarball-url.ts +31 -0
  220. package/src/commands/init/template-picker.tsx +147 -0
  221. package/src/commands/inspect-child-entry.ts +107 -0
  222. package/src/commands/inspect-contract.ts +87 -0
  223. package/src/commands/inspect-freshness.ts +217 -0
  224. package/src/commands/inspect-lock.ts +201 -0
  225. package/src/commands/inspect-options.ts +360 -0
  226. package/src/commands/inspect-orchestrate.ts +375 -0
  227. package/src/commands/inspect-process.ts +172 -0
  228. package/src/commands/inspect-ready.ts +65 -0
  229. package/src/commands/inspect-report.ts +235 -0
  230. package/src/commands/inspect-run-state.ts +296 -0
  231. package/src/commands/inspect-run.ts +157 -0
  232. package/src/commands/inspect-watchdog.ts +74 -0
  233. package/src/commands/install-joiner.ts +208 -0
  234. package/src/commands/login.ts +308 -0
  235. package/src/commands/models.ts +40 -0
  236. package/src/commands/parse-options.ts +36 -0
  237. package/src/commands/remix-package-json.ts +64 -0
  238. package/src/commands/remix.ts +379 -0
  239. package/src/commands/sdk-url.ts +141 -0
  240. package/src/commands/simulations.ts +133 -0
  241. package/src/commands/skills.ts +108 -0
  242. package/src/commands/store-files.ts +92 -0
  243. package/src/commands/stores.ts +703 -0
  244. package/src/commands/tiles-channel-commands.ts +115 -0
  245. package/src/commands/tiles-checkout.ts +351 -0
  246. package/src/commands/tiles-gallery-command.ts +95 -0
  247. package/src/commands/tiles-get-helpers.ts +27 -0
  248. package/src/commands/tiles-inspect.ts +276 -0
  249. package/src/commands/tiles-power-command.ts +308 -0
  250. package/src/commands/tiles-power-format.ts +396 -0
  251. package/src/commands/tiles-power-versions.ts +299 -0
  252. package/src/commands/tiles-publish-helpers.ts +145 -0
  253. package/src/commands/tiles-upload-command.ts +277 -0
  254. package/src/commands/tiles-version-commands.ts +201 -0
  255. package/src/commands/tiles-visibility-command.ts +103 -0
  256. package/src/commands/tiles.ts +257 -0
  257. package/src/commands/upgrade.ts +307 -0
  258. package/src/commit-in-progress.ts +42 -0
  259. package/src/creator-source-context.ts +97 -0
  260. package/src/creator-source-publish.ts +52 -0
  261. package/src/deferred-assets.ts +125 -0
  262. package/src/distribution.ts +28 -0
  263. package/src/errors.ts +61 -0
  264. package/src/install-command.ts +43 -0
  265. package/src/output.ts +62 -0
  266. package/src/poe-tile-config-files.ts +100 -0
  267. package/src/poe-tile-config-players.ts +168 -0
  268. package/src/poe-tile-config-remix.ts +166 -0
  269. package/src/poe-tile-config.ts +831 -0
  270. package/src/power-report-client.ts +55 -0
  271. package/src/prototype-startup.ts +21 -0
  272. package/src/publish-change-summary.ts +55 -0
  273. package/src/publish-overrides-validation.ts +49 -0
  274. package/src/publish-pack.ts +167 -0
  275. package/src/publish-phases.ts +57 -0
  276. package/src/publish-retry.ts +51 -0
  277. package/src/publish-tile-from-config.ts +434 -0
  278. package/src/recorder-stream.ts +169 -0
  279. package/src/remix-provenance.ts +156 -0
  280. package/src/resolve-client-credential.ts +71 -0
  281. package/src/resolve-media-uploads.ts +147 -0
  282. package/src/sdk-dependency.ts +54 -0
  283. package/src/sdk-skills.ts +85 -0
  284. package/src/should-skip-client-setup.ts +20 -0
  285. package/src/simulation-snapshot.ts +123 -0
  286. package/src/simulation-types.ts +74 -0
  287. package/src/simulations-client.ts +112 -0
  288. package/src/source-bundle.ts +466 -0
  289. package/src/staged-publish-cleanup.ts +44 -0
  290. package/src/staged-publish-deferred.ts +160 -0
  291. package/src/staged-publish.ts +401 -0
  292. package/src/store-file-upload.ts +268 -0
  293. package/src/store-request.ts +168 -0
  294. package/src/tar-canonical.ts +41 -0
  295. package/src/tar-extensions.ts +159 -0
  296. package/src/tar-extract.ts +193 -0
  297. package/src/tar-parse.ts +224 -0
  298. package/src/tar.ts +231 -0
  299. package/src/template-check-scripts.ts +18 -0
  300. package/src/tile-gallery-client.ts +82 -0
  301. package/src/types.ts +258 -0
  302. package/src/upload-concurrency.ts +54 -0
  303. package/src/whole-tile.ts +52 -0
@@ -0,0 +1,2407 @@
1
+ # Client API
2
+
3
+ The `joiner-sdk/v1/client.js` module is the client-side JavaScript interface for apps running inside Joiner tile frames. It provides store initialization, data access, and bot interaction — all from your app's frontend code.
4
+
5
+ ::: info Docs describe the latest SDK
6
+ This reference tracks the most recently published `joiner-sdk` tarball. If a documented method doesn't exist in your app (TypeScript error, or `undefined` at runtime), your app's SDK pin is older than the docs — see [Upgrading an existing app's SDK](cli.md#upgrading-the-sdk-in-an-existing-app). Recently introduced APIs carry an *Added <date>* note so you can tell at a glance.
7
+ :::
8
+
9
+ ```typescript
10
+ import { createPoe, PostMessageEnvironment, registerPoeTileElement } from "joiner-sdk/v1/client.js";
11
+ ```
12
+
13
+ ## Native round results helpers
14
+
15
+ Added September 2026; requires SDK/kernel 31 or later.
16
+ `createNativeResults({ room, restart, onErrorChange, schedule? })` returns
17
+ `{ update(finishedRoundOrNull), dispose() }` and coordinates native result
18
+ presentation without owning game rules or styles. `completeRound(ctx, input)`
19
+ commits a full current-round board, clears turns, and sends completion effects
20
+ from an already-validated mutator. It is exported by both client and backend.
21
+ See [native results](native-results.md) for the API, runtime requirement, and
22
+ subscription/mutator examples. Applications can still use the lower-level APIs
23
+ below for custom behavior.
24
+
25
+ ## Client APIs
26
+
27
+ - [`createNativeResults()`](#native-round-results-helpers) — Coordinate the native result lifecycle from live round snapshots
28
+ - [`completeRound()`](#native-round-results-helpers) — Commit round leaderboard, turn and notification effects in a mutator
29
+
30
+ - [`Poe.setupStore()`](#poe-setupstore) — Initialize a synced store
31
+ - [`Poe.store`](#poe-store) — Access the SyncedStoreClient after setup
32
+ - [`Poe.bundle`](#poe-bundle) — Load files from the app's bundle, including deferred files, and keep them cached for offline use
33
+ - [`Poe.getBundleAssetUrl()`](#poe-getbundleasseturl-path) — Deprecated; use `Poe.bundle.loadAsset()`
34
+ - [`Poe.tiles.list()`](#poe-tiles-list) — List all published apps
35
+ - [`Poe.tiles.get()`](#poe-tiles-get-typeid) — Fetch one published app by typeId
36
+ - [`Poe.tiles.search()`](#poe-tiles-search-query-limit) — Search the public app catalog
37
+ - [`Poe.tiles.preload()`](#poe-tiles-preload-typeid-instanceid) — Preload an app's bundle for instant loading
38
+ - [`Poe.tiles.syncStatus()`](#poe-tiles-syncstatus-typeid-instanceid) — Creation-lifecycle sync status of an instance on this device (subscribable)
39
+ - [`Poe.open()`](#poe-open-typeid-instanceid-openprops-anchorsortkey-placement-viewwidth) — Navigate to a different app (or open it in split view alongside the caller)
40
+ - [`Poe.showTileLauncher()`](#poe-showtilelauncher) — Ask the host to show the standard tile launcher
41
+ - [`Poe.users.openProfile()`](#poe-users-openprofile-userid-username) — Open a user's profile UI in the host
42
+ - [`Poe.room.openInvitePicker()`](#poe-room-openinvitepicker) — Open the host Add members invite surface for the calling app instance
43
+ - [`Poe.room.openChat()`](#poe-room-openchat) — Reveal the containing room's chat in the host-native surface
44
+ - [`Poe.room.pickMembers()`](#poe-room-pickmembers) — Pick room members, optionally adding contacts to the room first
45
+ - [`Poe.room.tileEnd()`](#poe-room-tileend-input) — Show the host end-of-tile UI and optionally replay
46
+ - [`Poe.room.setShareLeaderboardId()`](#poe-room-setshareleaderboardid-leaderboardid) — Make current-page share links point at a tile-owned leaderboard
47
+ - [`Poe.room.dismissTileEnd()`](#poe-room-dismisstileend-opts) — Programmatically dismiss this client's tile-end overlay (shared-instance team games)
48
+ - [`Poe.agents.create()`](#poe-agents-create-agentid-name-model-tools-room) — Create an agent owned by the calling user, optionally adding it to a room
49
+ - [`Poe.agents.delete()`](#poe-agents-delete-agentid) — Delete one of your agents outright (irreversible)
50
+ - [`Poe.agents.addToRoom()` / `Poe.agents.removeFromRoom()`](#poe-agents-addtoroom-agentid-typeid-instanceid-poe-agents-removefromroom-agentid-typeid-instanceid) — Add/remove an existing agent as a room member
51
+ - [`Poe.agents.listTools()`](#poe-agents-listtools) — List the first-party agent system-tool catalog
52
+ - [`Poe.agents.listTemplates()`](#poe-agents-listtemplates) — List the first-party agent-template catalog
53
+ - [`Poe.agents.listMine()`](#poe-agents-listmine) — List your own live agents
54
+ - [`Poe.track()`](#poe-track-event-properties) — Send a privacy-filtered analytics event
55
+ - [`Poe.openExternalUrl()`](#poe-openexternalurl-url) — Open a web link via the host (platform links navigate in place; other links need user confirmation)
56
+ - [`<poe-tile>`](#poe-tile-custom-element) — Embed a child app inline
57
+ - [`Poe.getOpenProps()`](#poe-getopenprops) — Read data passed by a parent app
58
+ - [`watchEntryContext()`](#watchentrycontext) — Get the notification the user tapped to open the tile, and the entry context attached to it
59
+ - [`Poe.consumeEntryContext()`](#poe-consumeentrycontext) — Deprecated for notifications: use `watchEntryContext()`
60
+ - [`Poe.parent`](#poe-parent) — Parent store identity (for child apps)
61
+ - [`Poe.topOrigin`](#poe-toporigin) — Origin of the top (host) document, for building absolute URLs from sandboxed iframes
62
+ - [`Poe.interfaceLanguages`](#poe-interfacelanguages) — The host's interface languages, preferred over `navigator.languages` when localizing a tile
63
+ - [`Poe.haptics`](#poe-haptics) — Trigger cross-platform haptic feedback
64
+ - [`Poe.motion.claim()`](#device-motion) — Tell the host this tile uses device motion as input, so shake-to-report stands down
65
+ - [`resumeAudioContext()`](#resumeaudiocontext) — Recover Web Audio after browser or iOS system-audio interruptions
66
+ - [`createVerticalScrollBounceMount()`](#createverticalscrollbouncemount) — Create a root render target with native vertical pull bounce
67
+ - [`installVerticalScrollBounce()`](#installverticalscrollbounce) — Add native vertical pull bounce to a custom scroll area
68
+ - [`isIosApp()`](#isiosapp) — Detect the iOS app WebView, including app iframes
69
+ - [`isAndroidApp()`](#isandroidapp) — Detect the Android app WebView, including app iframes
70
+ - [`notifyActivity()`](#notifyactivity) — Notify the manager of activity (preview, unread)
71
+ - [`setTurn()` / `clearTurn()`](#setturn-clearturn) — Declare whose turn it is (the "Your Turn" indicator)
72
+ - [`notifyInProgress()`](#notifyinprogress) — Report long-running work (the Activity-tab-row spinner)
73
+ - [`assertRoomMember()`](#assertroommember) — Server-side validation that a user is still in the caller's room
74
+ - [`notifyUsersAddedToTile()`](#notifyusersaddedtotile) — Standard room-aware "added/assigned to this tile" notification
75
+ - [`addInstanceToRoom()`](#addinstancetoroom) — Register an app instance as a member of a flat room
76
+ - [`getCurrentUserId()`](#getcurrentuserid) — Read the current user's userId from a store (UI/effect helper)
77
+
78
+ ::: warning Poe Employee Note
79
+ Currently the platform injects an [import map](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap) into the app's `index.html` at serve time, which is what makes `createPoe` importable without a bundler. A no-build app imports it from the name the import map gives, poe-tiles-sdk/v1/client.js, because its source ships unchanged. A bundled build writes that same name for its `joiner-sdk/v1/client.js` imports. In the future we'll probably want creators to include a script tag instead (e.g. `<script src="https://poe.com/v1/poe-tiles-sdk.js"></script>`) so the mechanism is more explicit and doesn't require server-side HTML rewriting.
80
+ :::
81
+
82
+ ## Background
83
+
84
+ Apps run inside sandboxed iframes. To ensure apps load even when offline, app bundles are not fetched over HTTP at runtime. Instead, the top document caches all bundle assets and serves them to the iframe via `postMessage`. This is why APIs like [`Poe.bundle.loadAsset()`](#poe-bundle) exist — they request assets from the top document's cache and return blob URLs, rather than making network requests.
85
+
86
+ ## Initialization
87
+
88
+ Every app must explicitly create a Poe instance before using any APIs. This happens once, in your app's **entry file** — `tile/src/entry.ts` (or `entry.tsx`) in the official templates, whose header comment reads "the only file that imports joiner-sdk":
89
+
90
+ ```javascript
91
+ import { createPoe, PostMessageEnvironment, registerPoeTileElement } from "joiner-sdk/v1/client.js";
92
+
93
+ const environment = new PostMessageEnvironment();
94
+ const Poe = createPoe({ environment });
95
+
96
+ // Only needed if your app uses <poe-tile> to embed other apps
97
+ registerPoeTileElement(environment);
98
+ ```
99
+
100
+ `createPoe()` returns the Poe API object and automatically registers it as the module-level singleton, so code-split chunks can access it. Pass `{ singleton: false }` to disable this (useful in tests).
101
+
102
+ ### Reaching `Poe` from the rest of your app
103
+
104
+ Every `Poe.*` example in this reference assumes a `Poe` in scope. `Poe` is **not** a global variable — nothing outside the entry file gets one implicitly. Keep the entry file the only module that imports the SDK, and hand what you need to the rest of your app:
105
+
106
+ - **Pass the whole object** when a module uses several APIs.
107
+ - **Pass one capability** when it uses one — give a board component `Poe.haptics` rather than all of `Poe`. Narrower to stub in tests.
108
+
109
+ Types come from the same entry point, so a receiving module can be typed without importing any runtime SDK code:
110
+
111
+ ```typescript
112
+ import type { PoeAPI } from "joiner-sdk/v1/client.js";
113
+
114
+ // The whole API…
115
+ function createBoard(poe: PoeAPI) {
116
+ poe.haptics.impact("light");
117
+ }
118
+
119
+ // …or a single capability.
120
+ function createScoreboard(haptics: PoeAPI["haptics"]) {
121
+ haptics.notification("success");
122
+ }
123
+ ```
124
+
125
+ How you thread it through is your framework's business — a function argument, a component prop, a context or store object, or a module-level variable you assign at startup. The templates already do exactly this with the synced store (`createApp(appRoot, store)` in the plain-JS template, `<App store={store} />` in the component ones); extend that same call with whatever else the app needs:
126
+
127
+ ```javascript
128
+ // entry file
129
+ const Poe = createPoe({ environment });
130
+ const store = Poe.setupStore(myClientConfig);
131
+
132
+ createApp(appRoot, store, Poe.haptics); // or <App store={store} haptics={Poe.haptics} />
133
+ ```
134
+
135
+ For a module that genuinely cannot be handed the instance — a lazily imported chunk, say — call `getPoeInstance()` from `joiner-sdk/v1/client.js`. It returns the singleton that `createPoe()` registered, and throws if `createPoe()` hasn't run yet. Prefer passing the value explicitly where you can; it keeps the dependency visible and the module testable.
136
+
137
+ ## Core APIs
138
+
139
+ ### `Poe.setupStore()`
140
+
141
+ Initialize a synced store inside your app.
142
+
143
+ ```javascript
144
+ async function addTodo(ctx, input) {
145
+ await ctx
146
+ .table("todos")
147
+ .set({ itemKey: input.id, value: { text: input.text, done: false } });
148
+ }
149
+
150
+ const store = Poe.setupStore({ mutators: { addTodo }, schemaVersion: 1 });
151
+ await store.waitForBootstrap();
152
+ // render UI
153
+ ```
154
+
155
+ `await store.waitForBootstrap()` before rendering UI. It resolves as soon as authoritative data is ready from *either* local cache or first server pull, so offline-capable launches (cached instance, or a fresh instance declared via `Poe.tiles.prepareNewInstances`) unblock immediately. Don't wait for a server milestone here — doing so stalls offline launches and brand-new prepared instances that have no server state to fetch. Reserve `waitForServerData()` for the first server-origin data event, or `waitForInitialPull()` for the point when the full initial pull has been applied, in specialized tests and Node-side scripts.
156
+
157
+ Store background errors have a built-in notice with contextual guidance, the visible diagnostic, **Copy error**, and **Dismiss notification**. Copying does not retry a change or reload the tile. If clipboard access is unavailable, select the diagnostic to copy it manually. Check the tile before repeating a failed action. Apps that provide their own background-error UI can disable the generic notice with `backgroundErrorToast: false` in the setup options; reporting and background-error listeners still run.
158
+
159
+ ### `Poe.store`
160
+
161
+ A [`SyncedStoreClient`](../../synced-store/references/client-api-reference.md) reference. Available after calling `setupStore()`.
162
+
163
+ ### `Poe.bundle`
164
+
165
+ Loads files from the tile's own bundle, including deferred files. Requires SDK/kernel 67; gate with `Poe.has("bundle.loadAsset")` on older hosts. Where files go and when to defer one: [assets.md](./assets.md).
166
+
167
+ ```javascript
168
+ const { url } = await Poe.bundle.loadAsset("/assets/hero.png");
169
+ img.src = url;
170
+ await Poe.bundle.loadAsset("/deferred/intro.mp4", { cache: false });
171
+ await Poe.bundle.ensureAssetCached(["/deferred/level-2.mp3"]);
172
+ ```
173
+
174
+ - **`loadAsset(path, { signal?, cache? })`** resolves `{ url, contentType, size, source }`. `url` is a `blob:` URL; `source` is `"bundle"`, `"cache"` or `"network"`. A deferred file is cached by default; `cache: false` skips the cache. Paths start at the bundle root with `/`.
175
+ - **`ensureAssetCached(path | paths)`** keeps files on the device for offline use, at most 256 paths per call.
176
+ - **`getAssetUrl(path)`** resolves just the `url`.
177
+
178
+ A file the host cannot provide rejects with `BundleAssetUnavailableError` (`joiner-sdk/v1/client.js`). Its `reason` is `"offline"` (a deferred file is not cached and could not be downloaded), `"not_found"` or `"integrity"`. Call again to retry. Importing the class by name requires SDK 67 at link time and breaks the whole tile on an older app, so check `error.name === "BundleAssetUnavailableError"` instead when the tile also supports older apps.
179
+
180
+ ### `Poe.getBundleAssetUrl(path)`
181
+
182
+ **Deprecated:** use [`Poe.bundle.loadAsset(path)`](#poe-bundle); its `url` is the same `blob:` URL.
183
+
184
+ ### `Poe.tiles.list()`
185
+
186
+ List published apps with cursor pagination. Returns `{ tiles, nextCursor? }`, where `tiles` is an array of `Tile` objects with `id`, `handle`, `creator_id`, `creator_handle`, `created_at`, and `updated_at`.
187
+
188
+ ```javascript
189
+ const page1 = await Poe.tiles.list({ limit: 20 });
190
+ console.log(page1.tiles.map(a => a.handle));
191
+
192
+ if (page1.nextCursor) {
193
+ const page2 = await Poe.tiles.list({ cursor: page1.nextCursor, limit: 20 });
194
+ console.log(page2.tiles.map(a => a.handle));
195
+ }
196
+ ```
197
+
198
+ Use this to discover available apps or build an app directory UI.
199
+
200
+ **Parameters:**
201
+ - `limit` — max hits, 1..200 (defaults to 20 server-side)
202
+ - `cursor` — opaque cursor from the previous page
203
+ - `creatorHandle` — restrict results to a single creator
204
+
205
+ ### `Poe.tiles.get({ typeId })`
206
+
207
+ Fetch one published app by typeId. Use this when you already have a persisted app reference and need display metadata; it avoids loading the full catalog.
208
+
209
+ ```javascript
210
+ const app = await Poe.tiles.get({ typeId: "todo-list" });
211
+ console.log(app.handle);
212
+ ```
213
+
214
+ **Parameters:**
215
+ - `typeId` — app type ID (`Tile.id`)
216
+
217
+ **Caching:** Each `typeId` is cached persistently in the host with a 5-minute stale time — cached tiles stay readable offline.
218
+
219
+ ### `Poe.tiles.getByHandle({ creatorHandle, tileHandle })`
220
+
221
+ Resolve one published app by creator handle + app handle (detail-quality payload including `long_description` and `media`). Same caching and reactive affordances as `Poe.tiles.get`.
222
+
223
+ ### Reactive reads: `Poe.query(ref)`
224
+
225
+ Cacheable reads (`Poe.tiles.get`, `Poe.tiles.getByHandle`, `Poe.tiles.list`) also expose `.query(input)` and `.key(input)` for reactive UI. Build a ref, then subscribe: the cached value arrives immediately (even offline), followed by a fresh snapshot when the host revalidates.
226
+
227
+ ```javascript
228
+ const ref = Poe.tiles.get.query({ typeId: "todo-list" });
229
+ const unsubscribe = Poe.query(ref).subscribe((snapshot) => {
230
+ render(snapshot.data, {
231
+ isStale: snapshot.isStale,
232
+ isRevalidating: snapshot.isRevalidating,
233
+ error: snapshot.error,
234
+ });
235
+ });
236
+ ```
237
+
238
+ The controller also offers `read()` (one snapshot, never fetches), `watch()` (`for await` sugar over the same stream), and `refetch()` (force a network fetch). SolidJS apps can use `createPoeQuery` from `joiner-sdk/v1/solid` instead of hand-wiring `subscribe`.
239
+
240
+ Per-call cache overrides ride the second argument of the imperative call: `Poe.tiles.get({ typeId }, { cache: { behavior: "cache-only" } })`. Behaviors: `stale-while-revalidate` (default), `cache-first`, `network-only`, `cache-only` (throws on a cache miss instead of fetching).
241
+
242
+ ### `Poe.tiles.search({ query, limit? })`
243
+
244
+ Full-text search the public app catalog by handle / creator handle. Returns full `Tile` records — same shape as `Poe.tiles.list()` — so you can render avatars and descriptions without a second round-trip.
245
+
246
+ ```javascript
247
+ const matches = await Poe.tiles.search({ query: "chess", limit: 10 });
248
+ console.log(matches.map((a) => a.handle));
249
+ ```
250
+
251
+ **Parameters:**
252
+ - `query` — search string (1..500 chars after trim)
253
+ - `limit` — max hits, 1..50 (defaults to 20 server-side)
254
+
255
+ **Caching:** Each `(query, limit)` pair is cached in the host for 5 minutes, so debounced retypes of the same query are served from memory.
256
+
257
+ ### `Poe.tiles.preload({ typeId, instanceId? })`
258
+
259
+ Preload an app's bundle so that a subsequent `<poe-tile type-id="...">` loads instantly. The top document fetches all bundle files and caches the self-contained HTML template in IndexedDB.
260
+
261
+ ```javascript
262
+ // Preload an app you know the user is likely to open
263
+ await Poe.tiles.preload({ typeId: "my-game" });
264
+
265
+ // Preload with an instance ID (reserved for future use)
266
+ await Poe.tiles.preload({ typeId: "my-chat", instanceId: "room-42" });
267
+ ```
268
+
269
+ ### `Poe.tiles.syncStatus({ typeId, instanceId })`
270
+
271
+ Creation-lifecycle sync status of one tile instance **as known on this device**. Pure local read — never a network request — so it works offline and for instances that are not currently rendered.
272
+
273
+ Returns `{ status }` with one of three values (monotonic per device):
274
+
275
+ - `"unknown"` — no local record of the instance on this device. It may still exist server-side; a local client cannot know.
276
+ - `"local-only"` — created locally (e.g. offline via `Poe.tiles.prepareNewInstances` or an optimistic first mutation) but the server has not yet confirmed the instance exists. **This is normal offline operation that reconciles automatically on reconnect — never render it as an error.** Keep routine sync in the background; do not add a sync hint or badge by default.
277
+ - `"server-confirmed"` — the server has confirmed the instance (at least one server-verified commit landed on this device).
278
+
279
+ Pending mutations *after* creation do not change the status — this API tracks creation lifecycle only, not "are all my edits flushed" (use `store.getPendingMutations()` / `store.onPendingMutationsChanged` for that).
280
+
281
+ ```javascript
282
+ const { status } = await Poe.tiles.syncStatus({
283
+ typeId: "my-game",
284
+ instanceId: "match-42",
285
+ });
286
+ ```
287
+
288
+ When tile behavior depends on instance confirmation, subscribe through `Poe.query(Poe.tiles.syncStatus.query({ typeId, instanceId }))` (same reactive contract as `Poe.tiles.get.query`).
289
+
290
+ Snapshots stream as the status changes; consecutive snapshots may repeat a status, so compare `snapshot.data.status` before reacting. The direct call always recomputes from local storage, so it is never stale.
291
+
292
+ ### `Poe.open({ typeId, instanceId, openProps?, anchorSortKey?, placement?, viewWidth? })`
293
+
294
+ Navigate the root app to a different app. This is how a sub-app requests the platform to switch to another app at the top level (as opposed to embedding it inline with `<poe-tile>`).
295
+
296
+ To open a store that has **never existed before**, first declare its genesis with [`Poe.tiles.prepareNewInstances`](#poe-tiles-preparenewinstances-instances) and await it — there is no `isNew` parameter on `Poe.open`.
297
+
298
+ ```javascript
299
+ // Open another app, passing data via openProps
300
+ await Poe.open({
301
+ typeId: "my-game",
302
+ instanceId: "lobby-123",
303
+ openProps: { inviteCode: "abc123" },
304
+ });
305
+
306
+ // Open a large synced-store app around a known sortKey.
307
+ await Poe.open({
308
+ typeId: "chat",
309
+ instanceId: "room-42",
310
+ anchorSortKey: "msg/042",
311
+ openProps: {
312
+ openedSearchResult: {
313
+ itemKey: "message-042",
314
+ tableName: "messages",
315
+ sortKey: "msg/042",
316
+ },
317
+ },
318
+ });
319
+
320
+ // Open the target alongside the caller in a split layout on desktop. On
321
+ // mobile, this falls through to a normal forward navigation, so the same
322
+ // call works on every form factor without branching in app code.
323
+ await Poe.open({
324
+ typeId: "my-canvas",
325
+ instanceId: "canvas-for-chat-42",
326
+ placement: "splitView",
327
+ viewWidth: "260px", // caller's pane width; opened app fills the remainder
328
+ });
329
+ ```
330
+
331
+ The opened app reads the data via `Poe.getOpenProps()`. By default `Poe.open()` replaces the current view (the root app navigates to the target). Pass `placement: "splitView"` to ask the root to render the target alongside the caller; on roots that do not support split view, or on narrow viewports where there is no room for two panes, the hint is ignored and the call behaves like a normal navigation.
332
+
333
+ | Parameter | Type | Required | Description |
334
+ |-----------|------|----------|-------------|
335
+ | `typeId` | string | Yes | The app type ID to open |
336
+ | `instanceId` | string | Yes | Instance ID for the app's store |
337
+ | `openProps` | JSONValue | No | JSON-serializable data passed to the opened app (readable via `Poe.getOpenProps()`) |
338
+ | `anchorSortKey` | string | No | Sort key used by outward pull windows in the opened app. Use it with app-specific `openProps` when you need both store-level anchoring and UI-level context/highlighting. |
339
+ | `placement` | `"current" \| "splitView"` | No | `"current"` (default) replaces the root view. `"splitView"` opens the target alongside the caller on roots that support a split layout (e.g. the manager's two-column layout on desktop and tablets); phones in any orientation and other narrow / unsupported form factors ignore the hint and behave like `"current"`. |
340
+ | `splitViewFallback` | `"navigate" \| "none"` | No | What happens when a `"splitView"` placement cannot be honored (narrow viewport, nothing in the main pane to sit beside, a user-pinned side pane). `"navigate"` (default) falls back to a plain forward navigation — right for a user gesture, which should still land somewhere. `"none"` drops the open instead — the only safe choice for an open no user gesture caused (e.g. auto-docking a companion view when new data arrives), which must never yank the user off the surface they are looking at. The host also remembers when the user closes a `"none"`-opened pane and drops later automatic opens from the same caller until they deliberately reopen it or revisit the surface. Only meaningful with `placement: "splitView"`. |
341
+ | `paneWidth` | string | No | Width of the OPENED pane for automatic (`splitViewFallback: "none"`) opens, which dock as a fixed-width sidecar rather than a flex split. `px` lengths only (e.g. `"840px"` to fit two phone-width frames); other values fall back to the host's default sidecar width, and the host clamps against the viewport. Ignored for gesture splitView opens — size those with `viewWidth`. |
342
+ | `simulate` | boolean | No | With `placement: "splitView"` + `splitViewFallback: "none"`: ask the host to dock a MULTIPLAYER SIMULATION of `typeId` (side-by-side simulated players, created or reused by the host) instead of mounting `instanceId` — the useful companion for a tile that cannot be played alone. Creator-only: the host's server refuses simulations of tiles the caller did not author. |
343
+ | `contentKey` | string | No | With `placement: "splitView"` + `splitViewFallback: "none"`: an opaque identity for the CONTENT this automatic open shows (e.g. the id of the event that produced it). When a repeat open carries the SAME key as the pane the host already docked, the host may skip its refresh work and leave the running pane untouched — so re-sending your newest request after a remount doesn't blank a pane that is already current — while a new key still refreshes. Compared only, never rendered; the host drops oversized keys (≤128 chars) and then always refreshes. |
344
+ | `viewWidth` | string | No | CSS length in `px` or `%` controlling the *caller's* pane in the split layout (e.g. `"260px"`, `"30%"`). Other units (`rem`, `em`, `vw`, `calc(...)`, etc.) are rejected to keep the host-side parser tight; invalid values silently fall back to the default split. The opened app's pane takes the remaining space. Only meaningful with `placement: "splitView"`. Useful when the caller is a fixed-width picker/sidebar and wants the opened app to take the rest of the screen. |
345
+ | `room` | tagged union | No | Flat-room mode for the opened app. One of: `{ kind: "self" }` (opened app owns its own roster, standalone); `{ kind: "inherit" }` (opened app joins the caller's room — DEFAULT when omitted); `{ kind: "explicit", storeTypeId, instanceId }` (opened app joins an explicit room). See [`<poe-tile>` Attributes](#attributes) for the equivalent HTML form. |
346
+
347
+
348
+ Inside an iframe, the app reads its actual rendered size with `window.innerWidth` / `window.innerHeight` (and `ResizeObserver` for changes) — the `viewWidth` value is a hint for the host layout, not something the opened app needs to read directly.
349
+
350
+ ### `Poe.tiles.prepareNewInstances({ instances })`
351
+
352
+ Declare `$bootstrapStore` genesis for one or more freshly-minted stores. **Await it BEFORE rendering the store (`<poe-tile>`) or `Poe.open`-ing it.** It only writes to durable per-instance client metadata (no network round-trip); the genesis actually runs when one of the stores is opened.
353
+
354
+ `instances` is an array of `BootstrapStoreSpec` entries for the whole gesture (the target plus any room/helper siblings). Each spec names `typeId`, `instanceId`, `room` (`self`, `rootGroup`, or `memberOf`, optional `parent`), an optimistic `PoeUserInfo[]` roster, and optional `roomMemberInstances`.
355
+
356
+ **Opening ANY one instance in the group creates ALL of them.** The opened store's session carries the persisted specs; the server resolves + validates the whole group's rosters and fans out `$bootstrapStore` genesis to every sibling (self-healing until all are pinned). You only need to open one.
357
+
358
+ Mint a fresh `instanceId` for each genesis. If an id can already name a store — you derive it from other values, or you prepare the same id again on a later open — pass `ensureExists: true`. The store still opens offline, but not as its creator: `store.isCreator` is false and `makeUniqueId()` waits for the first pull, so a second device never reuses the creator's unique-id namespace. Genesis still runs if the store is really new.
359
+
360
+ #### Creating a new room with seeded membership
361
+
362
+ Use `prepareNewInstances` to create a new instance in a NEW room whose membership is seeded from specs you supply — the "rematch" pattern. Mint a new instanceId yourself, declare the genesis, then open the instance with `room: { kind: "self" }` when it owns its own room. Build a `BootstrapStoreSpec` from your own `$users` / `$userInfo` tables (available offline):
363
+
364
+ ```javascript
365
+ // Rematch: same players, fresh game, fresh room.
366
+ const roster = await Poe.store.query(async (tx) => {
367
+ const members = await tx.table("$users").scan().values().toArray();
368
+ const userInfo = new Map(
369
+ (await tx.table("$userInfo").scan().values().toArray()).map((info) => [
370
+ info.userId,
371
+ info,
372
+ ]),
373
+ );
374
+ return members
375
+ // Drop removed members, and drop agent members (`agent_*`): the server
376
+ // resolves every seeded id through the central user directory, which
377
+ // agents are not in, so a listed agent is dropped from the new room. Re-add
378
+ // agents through the normal flow once the rematch opens.
379
+ .filter((m) => m.removedAt === undefined && !m.userId.startsWith("agent_"))
380
+ .map((m) => userInfo.get(m.userId))
381
+ .filter((info) => info !== undefined);
382
+ });
383
+ // Use the portable `generateUUID()` helper, not `crypto.randomUUID()` — the
384
+ // latter is unavailable on non-secure LAN / dev origins (common for local and
385
+ // mobile testing) and would throw before `Poe.open()` runs.
386
+ const newInstanceId = generateUUID();
387
+ const selfRef = { typeId: MY_TYPE_ID, instanceId: newInstanceId };
388
+ // 1. Declare genesis (writes durable client metadata only).
389
+ await Poe.tiles.prepareNewInstances({
390
+ instances: [
391
+ {
392
+ ...selfRef,
393
+ room: { type: "self" },
394
+ users: roster,
395
+ roomMemberInstances: [selfRef],
396
+ },
397
+ ],
398
+ });
399
+ // 2. Open the tile — this drives the genesis for the whole group.
400
+ await Poe.open({
401
+ typeId: MY_TYPE_ID,
402
+ instanceId: newInstanceId,
403
+ room: { kind: "self" },
404
+ openProps: { rematch: { players: roster.map((user) => user.userId) } },
405
+ });
406
+ ```
407
+
408
+ Semantics and rules:
409
+
410
+ - Every fresh store opened by the gesture needs a matching spec in `instances`. If you create a separate chat/room store plus an app store, include both: the room spec usually uses `room: { type: "self" }`, and the app spec uses `room: { type: "memberOf", room: roomRef }`.
411
+ - The caller must be included in each spec's `users`, and every listed user must already be an active member of the caller's room or the parent room. This is a same-membership primitive, not an invite primitive — to add NEW people afterward, use `Poe.room.pickMembers()`.
412
+ - Validation happens server-side when the request arrives. The server re-resolves profile data from the canonical user source, validates membership, and drops invalid seed entries into the rejected-bootstrap table instead of trusting client-supplied display data.
413
+ - **Works offline**: the seed survives reloads and long offline sessions. The kernel stores pending bootstrap specs in durable local metadata and replays creator context for the browser that created the instance until the server has applied the bootstrap.
414
+ - **Discovery is app-level.** Seeding gives users *access*; it does not put the new room in their sidebar. Announce it from a mutator (e.g. `notifyActivity` / `setTurn`) after opening, and pass the roster's display data via `openProps` so your UI can render players before the first sync.
415
+
416
+ #### Auto-replace semantics for `placement: "splitView"`
417
+
418
+ The split-view (right) pane has an owner. A subsequent `placement: "splitView"` call replaces it only when:
419
+
420
+ - the pane is empty, or
421
+ - the current pane was opened by a previous `placement: "splitView"` call (center-owned).
422
+
423
+ A pane the user opened manually from the host's UI (e.g. a "pin to side" menu) is treated as user-pinned and is preserved — the new call falls back to a plain forward navigation in the caller's pane and the user-pinned side is left alone. A plain `Poe.open()` (default `placement: "current"`) likewise leaves a user-pinned side pane intact.
424
+
425
+ ### `Poe.showTileLauncher()`
426
+
427
+ Ask the host manager to render the standard tile launcher. The host owns catalog browsing/search UI, mints the selected tile instance and child room ids, dispatches `recieveTileStarted` on the calling store, then opens the selected tile. Cancel resolves `null`.
428
+
429
+ ```typescript
430
+ const result = await Poe.showTileLauncher();
431
+ if (result) {
432
+ console.log("Started", result.tileTypeId, result.tileInstanceId);
433
+ }
434
+ ```
435
+
436
+ The calling app must call `Poe.setupStore()` before using this API — the call resolves your store to identify the caller, and throws without one.
437
+
438
+ Implement a store mutator named `recieveTileStarted` (spelling intentional) to persist the launch in your app:
439
+
440
+ ```typescript
441
+ type TileLauncherStartedInput = {
442
+ itemKey: string;
443
+ tileTypeId: string;
444
+ tileInstanceId: string;
445
+ room: { storeTypeId: string; instanceId: string };
446
+ parentRoom?: { storeTypeId: string; instanceId: string };
447
+ timestamp: number;
448
+ };
449
+ ```
450
+
451
+ For chat-style launchers, use `room` as the newly-created child room and validate `parentRoom` against the current store before writing any launch rows.
452
+
453
+ ### `Poe.users.openProfile({ userId, username? })`
454
+
455
+ Ask the host to open a user's profile UI, for example from "Forwarded from Alice" attribution in a chat message.
456
+
457
+ ```javascript
458
+ await Poe.users.openProfile({
459
+ userId: "u123",
460
+ username: "alice",
461
+ });
462
+ ```
463
+
464
+ | Parameter | Type | Required | Description |
465
+ |-----------|------|----------|-------------|
466
+ | `userId` | string | Yes | Stable user ID for the profile to open |
467
+ | `username` | string | No | Optional, tolerated hint only — the host resolves the profile from `userId`. The call never rejects on a missing `username`. Whether another user's profile can be opened is gated by the host's `viewOtherProfiles` capability (check `Poe.capabilities` before offering the affordance); the host drops an open it can't route. |
468
+
469
+ For an account you know only by its public handle (no user id — e.g. a model
470
+ lab from the model catalog's `owner.handle`), pass `{ handle }` instead; the
471
+ host navigates to its handle-resolving profile route:
472
+
473
+ ```javascript
474
+ await Poe.users.openProfile({ handle: "anthropic" });
475
+ ```
476
+
477
+ Prefer the `userId` form whenever you hold an id (roster rows, `$userInfo`):
478
+ handles are renameable, and the host resolves an id to the account's *current*
479
+ handle at open time.
480
+
481
+ This is a UI navigation request only. It does not grant access to private profile data or bypass host-side permissions.
482
+
483
+ ### `Poe.room.openInvitePicker()`
484
+
485
+ Ask the host to open its Add members invite surface for the calling app instance. Takes no parameters — the host resolves the caller's identity from the trusted RPC context (the app cannot forge it). The host resolves the caller's canonical room, lets the user add contacts to that room, and keeps share/copy invite links targeted at the calling tile instance.
486
+
487
+ ```javascript
488
+ await Poe.room.openInvitePicker();
489
+ ```
490
+
491
+ The call resolves after the host accepts the request to show the surface; it does not return selected contacts, added members, or copied-link status. Calling from the root app is rejected — the root app owns the invite UI directly and does not need an RPC hop.
492
+
493
+ The Add members surface also leads with the host's "Discoverability" setting, where each member chooses who can join the session without an invite: their network, their contacts, or only invited people. It shows only where a change can succeed (not in a DM, a feedback thread, or a multiplayer sandbox). The `Poe.room.pickMembers()` picker shows the same setting (see below). There is no separate API for it, and the app cannot read its value.
494
+
495
+ ### `Poe.room.openChat()`
496
+
497
+ Ask the host to reveal the chat for the calling tile's containing room. The method takes no parameters: the host derives the calling tile from trusted RPC context, resolves its canonical room, and opens chat in the layout-native surface (an accessory pane on wide manager layouts or a sheet on compact layouts). If that room chat is already visible, the request is a no-op that preserves its mounted state and scroll position. Calls from a tile that is not inside a chat room are ignored.
498
+
499
+ ```javascript
500
+ await Poe.room.openChat();
501
+ ```
502
+
503
+ Calling from the root app is rejected because the root already owns the chat surface.
504
+
505
+ ### `Poe.room.pickMembers()`
506
+
507
+ Open the host's room member picker and return the selected room members. Existing room members are just selected. Child rooms also show active members of the parent group in a separate **People in the group** section unless the child has a live local `$users` row for that user (someone who left the child room stays pickable). Picking one adds them to the child room before returning them, with `source: "existingRoomMember"` and `addedToRoom: true`; your tile's own `$users` lists them once the room passes the add on to its tiles. Contacts are shown by default; pass `addFromContacts: false` to restrict the picker to members of the room and its group. Selecting a contact adds them to the room before returning them. If the calling app is in a `dm-*` room, selecting contacts moves the app to a 1:1 DM or a new group room as needed instead of adding people to the frozen DM membership.
508
+
509
+ ```typescript
510
+ const result = await Poe.room.pickMembers({
511
+ title: "Choose player",
512
+ selection: { max: 1 },
513
+ // `excludeUserIds` hides rows entirely — e.g. drop the current user, since a
514
+ // "Sit here" affordance already covers seating yourself.
515
+ excludeUserIds: [currentUserId].filter(Boolean),
516
+ // Already-seated players stay visible but render as "Playing" and are not
517
+ // selectable. Pass them as `playingUserIds`, NOT `excludeUserIds` — excluded
518
+ // rows are filtered out before the "Playing" marker is applied, so seats put
519
+ // in `excludeUserIds` would be hidden instead of shown as taken.
520
+ playingUserIds: [game.whiteUserId, game.blackUserId].filter(Boolean),
521
+ });
522
+
523
+ const user = result?.users[0];
524
+ if (user) {
525
+ await store.mutate.assignSeat({
526
+ seatId: "black",
527
+ userId: user.userId,
528
+ notify: "default",
529
+ now: Date.now(),
530
+ });
531
+ }
532
+ ```
533
+
534
+ Use `excludeUserIds` to hide users the app does not want selectable. Use `playingUserIds` to keep a room member visible but mark them as already `Playing`; those rows are not selectable. Contacts and the share/copy invite-link footer are both shown by default. Above the link, the picker shows the host's "Discoverability" setting for the session (the same one `Poe.room.openInvitePicker()` shows), so a player choosing opponents can also let their network or contacts join without an invite. Pass `addFromContacts: false` to restrict selection to members of the room and its group (a group member is still added to the room when picked), or `shareLink: false` to hide the link footer and the "Discoverability" setting.
535
+
536
+ The result is `null` when the user cancels. Otherwise it includes the resolved room ref plus user snapshots:
537
+
538
+ ```typescript
539
+ type RoomPickMembersResult = {
540
+ room: { storeTypeId: string; instanceId: string };
541
+ users: Array<{
542
+ userId: string;
543
+ username: string;
544
+ displayName: string;
545
+ profilePicture: string;
546
+ source: "existingRoomMember" | "addedContact";
547
+ addedToRoom: boolean;
548
+ }>;
549
+ };
550
+ ```
551
+
552
+ Picked contacts come back with `source: "addedContact"`; everyone else comes back with `source: "existingRoomMember"`. A pick from the parent-room section is added to this room first, so it comes back with `addedToRoom: true`. The promise resolves only once this tile's own `$users` lists every picked user (bounded at about 10 seconds), so a mutation that seats them right after it resolves passes `assertRoomMember`.
553
+
554
+ Treat the result as UI input, not authority. Mutators that write app state for a picked user should call `assertRoomMember(ctx, { userId })` on the server-authoritative pass before committing the assignment.
555
+
556
+ ### `Poe.room.tileEnd(input)`
557
+
558
+ Ask the host to show the standard end-of-tile UI for a persisted leaderboard. The host derives the calling tile instance from trusted RPC context, subscribes to `getLeaderboard(ctx, { leaderboardId })` in that instance's synced store, and hydrates profiles. Ranked entries render first; every other active human room member is appended without a score in room join order, while agents are excluded. Optimistic mutator writes appear immediately and confirmed updates remain live while the sheet is open.
559
+
560
+ Because the end sheet opens immediately, a game must not call `tileEnd()` in the same moment it detects a terminal result. First keep the playfield visible long enough to finish the decisive animation and explain why the player won or lost, then leave a readable beat before calling this API. See [game UX best practices](./game-ux-best-practices.md) for the terminal-reveal sequence.
561
+
562
+ Persist scores and presentation from a tile-defined mutator with `setLeaderboard(...)` or `setLeaderboardScore(...)`; `tileEnd()` carries only the board id plus optional actions/round behavior. Use the same `leaderboardId` for writes, `getLeaderboard(...)` reads, and this call. If your page shows a persistent leaderboard without opening tile-end, call [`Poe.room.setShareLeaderboardId()`](#poe-room-setshareleaderboardid-leaderboardid) instead.
563
+
564
+ Leaderboard scores are numeric: `setLeaderboard` accepts `players: Record<string, number>` or `everyone: number`, never `"WON"`, `"LOST"`, or `"TIE"`. Choose your tile's numeric scoring rules explicitly; the SDK does not convert outcomes into scores. To show an outcome label, use `setLeaderboardScore` with a numeric `score` and a separate `displayScore` (for example, `{ userId, score: 1, displayScore: "Won" }`). For a current-round result that can decrease, use `mode: "replace"`; the default `"merge"` keeps each user's best score.
565
+
566
+ ```typescript
567
+ const result = await Poe.room.tileEnd({ leaderboardId: "default" });
568
+ if (result.playAgain) {
569
+ await store.mutate.startRound({});
570
+ }
571
+ ```
572
+
573
+ ```typescript
574
+ await store.mutate.finishRun({
575
+ score: finalScore,
576
+ });
577
+
578
+ await Poe.room.tileEnd({
579
+ leaderboardId: "daily",
580
+ });
581
+ ```
582
+
583
+ ```typescript
584
+ type RoomTileEndInput = {
585
+ leaderboardId: string;
586
+ round?: string;
587
+ dismissable?: boolean;
588
+ actions?: {
589
+ nudge?: boolean;
590
+ playAgain?: boolean;
591
+ review?: { label: string };
592
+ };
593
+ };
594
+
595
+ type RoomTileEndResult = {
596
+ // `true` only when `outcome === "playAgain"` (kept for back-compat).
597
+ playAgain: boolean;
598
+ // How the end UI settled:
599
+ // - "playAgain" — user tapped Play Again
600
+ // - "review" — user tapped your `actions.review` button (see below)
601
+ // - "closed" — user dismissed otherwise (picked another tile, navigated away)
602
+ // - "dismissed" — superseded programmatically via Poe.room.dismissTileEnd()
603
+ outcome: "playAgain" | "review" | "closed" | "dismissed";
604
+ };
605
+ ```
606
+
607
+ `dismissable` defaults to `true`: the overlay shows an on-frame close button (and
608
+ Escape dismisses) so the player can return to the tile. Pass `dismissable: false`
609
+ for a **terminal** tile-end where nothing behind the overlay is actionable — e.g. a
610
+ score-chase run that is already over — so a stray close can't strand the player on
611
+ a dead post-run screen. The overlay's own actions (Play Again, Try Next) and the
612
+ host chrome's back button remain the exits; programmatic closes and
613
+ `dismissTileEnd()` are unaffected.
614
+
615
+ `bestScore`, `label`, `unit`, and optional per-entry `displayScore` / `markdown`
616
+ come from the persisted leaderboard row. Labels are limited to 40 characters;
617
+ each unit form is limited to 20 characters. When provided, the label and both
618
+ unit forms must contain a non-whitespace character; blank or whitespace-only
619
+ values are rejected at the tile-end API boundary.
620
+
621
+ Each entry may also carry a `markdown` string (≤ 2048 chars), passed to
622
+ `setLeaderboardScore(ctx, { …, markdown })`. The host renders it — sanitized
623
+ (raw HTML stripped, then run through DOMPurify, images dropped), with single
624
+ newlines as line breaks — as a **detail column to the right** of that player's
625
+ name/score, so tall content (e.g. a Wordle-style attempt grid) uses horizontal
626
+ space instead of stacking below and inflating the row. It is display-only and
627
+ never affects ranking. Keep it compact and presentational (it is not a document
628
+ surface), and never put secrets or user-identifying URLs in it (it is shown to
629
+ every room member).
630
+
631
+ When a row has `markdown`, its `displayScore` moves under the player's name (on
632
+ the left). `displayScore` may be **multi-line** (rendered as stacked lines), so
633
+ you can show a primary score plus a secondary line — e.g. a guess count over a
634
+ streak:
635
+
636
+ ```typescript
637
+ await setLeaderboardScore(ctx, {
638
+ leaderboardId: "daily",
639
+ userId: ctx.userId,
640
+ score: guessCount,
641
+ bestScore: "lowest",
642
+ displayScore: `${guessCount}/6\n🔥 Streak ${streak}`, // stacked under the name
643
+ markdown: "🟩⬜⬜🟨⬜\n🟩🟩⬜⬜⬜\n🟩🟩🟩🟩🟩", // grid, to the right
644
+ });
645
+ ```
646
+
647
+ ### Where a board is stored: `sortKey`
648
+
649
+ Board rows are stored **always-loaded** by default, which means every board your
650
+ app writes is delivered on every pull. That is what makes `getLeaderboard(ctx,
651
+ { leaderboardId })` safe to call from any surface at any time, so most apps
652
+ should leave it alone.
653
+
654
+ Pass a `sortKey` only when you deliberately want boards **paged in** — a store
655
+ with many boards, or boards large enough that shipping them all on every pull is
656
+ the wrong trade — and add a `pullWindows` entry to your schema that covers the
657
+ keys you pick:
658
+
659
+ ```typescript
660
+ await setLeaderboardScore(ctx, {
661
+ leaderboardId: `season-${seasonId}`,
662
+ sortKey: `boards/${seasonId}`, // paged in by a "boards" pull window
663
+ userId: ctx.userId,
664
+ score,
665
+ });
666
+ ```
667
+
668
+ Two rules if you do. Keep the `sortKey` **stable per board** — it is the row's
669
+ storage position, so changing it moves the row and every write would re-key it.
670
+ And make sure any board a surface can open is inside a window that reaches it:
671
+ a board outside the delivered window reads as an **empty board**, not as
672
+ "still loading", and synced-store does not backfill a row that fell past the
673
+ window's byte budget on a later pull. Only *windowed* reads are sortKey-sensitive
674
+ this way — `getLeaderboard(...)` from a mounted store. Share links are not: the
675
+ invite page reads the board by exact `(table, id)` identity, so a link minted
676
+ with `Poe.room.setShareLeaderboardId` resolves a paged board fine. If you are not
677
+ sure you need this, you do not — omit `sortKey`.
678
+
679
+ `actions.playAgain: false` hides the Play again button for tiles with no
680
+ meaningful replay (a daily puzzle, a one-shot). `actions.review` adds a
681
+ tile-owned review button (label required, ≤ 40 chars — e.g. "Watch replay",
682
+ "View board"). When the user taps it the overlay closes and the promise
683
+ resolves with `outcome: "review"`; show your own review surface (the final
684
+ board, a step-through replay) with an in-tile way back, and call
685
+ `Poe.room.tileEnd()` again with the same leaderboard id when the user is done so
686
+ they return to the end screen:
687
+
688
+ ```typescript
689
+ const result = await Poe.room.tileEnd({
690
+ leaderboardId: "replay-scores",
691
+ actions: { review: { label: "Watch replay" } },
692
+ });
693
+ if (result.outcome === "playAgain") startNewRound();
694
+ else if (result.outcome === "review") openReplay(); // re-call tileEnd() on close
695
+ ```
696
+
697
+ `actions.nudge: true` shows a Nudge control for each active human member who
698
+ has no score on this board. A member can nudge the same person once every 24
699
+ hours per existing board. Before the first score creates a board, all
700
+ not-yet-created boards share one 24-hour limit for each sender and target. This
701
+ prevents fabricated board IDs from bypassing the cooldown. Only enable this for
702
+ a board that is still meaningfully playable: the platform intentionally does
703
+ not know whether an app-owned board is current, archived, or evergreen. The
704
+ option defaults to `false`.
705
+
706
+ The optional `round` is an app-owned id for this terminal round (e.g. the run's
707
+ start timestamp or a round id from your synced store). Pass it so a later
708
+ `Poe.room.dismissTileEnd({ supersedesRound })` can target exactly this overlay.
709
+ Keep it short — `round` (and `supersedesRound`) are rejected at ingestion if they
710
+ exceed 256 characters, so don't pass a serialized game state as the id.
711
+
712
+ When the user chooses another tile from the end UI, the host creates the rematch on the device after local synced-store hydration has supplied the exact roster and room refs: it reads cached/external `$$system.room`, `$users`, and `$userInfo`, mints a fresh room and instance, seeds the new room with the human players from the round, then opens the selected tile, unmounts the current tile, and resolves `{ playAgain: false }`. No server round-trip is needed for the end overlay or rematch creation itself, so the seeded room is durable across reloads and reconnects when the device is offline after creation. Agent players are not carried into the rematch room — a new round adds its own agents. If the current tile is already in a child room, the new room is a sibling; otherwise the current room becomes the parent. Choosing Play Again resolves `{ playAgain: true }` without navigating.
713
+ For score payloads, the host displays scored active humans' names and profile pictures ranked by the leaderboard settings, followed by unscored active humans as blank rows in room join order. `{ everyone: score }` is shown as a team score for all active players.
714
+
715
+ ### `Poe.room.setShareLeaderboardId(leaderboardId)`
716
+
717
+ Tell the host which tile-owned leaderboard should be used when the user copies or shares the current page's invite link. The host derives the calling tile instance from trusted RPC context, so tiles pass only the leaderboard id. The manager applies the setting only while that tile instance is the visible current page; route changes clear it.
718
+
719
+ Use this for pages that show a persistent leaderboard but do not open the tile-end overlay:
720
+
721
+ ```typescript
722
+ await store.mutate.submitScore({ score });
723
+ await Poe.room.setShareLeaderboardId("daily");
724
+ ```
725
+
726
+ ```typescript
727
+ Poe.room.setShareLeaderboardId(leaderboardId: string): Promise<void>;
728
+ ```
729
+
730
+ `leaderboardId` is app-owned, bounded, and should match the id you use with `setLeaderboard(ctx, ...)`, `setLeaderboardScore(ctx, ...)`, or `getLeaderboard(ctx, ...)`. Use `"default"` for the default board.
731
+
732
+ ### `Poe.room.dismissTileEnd(opts?)`
733
+
734
+ Programmatically dismiss **this client's** active tile-end overlay (instead of waiting for the user to tap). The calling tile instance is derived from trusted RPC context; you can only dismiss your own instance's overlay. The pending `Poe.room.tileEnd()` promise on this client resolves with `outcome: "dismissed"`.
735
+
736
+ This is the building block for a **shared-instance team game** where everyone plays one persistent instance: when one player advances the shared round, every other client clears its now-stale overlay on its own. It is per-client — the "everyone's screen clears" effect comes from each client calling this in reaction to shared synced-store state, not from a broadcast.
737
+
738
+ ```typescript
739
+ type RoomDismissTileEndInput = {
740
+ // Dismiss ONLY if the active overlay's `round` equals this (so a delayed
741
+ // call can't close a newer overlay). Omit to dismiss the active overlay
742
+ // unconditionally (simple single-round apps).
743
+ supersedesRound?: string;
744
+ };
745
+
746
+ Poe.room.dismissTileEnd(opts?: RoomDismissTileEndInput): Promise<void>;
747
+ ```
748
+
749
+ Resolves once the host handles the dismiss (no-op if no matching overlay is showing); rejects if no host supports dismissal or if called from the root app.
750
+
751
+ Typical shared-game pattern — tag the round on `tileEnd`, then dismiss when your synced state shows a new round is live:
752
+
753
+ ```typescript
754
+ // Install the dismiss watcher BEFORE awaiting tileEnd: the await blocks until
755
+ // this client's overlay settles, so a watcher registered AFTER it resolves is
756
+ // too late — there is no overlay left to dismiss. When the shared round advances
757
+ // (a peer started the next round), dismiss our now-stale overlay; tear the
758
+ // watcher down in `finally` once tileEnd has settled.
759
+ const unsubscribe = store.subscribe(
760
+ (tx) => tx.table("game").get("game"),
761
+ (game) => {
762
+ if (game?.round === finishedRoundId) return;
763
+ void Poe.room.dismissTileEnd({ supersedesRound: finishedRoundId });
764
+ },
765
+ );
766
+ try {
767
+ // Every client reports the team result tagged with the finished round id.
768
+ const result = await Poe.room.tileEnd({ leaderboardId: "team", round: finishedRoundId });
769
+ if (result.outcome === "playAgain") restartIfStillCurrent(finishedRoundId); // generation-guarded
770
+ // outcome "dismissed" / "closed" → another client drove it, or the user left; do nothing.
771
+ } finally {
772
+ unsubscribe();
773
+ }
774
+ ```
775
+
776
+ Make the restart **generation-guarded / idempotent** (restart only if the just-finished round is still current) — when several players tap Play Again at once, the platform does not serialize the restarts.
777
+
778
+ ### `Poe.agents.create({ agentId, name, model, tools?, room? })`
779
+
780
+ Create a new agent owned by the calling user. You mint the agent's `agentId` (an `agent_<uuid>`) and pass it as the **idempotency key**; the trusted host runs the whole creation server-side in one round-trip: it claims the per-creator-unique `name` in the caller's agents registry, initializes the agent's store with the given `model` and `tools`, and — when you pass a `room` — adds the new agent to that room in the same call.
781
+
782
+ ```typescript
783
+ // Use the portable `generateUUID()` helper, not `crypto.randomUUID()` — the
784
+ // latter is unavailable on non-secure LAN / dev origins (common for local and
785
+ // mobile testing).
786
+ const agentId = `agent_${generateUUID()}`;
787
+ const result = await Poe.agents.create({
788
+ agentId, // client-minted idempotency key — reuse it across retries
789
+ name: "Code Reviewer",
790
+ model: "anthropic/claude-sonnet-4-6",
791
+ tools: ["read_file"], // restricts the agent to these system tools (order ignored)
792
+ room: { typeId: "chat", instanceId: roomId }, // optional: create + add in one call
793
+ });
794
+ ```
795
+
796
+ `agentId`, `name`, and `model` are required (`name`/`model` are trimmed by the host); `name` is unique among the calling user's agents (case-insensitive). `tools` is the system-tool allow-list — an **explicit grant list** (deny-by-default): the agent may use exactly the tools named, and omitting it (or passing `[]`) gives the agent **no system tools** (the default for auto-created agents; grant tools later via a config edit). Tool order doesn't matter — it's treated as a set. `room` is optional; when supplied you must be a live member of that room (direct-message rooms are refused), and the room is validated before the agent is created so a bad room never leaves an orphaned agent.
797
+
798
+ `modelParams` is optional: the agent's **default model params** for `model` as `paramId → value` (for example `{ output_effort: "high" }` or `{ thinking_visibility: true }`), stored on the agent and applied to every run on that model over the catalog defaults (a stored value overrides its default), so a default that later moves in the catalog still moves for any param the agent never touched. Only ids the platform honors are accepted (`web_search` is not storable), and a stored value that later stops matching the model's options falls back to the catalog default instead of failing the run. The params belong to the agent's model: changing the model through the edit flow clears them unless the same edit supplies new ones. Omitted or `{}` means catalog defaults.
799
+
800
+ **The `agentId` is the idempotency key.** Mint it once per logical create intent and **reuse it across retries** (don't generate a fresh id on retry, or you lose idempotency). Calling `create` again with the same `agentId` returns your existing agent and **ignores the rest of the payload** — `reused` is `true` when the existing agent was returned and `false` when a fresh one was minted; the optional `room` add still applies on reuse. So a retry (or a double-submit) safely resolves to the same agent. Config changes go through the edit flow, never `create`. The promise rejects only on a *real* conflict — a **new** `agentId` whose `name` is already taken by a different agent — or when `modelParams` carries an id the platform does not honor or a value out of range, or when the room is invalid or initialization fails.
801
+
802
+ The returned `agentId` echoes the id you minted (an `agent_…` id usable as a room member id), and `addedToRoom` reports whether the optional `room` add succeeded. Agents join rooms through the membership APIs (below); apps never mount or read the agent's own store.
803
+
804
+ ### `Poe.agents.delete({ agentId })`
805
+
806
+ Delete one of your agents outright. The trusted host runs the whole cascade server-side: it removes the agent from **every** room it belongs to, releases its name back to your registry, purges its conversation history, and finally destroys the agent's own store (its config and memory). Creator-only.
807
+
808
+ **This is irreversible.** There is no undo and no tombstone to restore from — confirm with the user before calling it.
809
+
810
+ ```typescript
811
+ const result = await Poe.agents.delete({ agentId });
812
+ if (result.failedRooms.length > 0 || result.cleanupErrors.length > 0) {
813
+ // Not a failure — the delete is INCOMPLETE. Call it again to finish; every
814
+ // step is idempotent, so a retry re-attempts only what is left.
815
+ showRetryPrompt(result);
816
+ }
817
+ ```
818
+
819
+ **The promise resolving does not mean the agent is gone.** The whole cascade is idempotent and retryable, so a partial run reports what it finished instead of throwing:
820
+
821
+ - `roomsRemoved` — rooms the agent's membership was removed from this call.
822
+ - `failedRooms` — rooms whose removal failed. Non-empty means the agent is mid-delete: its name is not released and it can no longer be used, but it is not deleted either.
823
+ - `registryReleased` — whether the name claim was tombstoned.
824
+ - `agentStoreDestroyed` — whether the agent's own store is gone. This is the **last** step and only runs when everything before it succeeded.
825
+ - `cleanupErrors` — one message per step that did not complete.
826
+
827
+ Check those fields and re-call `delete` with the same `agentId` to finish an incomplete delete. The promise **rejects** only when the request itself failed — you are not the agent's creator, or the `agentId` is malformed. Deleting an already-deleted agent is a no-op.
828
+
829
+ ### `Poe.agents.addToRoom({ agentId, typeId, instanceId })` / `Poe.agents.removeFromRoom({ agentId, typeId, instanceId })`
830
+
831
+ Add or remove an existing agent as a member of a room. Use `addToRoom` to bring one of your agents into a room you're a live member of; use `removeFromRoom` to take it out. Both resolve once the membership change is committed.
832
+
833
+ ```typescript
834
+ await Poe.agents.addToRoom({ agentId, typeId: "chat", instanceId: roomId });
835
+ await Poe.agents.removeFromRoom({ agentId, typeId: "chat", instanceId: roomId });
836
+ ```
837
+
838
+ `addToRoom` requires that you are the agent's creator **and** a live member of the room; `removeFromRoom` is creator-only.
839
+
840
+ ### `Poe.agents.listTools()`
841
+
842
+ List the first-party agent system-tool catalog — the `{ id, displayName, description }` metadata for every built-in system tool an agent can be granted. Use it to render tool ids and display names in your own agent-building UI without hardcoding the list.
843
+
844
+ ```typescript
845
+ const tools = await Poe.agents.listTools();
846
+ // e.g. [{ id: "calculator", displayName: "Calculator", description: "Evaluates arithmetic expressions." }]
847
+
848
+ // The ids are exactly what `Poe.agents.create({ tools })` accepts:
849
+ await Poe.agents.create({
850
+ name: "Mathbot",
851
+ model: "anthropic/claude-sonnet-4-6",
852
+ tools: tools.map((tool) => tool.id),
853
+ });
854
+ ```
855
+
856
+ Read-only public metadata — it takes no arguments, requires no permissions, and returns the same catalog for everyone.
857
+
858
+ ### `Poe.agents.listTemplates()`
859
+
860
+ List the first-party agent-template catalog — the preset agent configurations (name, model, and tool grant) that pre-fill the agent-create form. Use it to render a template picker in your own agent-building UI without hardcoding the presets.
861
+
862
+ ```typescript
863
+ const templates = await Poe.agents.listTemplates();
864
+ // e.g. [{
865
+ // id: "math-helper",
866
+ // displayName: "Math Helper",
867
+ // description: "Works through arithmetic step by step using a calculator tool.",
868
+ // iconEmoji: "🧮",
869
+ // config: { suggestedName: "Math Helper", model: "anthropic/claude-sonnet-4-6", tools: ["calculator"] },
870
+ // }]
871
+
872
+ // A template's `config` is exactly what `Poe.agents.create` accepts — instantiation is a copy:
873
+ const template = templates.find((t) => t.id === "math-helper");
874
+ if (template) {
875
+ await Poe.agents.create({
876
+ name: template.config.suggestedName,
877
+ model: template.config.model,
878
+ // `config.tools` is `readonly string[]`; spread into a mutable copy for the create input.
879
+ tools: [...template.config.tools],
880
+ });
881
+ }
882
+ ```
883
+
884
+ Read-only public metadata — it takes no arguments, requires no permissions, and returns the same catalog for everyone. Picking a template only pre-fills the create form; there is no live template↔agent link after creation.
885
+
886
+ ### `Poe.agents.listMine()`
887
+
888
+ List **your own** live agents — the `{ agentId, name, model }` metadata for every agent you have created. Use it to render a picker of the caller's agents, or to resolve one of your agents by name to its `agentId` so you can add it to a room with `Poe.agents.addToRoom`.
889
+
890
+ ```typescript
891
+ const mine = await Poe.agents.listMine();
892
+ // e.g. [{ agentId: "agent_ab12…", name: "Math Helper", model: "anthropic/claude-sonnet-4-6" }]
893
+
894
+ // Resolve a name to an agentId (case-insensitive), then add it to a room:
895
+ const match = mine.find((a) => a.name.trim().toLowerCase() === "math helper");
896
+ if (match) {
897
+ await Poe.agents.addToRoom({ agentId: match.agentId, typeId: "chat", instanceId: roomId });
898
+ }
899
+ ```
900
+
901
+ Caller-scoped: it lists **only your own** agents (listing your own is not a permission escalation), so there is no way to enumerate or add another user's agents by a guessed name — always add by the opaque `agentId`.
902
+
903
+ ### `Poe.track(event, properties?)`
904
+
905
+ Send a fire-and-forget analytics event through the host-owned analytics pipeline.
906
+
907
+ ```javascript
908
+ Poe.track("tile_opened", { tileType: "chat" });
909
+ Poe.track("space_invite_sent", { channel: "share-link" });
910
+ ```
911
+
912
+ | Parameter | Type | Required | Description |
913
+ |-----------|------|----------|-------------|
914
+ | `event` | string | Yes | Event name matching `/^[a-z0-9_$-]+$/i`, up to 128 characters |
915
+ | `properties` | object | No | JSON-serializable property bag, up to 100 top-level keys and 32 KB serialized |
916
+
917
+ `Poe.track()` returns immediately and does not report whether an event was forwarded. The SDK, host kernel, and first-party relay all validate the envelope; invalid events, reserved keys, PII-looking keys, oversized payloads, anonymous users, or disabled analytics are silently dropped.
918
+
919
+ ### `Poe.openExternalUrl({ url })`
920
+
921
+ Ask the host to open a web link. This is the only way an app can open a link outside itself — the iframe sandbox has no `allow-popups`, so `window.open` and `target="_blank"` are blocked before the host can see them.
922
+
923
+ ```javascript
924
+ await Poe.openExternalUrl({ url: "https://example.com/rules" });
925
+ ```
926
+
927
+ | Parameter | Type | Required | Description |
928
+ |-----------|------|----------|-------------|
929
+ | `url` | string | Yes | An http(s) URL, up to 8192 characters |
930
+
931
+ The host decides how the link opens. A link back into the platform itself (same origin as the host and matching a real platform page — for example an invite link shared in chat) navigates in place, like any other in-app navigation, with no confirmation. Any other link shows the user a confirmation with the destination host before anything opens; the user can decline. When the user confirms, the link opens in a new tab on the web, or in the platform in-app browser inside the mobile apps. The returned promise resolves when the request is accepted (not when the user confirms or navigation happens) and rejects for invalid URLs (non-http(s) schemes, over-length).
932
+
933
+ ### `Poe.openBugReport({ debugId })`
934
+
935
+ Opens the host’s editable bug-report form with the debug ID and host-stamped tile/instance IDs. It does **not** submit feedback; the user reviews and sends the report. Keep original diagnostics in durable storage under that ID, and show product-owned error copy in the UI.
936
+
937
+ `debugId` must be 1–256 ASCII letters, digits, or `_./:-` characters. Use `Poe.has("openBugReport")` during rollout; on older hosts, tell the user to include the ID in **Report a bug** from the account menu. Calls reject for invalid input, a host that cannot open the form within 30 seconds, or a non-browser environment.
938
+
939
+ ### `<poe-tile>` Custom Element
940
+
941
+ ```html
942
+ <poe-tile type-id="my-game" instance-id="lobby-123"></poe-tile>
943
+ ```
944
+
945
+ A custom HTML element that renders a child app inline. This is how one app embeds and renders another app inside itself.
946
+
947
+ The child app runs in a sandboxed iframe within the element's shadow DOM. The embedded app calls `Poe.setupStore()` normally — it doesn't know it's embedded.
948
+
949
+ A `<poe-tile>` cannot embed a first-party Poe tile, such as chat, an agent console or Creator. The mount fails with "can only be opened by the root app; use Poe.open". Open those tiles with [`Poe.open()`](#poe-open-typeid-instanceid-openprops-anchorsortkey-placement-viewwidth), for example with `placement: "splitView"` to show one beside your app.
950
+
951
+ To use `<poe-tile>`, register it in your entry file:
952
+
953
+ ```javascript
954
+ import { registerPoeTileElement } from "joiner-sdk/v1/client.js";
955
+ registerPoeTileElement(environment);
956
+ ```
957
+
958
+ #### Attributes
959
+
960
+ | Attribute | Type | Required | Description |
961
+ |-----------|------|----------|-------------|
962
+ | `type-id` | string | Yes | The app type ID to embed (max 128 characters) |
963
+ | `instance-id` | string | Yes | Full instance ID for the child app's store. Callers construct this themselves, typically as `${parentInstanceId}-${childHandle}`. The same instance ID reconnects to the same store data. (max 256 characters) |
964
+ | `open-props` | string (JSON) | No | JSON-serializable data to pass to the child app at open time (max 10 MB). The child reads it via `Poe.getOpenProps()`. |
965
+ | `room` | `"self" \| "inherit" \| "explicit"` | No | Flat-room mode. `"inherit"` (default when omitted) — child joins the DOM-parent's room. `"self"` — child owns its own `$users` roster (standalone). `"explicit"` — child joins the room identified by paired `room-type-id` + `room-instance-id` attrs. |
966
+ | `room-type-id` | string | When `room="explicit"` | Store type ID of the explicit room (max 5,000 characters). |
967
+ | `room-instance-id` | string | When `room="explicit"` | Store instance ID of the explicit room (max 5,000 characters). |
968
+ | `opener-store-type-id` | string | No | *Logical* parent identity (type ID half) when this `<poe-tile>` is mounted by the root app on behalf of a `Poe.open` call. Lets `room="inherit"` resolve against the opener's `$$system:room` instead of the DOM-parent's (manager). Honored only by the root app — untrusted iframes stamping this on their own embedded `<poe-tile>` have no effect. (max 5,000 characters) |
969
+ | `opener-store-instance-id` | string | No | Pairs with `opener-store-type-id`. (max 5,000 characters) |
970
+ | `focus-on-mount` | boolean attribute | No | Focus the child iframe as soon as it mounts (including remounts and reloads), so keyboard-driven content receives key events without the user first clicking inside it. Set it only on the primary tile in view. It never steals focus from a focused text entry or from another `<poe-tile>`, nor — when the host document is itself framed inside another page and does not currently hold focus — from an ancestor document (a nested tile's content waits for the user's first click into it); a host-hidden tile defers the focus until it is revealed. When parent chrome that took focus (an overlay, a results sheet) closes and control returns to the still-mounted tile, call the element's `focusChild()` method to hand keyboard focus back — same opt-in and never-steal guards as the mount pass. |
971
+
972
+ To mount a `<poe-tile>` with an `instance-id` that has **never existed before**, first call [`Poe.tiles.prepareNewInstances`](#poe-tiles-preparenewinstances-instances) to declare its genesis, then render the element. There is no `is-new` attribute: the kernel reads the prepared spec from durable client metadata when the store mounts, treats it as a fresh creator (skips the IndexedDB probe and the server-`clientOrdinal` wait), and pins it via `$bootstrapStore`.
973
+
974
+ #### Visibility
975
+
976
+ **`document.visibilityState` is not enough.** The platform keeps your iframe mounted while it draws its own chrome over you — the room chat sheet opening on top of a running game, the results leaderboard your own `Poe.room.tileEnd()` call summons, a modal, an app switcher. Nothing in the DOM changes: `document.visibilityState` stays `"visible"`, your iframe keeps its size, and no focus event arrives. Every timer, animation frame, and scored countdown keeps running behind the cover unless you pause it.
977
+
978
+ `isPoeTileForeground()` is the answer to "is my app actually on screen". It is false when either the host covers you OR the browser page is hidden:
979
+
980
+ ```javascript
981
+ import {
982
+ isPoeTileForeground,
983
+ subscribePoeTileForegroundState,
984
+ } from "joiner-sdk/v1/client.js";
985
+
986
+ if (isPoeTileForeground()) startCountdown();
987
+
988
+ const unsubscribe = subscribePoeTileForegroundState((foreground) => {
989
+ if (foreground) resumeCountdown();
990
+ else pauseCountdown();
991
+ });
992
+ ```
993
+
994
+ `subscribePoeTileForegroundState` fires on transitions only — read `isPoeTileForeground()` for the current value — and returns an unsubscribe function.
995
+
996
+ The listener also receives a `detail` object if you want to know *why* the app went dark. Most apps ignore it and just pause:
997
+
998
+ ```javascript
999
+ subscribePoeTileForegroundState((foreground, { reason }) => {
1000
+ if (foreground) return resume(); // reason: "visible"
1001
+ if (reason === "covered") return pauseButStayWarm();
1002
+ teardown(); // reason: "backgrounded"
1003
+ });
1004
+ ```
1005
+
1006
+ `"covered"` is platform chrome drawn over your still-running iframe; `"backgrounded"` is the browser's own page visibility, which also throttles your timers and stops `requestAnimationFrame`. The listener does not re-fire when only the reason changes (covered, then also backgrounded) — the boolean is the contract.
1007
+
1008
+ **Any timed, scored, or animated app should pause on this.** A timer that keeps counting behind chat is a wrong score, not just wasted CPU.
1009
+
1010
+ Being covered does not change your app's standing with the platform: presence keeps ticking (other players still see you here) and your store keeps syncing. It only tells you nobody is looking.
1011
+
1012
+ `isPoeTileHostVisible()` / `subscribePoeTileHostVisibility()` are the narrower pair — host cover only, ignoring browser page visibility. Use them for "has the user actually seen this content" bookkeeping where a backgrounded tab is handled separately; prefer the foreground pair for anything you want to pause.
1013
+
1014
+ If your app itself hosts a child `<poe-tile>` and covers it with your own chrome, tell the child:
1015
+
1016
+ ```javascript
1017
+ import {
1018
+ setChildPoeTileHostCovered,
1019
+ setChildPoeTileHostVisible,
1020
+ } from "joiner-sdk/v1/client.js";
1021
+
1022
+ // Your chrome is drawn OVER the child, but the user is still "in" it.
1023
+ setChildPoeTileHostCovered(childPoeTileElement, true);
1024
+ setChildPoeTileHostCovered(childPoeTileElement, false);
1025
+
1026
+ // The child is no longer the surface the user is on at all.
1027
+ setChildPoeTileHostVisible(childPoeTileElement, false);
1028
+ setChildPoeTileHostVisible(childPoeTileElement, true);
1029
+ ```
1030
+
1031
+ Both reach the child as the same `isPoeTileForeground() === false`. Prefer `setChildPoeTileHostCovered` when the user is still in that child: `hostVisible: false` additionally tells the platform the child is no longer attended, which pauses its presence heartbeat and foreground store pulls.
1032
+
1033
+ Foreground-only work — animation loops, physics, polling, audio, WebGL rendering — should gate its scheduling on the same signal:
1034
+
1035
+ ```javascript
1036
+ let foreground = isPoeTileForeground();
1037
+ let raf = 0;
1038
+
1039
+ const unsubscribe = subscribePoeTileForegroundState((next) => {
1040
+ foreground = next;
1041
+ if (foreground) scheduleRenderLoop();
1042
+ });
1043
+
1044
+ function scheduleRenderLoop() {
1045
+ if (raf !== 0 || !foreground) return;
1046
+ raf = requestAnimationFrame(renderLoop);
1047
+ }
1048
+
1049
+ function renderLoop() {
1050
+ raf = 0;
1051
+ if (!foreground) return;
1052
+ // Do foreground-only work.
1053
+ scheduleRenderLoop();
1054
+ }
1055
+
1056
+ scheduleRenderLoop();
1057
+ ```
1058
+
1059
+ #### Usage
1060
+
1061
+ ```html
1062
+ <!-- Vanilla HTML -->
1063
+ <poe-tile type-id="chat" instance-id="parent-123-my-chat-1"></poe-tile>
1064
+
1065
+ <!-- With open props (HTML attribute) -->
1066
+ <poe-tile type-id="chat" instance-id="parent-123-my-chat-1" open-props='{"theme":"dark"}'></poe-tile>
1067
+ ```
1068
+
1069
+ ```jsx
1070
+ // React — construct instance-id from parent's instanceId + child handle
1071
+ <poe-tile
1072
+ type-id={selectedApp.typeId}
1073
+ instance-id={`${instanceId}-${selectedApp.id}`}
1074
+ style={{ display: "block", flex: "1", minHeight: "0" }}
1075
+ />
1076
+ ```
1077
+
1078
+ ```javascript
1079
+ // Programmatic — set openProps via JS property (overrides attribute)
1080
+ const el = document.createElement("poe-tile");
1081
+ el.setAttribute("type-id", "chat");
1082
+ el.setAttribute("instance-id", "parent-123-my-chat-1");
1083
+ el.openProps = { theme: "dark", userId: "abc" };
1084
+ document.body.appendChild(el);
1085
+ ```
1086
+
1087
+ #### TypeScript JSX Support
1088
+
1089
+ To use `<poe-tile>` in TypeScript React projects, add a type declaration:
1090
+
1091
+ ```typescript
1092
+ declare module "react" {
1093
+ namespace JSX {
1094
+ interface IntrinsicElements {
1095
+ "poe-tile": React.DetailedHTMLProps<
1096
+ React.HTMLAttributes<HTMLElement> & {
1097
+ "type-id": string;
1098
+ "instance-id": string;
1099
+ "open-props"?: string;
1100
+ },
1101
+ HTMLElement
1102
+ >;
1103
+ }
1104
+ }
1105
+ }
1106
+ ```
1107
+
1108
+ #### How It Works
1109
+
1110
+ 1. On mount, the element calls `apps.openChild` via `postMessage` to the top-level document (with optional `openProps`)
1111
+ 2. The host registers the instance, injects session config and openProps into the HTML template
1112
+ 3. A blob URL is created from the HTML and loaded in a sandboxed iframe (`allow-scripts allow-forms`)
1113
+ 4. The child app communicates with the platform via `window.top.postMessage` using a nonce for routing
1114
+ 5. On unmount, the iframe is removed and the blob URL is revoked
1115
+
1116
+ ### `Poe.getOpenProps()`
1117
+
1118
+ Read JSON data passed by the parent app when this app was opened via `<poe-tile>`. Returns `null` if no props were passed or if this is a top-level app.
1119
+
1120
+ ```javascript
1121
+ const props = Poe.getOpenProps();
1122
+ if (props) {
1123
+ console.log(props.theme); // "dark"
1124
+ }
1125
+ ```
1126
+
1127
+ Open props are **read-once at startup** — they are baked into the HTML when the iframe is created and are not reactive. For reactive parent-child communication, use Synced Store.
1128
+
1129
+ ### `watchEntryContext()`
1130
+
1131
+ Get the **entry context** for this open: the notification the user tapped to get here, and the small creator-defined payload a sender attached to it. Call it once at startup, on every open.
1132
+
1133
+ ```typescript
1134
+ import { watchEntryContext } from "joiner-sdk/v1/shared.js";
1135
+
1136
+ type NotificationEntryContextDelivery = {
1137
+ source: "push" | "banner" | "badge";
1138
+ notification: {
1139
+ context: JSONValue; // what a sender attached via notifyActivity's push.context
1140
+ senderId?: string; // the responsible user (absent for system notifications)
1141
+ sentAtMs: number; // when the notification was enqueued
1142
+ };
1143
+ };
1144
+
1145
+ const stopWatching = watchEntryContext(Poe, (entry) => {
1146
+ // context is creator-defined JSON: narrow it defensively before use
1147
+ const context = entry.notification.context;
1148
+ if (
1149
+ context === null ||
1150
+ typeof context !== "object" ||
1151
+ Array.isArray(context) ||
1152
+ context.kind !== "challenge"
1153
+ ) {
1154
+ return;
1155
+ }
1156
+ // Opened from a challenge push. Wait for your own data, then decide
1157
+ // whether the challenge still stands before showing anything.
1158
+ void store.waitForBootstrap().then(() => showChallengeIfStillOpen(context));
1159
+ });
1160
+ ```
1161
+
1162
+ - **The listener runs when the notification arrives, which is usually after your tile has started.** The tile opens at once; it does not wait for the notification's record to reach the device. The listener is called a moment later, often after your first paint, and never on a normal open. On some hosts it is called before `watchEntryContext()` returns. So do not read the context to decide what your first screen is: render the default screen, then react when the listener runs (show an overlay, scroll to an entity, switch to the day the notification was about). A notification that has not reached the device within about ten seconds is not handed to this open; it can arrive on the tile's next open instead, which is one more reason to check it against your store.
1163
+ - **Wait for your store inside the listener.** The context can arrive before or after `store.waitForBootstrap()` resolves.
1164
+ - **`source`**: `"push"` (tapped an OS notification), `"banner"` (tapped the in-app foreground notification banner), or `"badge"` (tapped a badged in-app row / app-icon badge). `push` and `banner` resolve the *exact* notification tapped; `badge` resolves the newest unconsumed notification for the tile.
1165
+ - **`notification.context`**: the exact JSON a sender passed to [`notifyActivity`'s `push.context`](#notifyactivity). This is a **stale-able hint, not authoritative state**: by the time the recipient opens the tile the challenge may already be beaten, the turn already played, the message already read. **Always re-derive display state from your store** and use the context only to decide *what to surface*. A push sent **without** `push.context` may not reach the listener at all; attach a `push.context` to any notification the tile must recognize on arrival.
1166
+ - **Once per notification, per device, at least once.** Taking a notification acknowledges it, so a later open does not see it again, and opening on your phone does not consume it on your tablet. A crash before the acknowledgement re-delivers it on the next open, so keep the reaction idempotent: a rare duplicate overlay is acceptable.
1167
+ - **Route-mounted tile only.** A DOM-nested [`tiles.openChild`](#poe-tile-custom-element) child is never called; if a child needs the context, the parent forwards what it needs via `openProps`.
1168
+ - **`{ skipAfterPlayerInput: true }` (third argument) for games an overlay would interrupt.** Because the context can arrive a second or two after the tile is on screen, a fast game may already be under way. With this option a context that arrives after the player's first tap, click or key press in the tile is dropped (and still consumed) instead of reaching the listener. Use it for action games; leave it off for turn-based tiles and chat-like tiles, where a late recap or scroll is still welcome.
1169
+ - **Returns an unsubscribe.** Most tiles watch for their whole life and never call it.
1170
+
1171
+ **When to attach context, and when to show nothing.** Attach `push.context` when tapping the notification should land the user somewhere more specific than the tile's default screen: a challenge overlay, a game-over recap, first-turn framing, or a scroll to the referenced entity. Keep the payload tiny (an id plus a `kind` discriminator) and validate against your store on arrival: show the overlay only if the challenge still stands, scroll only if the message is in loaded history, otherwise fall through to a normal open. Do **not** attach context (or show any special UI) for routine, low-signal events (an ordinary turn on move 23, a daily nudge) where a plain open is exactly right; a mistimed overlay is worse than none.
1172
+
1173
+
1174
+ ### `Poe.consumeEntryContext()`
1175
+
1176
+ **Deprecated for notifications. Use [`watchEntryContext()`](#watchentrycontext).** This synchronous read can only return what was already on the device when the tile was created, and the tile is no longer held back until the notification's record arrives. So for a notification open it now returns `{ source: "direct" }`, the same as a normal open, and a tile that relies on it never sees its entry context.
1177
+
1178
+ ```typescript
1179
+ const entry = Poe.consumeEntryContext(); // { source: "direct" } on a notification open
1180
+ ```
1181
+
1182
+ The call still exists and never throws, so an existing tile keeps running; it just opens on its default screen. To migrate, replace the read with `watchEntryContext(Poe, listener)` and move whatever used the result into the listener. A value this call returned was consumed, so `watchEntryContext()` reads it for you where a host still supplies one: do not call both.
1183
+
1184
+ ### `Poe.parent`
1185
+
1186
+ The parent store's identity, available for child apps opened via `<poe-tile>` or `Poe.open()`. Returns `null` for root apps (apps not opened as children of another app).
1187
+
1188
+ ```typescript
1189
+ type ParentStoreInfo = {
1190
+ storeTypeId: string;
1191
+ instanceId: string;
1192
+ };
1193
+
1194
+ Poe.parent; // { storeTypeId: "my-parent-app", instanceId: "room-42" } or null
1195
+ ```
1196
+
1197
+ Use this to pass the parent's store identity as input to mutators that dispatch [external mutations](../../synced-store/references/external-stores.md) to the parent store:
1198
+
1199
+ ```javascript
1200
+ // In the child app's UI code (client-only):
1201
+ await store.mutate.notifyParent({
1202
+ parentTypeId: Poe.parent.storeTypeId,
1203
+ parentInstanceId: Poe.parent.instanceId,
1204
+ message: "task completed",
1205
+ });
1206
+
1207
+ // In the mutator (runs on both client and server):
1208
+ notifyParent: async (ctx, input) => {
1209
+ ctx.mutateExternal({
1210
+ storeTypeId: input.parentTypeId,
1211
+ instanceId: input.parentInstanceId,
1212
+ mutationName: "receiveChildNotification",
1213
+ input: input.message,
1214
+ });
1215
+ },
1216
+ ```
1217
+
1218
+ This pattern works because the parent identity flows as regular mutation input — the server doesn't need to know about parent/child app relationships.
1219
+
1220
+ ### `Poe.topOrigin`
1221
+
1222
+ Origin of the top (host) document — e.g. `"https://poe.com"` in production, `"http://localhost:5105"` in dev. Apps read it to build absolute URLs that resolve against the host instead of the sandboxed iframe.
1223
+
1224
+ ```typescript
1225
+ Poe.topOrigin; // "https://poe.com" or undefined
1226
+ ```
1227
+
1228
+ Joiner tiles run inside a sandboxed blob-URL iframe. Inside that iframe, `window.location.origin` is the string `"null"` (sandboxed) or an app-hosting subdomain — neither routes to the host's UI. The platform therefore injects the top document's origin into the iframe via `<div id="poe-config" data-top-origin="...">`, which `PostMessageEnvironment` reads and exposes here.
1229
+
1230
+ Returns `undefined` on older hosts that don't inject the attribute; apps should fall back to path-only URLs in that case so they degrade gracefully.
1231
+
1232
+ ```typescript
1233
+ // Build a shareable invite URL.
1234
+ const path = `/invites/${encodeURIComponent(code)}`;
1235
+ const shareUrl = Poe.topOrigin ? `${Poe.topOrigin}${path}` : path;
1236
+ await navigator.clipboard.writeText(shareUrl);
1237
+ ```
1238
+
1239
+ For top-document apps (trusted apps not running in an iframe) that construct a `PostMessageEnvironment` manually, pass `topOrigin: window.location.origin` in the constructor options.
1240
+
1241
+ ### `Poe.interfaceLanguages`
1242
+
1243
+ The host's interface language preferences, as BCP 47 tags with the most preferred first (e.g. `["fr"]`). Apps that localize their own UI should prefer this over `navigator.languages`.
1244
+
1245
+ ```typescript
1246
+ const languages = Poe.interfaceLanguages ?? navigator.languages;
1247
+ ```
1248
+
1249
+ A host can let the viewer pick an interface language (Poe's Language setting) and keep that choice where a sandboxed tile cannot read it, so `navigator.languages` inside the iframe would still report the browser's own languages. The platform injects the host's list into the iframe via `<div id="poe-config" data-interface-languages="...">` when the tile mounts. A change takes effect on the next mount; the host reloads after the viewer changes it.
1250
+
1251
+ Returns `undefined` when the host supplies no list (no choice made, or an older host); fall back to `navigator.languages`, as above.
1252
+
1253
+ ### `Poe.capabilities`
1254
+
1255
+ Resolved host surface capabilities — a flag map describing which surfaces the host enables. Always a full object: any flag the host did not restrict (or the whole config when the host imposes no restrictions) reads as enabled, so `Poe.capabilities.<flag>` is safe to read without a null check.
1256
+
1257
+ ```typescript
1258
+ Poe.capabilities; // { agents: true, ownChats: true, ... }
1259
+ ```
1260
+
1261
+ Most apps do not need this — it exists for first-party host surfaces that hide their own affordances when the host runs in a restricted mode (for example a host that disables agent/AI affordances). The host bakes the set into the iframe via `<div id="poe-config" data-capabilities="...">`, which `PostMessageEnvironment` reads and `createPoe` resolves against the all-enabled default. It is UI defense-in-depth only — the server is always the authority on what an app may actually do.
1262
+
1263
+ ### `Poe.haptics`
1264
+
1265
+ Trigger cross-platform hardware haptic feedback. Fire-and-forget — calls return immediately and the device buzzes on platforms that have hardware support. Modeled on Apple's `UIFeedbackGenerator` taxonomy because it's the richest target the platform mapping has to satisfy.
1266
+
1267
+ ```typescript
1268
+ // Discrete tactile feedback for a user action.
1269
+ Poe.haptics.impact("light" | "soft" | "medium" | "rigid" | "heavy");
1270
+
1271
+ // Outcome feedback for a completed operation.
1272
+ Poe.haptics.notification("success" | "warning" | "error");
1273
+
1274
+ // A small tap each time the selected value changes (slider tick, picker wheel).
1275
+ Poe.haptics.selection();
1276
+ ```
1277
+
1278
+ Safe to call from any context — no `isPoeNativeBridgeAvailable()` gate needed. Platforms with no haptic-capable path silently no-op.
1279
+
1280
+ #### Platform support
1281
+
1282
+ | Platform | What plays |
1283
+ | --- | --- |
1284
+ | iOS app | `UIImpactFeedbackGenerator` / `UINotificationFeedbackGenerator` / `UISelectionFeedbackGenerator` via a JS-bridge call. Best fidelity. |
1285
+ | Android app and mobile web (same code path) | `navigator.vibrate` with a fixed duration per style. The Android app's WebView is Chromium and supports the Vibration API directly, so the feel is identical between in-app and mobile web on the same device. |
1286
+ | iOS Safari 17.4+ (mobile web) | A single subtle tap, via the `<input switch>` label-click trick. **All styles collapse to the same tick on this path** — see "Limitations" below. |
1287
+ | Desktop browsers, older iOS Safari | Silent no-op. |
1288
+
1289
+ #### Usage
1290
+
1291
+ ```typescript
1292
+ // In a button handler:
1293
+ function onTapAttack() {
1294
+ Poe.haptics.impact("medium");
1295
+ // …apply game-state change
1296
+ }
1297
+
1298
+ // On a successful save:
1299
+ async function onSave() {
1300
+ await persist();
1301
+ Poe.haptics.notification("success");
1302
+ }
1303
+
1304
+ // While dragging a value slider:
1305
+ function onSliderTick() {
1306
+ Poe.haptics.selection();
1307
+ }
1308
+ ```
1309
+
1310
+ Haptics calls are fire-and-forget by design — there's no `await` and no return value to check. Don't gate UI on a successful haptic; let it be a finishing touch on top of whatever the user did.
1311
+
1312
+ #### Limitations
1313
+
1314
+ - **No custom patterns.** The API is intentionally semantic-only. iOS doesn't expose arbitrary haptic patterns to web code, so a raw-pattern API would silently degrade on half your users. The semantic taxonomy maps cleanly to every platform that has any haptic support.
1315
+ - **iOS Safari is one-intensity.** On iOS mobile web, every style fires the same subtle tap — `impact("heavy")` and `selection()` feel identical.
1316
+ - **iOS Safari < 17.4 is silent.** No fallback exists short of audio cues you'd implement yourself. Same answer applies to desktop browsers.
1317
+ - **User can disable haptics.** All platforms respect the user's system-level haptics setting — the call still resolves, but the device stays still. Don't treat haptic feedback as a reliable signal that the user noticed the action.
1318
+
1319
+ ### Device motion
1320
+
1321
+ Tilt and shake are web input: a tile listens to `deviceorientation` and `devicemotion` itself, and the host delegates the sensor permissions to every tile frame. The recipe (request from a tap, judge the readings, fall back to touch, say so once), and the controls model (Touch default, Tilt opt-in, calibration) are in the shared [device motion reference](../../poe-tiles-cli/references/device-motion.md); read it before designing input for a tilt or shake game. The SDK adds two things once the tile is integrated:
1322
+
1323
+ ```typescript
1324
+ // In the same code path that subscribes to motion events:
1325
+ let releaseMotion: (() => void) | null = null;
1326
+ function enableTilt() {
1327
+ if (releaseMotion) return; // already on: one claim per subscription
1328
+ window.addEventListener("deviceorientation", onTilt);
1329
+ if (Poe.has("motion.claim")) releaseMotion = Poe.motion.claim();
1330
+ }
1331
+ // Where the tile stops listening (menu, game over):
1332
+ function disableTilt() {
1333
+ window.removeEventListener("deviceorientation", onTilt);
1334
+ releaseMotion?.();
1335
+ releaseMotion = null;
1336
+ }
1337
+ ```
1338
+
1339
+ - **`Poe.motion.claim()`** tells the host this tile is using device motion as game input and returns a disposer. While a claim is held and the tile is on screen, the Joiner apps' shake-to-report gesture stands down, because a flick or tilt mechanic cannot be told from a shake; without it the bug-report sheet opens mid-game. Call it whatever the permission outcome (a denied player can still retry), but not when the events do not exist at all (`typeof DeviceMotionEvent === "undefined"` is terminal, and shake-to-report should stay armed), in the code path that subscribes, and release it where the tile unsubscribes. Leaving the tile releases automatically within a few seconds; host chrome covering a tile the player opened directly releases at once (a tile nested inside another tile releases on leaving only). Players still reach "Report a bug" from the sidebar and the You page. The claim also keeps the screen on during tilt play: while the tile holds it and the player is moving the phone, the Joiner apps (from the releases that add this) stop the screen from dimming and locking, and a phone left lying still locks as usual. There is nothing to call, and a tile cannot request a screen wake lock itself. Gate the call with `Poe.has("motion.claim")` while the host rolls out.
1340
+ - **Persist the controls choice** in a `privateOfUser` table. That row is scoped to the instance and the player: reopening the same instance on any device restores the preference, and a new instance starts on Touch. There is no cross-instance per-user memory, and browser storage is blocked in the sandbox.
1341
+
1342
+ ## Synced Store Helpers
1343
+
1344
+ Convenience helpers for common store operations — notifying the sidebar of activity. These wrap `ctx.mutateExternal()` so you don't need to know the manager's store type ID or mutation names.
1345
+
1346
+ Import from the client SDK:
1347
+
1348
+ ```typescript
1349
+ import {
1350
+ notifyActivity,
1351
+ notifyInProgress,
1352
+ setTurn,
1353
+ clearTurn,
1354
+ addInstanceToRoom,
1355
+ } from "joiner-sdk/v1/client.js";
1356
+ import {
1357
+ assertRoomMember,
1358
+ notifyUsersAddedToTile,
1359
+ } from "joiner-sdk/v1/shared.js";
1360
+ ```
1361
+
1362
+ ### `notifyActivity()`
1363
+
1364
+ Notify the manager of activity in this app instance. Five independent dials — `preview` (sidebar text), `recency` (whether the space also moves to the top of the Activity tab list), `unread: "increment"` (app-owned unread count → numeric badge in the sidebar and contribution to the ACTIVITY-TAB-header total), `push` (OS-level push notification), and `postToChat` (append one announcement row to the containing chat room). Recency defaults by attention: a call carrying `push`, `unread: "increment"`, or `postToChat` (a new transcript item) bumps the space to the top; a passive preview-only call refreshes the row in place without reordering (matching mainstream messenger behavior, where only new items and badge-worthy events reorder the list). Leave `unread` omitted in both the schema and client config to use the standard SDK behavior. Do not add `expectNoUnread()` merely because the tile currently sends no notifications — it asserts the tile never badges anyone and cannot actually suppress a badge if it does. Pick the right activity combination and target it precisely with `targetUserIds`. See [When to notify, and at what level](#when-to-notify-and-at-what-level) below.
1365
+
1366
+ ```typescript
1367
+ await notifyActivity(ctx, {
1368
+ preview: input.text.slice(0, 200),
1369
+ previewTimestamp: Date.now(),
1370
+ unread: "increment",
1371
+ // Mobile push composes "<tile>: <room/opponent>" when `title` is omitted.
1372
+ // Desktop notifications from creator tiles use the catalog identity.
1373
+ push: {
1374
+ body: input.text.slice(0, 200),
1375
+ },
1376
+ });
1377
+ ```
1378
+
1379
+ **Parameters:**
1380
+
1381
+ | Field | Type | Description |
1382
+ |-------|------|-------------|
1383
+ | `preview` | `string` | Preview text for the sidebar (e.g., last message). Self-contained — no sender prefix is added, so name who acted: "You …" in the actor's own call, "{displayName} …" for everyone else, never a bare verb phrase. |
1384
+ | `previewTimestamp` | `number` | Timestamp of the activity (content metadata). The Activity tab row's *visible* time label advances only on bumping activity, so the times users see always match the ordering they see — a `"preserve"` refresh updates the preview text without restamping the row's time. |
1385
+ | `recency` | `"bump" \| "preserve"` (optional) | Whether this activity moves the space to the top of the Activity tab list (`"bump"`) or refreshes the row's preview in place — position and visible time label unchanged (`"preserve"`). Defaults by attention: `"bump"` when the call carries `push`, `unread: "increment"`, or `postToChat` (a new transcript item in the containing chat), `"preserve"` otherwise. Override with `"bump"` for a badge-less event that is still a new item users would call "the latest thing that happened here" (e.g. a system announcement whose unread is handled elsewhere), or `"preserve"` for a badge-worthy event that only mutates an existing item (e.g. a reaction push). |
1386
+ | `unread` | `"increment"` (optional) | Increments each non-caller recipient's app-owned unread count by 1, lights up the per-space numeric badge, and contributes to the ACTIVITY-TAB-header total. Works with the default simple unread policy, or with an explicit `simpleUnread({ clearOn: "active" })`; omit it for preview updates that should not grow the badge. Not policy-aware: it badges recipients regardless of the declared unread policy (which is why the deprecated `noUnread()` cannot suppress it). |
1387
+ | `unreadToCaller` | `boolean` (optional, default `false`) | Opts the caller into `unread: "increment"` for a system-attributed receipt delivered back to that user (for example, an agent finishing work the user started). Requires `unread: "increment"` and requires the caller to be in the activity recipient set. |
1388
+ | `targetUserIds` | `string[]` (optional) | Specific users to notify. Omit to notify all active members. On the client, also controls whether the optimistic pass runs — see Behavior. |
1389
+ | `push` | `{ title?, body, kind?, pushToCaller? }` (optional) | When present, enqueues a push notification. Defaults to "every activity recipient *except* the caller" — see Push Notifications below. |
1390
+ | `push.title` | `string` (optional) | Mobile notification title override. Omit it to have the manager compose `"<tile>: <room/opponent>"` at delivery (matching the recipient's activity-tab-row title), the same as a `setTurn` push. Desktop honors title overrides only for trusted platform sources; `kind: "message"` alerts from those sources lead with the sender's display name instead. Ordinary creator tiles ignore this override on desktop. |
1391
+ | `push.body` | `string` | Notification body (typically preview / message text). |
1392
+ | `push.kind` | `"message" \| "reaction" \| "nudge" \| "invitation"` (optional) | Presentation intent for desktop notifications. Sender-based names and photos are restricted to trusted platform sources, such as chat and the built-in Creator: `message` uses the sender's identity with separate conversation context; the other kinds use the tile/conversation title and may show the participant photo. Ordinary creator tiles use their catalog name and image regardless of kind, falling back to a room or generic tile title when metadata is unavailable; sender, title, and context-image overrides cannot change that identity. Omit for general activity alerts. This changes presentation only, not recipients, unread counts, or click context. Unrecognized values render as general activity alerts. |
1393
+ | `push.pushToCaller` | `boolean` (optional, default `false`) | Opt the caller into the push subset. Use only when the activity is not user-attributable to the caller (e.g. a system event the caller happened to trigger, like a horse-race result). Throws if `true` and the caller is not in the activity recipient set. |
1394
+ | `push.context` | `JSONValue` (optional) | A small creator-defined **entry context** the recipient's tile is handed (via [`watchEntryContext()`](#watchentrycontext)) when they open the tile by tapping this notification. Size-capped at 4 KB serialized and validated at ingestion. A stale-able **hint**, not authoritative data — see [Entry context](#watchentrycontext). Must not contain secrets: only an opaque id transits the push vendor, but the payload is delivered to the recipient's devices and retained until TTL/cap cleanup. |
1395
+ | `postToChat` | `{ messageId, text, timestamp }` (optional) | Also appends one app-owned announcement message to the chat room that contains this app. The destination is resolved server-side from the source store's pinned `$$system/room`; callers cannot provide a chat id. If there is no containing chat room, `notifyActivity()` logs a warning and skips only the chat append. Chat validates `messageId` for API compatibility, but ignores it for row identity, uses its next `msg/...` sortKey, and derives a separate chat-owned itemKey from that sortKey. |
1396
+
1397
+ **Behavior:**
1398
+
1399
+ - **Client**: dispatches to the current user's manager only if `ctx.userId` is in `targetUserIds` (or `targetUserIds` is omitted); otherwise the client-side pass is a no-op and only the server's authoritative fan-out lands. This prevents a wrong-sidebar-state flash when `targetUserIds` excludes the caller (e.g. a "Your turn" notification sent to a single non-caller).
1400
+ - **Server**: dispatches to each user in `targetUserIds`, or all active members if omitted. Users not in the app's `$users` table are filtered out.
1401
+ - **Chat posting**: when `postToChat` is present, the server declares a sibling mutation to the containing chat room after the manager/unread declarations. If the app is not running inside a chat room, the helper logs a warning and skips that sibling mutation. The chat receiver writes the announcement row only; it does not call back into the manager, so one `notifyActivity()` call stays one manager activity.
1402
+
1403
+ **Actor-bump invariant:** every meaningful accepted user action that changes tile state or advances play must move this tile to the top of the actor's Activity tab. Emit the activity from the mutator that commits the action. When gameplay state is otherwise local, invoke a small activity mutator once at the semantic boundary (start/restart, completed stroke or drag, submitted choice), not on every pointer frame. When a person acted, send a separate actor-only activity with first-person copy ("You …"); only a shared fan-out whose preview names no human actor may include `ctx.userId` with `recency: "bump"` instead. The actor-only call uses `targetUserIds: [ctx.userId]` and `recency: "bump"`, and goes out without unread or push. Sender suppression keeps the actor from receiving their own push, but it does not make a preview-only activity bump: the explicit recency is still required. `setTurn` for the next player does not bump the actor; it only bumps newly marked turn-holders. Do not emit activity for rejected/no-op actions or transient input such as pointer movement, hover, or unsaved typing. Also skip per-user preferences visible only to the acting user — mute, volume, haptics, theme, and reduced motion — because they change only that person's presentation. Persist those preferences without notifying. Shared settings that affect other players or play — house rules, difficulty, round length, board size, and similar room-wide configuration — still bump.
1404
+
1405
+ ```typescript
1406
+ await notifyActivity(ctx, {
1407
+ preview: `You played ${moveLabel}`,
1408
+ previewTimestamp: input.playedAt,
1409
+ targetUserIds: [ctx.userId],
1410
+ recency: "bump",
1411
+ });
1412
+ ```
1413
+
1414
+ ### `setTurn()` / `clearTurn()`
1415
+
1416
+ Declare whose turn it is in the calling app instance — the data behind the manager's **"Your Turn"** indicator (a pill on the room/tile). Call these from inside your mutator, the same place you call `notifyActivity`. A new turn mark also moves the recipient's visible room to the top of the Activity tab without overwriting its existing preview. Each marked user's turn state is per-user-private — only that user ever sees their own "Your Turn."
1417
+
1418
+ `setTurn(ctx, input)` marks users up:
1419
+
1420
+ | Field | Type | Description |
1421
+ |-------|------|-------------|
1422
+ | `userIds` | `string[]` | Users to mark as "it's your turn" in this app instance. |
1423
+ | `replace` | `boolean` (optional, default `true`) | `true` → declarative replace: members currently up but **not** in `userIds` are cleared, so passing the turn to the next player clears the previous holder automatically. `false` → additive: only `userIds` are touched (e.g. a simultaneous game where players become ready one at a time). |
1424
+ | `push` | `boolean \| { title?, body }` (optional, default `true`) | `true` → default OS push to newly-added users (body "It's your turn.", title filled by the manager from the game/room name). `false` → mark silently. Object → override title/body. |
1425
+
1426
+ Marking is **idempotent** — re-marking an already-up user does nothing (no duplicate push, unread increment, or the Activity tab bump). A new turn mark increments the target's unread and bumps the target's visible room to the top of the Activity tab, so the actionable tile stays discoverable. Capped at `MAX_TURN_USER_IDS` users per call.
1427
+
1428
+ `clearTurn(ctx, input)` is explicit down-marking — the readable counterpart to `setTurn`'s implicit replace-clear:
1429
+
1430
+ - `{ userIds }` — clear just those users.
1431
+ - `{ all: true }` — clear every current turn-holder in this instance (e.g. game over).
1432
+
1433
+ `clearTurn` never touches unread (unread clears on view).
1434
+
1435
+ **Behavior:** the server pass fans out to each target user's manager; the client pass optimistically updates only the caller (so the mover's own pill clears the instant they take their turn). The authoritative fan-out lands on the server.
1436
+
1437
+ ```typescript
1438
+ import { clearTurn, setTurn } from "joiner-sdk/v1/client.js";
1439
+
1440
+ // Sequential game (chess, checkers): pass the turn to the next player. This
1441
+ // automatically bumps their room to the top of the Activity tab, increments unread,
1442
+ // marks "Your Turn," and sends the context-rich push.
1443
+ const preview = `${moverName} played ${moveLabel}`;
1444
+ await setTurn(ctx, {
1445
+ userIds: [nextPlayerId],
1446
+ push: { body: `${preview} — your move` },
1447
+ });
1448
+
1449
+ // Simultaneous game: several users up at once (still a replace).
1450
+ await setTurn(ctx, { userIds: [aliceId, bobId] });
1451
+
1452
+ // Add a player to the active set without disturbing the others.
1453
+ await setTurn(ctx, { userIds: [carolId], replace: false });
1454
+
1455
+ // Mark up silently (no OS push), e.g. a low-stakes nudge.
1456
+ await setTurn(ctx, { userIds: [nextPlayerId], push: false });
1457
+
1458
+ // Context-rich body — say what just happened instead of the generic default.
1459
+ // Build it from the move/turn that triggered the change.
1460
+ await setTurn(ctx, {
1461
+ userIds: [nextPlayerId],
1462
+ push: { body: `${moverName} took your ${pieceName} — your move` },
1463
+ });
1464
+
1465
+ // Tile end — clear everyone, explicitly.
1466
+ await clearTurn(ctx, { all: true });
1467
+
1468
+ // Clear one specific player (e.g. they resigned).
1469
+ await clearTurn(ctx, { userIds: [aliceId] });
1470
+ ```
1471
+
1472
+ **Make the push body context-rich and engaging.** The default `"It's your turn."` works, but a body that names *what just happened* — `"Jacob just took your bishop"`, `"It's your turn to guess the word"`, `"Aaron checked you — your move"` — is far more likely to pull a player back into the game. Build it from whatever triggered the turn change (the captured piece, the played card, the round/phase, the score to beat) and fall back to the generic default only when there's genuinely no context to add (e.g. an undo, the opening move). You usually only set `body`; the manager fills `title` from the game/room name.
1473
+
1474
+ **Do not add `notifyActivity` only to make a turn discoverable.** `setTurn` already bumps each newly marked recipient's room to the top of the Activity tab. Call `notifyActivity` separately when the sidebar preview should describe the move, or when the actor, spectators, or other non-turn-holders should also receive an activity update. Omit `unread` for the next player in that companion call because `setTurn` already increments it.
1475
+
1476
+ ### `notifyInProgress()`
1477
+
1478
+ Report that long-running work is happening in this app instance — the data behind the **spinner on the room's Activity tab row**. Call it from inside your mutator, the same place you call `notifyActivity`. It is not agent-specific: an AI turn, an image generation, a simulation, or any job the room is waiting on is the same signal to someone scanning their room list.
1479
+
1480
+ | Field | Type | Description |
1481
+ |-------|------|-------------|
1482
+ | `inProgress` | `boolean` | This store's **aggregate** answer: is *anything* still running here? |
1483
+ | `attemptKey` | `string` | Opaque identity of the active window of work (a job id, the driving queue item). **Required** while `inProgress`; ignored otherwise. |
1484
+ | `heartbeatSeq` | `number` (optional) | Monotonic "still working" counter. Each **increment** renews the viewer's stall clock; an unchanged value does not. |
1485
+ | `source` | `string` (optional, ≤32 chars) | Short producer label for display/debugging. Defaults to this store's type id. |
1486
+
1487
+ ```typescript
1488
+ import { notifyInProgress } from "joiner-sdk/v1/client.js";
1489
+
1490
+ // The work starts.
1491
+ await notifyInProgress(ctx, { inProgress: true, attemptKey: jobId });
1492
+
1493
+ // ...and when it ends, or you find nothing running.
1494
+ await notifyInProgress(ctx, { inProgress: false });
1495
+ ```
1496
+
1497
+ **Send the aggregate, not one job's boolean.** The platform keeps one entry per app instance, so the last thing you send is the whole instance's answer. With two jobs running, reporting `false` when the first finishes clears the spinner while the second is still going. Derive "is anything still running here?" from your store at every call site — which also means calling it from *every* mutator that can change that answer, including the ones that end work (a completion, a cancel, an error), not only the one that starts it.
1498
+
1499
+ **Work that runs longer than ~5 minutes must heartbeat.** The viewer expires an attempt roughly five minutes after its last new signal, so a crashed producer never strands a spinner. If your work legitimately runs longer, increment `heartbeatSeq` from something that is genuinely still alive and doing the work (a worker or bridge timer) — never from a UI re-render or a periodic reconcile, or a dead job's spinner would spin forever. Re-sending the *same* `attemptKey` with no heartbeat is always safe: it restates the current answer without reviving an attempt the viewer already gave up on. A retry that starts fresh work should send a **new** `attemptKey`, which restarts the clock.
1500
+
1501
+ **Behavior:** the server pass dispatches to this instance's active members; the client pass dispatches to the caller only, so their own spinner appears without a round trip. The signal is display-only — it never bumps the Activity tab order, previews, unread badges, or push notifications, so it is safe to send freely. Delivery is best-effort and covers the first ~150 members of a room; beyond that, members simply see no spinner. Calling it from a mutation another store dispatched throws, because cross-store mutations cannot dispatch further — defer that emission to an action.
1502
+
1503
+ ### `assertRoomMember()`
1504
+
1505
+ Validate inside a mutator that a user is an active member of this tile.
1506
+
1507
+ ```typescript
1508
+ await assertRoomMember(ctx, { userId: input.userId });
1509
+ ```
1510
+
1511
+ The client optimistic pass is a no-op. The server pass checks this tile's own `$users` and never reads another store. A tile launched inside a room keeps `$users` in sync with that room, so room members are listed there even if they have never opened the tile. `Poe.room.pickMembers()` adds any picked user who is not in the room yet (a contact, or a member of the parent group) and resolves once this tile lists them, so a user from the picker passes. A user who is only in the parent group and was never picked or invited is rejected.
1512
+
1513
+ Tiles bundle the SDK when they are built, so a published tile keeps the helper's behavior from its build until it is rebuilt.
1514
+
1515
+ ### `notifyUsersAddedToTile()`
1516
+
1517
+ Send standard "added/assigned to this tile" activity and push notification to selected room members.
1518
+
1519
+ ```typescript
1520
+ await notifyUsersAddedToTile(ctx, {
1521
+ targetUserIds: [input.userId],
1522
+ appName: "Checkers",
1523
+ reason: "assigned",
1524
+ previewTimestamp: input.now,
1525
+ });
1526
+ ```
1527
+
1528
+ The helper is server-only. It uses the same manager `receiveActivity` path as `notifyActivity`, but does not filter against the tile instance's local `$users`, so it can notify room members who have not opened the tile. The platform delivers only to members of this tile's room (or its parent group) and silently drops the rest, so a target who is not a member gets no notification while your mutation still commits. Use `notifyActivity()` directly for custom copy, unread behavior, or chat announcements.
1529
+
1530
+ **Unread policy is app-owned.** Leave `unread` omitted in both the schema and client config: by default, the SDK stores a per-user private unread projection and clears it when the host reports that the user is active in the tile. Do not add `expectNoUnread()` merely because the tile currently sends no notifications; keeping the default makes later `setTurn` and `notifyActivity({ unread: "increment" })` additions work without a policy migration. Apps with custom read semantics can declare `customUnread()` in both places and call `setUnreadCount(ctx, { count })` from their own mutators.
1531
+
1532
+ `expectNoUnread()` is the third choice, for an app that will never badge anyone. **It is an assertion, not a suppression switch** — hence the name. The increment paths are per-call and not policy-aware, so an app that declares it and then calls `unread: "increment"`, `setTurn`, or the automatic leaderboard notify still badges its recipients while declaring it does not. What the declaration buys is that the platform withholds the increment mutator, and treats any count that does appear as damage: it keeps the clear-side repair and clears on open whenever the local count reads positive. Declare it only if that is really true of your app; when in doubt, leave `unread` omitted. (**`noUnread()` is deprecated** — it is the former name for this policy. It read as "this app has no unread", a guarantee the platform cannot make, and it stays exported so tiles already published keep booting.)
1533
+
1534
+ **Push Notifications:**
1535
+
1536
+ When `push` is present, each recipient's manager enqueues a pending delivery row alongside the sidebar update.
1537
+
1538
+ - **Default sender-suppression.** The helper strips `push` from the caller's own dispatch. The caller's other devices still get the activity update via sync but no OS-level push for their own action. Override only when the activity isn't user-attributable to the caller — set `push.pushToCaller: true`.
1539
+ - **OS-level "currently in the app" suppression.** Don't ring the device a recipient is actively using is handled at the OS layer (`UNUserNotificationCenterDelegate` on iOS, equivalents on Android/web), not by the helper.
1540
+ - **Tap target is implicit.** Delivery channels construct deep-links from the calling app's `typeId` + `instanceId` — apps don't specify a URL.
1541
+
1542
+ **Limits:** Each notified user's manager is one external mutation target. The limit is `MAX_EXTERNAL_MUTATION_TARGETS` (200) unique target stores per commit.
1543
+
1544
+ #### When to notify, and at what level
1545
+
1546
+ | Activity kind | `unread` | `push` | Example |
1547
+ |---|---|---|---|
1548
+ | Action required from a specific user | `"increment"` | yes | "Jacob just took your bishop" — sent to the player whose turn it is (name the triggering event, not a bare "It's your turn") |
1549
+ | Opt-in interesting event | `"increment"` | yes | "Your friend beat your high score!" |
1550
+ | Passive update worth surfacing | `"increment"` | no | "Aaron reacted with 🎉" / "Spymaster gave a clue" — bumps the app and adds to the badge count, no ring |
1551
+ | Preview refresh without unread | omit | no | Updating a move preview for the actor/spectators, importing your own old messages, todo edits — refreshes the row's preview in place without reordering the Activity tab or growing the badge (pass `recency: "bump"` explicitly if the event should also reorder) |
1552
+
1553
+ Rules of thumb:
1554
+
1555
+ - **Push only when the user would want their phone to ring.** Required-action moments (turn games, incoming chat message, invite) and high-signal opt-in events (someone beat your score, a friend you know just played). Don't push on every state change — multi-player apps generate dozens of mutations per session, and pushing all of them is spam.
1556
+ - **Use `unread: "increment"` (without `push`) for "nice to know when you look".** Reactions, partial-progress events from collaborators, another player taking a non-blocking turn (e.g. spymaster choosing a clue while it's not yet your guess phase). This bumps the space, increments its numeric badge, and contributes to the sidebar's ACTIVITY TAB total — but doesn't ring the device.
1557
+ - **Omit `unread` for preview updates that should not grow the badge.** This includes a player's own durable action when another mechanism, such as `setTurn`, owns the recipient's unread state. If a player would expect a number to change and nothing else increments it, use `"increment"`. A badge-less call also does not reorder recipients' Activity tab lists (the `recency` attention default) — the recipient whose action matters is usually being bumped by `setTurn` or an `unread`/`push`-carrying call already.
1558
+ - **Keep caller unread opt-in exceptional.** User-authored activity is sender-suppressed by default. Set `unreadToCaller: true` only when the event is attributed to the app, system, or agent and is delivered back to the triggering user as a receipt.
1559
+ - **Choose `targetUserIds` deliberately.** Omit it only when every active member — including the actor — should read the same preview, which means no human actor is named in it. When a person acted, target the other members with the third-person copy and the actor with a separate first-person call. For targeted pushes, include only the intended recipients: the next player for "your turn," or the previous record-holder for "friend beat your score." Default sender-suppression handles "don't push the user who triggered the action" for you.
1560
+ - **Make the push body specific and engaging, not generic.** `"Jacob just took your bishop"` or `"It's your turn to guess the word"` pulls a player back far better than a bare `"It's your turn."` Build the body from whatever just happened — the move, the capture, the card played, the round/phase, the score to beat — and reserve the generic default for when there's genuinely no context. This applies to both `setTurn`'s `push` and `notifyActivity`'s `push`; compute the text in the same mutator that detects the event.
1561
+ - **Make `preview` self-contained.** It shows up in the Activity tab list with no other context — `"Alice: nice move"` reads better than `"nice move"`.
1562
+
1563
+ Concrete examples:
1564
+
1565
+ ```typescript
1566
+ // Turn-based game: setTurn alone makes the action discoverable to the next player.
1567
+ const nextPlayer = computeNextPlayer(state);
1568
+ const preview = `${currentPlayerName} played ${moveLabel}`;
1569
+ await setTurn(ctx, {
1570
+ userIds: [nextPlayer.userId],
1571
+ push: { body: `${preview} — your move` },
1572
+ });
1573
+
1574
+ // Optional: update the sidebar preview for every member. `preview` is one
1575
+ // string per call, so split by reader: third person for the other members,
1576
+ // first person for the actor. Push-less and unread-less, so the others' rows
1577
+ // refresh in place; the next player's room (setTurn) and the actor's own row
1578
+ // (the `recency: "bump"` call below) are the only ones that reorder.
1579
+ await notifyActivity(ctx, {
1580
+ preview,
1581
+ previewTimestamp: input.playedAt,
1582
+ targetUserIds: memberUserIds.filter((id) => id !== ctx.userId),
1583
+ });
1584
+ await notifyActivity(ctx, {
1585
+ preview: `You played ${moveLabel}`,
1586
+ previewTimestamp: input.playedAt,
1587
+ targetUserIds: [ctx.userId],
1588
+ recency: "bump",
1589
+ });
1590
+
1591
+ // Same game: spymaster picked a clue — badge + unread for the guessing team, no push
1592
+ await notifyActivity(ctx, {
1593
+ preview: `Spymaster: "${clue}" (${count})`,
1594
+ previewTimestamp: Date.now(),
1595
+ unread: "increment",
1596
+ targetUserIds: guessingTeamUserIds,
1597
+ });
1598
+
1599
+ // High-score game (e.g. poe-jump): someone finished a run — badge bump, no push.
1600
+ // Other members read the third-person preview; the shared chat transcript is
1601
+ // third person too. The runner gets a first-person preview of their own.
1602
+ const timestamp = Date.now();
1603
+ await notifyActivity(ctx, {
1604
+ preview: `${playerName} scored ${score}`,
1605
+ previewTimestamp: timestamp,
1606
+ unread: "increment",
1607
+ targetUserIds: memberUserIds.filter((id) => id !== ctx.userId),
1608
+ postToChat: {
1609
+ messageId: scoreEventId,
1610
+ text: `${playerName} scored ${score}`,
1611
+ timestamp,
1612
+ },
1613
+ });
1614
+ await notifyActivity(ctx, {
1615
+ preview: `You scored ${score}`,
1616
+ previewTimestamp: timestamp,
1617
+ targetUserIds: [ctx.userId],
1618
+ recency: "bump",
1619
+ });
1620
+
1621
+ // Same game: new player beat the previous record — push the previous record-holder
1622
+ if (score > previousBest.score && previousBest.userId !== ctx.userId) {
1623
+ await notifyActivity(ctx, {
1624
+ preview: `${playerName} beat your score (${score})`,
1625
+ previewTimestamp: Date.now(),
1626
+ unread: "increment",
1627
+ targetUserIds: [previousBest.userId],
1628
+ push: { body: `${playerName} beat your high score: ${score}` },
1629
+ });
1630
+ }
1631
+ ```
1632
+
1633
+ **You can skip hand-rolling the high-score case:** `setLeaderboardScore` fires this notification for you on a new high score (personalized push to every other active member + a chat announcement when the #1 changes hands, scorer suppressed) — it is **on by default**. Pass `{ notifyOnHighScore: false }` — `setLeaderboardScore(ctx, { … }, { notifyOnHighScore: false })` — to opt out; hand-roll it yourself only when you want custom copy/targeting, and then opt out so it doesn't double up.
1634
+
1635
+ When the board has a persisted `label`, every push/activity body and the chat announcement name it: `Alice just beat your score on May 30 best attempts with 9!`. This is how a tile that mints one board per day (or week, or season) tells the recipient WHICH board the score landed on — put the period in the label (`May 30 best attempts`), never deictic wording like "Today's best attempts": the notification is often read after the day rolls over, and each period's board keeps its label forever. A single evergreen board can skip the label and keep the shorter wording.
1636
+
1637
+ The chat announcement is built from the entry you just wrote: `displayScore` (or the raw score) as the headline. Add `summaryInChatAnnouncement: true` — `setLeaderboardScore(ctx, { … }, { summaryInChatAnnouncement: true })` — and the entry's `markdown` rides under it, so a board that already annotates each row with a result summary shows that result in the transcript instead of a bare number:
1638
+
1639
+ ```
1640
+ 🏆 Alice took the top spot with 2/6
1641
+ 🔥 Streak 1
1642
+
1643
+ 🟨⬛⬛🟩⬛
1644
+ 🟩🟩🟩🟩🟩
1645
+ ```
1646
+
1647
+ It is **off by default**, because a `markdown` written for the `tileEnd` overlay is read only by members who open the board, while chat is read by the whole room. Opt in only for a summary you mean to publish there — and remember chat renders it as markdown, so keep it to the result itself rather than links or headings.
1648
+
1649
+ ### `addInstanceToRoom()`
1650
+
1651
+ Register an app instance as a member of a flat room. The room owns its `$users` roster; member instances mirror that roster via fan-out from the room. Once registered, every `$addUsers` / `$removeUser` against the room reaches the member automatically — including users admitted before the member joined.
1652
+
1653
+ Import from the client SDK:
1654
+
1655
+ ```typescript
1656
+ import { addInstanceToRoom } from "joiner-sdk/v1/client.js";
1657
+ ```
1658
+
1659
+ Call from inside a mutation handler:
1660
+
1661
+ ```typescript
1662
+ const mutators = {
1663
+ // Running on the chat (a room). Register a launched game with the
1664
+ // chat's $room_member_instances so the game inherits the chat's
1665
+ // $users via the platform's room fan-out.
1666
+ launchGame: async (ctx, input) => {
1667
+ await addInstanceToRoom(ctx, {
1668
+ storeTypeId: input.gameTypeId,
1669
+ instanceId: input.gameInstanceId,
1670
+ });
1671
+ await ctx.table("games").set({
1672
+ itemKey: input.gameInstanceId,
1673
+ value: input,
1674
+ });
1675
+ },
1676
+ };
1677
+ ```
1678
+
1679
+ **Input shape:**
1680
+
1681
+ ```typescript
1682
+ {
1683
+ storeTypeId: string; // The app instance being registered
1684
+ instanceId: string;
1685
+ room?: { // Optional: explicit room ref
1686
+ storeTypeId: string;
1687
+ instanceId: string;
1688
+ };
1689
+ }
1690
+ ```
1691
+
1692
+ - **Omit `room`** when the calling store IS the room (the common `launchGame`-style case — the helper dispatches to the local store).
1693
+ - **Pass `room`** when the calling store is a *member* of the room and needs to register another app instance on the room's `$room_member_instances`. App-level mutators cannot read the local `$$system:room` row to auto-detect role, so the caller specifies it.
1694
+
1695
+ Idempotent on re-call (the platform mutator's `set` overwrites the identically-keyed row). Safe to race with the client-side `<poe-tile room="inherit">` flow — both converge on the same row.
1696
+
1697
+ The platform enforces a **single-room invariant**: if the target instance is already a member of a different room (its `$$system:room` points elsewhere) or is itself a room, the room's authorize refuses the dispatch (`external_access_denied`) and the row never lands. The `createPoeTileTestHarness` default open-door authorize does not run this check. An instance can be a member of at most one room at a time.
1698
+
1699
+ ### `getCurrentUserId()`
1700
+
1701
+ Read the current user's `userId` from a synced-store client.
1702
+
1703
+ ```typescript
1704
+ import { getCurrentUserId } from "joiner-sdk/v1/client.js";
1705
+
1706
+ // Once at app mount:
1707
+ const userId = await getCurrentUserId(store);
1708
+ ```
1709
+
1710
+ `store.userId` does not exist by design — the user identity lives in the query/mutator `ctx`. This helper runs a one-shot query that resolves to `tx.userId`, which is the recommended way to read it from UI code (effects, async resources, manual reads). For per-render reactive access, prefer reading `tx.userId` inside a `store.subscribe()` query callback.
1711
+
1712
+ ```typescript
1713
+ // SolidJS / async-init pattern:
1714
+ const [userIdResource] = createResource(
1715
+ () => store,
1716
+ (s) => getCurrentUserId(s),
1717
+ );
1718
+ ```
1719
+
1720
+ ### `store.files.getQuotaUsage()` — exact upload quota counters
1721
+
1722
+ Read the exact instance usage and limits plus the authenticated user's
1723
+ attributed usage:
1724
+
1725
+ ```typescript
1726
+ const usage = await store.files.getQuotaUsage();
1727
+ // usage.instance: { bytes, count, limitBytes, limitCount }
1728
+ // usage.user: { userId, bytes, count }
1729
+ ```
1730
+
1731
+ Client code can inspect only the acting user's usage. Backend actions can call
1732
+ `ctx.files.getQuotaUsage({ userId? })` when they need to inspect another user.
1733
+ The publish-time platform check remains authoritative if concurrent uploads
1734
+ race a client-side preflight.
1735
+
1736
+ ### `store.files.upload()` — managed file uploads
1737
+
1738
+ The store handle returned by `Poe.setupStore()` carries a `files` namespace
1739
+ for uploading user files (photos, attachments) into the instance's own store.
1740
+ The scaffold's canonical `InferSyncedStoreClient<YourSchema>` type describes
1741
+ this complete handle, including `files`; do not manually intersect a second
1742
+ extension type or inspect generated declaration files.
1743
+ Uploads are **app-controlled**: they work only when your schema declares the
1744
+ reserved `_requestUploadUrl` action and your backend implements it (see
1745
+ [backend-api.md](backend-api.md#_requestuploadurl--app-controlled-uploads)) —
1746
+ that handler is your policy gate, run server-side before every upload.
1747
+
1748
+ ```typescript
1749
+ const file = await store.files.upload({
1750
+ data: photoBlob, // Blob | Uint8Array
1751
+ name: "capture.jpg", // optional display metadata
1752
+ contentType: "image/jpeg", // optional hint; bytes are inspected anyway
1753
+ });
1754
+ // file: { status: "staged", fileId, fileKey: null, url: null, ... }
1755
+ ```
1756
+
1757
+ Enforce app rules (one per day, one per round) in the MUTATOR that claims the
1758
+ `fileId` — it is the authoritative gate anyway; the grant handler only sees
1759
+ `{ fileId, sizeBytes, name? }` and should gate what must be decided before
1760
+ the bytes upload, like a size cap (see
1761
+ [backend-api.md](backend-api.md#_requestuploadurl--app-controlled-uploads)).
1762
+
1763
+ `upload()` resolves after the host has durably staged the bytes and its
1764
+ background upload task. It returns a usable `fileId` immediately; subsequent
1765
+ mutations may reference that ID, and the store's push queue waits for
1766
+ publication before sending them. The file is NOT yet retained: write
1767
+ `file.fileId` into a table field declared under that table's `fileRefs` so the
1768
+ platform derives the `$files` claim row and keeps the bytes alive. An upload
1769
+ that no row ever claims expires.
1770
+
1771
+ Local staging accepts up to 60 files or 256 MiB per store. Browser staging also
1772
+ limits the signed-in account to 100 files or 256 MiB across stores and tabs
1773
+ on the same browser profile and origin. Exceeding either limit rejects
1774
+ `upload()` without evicting pending files. Published files awaiting claim
1775
+ settlement still occupy staging capacity.
1776
+
1777
+ `await store.files.uploads.get(file.fileId)` reports local staging or terminal
1778
+ failure state. It returns `null` after successful publication. Use it to render
1779
+ an upload failure UI; do not wait for publication before creating the claiming
1780
+ mutation.
1781
+
1782
+ `failure.reason` is one of these values:
1783
+
1784
+ - `network` — the last attempt got no usable server answer.
1785
+ - `server_error` — the server answered with a 5xx error.
1786
+ - `rate_limited` — the platform rate limit applied.
1787
+ - `uploads_disabled`, `denied_by_app` (+`appCode`), `quota_exceeded`,
1788
+ `file_too_large`, `not_authorized`, `invalid_request` — the platform or your
1789
+ handler refused the upload.
1790
+ - `integrity`, `expired`, `too_many_attempts` — the staged bytes did not match,
1791
+ the stage aged out, or the retries ran out.
1792
+
1793
+ Show a generic message for a reason your app does not know, because new hosts
1794
+ can add reasons. Use `failure.retryable`, not the reason, to decide whether the
1795
+ upload is still retrying. Do not show the raw reason string to players.
1796
+
1797
+ ```typescript
1798
+ // schema.ts — declare the claim field:
1799
+ tables: {
1800
+ submissions: {
1801
+ schema: table(z.object({ fileIds: z.array(z.string()) })),
1802
+ fileRefs: { strong: ["fileIds"] as ["fileIds"] },
1803
+ },
1804
+ },
1805
+ // then claim from a mutator:
1806
+ await ctx.table("submissions").set({
1807
+ itemKey: key,
1808
+ value: { fileIds: [file.fileId] },
1809
+ });
1810
+ ```
1811
+
1812
+ **Persist only `fileIds` in your rows — never a URL.** Mutator args are
1813
+ client-controlled, so a URL column would let any member display bytes that
1814
+ bypassed the pipeline. Resolve the display URL at render time instead:
1815
+
1816
+ ### `store.files.url(fileId)` — resolve a claimed file's display URL
1817
+
1818
+ ```typescript
1819
+ const src = await store.files.url(submission.fileIds[0]);
1820
+ ```
1821
+
1822
+ The host first reads local staged or cached bytes. A cold read downloads and
1823
+ verifies the authoritative file, then attempts bounded cache admission. The
1824
+ returned display URL belongs to this client and remains usable until explicit
1825
+ disposal, including after disk eviction. Public and `privateOfUser(self)` claims
1826
+ resolve; the uploader can also resolve their own unclaimed or server-only
1827
+ upload. Other members need a visible claim.
1828
+
1829
+ Use `store.files.url(fileId, { target: "external" })` for an HTTP URL passed to
1830
+ a document opener or another process. Store file IDs in rows, since display
1831
+ URLs are local to a client and serving origins may change.
1832
+
1833
+ Failures reject with a `FileUploadError` (import `isFileUploadError` from
1834
+ `joiner-sdk/v1/client.js`) carrying a typed `code`:
1835
+
1836
+ - `uploads_not_enabled` — the schema declares no `_requestUploadUrl` handler.
1837
+ - `upload_denied_by_app` — your handler threw an `ActionError`; its bounded
1838
+ code rides `error.appCode` (e.g. `"photo_too_large"`).
1839
+ - `quota_exceeded` identifies the quota in `error.quotaScope`. `"instance"`
1840
+ means server quota. `"store_staging"` and `"device_staging"` mean local
1841
+ staging capacity. Local staging errors include a readable message and
1842
+ `retryable: true`; retry after pending uploads settle and free capacity.
1843
+ - `rate_limited`, `file_too_large` — other platform limits.
1844
+ - `idempotency_conflict` — the `fileId` belongs to a different uploader.
1845
+ - `uploads_disabled` / `upload_failed` — deployment or transient failures
1846
+ (`error.retryable` says whether re-invoking `upload()` may succeed).
1847
+
1848
+ Uploads resolve after durable local staging and run under the host coordinator,
1849
+ including while offline or after a tile closes. The current SDK Node
1850
+ environment uses memory for file caches and the task ledger, so pending uploads
1851
+ and cached bytes do not survive a process restart. Claim mutations remain
1852
+ optimistic until publication permits their server push. Inspect pending or
1853
+ failed work with `store.files.uploads.get(fileId)`, and retain the draft until
1854
+ its claim is confirmed. Downscale camera photos before uploading, since grant
1855
+ handlers commonly cap `sizeBytes`.
1856
+
1857
+ ### `store.files.loadFile(fileId, options)` — load a file
1858
+
1859
+ Added November 2026; requires SDK/kernel 64 or later. Check
1860
+ `Poe.has("store.files.loadFile.url")` on older hosts.
1861
+
1862
+ ```typescript
1863
+ const { url } = await store.files.loadFile(fileId, {
1864
+ cachePriorityKey: row.sortKey, // optional
1865
+ });
1866
+ const once = await store.files.loadFile(fileId, { cache: false });
1867
+ ```
1868
+
1869
+ | Parameter | Type | Required | Meaning |
1870
+ | --- | --- | --- | --- |
1871
+ | `fileId` | `string` | yes | A claimed file ID from your rows. |
1872
+ | `cachePriorityKey` | `string \| number` | no | Keeps the file in the device cache longer; larger keys are kept longest. |
1873
+ | `cache` | `false` | no | Load without adding the file to the device cache. Cannot be combined with `cachePriorityKey`. |
1874
+
1875
+ Returns `Promise<{ url: string }>`, where `url` is a device URL for the
1876
+ downloaded bytes (for an `<img src>`, a `fetch`, or a download link). The file is read from the device
1877
+ when it is there and downloaded otherwise; by default it is then kept in the
1878
+ device cache so it loads offline later. Use `cache: false` for a file you show
1879
+ once, so it does not take cache space from files you want to keep. Bytes
1880
+ already on the device are still used.
1881
+
1882
+ The device may evict files from the cache under cache pressure. Keyed files are
1883
+ kept over unkeyed ones, and larger keys are kept longest, so the row's
1884
+ `sortKey` keeps recent rows' files over older ones.
1885
+
1886
+ ### `store.files.loadImage(fileId, { size })` — load a resized image
1887
+
1888
+ Added November 2026; requires SDK/kernel 64 or later. Check
1889
+ `Poe.has("store.files.loadImage.url")` on older hosts.
1890
+
1891
+ ```typescript
1892
+ const { url } = await store.files.loadImage(fileId, {
1893
+ size: "small", // optional; omit for the original
1894
+ cachePriorityKey: row.sortKey, // optional
1895
+ });
1896
+ ```
1897
+
1898
+ | Parameter | Type | Required | Meaning |
1899
+ | --- | --- | --- | --- |
1900
+ | `fileId` | `string` | yes | A claimed file ID from your rows. |
1901
+ | `size` | `"thumbnail" \| "small" \| "medium" \| "large"` | no | The image width to load: 128, 384, 768, or 1536 pixels. Omit it for the original image. |
1902
+ | `cachePriorityKey` | `string \| number` | no | As for `loadFile`. |
1903
+ | `cache` | `false` | no | As for `loadFile`. |
1904
+
1905
+ Returns `{ url }` like `loadFile`, a device URL for an `<img src>`. Each size is an
1906
+ exact width in image pixels; it is not scaled by the screen's pixel density, so
1907
+ for an image shown 192 CSS pixels wide on a 2x screen, pick `small`. The image
1908
+ keeps its aspect ratio and is never upscaled (a source narrower than the size
1909
+ comes back at its own width), and a larger copy already on the device may be
1910
+ returned instead of downloading a new one. Without `size` it loads the
1911
+ original, like `loadFile()`. `STORE_IMAGE_SIZE_WIDTHS` from
1912
+ `joiner-sdk/v1/shared.js` maps each size to its width.
1913
+
1914
+ A resized load rejects when the image is not on the device and cannot be
1915
+ downloaded, or when the source is not a JPEG, PNG, or WebP image; fall back to
1916
+ `store.files.loadFile()`. `store.files.cache.unpin(fileId)` removes the
1917
+ original and every resized copy.
1918
+
1919
+ `store.files.imageUrl(fileId, { displayWidth })` is deprecated: it loads the
1920
+ image the same way, but multiplies `displayWidth` by the pixel density and
1921
+ rounds up to the next width. Use `loadImage` with a `size`.
1922
+
1923
+ ### Recording which configuration produced an agent reply
1924
+
1925
+ If your app triggers agents (`Poe.agents.*`) and stores their replies, you can record the configuration each run actually executed on — the model, the tools it was allowed, the tool→model bindings, and which of those a per-trigger override replaced.
1926
+
1927
+ This is worth storing rather than looking up later, for two reasons: an agent's configuration is **overwritten in place with no history**, so editing it retroactively changes what every past reply appears to have been generated with; and a per-trigger override (`modelOverride` / `enabledTools` / `toolModels`) is **never persisted anywhere**, so it is unrecoverable once the run ends.
1928
+
1929
+ ```typescript
1930
+ import {
1931
+ type EffectiveAgentRunConfig,
1932
+ parseEffectiveRunConfigPlain,
1933
+ } from "joiner-sdk/v1/shared.js";
1934
+ ```
1935
+
1936
+ Declare the field on the row that stores the reply. Use `z.custom` for the type — do **not** import a Zod schema for it, because a schema reachable from your mutators lands in your app's eager bundle:
1937
+
1938
+ ```typescript
1939
+ // schema.ts
1940
+ generationConfig: z.custom<EffectiveAgentRunConfig>().optional(),
1941
+ ```
1942
+
1943
+ Then validate at the boundary where the snapshot arrives, and write it **once**:
1944
+
1945
+ ```typescript
1946
+ // In the mutator that records the reply. No `undefined` guard is needed —
1947
+ // `parseEffectiveRunConfigPlain` returns null for an absent or malformed value.
1948
+ const generationConfig = parseEffectiveRunConfigPlain(input.generationConfig);
1949
+
1950
+ // Spread only when non-null — see the two rules below.
1951
+ await ctx.table("messages").set({
1952
+ /* … */
1953
+ ...(generationConfig !== null ? { generationConfig } : {}),
1954
+ });
1955
+ ```
1956
+
1957
+ Two rules to follow, both of which are easy to get wrong:
1958
+
1959
+ - **`null` means NOT RECORDED — never "the agent's current configuration."** A row written before you added the field, a reply from something that is not an agent, and a run that failed before resolving a configuration all read as `null`. Rendering any of them as the live configuration reintroduces exactly the problem this solves. The same applies one level down: a field missing from a snapshot whose `v` predates it is also not-recorded, so never `??` a default onto a snapshot field.
1960
+ - **Write it on create only, and never rewrite it.** The snapshot cannot change within a run, so a later dispatch carrying one should be ignored. That is what makes the record trustworthy — and it means a retried run keeps the original.
1961
+
1962
+ `parseEffectiveRunConfigPlain` returns `null` instead of throwing, on purpose: a malformed snapshot should cost you the provenance record, never the reply it annotates. It is deliberately Zod-free so it is safe to call from a mutator.
1963
+
1964
+ ## Platform Helpers
1965
+
1966
+ Small utilities for detecting or configuring the runtime environment. Safe to call from any Joiner tile entry.
1967
+
1968
+ ### `resumeAudioContext()`
1969
+
1970
+ Resume a Web Audio context after a normal browser suspension or an iOS system-audio interruption such as an alarm or phone call. WebKit reports the non-standard state `"interrupted"`; checking only for `"suspended"` leaves the context silent until the tile is reopened.
1971
+
1972
+ Call the helper before scheduling a sound on a reused context. It is a no-op for running or closed contexts and contains resume failures because optional audio feedback must not interrupt input.
1973
+
1974
+ ```typescript
1975
+ import { resumeAudioContext } from "joiner-sdk/v1/client.js";
1976
+
1977
+ const context = new AudioContext();
1978
+ function playCue() {
1979
+ resumeAudioContext(context);
1980
+ // Create and start this cue's AudioNodes.
1981
+ }
1982
+ ```
1983
+
1984
+ The helper also covers a newly-created context that starts suspended, but it does not bypass autoplay policy: create or resume audio from a user gesture when the browser requires one.
1985
+
1986
+ <!-- Keep this explicit ID: GitHub and VitePress generate different heading slugs. -->
1987
+ <a id="render-budget"></a>
1988
+
1989
+ ### `createRenderBudget()` / `resolveRenderBudgetDefaults()`
1990
+
1991
+ Every continuous-render tile (a `requestAnimationFrame` loop that redraws a canvas every frame) should adopt the platform render budget. It applies the platform power defaults — a 60 fps render cap on mobile-like clients (desktop stays uncapped), a device-pixel-ratio cap of 1.5 on mobile (2 on desktop), no antialiasing or soft shadows above DPR 1, and the default WebGL `powerPreference` — and it reports detailed render stats (fps, missed frames, render CPU, draw calls) that the platform uses to find battery-hungry tiles. On lab hardware the DPR + fps defaults cut rendered pixels by ~59% on a high-refresh Android phone with no visible quality loss. They are defaults, not an enforced ceiling: a tile that knows its workload can override them (see "Quality overrides" below).
1992
+
1993
+ **If your tile owns its render loop** (plain canvas 2D, three.js, raw WebGL), create a budget and let it drive renderer construction and the frame gate:
1994
+
1995
+ ```typescript
1996
+ import { createRenderBudget } from "joiner-sdk/v1/client.js";
1997
+
1998
+ const budget = createRenderBudget({
1999
+ canvas, // prices each rendered frame for the pixels metric
2000
+ getDrawCalls: () => renderer?.info.render.calls, // three.js only; omit for canvas 2D
2001
+ });
2002
+ const renderer = new THREE.WebGLRenderer({ canvas, ...budget.rendererOptions() });
2003
+ budget.configureRenderer(renderer); // applies the DPR cap + shadow downgrade
2004
+
2005
+ function loop(now: number) {
2006
+ // The gate skips RENDERING only. Keep simulation and input handling at
2007
+ // full rAF cadence (with your usual dt clamp) so a skipped frame never
2008
+ // desyncs game state.
2009
+ const renderThisFrame = budget.shouldRenderFrame(now);
2010
+ stepSimulation();
2011
+ if (renderThisFrame) {
2012
+ budget.renderFrame(() => renderer.render(scene, camera));
2013
+ }
2014
+ requestAnimationFrame(loop);
2015
+ }
2016
+ ```
2017
+
2018
+ **Static scenes:** when your loop keeps ticking but the scene needs no repaint, call `budget.shouldRenderFrame(now, { idle: true })` before returning. It returns `false`, continues tick accounting and periodic telemetry, and ends the previous render interval so resuming does not count intentional idle time as missed frames. Resume the ordinary gate call as soon as input, simulation, a resize, or another invalidation requires a repaint. Keep simulation and input processing active during idle ticks.
2019
+
2020
+ This is the single biggest battery lever a canvas tile has, and "static" includes more screens than it sounds: the **menu / title screen, the game-over card, pause and how-to overlays, and any time host chrome covers the tile**. Players spend a large share of every session on those screens, and a loop that keeps redrawing them at 60 fps costs nearly as much as active play. Measured on a 2D canvas game on real phones, idle-gating the menu and game-over screens cut the tile's power on those screens by 30–48%, with one ambient frame every ~250 ms keeping the scene alive; return to full rate for about a second after input or a phase change so transitions stay smooth.
2021
+
2022
+ **Fewer frames before cheaper frames:** the cost of a canvas frame is mostly *producing and presenting a full-screen frame*, more than what is drawn on it — a canvas that only clears itself 60 times a second still used about two thirds of a full scene's rendering thread time. So render fewer frames first, then make the drawing cheaper (offset-fill shadows instead of `ctx.shadow*`, a cached background layer instead of a per-frame full-screen composite, sprite caches), which is worth about 13% of gameplay power on one phone in our measurements (inside run-to-run noise on another) and nothing on idle screens, which should not be rendering anyway.
2023
+
2024
+ **A lower `targetFps` during play is not a substitute:** whether it saves power depends on the device's power management (it paid on one measured phone and not on another, so it cannot be assumed from the platform), and only a person can judge whether it still feels smooth, so leave that decision to the creator. A cap that is taken saves less on a busy page: the compositor produces a frame whenever anything on the page changes, so a HUD value written every simulation tick, or a CSS animation or transition running while playing, keeps the page at the panel rate regardless of the canvas gate, and the cap then saves only the canvas's own work. Write HUD values inside the render callback, at the canvas cadence, and drive play-time effects from the render step rather than CSS keyframes or transitions, keeping their look.
2025
+
2026
+ **Two related habits:** only write DOM properties (`hidden`, `style.transform`, text) when the value changed, since an unchanged write each tick still forces a style recalculation; and adopt the budget before sizing your canvas, because a `resize()` that runs before adoption pins the buffer to pixel ratio 1 without anyone noticing. You can check all of this in a browser: count render calls per second on each screen (about 4 while idle-gated, 60 during play), confirm `canvas.width` equals its CSS width times the budget's resolved `pixelRatio`, and watch the page's frame rate during play equal the canvas target rather than the panel rate.
2027
+
2028
+ **WebGL context loss:** when the budget's `canvas` is a real canvas element, the budget also watches it for `webglcontextlost` / `webglcontextrestored` and records the event for the platform's reliability telemetry. A reclaimed context (common in mobile WebViews under memory pressure) makes every GL call a silent no-op — the loop keeps running at full fps while the canvas turns transparent, so the player sees your page background and nothing else. Pass `onContextLost` / `onContextRestored` to show and clear a visible notice; three.js re-initializes its own GL state on restore, so hiding the notice is usually all the recovery a tile needs:
2029
+
2030
+ ```typescript
2031
+ const budget = createRenderBudget({
2032
+ canvas,
2033
+ onContextLost: () => showNotice("Graphics paused by your device…"),
2034
+ onContextRestored: () => hideNotice(),
2035
+ });
2036
+ ```
2037
+
2038
+ Create ONE budget per document, not one per game round: the platform's power metric reads cumulative counters, so a fresh budget on every remount resets them mid-session and corrupts the tile's numbers. If your tile rebuilds its renderer across rounds or component remounts, use the SDK's shared-budget factory instead of managing the singleton yourself — `acquireSharedRenderBudget()` returns the document's one budget (creating it on first call), and `adoptSharedRenderBudgetRenderer(renderer)` re-points frame pricing, draw-call sampling, and the DPR cap at each freshly built renderer (`adoptSharedRenderBudgetCanvas(canvas)` is the flavor for canvas-2D tiles with no renderer object). Soft shadows: pick the shadow-map type from `budget.defaults.softShadows` instead of hardcoding `PCFSoftShadowMap`.
2039
+
2040
+ ```typescript
2041
+ import { adoptSharedRenderBudgetRenderer } from "joiner-sdk/v1/client.js";
2042
+
2043
+ // In the mount path that (re)builds the renderer — every mount adopts the
2044
+ // same document-scoped budget, so the platform's cumulative counters survive:
2045
+ const budget = adoptSharedRenderBudgetRenderer(renderer);
2046
+ ```
2047
+
2048
+ **If an engine owns the loop** (Phaser), you cannot wrap the render call — map the resolved values into the engine's own config with the pure resolver instead:
2049
+
2050
+ ```typescript
2051
+ import { resolveRenderBudgetDefaults } from "joiner-sdk/v1/client.js";
2052
+
2053
+ const defaults = resolveRenderBudgetDefaults();
2054
+ const game = new Phaser.Game({
2055
+ ...(defaults.targetFps !== null ? { fps: { limit: defaults.targetFps } } : {}),
2056
+ render: { powerPreference: defaults.powerPreference },
2057
+ // ...rest of your config
2058
+ });
2059
+ ```
2060
+
2061
+ Do NOT call `createRenderBudget()` from an engine-owned tile just to read `.defaults`: constructing a budget registers the helper as the iframe's render-stats producer and silences the platform's automatic instrumentation — if nothing then drives `shouldRenderFrame`/`renderFrame`, the tile stops reporting render stats entirely. `resolveRenderBudgetDefaults()` is side-effect free.
2062
+
2063
+ **If a tile does neither**, it still works and is still measured: the platform auto-instruments every tile with coarse render stats. But it renders unbudgeted — high-refresh Android panels run the loop at 90–120 fps and retina screens get uncapped-DPR buffers, both pure battery cost — and its telemetry stays coarse, so it shows up worse in the platform's per-tile power ranking without the detail to explain why.
2064
+
2065
+ #### Quality overrides
2066
+
2067
+ The resolved values are the platform's defaults, nothing more. A tile that wants different quality — a graphics-settings page, richer settings chosen from its own knowledge of its workload — passes explicit overrides, and the SDK honors them verbatim:
2068
+
2069
+ ```typescript
2070
+ const budget = createRenderBudget({
2071
+ canvas,
2072
+ maxPixelRatio: 3, // raise (or lower) the DPR cap
2073
+ antialias: true, // replace the resolved-DPR-based default
2074
+ targetFps: 30, // change the frame-gate target; applies on desktop too
2075
+ });
2076
+ // The same options work on acquireSharedRenderBudget() (first call only)
2077
+ // and on resolveRenderBudgetDefaults() for engine-owned tiles.
2078
+ ```
2079
+
2080
+ Prefer overriding through the budget over bypassing it: `shouldRenderFrame()` is also what counts frames and paces the platform's render stats, so routing around the gate corrupts your tile's telemetry, while an explicit `targetFps` keeps the whole instrument coherent (the gate paces against it, missed frames are judged against it, and the reported target reflects it). Overrides are stamped into the tile's power telemetry, so an opted-up tile shows up hotter in the fleet ranking *with the explanation attached* — never disguised as a regression.
2081
+
2082
+ Platform behavior worth knowing before overriding (documented, not enforced):
2083
+
2084
+ - **iOS WKWebView clamps `requestAnimationFrame` to ~60 Hz** even on 120 Hz ProMotion panels, so a higher `targetFps` there renders at ~60 while being truthfully judged against your request — expect a poor missed-frame ratio.
2085
+ - **Android WebView runs rAF at the panel rate**, so targets above 60 are reachable only on high-refresh panels.
2086
+ - **Sub-60 targets read as visibly choppy** on phones (the platform default is 60 for this reason).
2087
+ - **`maxPixelRatio` above the device's real DPR buys nothing** — the resolved ratio is `min(device DPR, maxPixelRatio)`.
2088
+
2089
+ ### `createVerticalScrollBounceMount()`
2090
+
2091
+ Create an inner render target inside a root element and opt the root into native vertical pull bounce, even when the app's content is shorter than the viewport. Use this for the normal iframe-document case where `#root` is the top-level scroll container.
2092
+
2093
+ Apps scaffolded from the official templates already call this in their entry file, so most apps do not need to add it manually.
2094
+
2095
+ ```typescript
2096
+ import { createVerticalScrollBounceMount } from "joiner-sdk/v1/client.js";
2097
+
2098
+ const root = document.getElementById("root");
2099
+ if (root) {
2100
+ const appRoot = createVerticalScrollBounceMount(root);
2101
+ renderApp(appRoot);
2102
+ }
2103
+ ```
2104
+
2105
+ The helper clears `root` and appends one generated content wrapper on every platform. Inside the iOS app, it also applies vertical overflow/momentum styles to `root` and makes the wrapper at least `calc(100% + 1px)` tall. The 1px overflow is intentional: it is the smallest reliable amount needed for WKWebView to enter the native rubber-band path.
2106
+
2107
+ ### `installVerticalScrollBounce()`
2108
+
2109
+ Opt a specific custom scroll area into native vertical pull bounce. Use this when only part of the app should bounce, such as a chat message list, while settings/invite/member panels should keep their own behavior.
2110
+
2111
+ ```typescript
2112
+ import { installVerticalScrollBounce } from "joiner-sdk/v1/client.js";
2113
+
2114
+ const cleanup = installVerticalScrollBounce({
2115
+ scrollElement: messagesScroller,
2116
+ contentElement: messagesList,
2117
+ });
2118
+ ```
2119
+
2120
+ `contentElement` must be a descendant of `scrollElement`. The helper returns a cleanup function that restores the previous inline styles. Outside the iOS app it validates the input and otherwise no-ops, so desktop, mobile web, and Android do not get a forced 1px scroll range. If the content later grows taller than the viewport, the same element remains the normal scroll container; no re-install is needed.
2121
+
2122
+ ### `isIosApp()`
2123
+
2124
+ Returns `true` when running inside the iOS app WebView, including sandboxed app iframes. Use this only for behavior that depends on the native app shell; use [`isIosWebkit()`](#isioswebkit) for broader iOS WebKit checks.
2125
+
2126
+ ```typescript
2127
+ import { isIosApp } from "joiner-sdk/v1/client.js";
2128
+
2129
+ if (isIosApp()) {
2130
+ // Native-app-only iOS behavior
2131
+ }
2132
+ ```
2133
+
2134
+ ### `isAndroidApp()`
2135
+
2136
+ Returns `true` when running inside the Android app WebView, including sandboxed app iframes. The Android counterpart of [`isIosApp()`](#isiosapp); use it for behavior that depends on the native Android app shell. (There is no `isAndroidWebkit()` — the Android WebView is Chromium, not WebKit.)
2137
+
2138
+ ```typescript
2139
+ import { isAndroidApp } from "joiner-sdk/v1/client.js";
2140
+
2141
+ if (isAndroidApp()) {
2142
+ // Native-app-only Android behavior
2143
+ }
2144
+ ```
2145
+
2146
+ ### `isIosWebkit()`
2147
+
2148
+ Returns `true` when running in iOS Safari or WKWebView (including the iOS app). Use only for genuine platform differences — most code should be platform-agnostic.
2149
+
2150
+ ```typescript
2151
+ import { isIosWebkit } from "joiner-sdk/v1/client.js";
2152
+
2153
+ if (isIosWebkit()) {
2154
+ // iOS-specific workaround
2155
+ }
2156
+ ```
2157
+
2158
+ ### `isMobileLikeClient()`
2159
+
2160
+ Returns `true` when the app is running inside the iOS or Android app **or** in a browser whose primary pointer is coarse (phones, tablets, touchscreen laptops in tablet mode). Returns `false` on regular desktops with a mouse and in Node / SSR contexts.
2161
+
2162
+ Use to gate UI that only makes sense on touch-primary devices — touch-only controls or mobile-specific install hints.
2163
+
2164
+ ```typescript
2165
+ import { isMobileLikeClient } from "joiner-sdk/v1/client.js";
2166
+
2167
+ if (isMobileLikeClient()) {
2168
+ // Render the touch joystick.
2169
+ }
2170
+ ```
2171
+
2172
+ ### `applyNativeAppGestureOverrides()`
2173
+
2174
+ Suppress default browser gestures (text selection, the iOS callout menu, and native link-drag) inside the native app's WebView, so the app feels like a native mobile app. Opt-in per app — call once at app startup (e.g. in your entry file).
2175
+
2176
+ Inputs, textareas, and contenteditable elements are opted back in so users can still select and copy text they've typed.
2177
+
2178
+ No-op outside the native app WebView — desktop browsers, iOS Safari, and Android Chrome keep their default behavior. Idempotent.
2179
+
2180
+ ```typescript
2181
+ import { applyNativeAppGestureOverrides } from "joiner-sdk/v1/client.js";
2182
+
2183
+ applyNativeAppGestureOverrides();
2184
+ ```
2185
+
2186
+ ### `suppressLongPressMagnifier()`
2187
+
2188
+ Suppress the iOS long-press magnifier loupe on one element. No tile may show the loupe, so call it on every non-scrolling surface a finger can rest on — a game canvas, a board, a draggable piece, and also the HUD, buttons, and menus. Apply it per element; the exceptions are native scrollers, form fields, and links. One call on the nearest non-scrolling container covers a group of controls (the HUD, a menu, a button row).
2189
+
2190
+ `applyNativeAppGestureOverrides()` stops the selection callout and text selection, but on iOS it does **not** stop every round magnifier loupe WebKit shows once a still finger starts its text-selection gesture. For a plain long press, `-webkit-user-select: none` stops the loupe. A tap followed quickly by a long press bypasses that CSS and opens the loupe even over non-selectable content, so a press-and-hold-to-charge or drag interaction can pop a magnifier mid-play. WebKit withholds that gesture only when the page cancels `touchstart`.
2191
+
2192
+ Pass the surface element. The helper sets `-webkit-user-select`, `user-select`, `-webkit-touch-callout`, and `touch-action` to `none` on it. It lets touches through until the first tap in the tile ends (or the first real click lands), and cancels `touchstart` for every touch on the element after that. The first tap stays a real tap, so it still lifts the iOS 30 fps limit on tile frames, which only a real click can do. The cost: if the very first tap is followed at once by a hold, the loupe can still appear that one time. It returns a function that removes the listeners and restores the CSS (call it on unmount). Applies on all iOS WebKit; a no-op that returns a no-op remover elsewhere (Android, desktop, server).
2193
+
2194
+ **Scope it deliberately.** `touch-action: none` stops panning and zooming on the element, and a cancelled `touchstart` also loses the synthesized `click`. Use the plain call where input comes from `pointerdown` / `pointerup`, with no `click` handlers on the surface. An element that must scroll natively cannot use the helper at all.
2195
+
2196
+ **Surfaces with `click` handlers (`preserveTaps`).** If taps on the element run on `click` handlers (buttons, menus, tap-to-move board cells, tap-to-place racks — `click` is also how keyboard activation reaches `<button>` cells), pass `{ preserveTaps: true }`. Every quick still tap is then re-dispatched as a synthetic bubbling `click` at the touched element, so click handlers and framework event delegation keep working during rapid taps; when iOS also sends its own click for the first tap, the helper stops that duplicate before your handlers see it; holds and drags produce no click; mouse, keyboard, and non-iOS platforms are untouched. A re-created tap is a press of at most 500 ms that travels at most 10 px. Nested installs re-create one click per tap. The synthetic click is `isTrusted: false` and does not focus inputs — never point this mode at form fields or navigation links.
2197
+
2198
+ ```typescript
2199
+ import { suppressLongPressMagnifier } from "joiner-sdk/v1/client.js";
2200
+
2201
+ // Pointer-driven canvas — plain call:
2202
+ const canvas = document.querySelector("canvas")!;
2203
+ const removeMagnifierSuppression = suppressLongPressMagnifier(canvas);
2204
+
2205
+ // Tap+drag board whose cells act on click — preserve taps:
2206
+ const board = document.getElementById("board")!;
2207
+ const removeBoardSuppression = suppressLongPressMagnifier(board, {
2208
+ preserveTaps: true,
2209
+ });
2210
+
2211
+ // later, on teardown:
2212
+ removeMagnifierSuppression();
2213
+ removeBoardSuppression();
2214
+ ```
2215
+
2216
+ ### `installKeyboardLayoutInset()`
2217
+
2218
+ Keep your app's layout above the iOS on-screen keyboard. On iOS the WKWebView does **not** resize when the keyboard opens — it just draws the keyboard on top of your content, so a bottom-anchored input or button ends up hidden behind it. Call this once at startup to opt in: the native shell then shrinks your scroll container (`#root` by default) by the live keyboard height, so the space the keyboard occupies is removed from your layout and bottom-anchored content stays visible. It animates in sync with the keyboard and is a **no-op outside the iOS app** (desktop, Safari, Chrome, Android are unaffected — they resize or scroll natively).
2219
+
2220
+ ```typescript
2221
+ import { installKeyboardLayoutInset } from "joiner-sdk/v1/client.js";
2222
+
2223
+ installKeyboardLayoutInset(); // shrinks #root; call once at startup
2224
+ installKeyboardLayoutInset({ selector: ".app-root" }); // custom container
2225
+ ```
2226
+
2227
+ Use it for a **full-viewport app that owns its own keyboard layout** — one with a scroll scaffold (`html, body { height: 100dvh; overflow: hidden }` and the container `overflow-y: auto`) and a docked input bar, like a chat composer. Registering also disables the WebView's native document scrolling while the app is mounted (so a drag with the keyboard up can't push your fixed chrome off-screen).
2228
+
2229
+ **Consequence — a non-docked input needs help.** Because registering suppresses WebKit's native scroll-to-focused, an input that lives in ordinary scroll flow (not docked above the keyboard) is no longer auto-revealed when it's focused — the keyboard will cover it. You have two options: dock the input's controls above the keyboard (a bottom bar that rides the shrunk container), or scroll them into view yourself with `createKeyboardFocusScroller()` below.
2230
+
2231
+ ### `createKeyboardFocusScroller()`
2232
+
2233
+ The companion to `installKeyboardLayoutInset()` for the scroll-it-yourself case: it scrolls a focused input's controls above the keyboard. On focus it eases the scroll container each animation frame so the controls ride up **with** the rising keyboard (rather than the keyboard covering the input and the page snapping afterward), and a manual drag aborts it. It's a no-op where the browser's own scroll-to-focused already reveals the input, so it's safe to leave in for every platform.
2234
+
2235
+ Wire it to the element wrapping the input **and** its buttons (e.g. the `<form>`): attach `ref` to that element, `onFocusIn` as its focus handler, and call `dispose()` on unmount.
2236
+
2237
+ ```tsx
2238
+ import {
2239
+ createKeyboardFocusScroller,
2240
+ installKeyboardLayoutInset,
2241
+ } from "joiner-sdk/v1/client.js";
2242
+ import { onCleanup } from "solid-js";
2243
+
2244
+ // once at startup:
2245
+ installKeyboardLayoutInset();
2246
+
2247
+ // in the component that renders the input (SolidJS shown; same idea in React/Preact):
2248
+ function GuessForm() {
2249
+ const scroller = createKeyboardFocusScroller();
2250
+ onCleanup(scroller.dispose);
2251
+ return (
2252
+ <form ref={scroller.ref} onFocusIn={scroller.onFocusIn} class="pb-4">
2253
+ <input placeholder="Your guess…" />
2254
+ <button type="submit">Guess</button>
2255
+ </form>
2256
+ );
2257
+ }
2258
+ ```
2259
+
2260
+ Options: `scrollRoot` (element or getter; defaults to the `#root` element) and `maxDurationMs` (how long to keep tracking the keyboard's rise; defaults to 800). Add a little bottom padding (e.g. `pb-4`) below the last control so it doesn't sit flush against the keyboard.
2261
+
2262
+ ## Framework Hooks
2263
+
2264
+ ### React — `useLiveQuery` (`joiner-sdk/v1/react`)
2265
+
2266
+ A React hook that subscribes to a live store query. Handles subscription lifecycle automatically and re-renders when data changes.
2267
+
2268
+ ```typescript
2269
+ import { useLiveQuery } from "joiner-sdk/v1/react";
2270
+
2271
+ function App({ store }) {
2272
+ const { data: items, isLoading } = useLiveQuery(store, (tx) =>
2273
+ tx.table("items").entries().toArray(),
2274
+ );
2275
+
2276
+ if (isLoading) return <div>Loading...</div>;
2277
+
2278
+ return (
2279
+ <ul>
2280
+ {(items ?? []).map(([, item]) => <li key={item.id}>{item.text}</li>)}
2281
+ </ul>
2282
+ );
2283
+ }
2284
+ ```
2285
+
2286
+ **Parameters:**
2287
+
2288
+ | Parameter | Type | Description |
2289
+ |-----------|------|-------------|
2290
+ | `store` | `InferSyncedStoreClient<Schema> \| null` | The store to subscribe to. Pass `null` to get loading state. |
2291
+ | `queryFn` | `(tx: QueryContext) => Promise<T>` | Query function run against a read transaction |
2292
+
2293
+ **Returns:** `{ data: T | undefined, isLoading: boolean }`
2294
+
2295
+ - `data` is `undefined` until the first query result arrives
2296
+ - When `queryFn` reference changes, previous data is kept until new results arrive
2297
+ - The hook automatically unsubscribes on unmount
2298
+
2299
+ ### SolidJS — `createLiveQuery` (`joiner-sdk/v1/solid`)
2300
+
2301
+ A SolidJS reactive primitive that subscribes to a live store query. Both parameters are accessors for fine-grained reactivity.
2302
+
2303
+ ```typescript
2304
+ import { Show, For } from "solid-js";
2305
+ import { createLiveQuery } from "joiner-sdk/v1/solid";
2306
+ import type { InferSyncedStoreClient } from "joiner-sdk/v1/client.js";
2307
+ import type { MySchema } from "./synced-store/schema";
2308
+
2309
+ type MyStoreClient = InferSyncedStoreClient<MySchema>;
2310
+
2311
+ function App(props: { store: MyStoreClient }) {
2312
+ const { data, isLoading } = createLiveQuery(
2313
+ () => props.store,
2314
+ () => (tx) => tx.table("items").entries().toArray(),
2315
+ );
2316
+
2317
+ return (
2318
+ <Show when={!isLoading()} fallback={<div>Loading...</div>}>
2319
+ <For each={data() ?? []}>
2320
+ {([, item]) => <li>{item.text}</li>}
2321
+ </For>
2322
+ </Show>
2323
+ );
2324
+ }
2325
+ ```
2326
+
2327
+ **Parameters:**
2328
+
2329
+ | Parameter | Type | Description |
2330
+ |-----------|------|-------------|
2331
+ | `storeAccessor` | `Accessor<InferSyncedStoreClient<Schema> \| null>` | Accessor returning the store (or `null` for loading) |
2332
+ | `queryFnAccessor` | `Accessor<(tx: QueryContext) => Promise<T>>` | Accessor returning the query function |
2333
+
2334
+ **Returns:** `{ data: Accessor<T | undefined>, isLoading: Accessor<boolean> }`
2335
+
2336
+ - Both params are accessors — SolidJS tracks signal reads for automatic re-subscription
2337
+ - `onCleanup` handles unsubscription automatically
2338
+
2339
+ ### SolidJS — `createLiveQueryResource` (`joiner-sdk/v1/solid`)
2340
+
2341
+ Suspense-aware sibling of `createLiveQuery`. It subscribes to the same live query shape, but exposes the initial result through a Solid `Resource`; later subscription results mutate that resource.
2342
+
2343
+ ```typescript
2344
+ import { For, Suspense } from "solid-js";
2345
+ import { createLiveQueryResource } from "joiner-sdk/v1/solid";
2346
+
2347
+ function App(props: { store: MyStoreClient }) {
2348
+ const { data } = createLiveQueryResource(
2349
+ () => props.store,
2350
+ () => (tx) => tx.table("items").entries().toArray(),
2351
+ );
2352
+
2353
+ return (
2354
+ <Suspense fallback={<div>Loading...</div>}>
2355
+ <For each={data() ?? []}>
2356
+ {([, item]) => <li>{item.text}</li>}
2357
+ </For>
2358
+ </Suspense>
2359
+ );
2360
+ }
2361
+ ```
2362
+
2363
+ **Returns:** `{ data: Resource<T | undefined>, isLoading: Accessor<boolean> }`
2364
+
2365
+
2366
+ ### Retrying the current tile
2367
+
2368
+ *Added 2026-09-10.*
2369
+
2370
+ Import `requestTileReload` from `joiner-sdk/v1/client.js`. Call it from an explicit Retry action when the current document cannot recover. The owning host remounts the same instance and open props in a fresh frame. This preserves stored history; disposable unsaved UI state is recreated. It does not request a bundle upgrade, migrate data, or clear caches. If the session was disconnected because it was opened somewhere else, the host reloads the whole page instead, since only a page reload reconnects it.
2371
+
2372
+ ```ts
2373
+ const result = await requestTileReload();
2374
+ if (result.status !== "accepted") {
2375
+ // Show result.message and let the user try again.
2376
+ }
2377
+ ```
2378
+
2379
+ Disable Retry while pending. Repeated calls share one pending request. `accepted` means the host accepted the request, not that the replacement loaded. Other results are `unavailable`, `timeout` (no acknowledgement within five seconds), or `failed`, each with a user-facing `message`. Older hosts and unsupported nested wrappers time out with guidance to reload the page. The top document and a same-origin framed HTTP kernel shell can reload themselves; sandboxed iframe documents never navigate their own blob URL. The SDK's store access notice already uses this recovery action.
2380
+
2381
+ ### Correlating mutation failures across retries
2382
+
2383
+ *Added 2026-09-29; `flushDelivered()` added 2026-09-30.*
2384
+
2385
+ Import `createMutationFailureObserver` from `joiner-sdk/v1/client.js` when an interface keeps editable input while retrying a rejected mutation. Create one observer per store session. Supply `requests`, `matchesInput`, `isCurrent`, `hasAccepted`, and `onDiagnostic`. Capture immutable inputs and register the new request's deferred `identity` synchronously before validation or mutation creation; resolve it from the mutation result, or with `undefined` if creation fails.
2386
+
2387
+ All three request callbacks (`isCurrent`, `hasAccepted`, `onDiagnostic`) receive captured shallow copies of plain records. Compare stable key/epoch fields, never object identity; do not rely on prototype methods or fields assigned after delivery. Inputs must be immutable and structured-cloneable (unwrap reactive proxies before capture). Invalid inputs or throwing diagnostic callbacks produce no diagnostic and never establish acceptance.
2388
+
2389
+ Transient store retries do not produce request diagnostics. Commit contention (`optimistic_lock_conflict`) retains the write and retries with overload backoff indefinitely; it never consumes the refusal budget or produces an exhaustion diagnostic. Repeated `mutation_id_mismatch` and `schema_version_mismatch` refusals can exhaust that budget, causing the store to revert the mutation as a non-retriable `unexpected_error`. The observer can then emit a `current-attempt` diagnostic for a matching current request, alongside the separate stuck-mutation background error.
2390
+
2391
+ The host has exported the observer since runtime 47, but the current Vite plugin infers runtime 48 for every `createMutationFailureObserver` import from `joiner-sdk/v1/client.js`, including observer-only use. Declare `poeTile({ minSdkVersion: 48 })` for that entry. The emitted minimum is the greater of the configured and inferred floors, so declaring 47 does not make the build compatible with runtime 47. `Poe.has(...)` cannot guard a missing named import.
2392
+
2393
+ For Vite-built tiles, importing `createMutationFailureObserver` from `joiner-sdk/v1/mutation-failure-observer.js` bundles the portable helper into the tile. This subpath needs no host runtime upgrade; use an SDK package version that includes it.
2394
+
2395
+ When `hasAccepted` reads a store with optimistic changes, register a deferred `settled` promise on the request before invoking `mutate`, alongside the deferred `identity`. Resolve only the diagnostic gate with `settled.resolve(result.confirmed.catch(() => {}))`; this handles abandonment even if no failure event reaches the observer. The original `result.confirmed` retains its rejection and application handling; this derived gate does not convert abandonment into acceptance. If mutation creation fails, resolve the gate in `finally`. Do not assign `settled` after a failure has arrived: the observer captures the request at delivery. The observer waits for `settled` to fulfill or reject before checking current-request eligibility and authoritative acceptance, so an optimistic value cannot suppress a rejection diagnostic. Settlement means processing/rollback finished, not success; `hasAccepted` must still check authoritative application evidence. Omit `settled` only when that check cannot observe an in-flight optimistic write.
2396
+
2397
+ `current-attempt` diagnostics match both client and mutation IDs. `historical-request` means identity metadata is unavailable: the failure concerns this input, but may belong to an earlier attempt. Never clear newer input or declare the current attempt failed from historical evidence. `confirmed` means processed, not successful; use authoritative application evidence for `hasAccepted`. The observer never retries or changes application state. Dispose it when the store session ends. Absence of a diagnostic does not establish success, because sufficiently late failures can outlive the SDK's bounded recent-mutation cache.
2398
+
2399
+ `isCurrent` receives a shallow captured request. Compare its stable key and epoch (or equivalent caller-owned generation), not object reference equality.
2400
+
2401
+ A request record may also include `settled?: Promise<unknown>`, supplied by the caller as a completion-only gate. Follow the deferred-gate pattern above: `settled.resolve(result.confirmed.catch(() => {}))`, and resolve the gate if mutation creation fails. Keep the original `result.confirmed` rejection and application handling separate. The gate must finish only when that request's mutation lifecycle or caller-owned bookkeeping finishes; it does not certify acceptance. It is optional and is not supplied by the observer.
2402
+
2403
+ The callable disposer also exposes `await observer.flushDelivered({ key: request.key, epoch: request.epoch })`. It captures that selector and waits only for inspections already registered for that attempt; later failures and other attempts are excluded. The `key`/`epoch` pair must uniquely identify each tracked attempt; change the epoch for every retry, including a retry with identical input. An undefined epoch is one exact value, not a wildcard. Resolve that attempt's identity and settled promises first, then keep it current until the checkpoint completes. Never await it from those dependencies or an observer callback, which would wait on itself. The checkpoint does not prove acceptance or the absence of future errors. Call `observer()` to unsubscribe.
2404
+
2405
+ `flushDelivered()` requires SDK runtime version 48 or newer when the observer is imported from the client entry (`joiner-sdk/v1/client.js`). The Vite import gate already enforces that floor for both observer-only and checkpoint use; the bundled portable `joiner-sdk/v1/mutation-failure-observer.js` subpath needs no host runtime upgrade.
2406
+
2407
+ The no-argument `observer.flushDelivered()` is an advanced observer-wide checkpoint. It waits for every captured attempt, so **all** tracked identity and settled gates must be resolved before awaiting it—including any new retry that has not yet called `mutate`. Use the explicit selector when retiring one request.