@picassohq/cli 0.0.0-stage → 1.0.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 (230) hide show
  1. package/agents/browser_agent.yaml +53 -0
  2. package/agents/code_reviewer.yaml +49 -0
  3. package/agents/codebase_investigator.yaml +70 -0
  4. package/agents/design_auditor.yaml +50 -0
  5. package/agents/devex_auditor.yaml +50 -0
  6. package/agents/doc_writer.yaml +54 -0
  7. package/agents/engineering_architect.yaml +51 -0
  8. package/agents/generalist.yaml +55 -0
  9. package/agents/migration_planner.yaml +51 -0
  10. package/agents/product_reviewer.yaml +48 -0
  11. package/agents/qa_operator.yaml +52 -0
  12. package/agents/release_engineer.yaml +50 -0
  13. package/agents/security_auditor.yaml +62 -0
  14. package/agents/test_writer.yaml +52 -0
  15. package/assets/first-light-lockup.png +0 -0
  16. package/assets/first-light-tagline.png +0 -0
  17. package/assets/house/README.md +26 -0
  18. package/assets/house/auraone-banner.png +0 -0
  19. package/assets/house/auraone-logo.png +0 -0
  20. package/assets/house/kiro-prism-banner.png +0 -0
  21. package/assets/house/kiro-prism-logo.png +0 -0
  22. package/assets/house/picasso-banner.png +0 -0
  23. package/assets/house/picasso-logo.png +0 -0
  24. package/assets/wordmark-app.png +0 -0
  25. package/assets/wordmark-tight.png +0 -0
  26. package/assets/wordmark.png +0 -0
  27. package/design/styles.css +1042 -0
  28. package/dist/build-info.json +37 -0
  29. package/dist/index.js +3028 -0
  30. package/goals/cli-hardening.yaml +40 -0
  31. package/goals/repo-maintenance.yaml +40 -0
  32. package/package.json +49 -4
  33. package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
  34. package/runtime/dsh/picasso-ecosystem.community.json +185 -0
  35. package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
  36. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
  37. package/runtime/dsh/picasso-isolation.patch.yml +25 -0
  38. package/runtime/dsh/picasso-providers.patch.yml +373 -0
  39. package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
  40. package/runtime/dsh/picasso-sdk.patch.yml +204 -0
  41. package/runtime/engine-manifest.json +214 -0
  42. package/runtime/package.json +6 -0
  43. package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
  44. package/runtime/packages/picasso-cache-probe/index.js +477 -0
  45. package/runtime/packages/picasso-cache-probe/package.json +38 -0
  46. package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
  47. package/runtime/packages/picasso-commands/fresh-review.js +573 -0
  48. package/runtime/packages/picasso-commands/index.js +497 -0
  49. package/runtime/packages/picasso-commands/package.json +28 -0
  50. package/runtime/packages/picasso-instructions/conflicts.js +115 -0
  51. package/runtime/packages/picasso-instructions/formats.js +145 -0
  52. package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
  53. package/runtime/packages/picasso-instructions/glob.js +114 -0
  54. package/runtime/packages/picasso-instructions/globals.js +90 -0
  55. package/runtime/packages/picasso-instructions/imports.js +123 -0
  56. package/runtime/packages/picasso-instructions/index.js +326 -0
  57. package/runtime/packages/picasso-instructions/modes.js +64 -0
  58. package/runtime/packages/picasso-instructions/package.json +30 -0
  59. package/runtime/packages/picasso-instructions/parse.js +134 -0
  60. package/runtime/packages/picasso-instructions/report.js +161 -0
  61. package/runtime/packages/picasso-instructions/resolve.js +939 -0
  62. package/runtime/packages/picasso-instructions/scan.js +181 -0
  63. package/runtime/packages/picasso-instructions/settings.js +150 -0
  64. package/runtime/packages/picasso-instructions/skills.js +345 -0
  65. package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
  66. package/runtime/packages/picasso-lean-context/index.js +6049 -0
  67. package/runtime/packages/picasso-lean-context/package.json +26 -0
  68. package/runtime/packages/picasso-lean-context/timeline.js +417 -0
  69. package/runtime/packages/picasso-librarian/classify.js +146 -0
  70. package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
  71. package/runtime/packages/picasso-librarian/index.js +878 -0
  72. package/runtime/packages/picasso-librarian/notes.js +159 -0
  73. package/runtime/packages/picasso-librarian/package.json +34 -0
  74. package/runtime/packages/picasso-librarian/state.js +478 -0
  75. package/runtime/packages/picasso-memory/index.js +1184 -0
  76. package/runtime/packages/picasso-memory/package.json +21 -0
  77. package/runtime/packages/picasso-model-router/connections.js +895 -0
  78. package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
  79. package/runtime/packages/picasso-model-router/index.js +1081 -0
  80. package/runtime/packages/picasso-model-router/package.json +30 -0
  81. package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
  82. package/runtime/packages/picasso-options/index.js +263 -0
  83. package/runtime/packages/picasso-options/package.json +28 -0
  84. package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
  85. package/runtime/packages/picasso-progress-reports/index.js +267 -0
  86. package/runtime/packages/picasso-progress-reports/package.json +30 -0
  87. package/runtime/packages/picasso-progress-reports/report.js +235 -0
  88. package/runtime/packages/picasso-sdk-server/aside.js +128 -0
  89. package/runtime/packages/picasso-sdk-server/connections.js +38 -0
  90. package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
  91. package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
  92. package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
  93. package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
  94. package/runtime/packages/picasso-sdk-server/goal.js +131 -0
  95. package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
  96. package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
  97. package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
  98. package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
  99. package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
  100. package/runtime/packages/picasso-sdk-server/index.js +886 -0
  101. package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
  102. package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
  103. package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
  104. package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
  105. package/runtime/packages/picasso-sdk-server/package.json +50 -0
  106. package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
  107. package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
  108. package/runtime/packages/picasso-sdk-server/queue.js +322 -0
  109. package/runtime/packages/picasso-sdk-server/requester.js +43 -0
  110. package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
  111. package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
  112. package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
  113. package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
  114. package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
  115. package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
  116. package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
  117. package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
  118. package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
  119. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
  120. package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
  121. package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
  122. package/runtime/packages/picasso-web-search/backends.js +350 -0
  123. package/runtime/packages/picasso-web-search/config.js +121 -0
  124. package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
  125. package/runtime/packages/picasso-web-search/failure.js +111 -0
  126. package/runtime/packages/picasso-web-search/format.js +35 -0
  127. package/runtime/packages/picasso-web-search/index.js +66 -0
  128. package/runtime/packages/picasso-web-search/package.json +38 -0
  129. package/runtime/packages/picasso-web-search/router.js +155 -0
  130. package/runtime/packages/picasso-x-reader/circle.js +324 -0
  131. package/runtime/packages/picasso-x-reader/command.js +169 -0
  132. package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
  133. package/runtime/packages/picasso-x-reader/index.js +170 -0
  134. package/runtime/packages/picasso-x-reader/package.json +39 -0
  135. package/runtime/packages/picasso-x-reader/read.js +370 -0
  136. package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
  137. package/runtime/packages/picasso-x-reader/settings.js +131 -0
  138. package/runtime/packages/picasso-x-reader/urls.js +154 -0
  139. package/runtime/packages/picasso-x-reader/xmd.js +512 -0
  140. package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
  141. package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
  142. package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
  143. package/runtime/plugins/picasso-auto-approve/package.json +28 -0
  144. package/runtime/plugins/picasso-browser/index.js +424 -0
  145. package/runtime/plugins/picasso-browser/package.json +28 -0
  146. package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
  147. package/runtime/plugins/picasso-checkpoints/index.js +885 -0
  148. package/runtime/plugins/picasso-checkpoints/package.json +29 -0
  149. package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
  150. package/runtime/plugins/picasso-commands/index.js +497 -0
  151. package/runtime/plugins/picasso-commands/package.json +28 -0
  152. package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
  153. package/runtime/plugins/picasso-instructions/formats.js +145 -0
  154. package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
  155. package/runtime/plugins/picasso-instructions/glob.js +114 -0
  156. package/runtime/plugins/picasso-instructions/globals.js +90 -0
  157. package/runtime/plugins/picasso-instructions/imports.js +123 -0
  158. package/runtime/plugins/picasso-instructions/index.js +326 -0
  159. package/runtime/plugins/picasso-instructions/modes.js +64 -0
  160. package/runtime/plugins/picasso-instructions/package.json +30 -0
  161. package/runtime/plugins/picasso-instructions/parse.js +134 -0
  162. package/runtime/plugins/picasso-instructions/report.js +161 -0
  163. package/runtime/plugins/picasso-instructions/resolve.js +939 -0
  164. package/runtime/plugins/picasso-instructions/scan.js +181 -0
  165. package/runtime/plugins/picasso-instructions/settings.js +150 -0
  166. package/runtime/plugins/picasso-instructions/skills.js +345 -0
  167. package/runtime/plugins/picasso-lean-context/index.js +6049 -0
  168. package/runtime/plugins/picasso-lean-context/package.json +26 -0
  169. package/runtime/plugins/picasso-lean-context/timeline.js +417 -0
  170. package/runtime/plugins/picasso-librarian/classify.js +146 -0
  171. package/runtime/plugins/picasso-librarian/index.js +878 -0
  172. package/runtime/plugins/picasso-librarian/notes.js +159 -0
  173. package/runtime/plugins/picasso-librarian/package.json +34 -0
  174. package/runtime/plugins/picasso-librarian/state.js +478 -0
  175. package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
  176. package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
  177. package/runtime/plugins/picasso-mail/inbox.js +207 -0
  178. package/runtime/plugins/picasso-mail/index.js +293 -0
  179. package/runtime/plugins/picasso-mail/package.json +22 -0
  180. package/runtime/plugins/picasso-memory/index.js +1184 -0
  181. package/runtime/plugins/picasso-memory/package.json +21 -0
  182. package/runtime/plugins/picasso-model-router/connections.js +895 -0
  183. package/runtime/plugins/picasso-model-router/index.js +1081 -0
  184. package/runtime/plugins/picasso-model-router/package.json +30 -0
  185. package/runtime/plugins/picasso-options/index.js +263 -0
  186. package/runtime/plugins/picasso-options/package.json +28 -0
  187. package/runtime/plugins/picasso-progress-reports/index.js +267 -0
  188. package/runtime/plugins/picasso-progress-reports/package.json +30 -0
  189. package/runtime/plugins/picasso-progress-reports/report.js +235 -0
  190. package/runtime/plugins/picasso-provider-models/index.js +436 -0
  191. package/runtime/plugins/picasso-provider-models/package.json +28 -0
  192. package/runtime/plugins/picasso-repo-index/index.js +1850 -0
  193. package/runtime/plugins/picasso-repo-index/package.json +28 -0
  194. package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
  195. package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
  196. package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
  197. package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
  198. package/runtime/plugins/picasso-trackers/index.js +895 -0
  199. package/runtime/plugins/picasso-trackers/package.json +28 -0
  200. package/runtime/plugins/picasso-web-search/backends.js +350 -0
  201. package/runtime/plugins/picasso-web-search/config.js +121 -0
  202. package/runtime/plugins/picasso-web-search/failure.js +111 -0
  203. package/runtime/plugins/picasso-web-search/format.js +35 -0
  204. package/runtime/plugins/picasso-web-search/index.js +66 -0
  205. package/runtime/plugins/picasso-web-search/package.json +38 -0
  206. package/runtime/plugins/picasso-web-search/router.js +155 -0
  207. package/runtime/plugins/picasso-x-reader/circle.js +324 -0
  208. package/runtime/plugins/picasso-x-reader/command.js +169 -0
  209. package/runtime/plugins/picasso-x-reader/index.js +170 -0
  210. package/runtime/plugins/picasso-x-reader/package.json +39 -0
  211. package/runtime/plugins/picasso-x-reader/read.js +370 -0
  212. package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
  213. package/runtime/plugins/picasso-x-reader/settings.js +131 -0
  214. package/runtime/plugins/picasso-x-reader/urls.js +154 -0
  215. package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
  216. package/runtime/relay/attachment-text.mjs +737 -0
  217. package/runtime/relay/companion/companion.css +126 -0
  218. package/runtime/relay/companion/companion.js +648 -0
  219. package/runtime/relay/companion/icon.svg +5 -0
  220. package/runtime/relay/companion/index.html +25 -0
  221. package/runtime/relay/companion/manifest.json +13 -0
  222. package/runtime/relay/companion/sw.js +41 -0
  223. package/runtime/relay/main.mjs +37252 -0
  224. package/runtime/relay/model-listing.mjs +614 -0
  225. package/runtime/relay/versions-routes.mjs +1198 -0
  226. package/runtime/verify-plugins.mjs +205 -0
  227. package/runtime-lock/package-lock.json +10779 -0
  228. package/runtime-lock/package.json +7 -0
  229. package/scripts/install-runtime.mjs +400 -0
  230. package/README.md +0 -3
@@ -0,0 +1,648 @@
1
+ /* eslint-env browser */
2
+ /* Picasso companion (B09 Tier 1): pairs with the Mac relay over one-time codes, then watches threads,
3
+ * answers approvals/questions and sends prompts. Scoped `pct_` token in localStorage; EventSource carries
4
+ * it in `?token=` (the only auth a browser EventSource can send) — fetch() uses the Authorization header.
5
+ * Streams reopen on drop, on pageshow and on visibilitychange (backgrounded Safari suspends sockets);
6
+ * every reopen yields a fresh baseline, so nothing needs resuming by cursor.
7
+ */
8
+ (() => {
9
+ 'use strict';
10
+
11
+ const STORE_KEY = 'picasso.companion';
12
+ const STALE_AFTER_MS = 20_000;
13
+
14
+ const $app = document.getElementById('app');
15
+ const state = {
16
+ cred: loadCred(), // {token, device, base}
17
+ screen: 'threads', // 'threads' | 'thread' | 'needs' | 'pair'
18
+ threadId: null,
19
+ threads: [],
20
+ pending: new Map(), // eventId -> {kind:'approval'|'question', ...}
21
+ items: [], // folded thread items
22
+ running: false,
23
+ liveText: '',
24
+ lastEventAt: 0,
25
+ streams: [],
26
+ error: '',
27
+ };
28
+
29
+ function loadCred() {
30
+ try {
31
+ const raw = JSON.parse(localStorage.getItem(STORE_KEY) || 'null');
32
+ if (raw && raw.token && raw.device && raw.base === location.origin) return raw;
33
+ } catch { /* fall through */ }
34
+ return null;
35
+ }
36
+ function saveCred(c) { localStorage.setItem(STORE_KEY, JSON.stringify(c)); }
37
+ function dropCred() { localStorage.removeItem(STORE_KEY); }
38
+
39
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
40
+ const fmtWhen = (ms) => {
41
+ if (!ms) return '';
42
+ const d = new Date(ms);
43
+ const today = new Date().toDateString() === d.toDateString();
44
+ return today ? d.toTimeString().slice(0, 5) : d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
45
+ };
46
+ const relAgo = (ms) => {
47
+ const s = Math.max(0, Math.round((Date.now() - ms) / 1000));
48
+ if (s < 5) return 'just now';
49
+ if (s < 60) return `${s}s ago`;
50
+ const m = Math.round(s / 60);
51
+ if (m < 60) return `${m}m ago`;
52
+ return `${Math.round(m / 60)}h ago`;
53
+ };
54
+
55
+ async function api(path, opts = {}) {
56
+ const res = await fetch(path, {
57
+ ...opts,
58
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${state.cred.token}`, ...(opts.headers || {}) },
59
+ });
60
+ if (res.status === 401) { dropCred(); location.assign('/pair'); throw new Error('unpaired'); }
61
+ const body = res.status === 204 ? {} : await res.json().catch(() => ({}));
62
+ if (!res.ok) {
63
+ const err = (body.error && (body.error.message || body.error.code)) || body.error || `HTTP ${res.status}`;
64
+ throw new Error(String(err));
65
+ }
66
+ return body;
67
+ }
68
+
69
+ /* Reconnecting SSE. EventSource retries transient drops itself; this layer catches CLOSED sockets,
70
+ * bfcache restores and iOS suspension — reopening always lands on a fresh baseline. */
71
+ function follow(path, events, onState) {
72
+ let es = null, closed = false, tries = 0, timer = null;
73
+ const sep = path.includes('?') ? '&' : '?';
74
+ const src = `${path}${sep}token=${encodeURIComponent(state.cred.token)}`;
75
+ const open = () => {
76
+ if (closed) return;
77
+ try { es && es.close(); } catch { /* noop */ }
78
+ es = new EventSource(src);
79
+ es.onopen = () => { tries = 0; state.lastEventAt = Date.now(); onState && onState('live'); paintStatus(); };
80
+ es.onerror = () => {
81
+ onState && onState('reconnecting'); paintStatus();
82
+ if (es.readyState === EventSource.CLOSED) schedule();
83
+ };
84
+ for (const [name, fn] of Object.entries(events)) {
85
+ es.addEventListener(name, (e) => {
86
+ state.lastEventAt = Date.now();
87
+ let data = e.data;
88
+ try { data = JSON.parse(e.data); } catch { /* keep raw */ }
89
+ try { fn(data); } catch (err) { console.error('event handler', name, err); }
90
+ paintStatus();
91
+ });
92
+ }
93
+ };
94
+ const schedule = () => {
95
+ if (closed || timer) return;
96
+ timer = setTimeout(() => { timer = null; open(); }, Math.min(15_000, 1_000 * 2 ** tries++));
97
+ };
98
+ const wake = () => {
99
+ if (closed || document.hidden) return;
100
+ if (!es || es.readyState === EventSource.CLOSED) { tries = 0; open(); }
101
+ else if (Date.now() - state.lastEventAt > STALE_AFTER_MS) { tries = 0; open(); } // suspended socket never errored
102
+ };
103
+ document.addEventListener('visibilitychange', wake);
104
+ window.addEventListener('pageshow', wake);
105
+ open();
106
+ const handle = {
107
+ close() {
108
+ closed = true;
109
+ if (timer) clearTimeout(timer);
110
+ try { es && es.close(); } catch { /* noop */ }
111
+ document.removeEventListener('visibilitychange', wake);
112
+ window.removeEventListener('pageshow', wake);
113
+ },
114
+ };
115
+ state.streams.push(handle);
116
+ return handle;
117
+ }
118
+ function closeStreams() { for (const s of state.streams.splice(0)) s.close(); }
119
+
120
+ /* ---------- pairing ---------- */
121
+
122
+ function pairScreen(code) {
123
+ state.screen = 'pair';
124
+ $app.innerHTML = `
125
+ <main class="u-pad-top">
126
+ <div class="card u-pad">
127
+ <div class="u-title">Pair with this Mac</div>
128
+ <div class="fine u-mb16">This pairs the phone for threads and approvals — not full control of the Mac.</div>
129
+ <div class="field">
130
+ <label for="code">Pair code</label>
131
+ <input id="code" class="code" maxlength="6" autocapitalize="characters" autocorrect="off"
132
+ autocomplete="one-time-code" inputmode="text" value="${esc(code || '')}" placeholder="······">
133
+ </div>
134
+ <div class="field">
135
+ <label for="devname">This device</label>
136
+ <input id="devname" maxlength="60" value="${esc(deviceName())}"
137
+ class="u-field">
138
+ </div>
139
+ <div id="pairerr"></div>
140
+ <button class="btn acc u-full" id="pairbtn">Pair</button>
141
+ </div>
142
+ </main>`;
143
+ const input = document.getElementById('code');
144
+ document.getElementById('pairbtn').onclick = () => doPair(input.value);
145
+ input.addEventListener('keydown', (e) => { if (e.key === 'Enter') doPair(input.value); });
146
+ if (code) doPair(code);
147
+ }
148
+
149
+ function deviceName() {
150
+ const ua = navigator.userAgent;
151
+ if (/iPhone/.test(ua)) return 'iPhone';
152
+ if (/iPad/.test(ua)) return 'iPad';
153
+ if (/Android/.test(ua)) return 'Android phone';
154
+ return 'Companion device';
155
+ }
156
+
157
+ async function doPair(code) {
158
+ const err = document.getElementById('pairerr');
159
+ err.innerHTML = '';
160
+ const btn = document.getElementById('pairbtn');
161
+ btn.disabled = true;
162
+ try {
163
+ const res = await fetch('/pair/exchange', {
164
+ method: 'POST', headers: { 'content-type': 'application/json' },
165
+ body: JSON.stringify({ code: String(code || '').trim(), name: document.getElementById('devname').value }),
166
+ });
167
+ const body = await res.json().catch(() => ({}));
168
+ if (!res.ok) {
169
+ err.innerHTML = `<div class="banner err u-mb12">${esc((body.error && body.error.message) || body.error || `HTTP ${res.status}`)}</div>`;
170
+ return;
171
+ }
172
+ saveCred({ token: body.token, device: body.device, base: location.origin });
173
+ history.replaceState(null, '', '/pair');
174
+ location.reload();
175
+ } catch {
176
+ err.innerHTML = '<div class="banner err u-mb12">Could not reach the Mac.</div>';
177
+ } finally {
178
+ btn.disabled = false;
179
+ }
180
+ }
181
+
182
+ /* ---------- shell ---------- */
183
+
184
+ function chrome(title, sub, tabs) {
185
+ return `
186
+ <header class="bar">
187
+ ${state.screen === 'thread' ? '<button class="btn quiet u-px8" id="back">‹ Threads</button>' : ''}
188
+ <div class="u-grow">
189
+ <div class="title" id="tt">${esc(title)}</div>
190
+ ${sub ? `<div class="sub">${esc(sub)}</div>` : ''}
191
+ </div>
192
+ ${tabs ? `<nav class="tabs">
193
+ <button data-go="threads" class="${state.screen === 'threads' || state.screen === 'thread' ? 'on' : ''}">Threads</button>
194
+ <button data-go="needs" class="${state.screen === 'needs' ? 'on' : ''}">Needs you${state.pending.size ? `<span class="dot">${state.pending.size}</span>` : ''}</button>
195
+ </nav>` : ''}
196
+ </header>`;
197
+ }
198
+
199
+ function paintStatus() {
200
+ const el = document.getElementById('statusline');
201
+ if (!el) return;
202
+ const stale = state.lastEventAt && Date.now() - state.lastEventAt > STALE_AFTER_MS;
203
+ el.className = `statusline${stale ? ' stale' : ''}`;
204
+ el.innerHTML = `<span class="pulse"></span>${stale ? `Reconnecting… quiet since ${relAgo(state.lastEventAt)}` : state.lastEventAt ? `Live · updated ${relAgo(state.lastEventAt)}` : 'Connecting…'}`;
205
+ }
206
+
207
+ function bindChrome() {
208
+ const back = document.getElementById('back');
209
+ if (back) back.onclick = () => showThreads();
210
+ for (const b of document.querySelectorAll('nav.tabs button')) b.onclick = () => (b.dataset.go === 'needs' ? showNeeds() : showThreads());
211
+ }
212
+
213
+ /* ---------- threads ---------- */
214
+
215
+ async function showThreads() {
216
+ state.screen = 'threads';
217
+ state.threadId = null;
218
+ closeStreams();
219
+ $app.innerHTML = chrome('Picasso', null, true) + '<main><div id="list" class="card"><div class="empty">Loading…</div></div><div id="notify" class="card u-mt12"></div></main><div class="statusline" id="statusline"></div>';
220
+ bindChrome();
221
+ void paintNotify();
222
+ const refresh = async () => {
223
+ try {
224
+ const list = await api('/threads');
225
+ // dsh session/list rows: sessionId, title?, cwd, updatedAt (ms), running, origin ('subagent' rows stay
226
+ // inside their parent's view), lastReplyPreview (relay-attached), archived (only with ?include=archived).
227
+ state.threads = (list.items || []).filter((t) => t.sessionId && t.origin !== 'subagent' && !t.archived);
228
+ paintThreads();
229
+ } catch (e) {
230
+ const list = document.getElementById('list');
231
+ if (list) list.innerHTML = `<div class="empty">${esc(e.message)}</div>`;
232
+ }
233
+ };
234
+ let debounce = null;
235
+ follow('/control/events', {
236
+ control: () => { if (!debounce) debounce = setTimeout(() => { debounce = null; refresh(); }, 400); },
237
+ end: () => {},
238
+ });
239
+ await refresh();
240
+ // Approvals badge comes from the host-wide stream: keep it open for the tab count.
241
+ follow(`/interactions?device=${encodeURIComponent(state.cred.device.id)}`, needsEvents());
242
+ }
243
+
244
+ function paintThreads() {
245
+ const list = document.getElementById('list');
246
+ if (!list) return;
247
+ if (!state.threads.length) {
248
+ list.innerHTML = '<div class="empty"><div class="big">No threads yet</div>Start one on the Mac, or send one from here.</div>';
249
+ return;
250
+ }
251
+ const needing = new Set([...state.pending.values()].map((p) => p.sessionId));
252
+ list.innerHTML = state.threads.map((t) => `
253
+ <div class="row" data-id="${esc(t.sessionId)}">
254
+ <span class="mark ${needing.has(t.sessionId) ? 'need' : t.running ? 'run' : 'idle'}"></span>
255
+ <div class="t">
256
+ <div class="l1">${esc(t.title || t.cwd || t.sessionId)}</div>
257
+ <div class="l2">${esc(t.lastReplyPreview || t.cwd || '')}</div>
258
+ </div>
259
+ <span class="when">${fmtWhen(t.updatedAt)}</span>
260
+ </div>`).join('');
261
+ for (const row of list.querySelectorAll('.row')) row.onclick = () => showThread(row.dataset.id);
262
+ }
263
+
264
+ /* ---------- one thread ---------- */
265
+
266
+ function foldEvent(event) {
267
+ const d = event.data || {};
268
+ switch (event.type) {
269
+ case 'turn/start':
270
+ state.running = true; state.liveText = '';
271
+ state.items.push({ kind: 'note', text: `Turn ${d.turn ?? ''}`.trim() });
272
+ break;
273
+ case 'turn/end':
274
+ state.running = false; state.liveText = '';
275
+ break;
276
+ case 'user/message': {
277
+ if (d.role !== 'user') break;
278
+ if (d.source && d.source.kind && d.source.kind !== 'user') break;
279
+ const text = blocksText(d.content);
280
+ if (text) state.items.push({ kind: 'user', text });
281
+ break;
282
+ }
283
+ case 'assistant/message':
284
+ for (const b of (d.message && d.message.content) || []) {
285
+ if (b.type === 'text' && b.text) { state.items.push({ kind: 'bot', text: b.text }); state.liveText = ''; }
286
+ else if ((b.type === 'reasoning' || b.type === 'thinking') && b.text) state.items.push({ kind: 'think', text: b.text });
287
+ }
288
+ break;
289
+ case 'tool/call':
290
+ state.items.push({ kind: 'tool', callId: d.callId || '', name: d.name || 'tool', target: toolTarget(d.arguments), status: 'run' });
291
+ break;
292
+ case 'tool/result': {
293
+ const callId = (d.message && (d.message.toolCallId || (d.message.source && d.message.source.callId))) || '';
294
+ const item = [...state.items].reverse().find((i) => i.kind === 'tool' && i.callId === callId);
295
+ if (item) {
296
+ item.status = (d.message && d.message.isError) || d.error ? 'fail' : 'ok';
297
+ const full = blocksText(d.message && d.message.content);
298
+ if (full) item.preview = full.slice(0, 200);
299
+ }
300
+ break;
301
+ }
302
+ case 'approval/asked':
303
+ state.items.push({ kind: 'note', text: `Approval asked: ${d.toolName || ''}` });
304
+ break;
305
+ case 'session/title':
306
+ if (d.title) document.getElementById('tt') && (document.getElementById('tt').textContent = d.title);
307
+ break;
308
+ case 'command/run':
309
+ state.items.push({ kind: 'note', text: `/${d.name || 'command'}` });
310
+ break;
311
+ case 'command/done':
312
+ if (d.text) state.items.push({ kind: 'note', text: d.text });
313
+ break;
314
+ case 'compaction/summary':
315
+ state.items.push({ kind: 'note', text: 'Context compacted' });
316
+ break;
317
+ case 'model/selection':
318
+ if (d.model) state.items.push({ kind: 'note', text: `Model: ${d.model}` });
319
+ break;
320
+ default: break;
321
+ }
322
+ }
323
+
324
+ function foldFrame(frame) {
325
+ if (!frame || typeof frame !== 'object') return;
326
+ if (frame.type === 'event' && frame.event) return foldEvent(frame.event);
327
+ // dsh `session/follow` (assistantStream: true) wraps live model chunks as {type:'assistant-stream', frame:{type:'chunk', chunk}}.
328
+ if (frame.type === 'assistant-stream' && frame.frame && frame.frame.type === 'chunk') {
329
+ const c = frame.frame.chunk || {};
330
+ if ((c.type === 'text' || c.type === 'text-delta') && c.text) state.liveText += c.text;
331
+ return;
332
+ }
333
+ if (frame.type === 'chunk') {
334
+ const c = frame.chunk || {};
335
+ if ((c.type === 'text' || c.type === 'text-delta') && c.text) state.liveText += c.text;
336
+ return;
337
+ }
338
+ if (frame.type === 'snapshot') {
339
+ state.items = [];
340
+ state.liveText = '';
341
+ for (const record of frame.records || []) {
342
+ if (record.type === 'event' && record.event) foldEvent(record.event);
343
+ else if (record.seq !== undefined) foldEvent(record);
344
+ }
345
+ }
346
+ }
347
+
348
+ function blocksText(content) {
349
+ return ((content || []).map((b) => (b.type === 'text' ? b.text : b.type === 'tool-result' ? blocksText(b.content) : null)).filter(Boolean) || []).join('');
350
+ }
351
+ function toolTarget(args) {
352
+ try {
353
+ const parsed = JSON.parse(args || '');
354
+ for (const k of ['file_path', 'path', 'command', 'pattern', 'query', 'url', 'description']) {
355
+ if (typeof parsed[k] === 'string') return parsed[k].split('\n')[0];
356
+ }
357
+ } catch { /* not json */ }
358
+ return '';
359
+ }
360
+
361
+ function showThread(id) {
362
+ state.screen = 'thread';
363
+ state.threadId = id;
364
+ state.items = [];
365
+ state.liveText = '';
366
+ state.running = false;
367
+ closeStreams();
368
+ const thread = state.threads.find((t) => t.sessionId === id);
369
+ $app.innerHTML = chrome('', thread ? thread.cwd : '', true) + `
370
+ <main><div class="feed" id="feed"><div class="empty">Following…</div></div></main>
371
+ <div class="statusline" id="statusline"></div>
372
+ <div class="composer">
373
+ <textarea id="prompt" rows="1" placeholder="Send to this thread…"></textarea>
374
+ <button class="btn acc" id="send">Send</button>
375
+ </div>`;
376
+ bindChrome();
377
+ const ta = document.getElementById('prompt');
378
+ document.getElementById('send').onclick = () => sendPrompt();
379
+ ta.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendPrompt(); } });
380
+ ta.addEventListener('input', () => { ta.style.height = 'auto'; ta.style.height = `${Math.min(120, ta.scrollHeight)}px`; });
381
+ follow(`/threads/${encodeURIComponent(id)}/events`, {
382
+ dsh: (frame) => { foldFrame(frame); paintFeed(); },
383
+ approval: (a) => { state.pending.set(a.eventId, { kind: 'approval', ...a }); paintFeed(); paintTabBadge(); },
384
+ 'interaction-cancelled': (c) => { state.pending.delete(c.eventId); paintFeed(); paintTabBadge(); },
385
+ 'approval-answered': (a) => { state.pending.delete(a.eventId); paintFeed(); paintTabBadge(); },
386
+ 'question-answered': (q) => { state.pending.delete(q.eventId); paintFeed(); paintTabBadge(); },
387
+ question: (q) => { state.pending.set(q.eventId, { kind: 'question', ...q }); paintFeed(); paintTabBadge(); },
388
+ status: (s) => { if (!s.sessionId || s.sessionId === id) { state.running = !!s.running; paintFeed(); } },
389
+ error: (e) => { state.items.push({ kind: 'note', text: `Error: ${e.message || 'unknown'}` }); paintFeed(); },
390
+ end: () => {},
391
+ });
392
+ // Approvals for this thread also live on the host-wide stream kept open by the tabs badge.
393
+ follow(`/interactions?device=${encodeURIComponent(state.cred.device.id)}`, needsEvents());
394
+ async function sendPrompt() {
395
+ const text = ta.value.trim();
396
+ if (!text) return;
397
+ ta.value = '';
398
+ ta.style.height = 'auto';
399
+ try { await api(`/threads/${encodeURIComponent(id)}/prompt`, { method: 'POST', body: JSON.stringify({ text, mode: 'queue' }) }); }
400
+ catch (e) { state.items.push({ kind: 'note', text: `Not sent: ${e.message}` }); paintFeed(); }
401
+ }
402
+ }
403
+
404
+ function paintFeed() {
405
+ const feed = document.getElementById('feed');
406
+ if (!feed) return;
407
+ const pendingHere = [...state.pending.values()].filter((p) => p.sessionId === state.threadId);
408
+ let html = state.items.map(itemHtml).join('');
409
+ if (state.liveText) html += `<div class="msg bot">${esc(state.liveText)}</div>`;
410
+ html += pendingHere.map(needCardHtml).join('');
411
+ if (state.running) html += '<div class="msg note">Working…</div>';
412
+ feed.innerHTML = html || '<div class="empty">Nothing yet — send the first prompt below.</div>';
413
+ bindNeeds(feed);
414
+ feed.scrollIntoView(false);
415
+ window.scrollTo(0, document.body.scrollHeight);
416
+ }
417
+
418
+ function itemHtml(i) {
419
+ switch (i.kind) {
420
+ case 'user': return `<div class="msg user">${esc(i.text)}</div>`;
421
+ case 'bot': return `<div class="msg bot">${esc(i.text)}</div>`;
422
+ case 'think': return `<div class="msg think">${esc(i.text)}</div>`;
423
+ case 'note': return `<div class="msg note">${esc(i.text)}</div>`;
424
+ case 'tool': return `<div class="tool"><span class="name">${esc(i.name)}</span><span class="target">${esc(i.target)}</span><span class="st ${i.status}">${i.status === 'run' ? 'running' : i.status === 'ok' ? 'done' : 'failed'}</span>${i.preview ? `<span class="prev">${esc(i.preview)}</span>` : ''}</div>`;
425
+ default: return '';
426
+ }
427
+ }
428
+
429
+ /* ---------- needs you ---------- */
430
+
431
+ function needsEvents() {
432
+ return {
433
+ approval: (a) => { state.pending.set(a.eventId, { kind: 'approval', ...a }); if (state.screen === 'needs') paintNeeds(); paintTabBadge(); paintThreadsSafe(); },
434
+ question: (q) => { state.pending.set(q.eventId, { kind: 'question', ...q }); if (state.screen === 'needs') paintNeeds(); paintTabBadge(); paintThreadsSafe(); },
435
+ 'interaction-cancelled': (c) => { state.pending.delete(c.eventId); repaintNeeds(); paintTabBadge(); paintThreadsSafe(); },
436
+ 'approval-answered': (a) => { state.pending.delete(a.eventId); repaintNeeds(); paintTabBadge(); paintThreadsSafe(); },
437
+ 'question-answered': (q) => { state.pending.delete(q.eventId); repaintNeeds(); paintTabBadge(); paintThreadsSafe(); },
438
+ threads: () => paintThreadsSafe(),
439
+ status: () => {},
440
+ 'browser-action': () => {},
441
+ 'browser-action-cancelled': () => {},
442
+ end: () => {},
443
+ };
444
+ }
445
+ function paintThreadsSafe() { if (state.screen === 'threads') paintThreads(); else if (state.screen === 'thread') paintFeed(); }
446
+ function repaintNeeds() { if (state.screen === 'needs') paintNeeds(); }
447
+ function paintTabBadge() {
448
+ const dot = document.querySelector('nav.tabs button[data-go="needs"] .dot');
449
+ if (state.pending.size && !dot) {
450
+ const btn = document.querySelector('nav.tabs button[data-go="needs"]');
451
+ if (btn) btn.innerHTML = `Needs you<span class="dot">${state.pending.size}</span>`;
452
+ } else if (dot) {
453
+ if (state.pending.size) dot.textContent = String(state.pending.size);
454
+ else dot.remove();
455
+ }
456
+ }
457
+
458
+ function showNeeds() {
459
+ state.screen = 'needs';
460
+ closeStreams();
461
+ $app.innerHTML = chrome('Needs you', `${state.pending.size} waiting`, true) + '<main><div class="feed" id="needs"></div></main><div class="statusline" id="statusline"></div>';
462
+ bindChrome();
463
+ follow(`/interactions?device=${encodeURIComponent(state.cred.device.id)}`, needsEvents());
464
+ paintNeeds();
465
+ }
466
+
467
+ function paintNeeds() {
468
+ const box = document.getElementById('needs');
469
+ if (!box) return;
470
+ const items = [...state.pending.values()];
471
+ box.innerHTML = items.length ? items.map(needCardHtml).join('') : '<div class="empty"><div class="big">Nothing needs you</div>Approvals and questions land here.</div>';
472
+ bindNeeds(box);
473
+ }
474
+
475
+ function needCardHtml(p) {
476
+ if (p.kind === 'question') {
477
+ return `<div class="need" data-ev="${esc(p.eventId)}">
478
+ <div class="kind">Question</div>
479
+ ${(p.questions || []).map((q, qi) => `
480
+ <div class="q" data-qid="${esc(q.id)}">
481
+ ${q.header ? `<div class="hdr">${esc(q.header)}</div>` : ''}
482
+ <div class="qt">${esc(q.question)}</div>
483
+ ${(q.options || []).map((o) => `
484
+ <label class="opt"><input type="${q.multiSelect ? 'checkbox' : 'radio'}" name="q-${esc(p.eventId)}-${qi}" value="${esc(o.label)}">
485
+ <span>${esc(o.label)}${o.description ? `<div class="d">${esc(o.description)}</div>` : ''}</span></label>`).join('')}
486
+ <input class="opt-custom u-field-sm" placeholder="Or your own answer">
487
+ </div>`).join('')}
488
+ <div class="acts">
489
+ <button class="btn acc" data-act="answer">Answer</button>
490
+ <button class="btn quiet" data-act="decline">Skip</button>
491
+ </div>
492
+ <div class="fine">Thread ${esc(shortId(p.sessionId))}</div>
493
+ </div>`;
494
+ }
495
+ return `<div class="need" data-ev="${esc(p.eventId)}">
496
+ <div class="kind">Approval</div>
497
+ <div class="what">${esc(p.toolName || 'Tool call')}</div>
498
+ ${(p.displayReason && (p.displayReason.en || p.displayReason)) || p.reason ? `<div class="why">${esc((p.displayReason && (p.displayReason.en || p.displayReason)) || p.reason)}</div>` : ''}
499
+ <div class="acts">
500
+ <button class="btn acc" data-act="allow">Allow</button>
501
+ <button class="btn" data-act="allow-session" title="Always allow this tool in this thread">Always allow</button>
502
+ <button class="btn warn" data-act="deny">Deny</button>
503
+ </div>
504
+ <div class="fine">Always allow applies to this thread only. Thread ${esc(shortId(p.sessionId))}</div>
505
+ </div>`;
506
+ }
507
+ const shortId = (id) => (id && id.length > 10 ? `${id.slice(0, 6)}…${id.slice(-4)}` : id || '');
508
+
509
+ function bindNeeds(root) {
510
+ for (const card of root.querySelectorAll('.need')) {
511
+ const ev = card.dataset.ev;
512
+ for (const btn of card.querySelectorAll('button[data-act]')) {
513
+ btn.onclick = async () => {
514
+ btn.disabled = true;
515
+ try {
516
+ const act = btn.dataset.act;
517
+ if (act === 'decline') {
518
+ await api(`/interactions/${encodeURIComponent(ev)}`, { method: 'POST', body: JSON.stringify({ decline: true }) });
519
+ } else if (act === 'answer') {
520
+ const answers = [];
521
+ for (const q of card.querySelectorAll('.q')) {
522
+ const picked = [...q.querySelectorAll('input[type=checkbox]:checked,input[type=radio]:checked')].map((i) => i.value);
523
+ const custom = q.querySelector('.opt-custom').value.trim();
524
+ answers.push({ id: q.dataset.qid, selected: picked, ...(custom ? { custom } : {}) });
525
+ }
526
+ await api(`/interactions/${encodeURIComponent(ev)}`, { method: 'POST', body: JSON.stringify({ answers }) });
527
+ } else {
528
+ await api(`/interactions/${encodeURIComponent(ev)}`, { method: 'POST', body: JSON.stringify({ decision: act }) });
529
+ }
530
+ state.pending.delete(ev);
531
+ if (state.screen === 'needs') paintNeeds(); else paintFeed();
532
+ paintTabBadge();
533
+ } catch (e) {
534
+ btn.disabled = false;
535
+ const note = document.createElement('div');
536
+ note.className = 'banner err';
537
+ note.style.margin = '4px 0 0';
538
+ note.textContent = e.message;
539
+ card.appendChild(note);
540
+ }
541
+ };
542
+ }
543
+ }
544
+ }
545
+
546
+ /* ---------- phone notifications (Web Push from the Mac, per device) ---------- */
547
+
548
+ const pushSupported = () => window.isSecureContext && 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;
549
+ const isAppleMobile = () => /iPhone|iPad/.test(navigator.userAgent);
550
+ const isStandalone = () => window.matchMedia('(display-mode: standalone)').matches || navigator.standalone === true;
551
+
552
+ function b64uToBytes(text) {
553
+ const b64 = text.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (text.length % 4)) % 4);
554
+ const raw = atob(b64);
555
+ return Uint8Array.from(raw, (c) => c.charCodeAt(0));
556
+ }
557
+ function sameKey(buffer, publicKey) {
558
+ if (!buffer) return false;
559
+ const a = new Uint8Array(buffer);
560
+ const b = b64uToBytes(publicKey);
561
+ return a.length === b.length && a.every((v, i) => v === b[i]);
562
+ }
563
+
564
+ async function pushRegistration() {
565
+ await navigator.serviceWorker.register('/pair/sw.js', { scope: '/pair' });
566
+ return navigator.serviceWorker.ready;
567
+ }
568
+
569
+ async function enablePush() {
570
+ // Ask first, inside the tap: iOS only shows the prompt for a user gesture.
571
+ const permission = await Notification.requestPermission();
572
+ if (permission !== 'granted') throw new Error('Notifications are blocked for this page. Allow them in the phone settings.');
573
+ const reg = await pushRegistration();
574
+ const { publicKey } = await api('/push/key');
575
+ let sub = await reg.pushManager.getSubscription();
576
+ if (sub && !sameKey(sub.options && sub.options.applicationServerKey, publicKey)) { await sub.unsubscribe(); sub = null; }
577
+ if (!sub) sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: b64uToBytes(publicKey) });
578
+ await api('/push/subscription', { method: 'PUT', body: JSON.stringify({ subscription: sub.toJSON(), enabled: true }) });
579
+ }
580
+
581
+ async function disablePush() {
582
+ await api('/push/subscription', { method: 'PATCH', body: JSON.stringify({ enabled: false }) });
583
+ }
584
+
585
+ async function paintNotify(message) {
586
+ const box = document.getElementById('notify');
587
+ if (!box) return;
588
+ const head = '<div class="t"><div class="l1">Notifications on this device</div><div class="l2">When a thread finishes, needs approval or has a question. Shows the thread title and status only.</div></div>';
589
+ if (!pushSupported()) {
590
+ const why = isAppleMobile() && !isStandalone()
591
+ ? 'Add Picasso to your Home Screen (Share, then Add to Home Screen), open it from there, then turn notifications on.'
592
+ : 'This browser cannot show notifications from this page.';
593
+ box.innerHTML = `<div class="row">${head}</div><div class="row"><div class="t"><div class="l2">${esc(why)}</div></div></div>`;
594
+ return;
595
+ }
596
+ let st = { subscribed: false, enabled: false };
597
+ try { st = await api('/push/subscription'); }
598
+ catch (e) {
599
+ box.innerHTML = `<div class="row">${head}</div><div class="row"><div class="t"><div class="l2">${esc(/not enabled/.test(e.message) ? 'This Mac does not offer notifications.' : e.message)}</div></div></div>`;
600
+ return;
601
+ }
602
+ const reg = await navigator.serviceWorker.getRegistration('/pair').catch(() => undefined);
603
+ const sub = reg ? await reg.pushManager.getSubscription().catch(() => null) : null;
604
+ const on = Boolean(st.subscribed && st.enabled && sub && Notification.permission === 'granted');
605
+ const note = message || (Notification.permission === 'denied' ? 'Notifications are blocked for this page in the phone settings.' : on ? 'On' : 'Off');
606
+ box.innerHTML = `
607
+ <div class="row">${head}<button class="btn${on ? '' : ' acc'}" id="pushtoggle">${on ? 'Turn off' : 'Turn on'}</button></div>
608
+ <div class="row"><div class="t"><div class="l2" id="pushnote">${esc(note)}</div></div>
609
+ <button class="btn" id="pushtest"${st.subscribed && sub ? '' : ' disabled'}>Send test notification</button></div>`;
610
+ const toggle = document.getElementById('pushtoggle');
611
+ toggle.onclick = async () => {
612
+ toggle.disabled = true;
613
+ try {
614
+ if (on) await disablePush(); else await enablePush();
615
+ await paintNotify();
616
+ } catch (e) { await paintNotify(e.message); }
617
+ };
618
+ const testBtn = document.getElementById('pushtest');
619
+ testBtn.onclick = async () => {
620
+ testBtn.disabled = true;
621
+ try {
622
+ await api('/push/test', { method: 'POST', body: '{}' });
623
+ await paintNotify('Test sent. It should arrive in a few seconds.');
624
+ } catch (e) { await paintNotify(`Test not sent: ${e.message}`); }
625
+ };
626
+ }
627
+
628
+ /* ---------- boot ---------- */
629
+
630
+ (function start() {
631
+ const code = /[#&]c=([A-Za-z0-9]+)/.exec(location.hash)?.[1] || /[#&]c=([A-Za-z0-9]+)/.exec(location.search)?.[1];
632
+ if (!state.cred) {
633
+ pairScreen(code);
634
+ return;
635
+ }
636
+ if (code) history.replaceState(null, '', '/pair'); // already paired: drop a stray code from the URL
637
+ // A tapped notification opens `/pair#t=<thread>` (or messages an open page): land on that thread.
638
+ const opened = /[#&]t=([^&]+)/.exec(location.hash)?.[1];
639
+ if (opened) history.replaceState(null, '', '/pair');
640
+ if ('serviceWorker' in navigator) {
641
+ navigator.serviceWorker.addEventListener('message', (e) => {
642
+ if (e.data && e.data.type === 'open-thread' && typeof e.data.threadId === 'string') showThread(e.data.threadId);
643
+ });
644
+ }
645
+ void showThreads().then(() => { if (opened) showThread(decodeURIComponent(opened)); });
646
+ setInterval(paintStatus, 5_000);
647
+ })();
648
+ })();
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
2
+ <rect width="64" height="64" rx="14" fill="#F7F6F2"/>
3
+ <circle cx="24" cy="32" r="12" fill="none" stroke="#4F7D68" stroke-width="5"/>
4
+ <circle cx="44" cy="32" r="8" fill="#4F7D68"/>
5
+ </svg>