ccdeck 3.82.3 → 4.0.0

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 (146) hide show
  1. package/LICENSING.md +42 -4
  2. package/README.md +183 -72
  3. package/THIRD_PARTY_NOTICES.md +243 -17
  4. package/bin/cli/login-item.js +5 -0
  5. package/bin/cli/tui.js +58 -4
  6. package/bin/deck.js +27 -1
  7. package/dist/web/assets/AccountBridge-OQHT5qmS.js +1 -0
  8. package/dist/web/assets/AccountSection-BpIHPhF3.js +1 -0
  9. package/dist/web/assets/BrowserWatchModal-DBdt52v7.js +1 -0
  10. package/dist/web/assets/FeedbackConversations-BJjgXI0-.js +1 -0
  11. package/dist/web/assets/IntegrationModal-DQ0vEz4X.js +7 -0
  12. package/dist/web/assets/IntegrationSkeleton-JCPbqp96.js +1 -0
  13. package/dist/web/assets/RadioPanel-Be6AkrKl.js +1 -0
  14. package/dist/web/assets/StageShell-Dq0JOQhd.js +4 -0
  15. package/dist/web/assets/TrafficRadar-7jqJbhaK.js +8 -0
  16. package/dist/web/assets/UsageHistoryModal-ckawZGoe.js +1 -0
  17. package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
  18. package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
  19. package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
  20. package/dist/web/assets/app-40gNTTfq.js +361 -0
  21. package/dist/web/assets/app-BRjYF6oD.css +1 -0
  22. package/dist/web/assets/{index-B4c5MZCc.js → index-XIY3yFiN.js} +1 -1
  23. package/dist/web/assets/inspector-status-pane-BV_m7eBv.js +1 -0
  24. package/dist/web/assets/screens-9_ivqfcF.js +12 -0
  25. package/dist/web/assets/screens-DUniTTbC.css +1 -0
  26. package/dist/web/assets/stage-board-NF_wgGRA.js +2 -0
  27. package/dist/web/assets/use-account-BUmI-A8e.js +1 -0
  28. package/dist/web/assets/xterm-4jYizCpg.js +27 -0
  29. package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
  30. package/dist/web/index.html +16 -6
  31. package/package.json +13 -1
  32. package/release-notes.json +79 -0
  33. package/src/server/account-client.mjs +196 -0
  34. package/src/server/account-connect.mjs +238 -0
  35. package/src/server/account-flag.mjs +106 -0
  36. package/src/server/account-projects.mjs +1 -1
  37. package/src/server/account-service.mjs +532 -0
  38. package/src/server/account-status.mjs +293 -0
  39. package/src/server/account-store.mjs +137 -0
  40. package/src/server/account-sync.mjs +473 -0
  41. package/src/server/account-token-store.mjs +216 -0
  42. package/src/server/account-ui-fields.mjs +126 -0
  43. package/src/server/account-watch.mjs +1 -1
  44. package/src/server/browser-watch-log.mjs +1 -1
  45. package/src/server/browser-watch-store.mjs +1 -1
  46. package/src/server/ccdeck-account-routes.mjs +252 -0
  47. package/src/server/ccusage-install.mjs +2 -2
  48. package/src/server/ccusage-registry.mjs +4 -4
  49. package/src/server/ccusage-session.mjs +11 -0
  50. package/src/server/claude-accounts.mjs +1 -1
  51. package/src/server/claude-recovery.mjs +9 -4
  52. package/src/server/claude-settings-catalog.mjs +6 -6
  53. package/src/server/claude-settings.mjs +1 -1
  54. package/src/server/codex-auto.mjs +1 -1
  55. package/src/server/codex-cost-usage.mjs +7 -2
  56. package/src/server/codex-live-checkpoint.mjs +24 -9
  57. package/src/server/codex-live-engine.mjs +14 -4
  58. package/src/server/codex-live-handoff.mjs +53 -9
  59. package/src/server/codex-names.mjs +49 -0
  60. package/src/server/codex-translate.mjs +1 -1
  61. package/src/server/codex-ultrafast.d.mts +3 -0
  62. package/src/server/codex-ultrafast.mjs +5 -0
  63. package/src/server/codex-watch.mjs +25 -0
  64. package/src/server/command-panel-engine.mjs +300 -0
  65. package/src/server/command-panel-platform.mjs +99 -0
  66. package/src/server/cswap-auto-choice.mjs +1 -1
  67. package/src/server/cswap-auto-loop.mjs +1 -1
  68. package/src/server/cswap-install.mjs +21 -40
  69. package/src/server/deck-home.mjs +6 -0
  70. package/src/server/deck-prefs.mjs +53 -1
  71. package/src/server/detach.mjs +1 -1
  72. package/src/server/engine-download.mjs +277 -0
  73. package/src/server/engine-install.mjs +378 -0
  74. package/src/server/engine-package.mjs +267 -0
  75. package/src/server/event-log.mjs +7 -1
  76. package/src/server/event-pipeline.mjs +29 -1
  77. package/src/server/ghostty-handoff.mjs +81 -0
  78. package/src/server/index.mjs +143 -5
  79. package/src/server/installer.mjs +4 -1
  80. package/src/server/integrations/jira-write-guard.mjs +14 -208
  81. package/src/server/integrations/store.mjs +37 -19
  82. package/src/server/integrations/write-guard.mjs +223 -0
  83. package/src/server/intel-cpu-temperature.mjs +26 -0
  84. package/src/server/lifecycle.mjs +69 -6
  85. package/src/server/log-replay.mjs +4 -0
  86. package/src/server/login-service.mjs +116 -14
  87. package/src/server/macmon.mjs +1 -1
  88. package/src/server/npm-latest.mjs +1 -1
  89. package/src/server/org-telemetry.mjs +1 -1
  90. package/src/server/output-watch.mjs +4 -1
  91. package/src/server/panel-provenance.mjs +390 -0
  92. package/src/server/pinned-build.mjs +14 -0
  93. package/src/server/prefs-refusal.mjs +8 -1
  94. package/src/server/prefs-routes.mjs +60 -11
  95. package/src/server/pro-engine-client.mjs +339 -0
  96. package/src/server/pro-engine-install.mjs +294 -0
  97. package/src/server/pro-engine-terminal.mjs +308 -0
  98. package/src/server/project-discovery.mjs +139 -0
  99. package/src/server/provider-session-name.mjs +58 -0
  100. package/src/server/quota-closes.mjs +1 -1
  101. package/src/server/quota-history.mjs +1 -1
  102. package/src/server/reports.mjs +86 -21
  103. package/src/server/request-gates.mjs +34 -5
  104. package/src/server/restart-note.mjs +1 -1
  105. package/src/server/seed-boundary.mjs +489 -0
  106. package/src/server/session-counts.mjs +244 -0
  107. package/src/server/session-deck-names.mjs +143 -0
  108. package/src/server/session-enrichment.mjs +43 -6
  109. package/src/server/session-name-route.mjs +73 -0
  110. package/src/server/session-summary.mjs +12 -1
  111. package/src/server/session-transcript-routes.mjs +167 -0
  112. package/src/server/swap-log.mjs +1 -1
  113. package/src/server/system-metrics.mjs +57 -0
  114. package/src/server/terminal-bridge.mjs +485 -0
  115. package/src/server/terminal-folder.mjs +61 -0
  116. package/src/server/terminal-js-routes.mjs +752 -0
  117. package/src/server/terminal-routes.mjs +553 -0
  118. package/src/server/terminal-sessions.mjs +759 -0
  119. package/src/server/terminal-socket.mjs +403 -0
  120. package/src/server/terminal-target.mjs +928 -0
  121. package/src/server/thermal-metrics.mjs +13 -9
  122. package/src/server/tmux-control.mjs +1319 -0
  123. package/src/server/tmux-download.mjs +220 -0
  124. package/src/server/tmux.mjs +542 -0
  125. package/src/server/token-redact.mjs +42 -3
  126. package/src/server/tool-audit-report.mjs +44 -6
  127. package/src/server/tool-audit-routes.mjs +12 -1
  128. package/src/server/tool-audit.mjs +42 -8
  129. package/src/server/traffic-radar-monitor.mjs +1 -1
  130. package/src/server/traffic-radar-permission.mjs +1 -1
  131. package/src/server/transcript-gate.mjs +1 -1
  132. package/src/server/transcript-scan.mjs +15 -7
  133. package/src/server/transcript-turns.mjs +154 -0
  134. package/src/server/tui-network.mjs +1 -0
  135. package/src/server/tui-view.mjs +28 -0
  136. package/src/server/utf8-carry.mjs +159 -0
  137. package/src/server/uv-bootstrap.mjs +2 -2
  138. package/src/server/windows-acl.mjs +158 -0
  139. package/src/server/ws-frames.mjs +690 -0
  140. package/dist/web/assets/BrowserWatchModal-BmRTh_xT.js +0 -1
  141. package/dist/web/assets/IntegrationModal-C_f526aV.js +0 -7
  142. package/dist/web/assets/RadioPanel-D2rkf9cg.js +0 -1
  143. package/dist/web/assets/TrafficRadar-BOgVBLIN.js +0 -8
  144. package/dist/web/assets/UsageHistoryModal-BJPTFwM9.js +0 -1
  145. package/dist/web/assets/app-CbXmr9rC.css +0 -1
  146. package/dist/web/assets/app-DZdZoqJ6.js +0 -358
@@ -0,0 +1,473 @@
1
+ // Settings sync between this deck and its account: the deck server's half
2
+ // (design 4.6).
3
+ //
4
+ // WHERE EACH HALF LIVES. The settings themselves stay in the browser's
5
+ // localStorage, as they always have — the theme, text size, density, the
6
+ // panels, sound and the rest of account-ui-fields.mjs. The tab tells this
7
+ // module what the person changed (POST /api/account/ui), and applies what the
8
+ // account says (the `apply` values, then POST /api/account/ui/applied). This
9
+ // module holds the account's side: which profile this device is bound to, the
10
+ // last revision it knows of, edits not yet saved, a conflict, values a tab has
11
+ // not applied yet — and keeps all of it in account.json, so a restart loses
12
+ // neither a pending edit nor a conflict.
13
+ //
14
+ // SAVED IS NOT APPLIED. Saved is the API's revision of the bound profile;
15
+ // applied is the revision a tab on this machine has really put on screen, which
16
+ // the next status frame reports. With no tab open the two differ, and the
17
+ // console says so ("Saved r15 · Applied r14") rather than pretending.
18
+ //
19
+ // NO AUTOMATIC MERGING. A save against a stale revision is a 409 with the
20
+ // latest; the edit stays pending and the conflict is raised, and the person
21
+ // picks: Use latest (drop the draft) or Save mine over rN. A pull that finds a
22
+ // newer revision while an edit is pending raises the same conflict instead of
23
+ // applying over the edit.
24
+ //
25
+ // A DIFFERENT ACCOUNT NEVER GETS THIS DECK'S SETTINGS BY ITSELF. On a first
26
+ // connect, or a reconnect to the account this deck was last connected to, the
27
+ // tab's values are uploaded as the device profile. Connected to another
28
+ // account, nothing is uploaded until somebody asks ("Save this deck's settings
29
+ // to …") or makes an edit.
30
+ import {
31
+ DEFAULT_OVERRIDES, UI_SCHEMA, cleanUiValues, resolveUiValues, splitByOverrides,
32
+ } from "./account-ui-fields.mjs";
33
+
34
+ const revisionOf = v => (Number.isInteger(v) && v >= 0 ? v : 0);
35
+
36
+ /** A profile from the API, kept as the parts this deck uses. */
37
+ function keptProfile(p) {
38
+ if (!p || typeof p !== "object") return null;
39
+ return {
40
+ id: typeof p.id === "string" ? p.id : null,
41
+ kind: p.kind === "shared" ? "shared" : "device",
42
+ revision: revisionOf(p.revision),
43
+ values: cleanUiValues(p.values).values,
44
+ updatedBy: p.updatedBy && typeof p.updatedBy === "object"
45
+ ? { kind: String(p.updatedBy.kind ?? ""), name: typeof p.updatedBy.name === "string" ? p.updatedBy.name.slice(0, 64) : "" }
46
+ : null,
47
+ };
48
+ }
49
+
50
+ /** A fresh sync state for a device the API just enrolled. */
51
+ export function initialSync({ accountId, previousAccountId, settings }) {
52
+ const same = !previousAccountId || previousAccountId === accountId;
53
+ return {
54
+ accountId,
55
+ mode: settings?.mode === "shared" ? "shared" : "independent",
56
+ overrides: [...DEFAULT_OVERRIDES],
57
+ profileId: settings?.profileId ?? null,
58
+ base: { id: settings?.profileId ?? null, kind: settings?.mode === "shared" ? "shared" : "device", revision: revisionOf(settings?.revision), values: {}, updatedBy: null },
59
+ own: null,
60
+ pending: null,
61
+ conflict: null,
62
+ apply: null,
63
+ appliedRevision: null,
64
+ local: {},
65
+ skipped: null,
66
+ initialUpload: same,
67
+ askUpload: !same,
68
+ saving: "idle",
69
+ };
70
+ }
71
+
72
+ /** Whatever account.json held, coerced. */
73
+ export function normaliseSync(raw) {
74
+ if (!raw || typeof raw !== "object" || typeof raw.accountId !== "string") return null;
75
+ const values = v => cleanUiValues(v).values;
76
+ const pending = raw.pending && typeof raw.pending === "object" && Object.keys(values(raw.pending.values)).length
77
+ ? { values: values(raw.pending.values), since: typeof raw.pending.since === "string" ? raw.pending.since : new Date(0).toISOString() }
78
+ : null;
79
+ return {
80
+ accountId: raw.accountId,
81
+ mode: raw.mode === "shared" ? "shared" : "independent",
82
+ overrides: Array.isArray(raw.overrides) ? raw.overrides.filter(k => typeof k === "string") : [...DEFAULT_OVERRIDES],
83
+ profileId: typeof raw.profileId === "string" ? raw.profileId : null,
84
+ base: keptProfile(raw.base) ?? { id: null, kind: "device", revision: 0, values: {}, updatedBy: null },
85
+ own: keptProfile(raw.own),
86
+ pending,
87
+ conflict: raw.conflict?.latest ? { latest: keptProfile(raw.conflict.latest), target: raw.conflict.target === "own" ? "own" : "bound" } : null,
88
+ apply: raw.apply && Number.isInteger(raw.apply.revision) ? { revision: raw.apply.revision, values: values(raw.apply.values) } : null,
89
+ appliedRevision: Number.isInteger(raw.appliedRevision) ? raw.appliedRevision : null,
90
+ local: values(raw.local),
91
+ skipped: raw.skipped && typeof raw.skipped === "object" ? { theme: typeof raw.skipped.theme === "string" ? raw.skipped.theme : undefined } : null,
92
+ initialUpload: raw.initialUpload === true,
93
+ askUpload: raw.askUpload === true,
94
+ saving: "idle",
95
+ };
96
+ }
97
+
98
+ /**
99
+ * The sync. `state` is the persisted object (initialSync or normaliseSync's);
100
+ * every change is handed to `persist(state)` and announced through `onChange`.
101
+ * `onUnauthorized(error)` is a final 401 from any call — the service's to
102
+ * handle, as the publisher's is.
103
+ */
104
+ export function createSync({ client, token, state: initial, persist = async () => {}, onChange = () => {}, onUnauthorized = () => {}, now = Date.now }) {
105
+ let s = initial;
106
+ let queue = Promise.resolve();
107
+
108
+ /** One operation at a time, in order: a save and a pull must never race
109
+ * over the same base revision. */
110
+ const serial = job => {
111
+ const run = queue.then(job, job);
112
+ queue = run.then(() => {}, () => {});
113
+ return run;
114
+ };
115
+
116
+ async function changed() {
117
+ try { await persist(s); } catch { /* the in-memory state stands; the next change tries again */ }
118
+ onChange();
119
+ }
120
+
121
+ /** What the account says this device shows: the bound profile, with the
122
+ * device's own values over it for the override keys in shared mode. */
123
+ const resolvedBase = () => resolveUiValues({ mode: s.mode, bound: s.base, own: s.own, overrides: s.overrides });
124
+
125
+ /** What this device shows now: the account's values, what a tab reported,
126
+ * and the edits not yet saved — in that order of precedence, lowest first. */
127
+ const shownValues = () => ({ ...resolvedBase(), ...s.local, ...(s.pending?.values ?? {}) });
128
+
129
+ /** A 401 that ends the device. Anything else is the caller's to handle. */
130
+ function unauthorized(res) {
131
+ if (res.status === 401 && ["device_revoked", "invalid_token", "account_gone"].includes(res.error)) {
132
+ onUnauthorized(res.error);
133
+ return true;
134
+ }
135
+ return false;
136
+ }
137
+
138
+ /** The settings document, taken in: the binding, both profiles. */
139
+ function takeDocument(doc) {
140
+ if (!doc || typeof doc !== "object") return false;
141
+ const profile = keptProfile(doc.profile);
142
+ if (!profile) return false;
143
+ s.mode = doc.mode === "shared" ? "shared" : "independent";
144
+ s.overrides = Array.isArray(doc.overrides) ? doc.overrides.filter(k => typeof k === "string") : s.overrides;
145
+ s.profileId = profile.id;
146
+ s.base = profile;
147
+ s.own = keptProfile(doc.own) ?? (s.mode === "independent" ? profile : s.own);
148
+ return true;
149
+ }
150
+
151
+ /**
152
+ * Values for one profile's PUT: every key of it this deck writes there, with
153
+ * the edits over them. In shared mode that is only the override keys for the
154
+ * device's own profile, and everything but them for the shared one (design
155
+ * 3.5): the API refuses either the other way round with a 400 naming the key,
156
+ * and both profiles can hold keys this deck must not send back — the own
157
+ * profile still has what it showed while it was independent, and the console
158
+ * may give the shared profile a sound for the machines that do not keep
159
+ * their own. A key left out here is not unset: the API keeps those as stored.
160
+ */
161
+ async function put(profile, edits, target) {
162
+ const stored = s.mode === "shared" ? splitByOverrides(profile.values, s.overrides)[target === "own" ? "own" : "shared"] : profile.values;
163
+ return client.put("/v1/device/settings", {
164
+ profileId: profile.id,
165
+ baseRevision: profile.revision,
166
+ schema: UI_SCHEMA,
167
+ values: { ...stored, ...edits },
168
+ }, { token: token() });
169
+ }
170
+
171
+ /** Save what is pending, now. Resolves to what became of it. */
172
+ function save() {
173
+ return serial(async () => {
174
+ if (!s.pending || s.conflict || !token()) return "idle";
175
+ const edits = s.pending.values;
176
+ const { own: ownEdits, shared: boundEdits } = s.mode === "shared"
177
+ ? splitByOverrides(edits, s.overrides)
178
+ : { own: {}, shared: edits };
179
+ s.saving = "saving";
180
+ onChange();
181
+ for (const [target, part] of [["bound", boundEdits], ["own", ownEdits]]) {
182
+ if (!Object.keys(part).length) continue;
183
+ const profile = target === "bound" ? s.base : s.own;
184
+ if (!profile?.id) continue;
185
+ const res = await put(profile, part, target);
186
+ if (unauthorized(res)) { s.saving = "idle"; return "revoked"; }
187
+ if (res.ok && res.body?.profile) {
188
+ const saved = keptProfile(res.body.profile);
189
+ if (target === "bound") {
190
+ s.base = saved;
191
+ if (s.mode === "independent") s.own = saved;
192
+ // This device already shows what it just saved.
193
+ s.appliedRevision = saved.revision;
194
+ if (s.apply && s.apply.revision <= saved.revision) s.apply = null;
195
+ } else {
196
+ s.own = saved;
197
+ }
198
+ // Only the edits that were sent and have not changed since.
199
+ for (const [k, v] of Object.entries(part)) if (s.pending?.values[k] === v) delete s.pending.values[k];
200
+ s.local = { ...s.local, ...part };
201
+ continue;
202
+ }
203
+ if (res.status === 409 && res.error === "revision_conflict" && res.body?.latest) {
204
+ s.conflict = { latest: keptProfile(res.body.latest), target };
205
+ s.saving = "idle";
206
+ await changed();
207
+ return "conflict";
208
+ }
209
+ if (res.status === 409 && res.error === "profile_not_bound") {
210
+ // The binding moved under this deck. Read it again; the edit stays
211
+ // pending and goes to the right profile on the next try.
212
+ s.saving = "idle";
213
+ await pullDocument();
214
+ await changed();
215
+ return "rebound";
216
+ }
217
+ if (res.status === 400 || res.status === 413) {
218
+ // The API refused these values as values. Sending them again would
219
+ // be refused again, so they are dropped rather than retried forever.
220
+ for (const k of Object.keys(part)) delete s.pending?.values[k];
221
+ s.saving = "refused";
222
+ if (s.pending && !Object.keys(s.pending.values).length) s.pending = null;
223
+ await changed();
224
+ return "refused";
225
+ }
226
+ s.saving = "offline";
227
+ await changed();
228
+ return "offline";
229
+ }
230
+ if (s.pending && !Object.keys(s.pending.values).length) s.pending = null;
231
+ s.saving = "idle";
232
+ await changed();
233
+ return "saved";
234
+ });
235
+ }
236
+
237
+ /** GET the settings document, and take it in — or raise a conflict when an
238
+ * edit is pending and the account moved past it. No queueing: callers are
239
+ * already inside `serial`. */
240
+ async function pullDocument() {
241
+ const res = await client.get("/v1/device/settings", { token: token() });
242
+ if (unauthorized(res)) return "revoked";
243
+ if (!res.ok) return "offline";
244
+ const latest = keptProfile(res.body?.profile);
245
+ if (!latest) return "offline";
246
+ // Only an edit bound for THIS profile conflicts with it: in shared mode a
247
+ // pending sound change is the device's own profile's business.
248
+ const boundEdits = s.mode === "shared" ? splitByOverrides(s.pending?.values, s.overrides).shared : (s.pending?.values ?? {});
249
+ if (Object.keys(boundEdits).length && latest.id === s.base.id && latest.revision > s.base.revision) {
250
+ s.conflict = { latest, target: "bound" };
251
+ return "conflict";
252
+ }
253
+ takeDocument(res.body);
254
+ const revision = s.base.revision;
255
+ if (revision > (s.appliedRevision ?? -1)) {
256
+ const values = resolvedBase();
257
+ // Nothing to apply is still a revision this device has processed.
258
+ if (Object.keys(values).length) s.apply = { revision, values };
259
+ else s.appliedRevision = revision;
260
+ }
261
+ return "pulled";
262
+ }
263
+
264
+ const pull = () => serial(async () => {
265
+ const out = await pullDocument();
266
+ await changed();
267
+ return out;
268
+ });
269
+
270
+ /**
271
+ * A tab's report. `initial` is a tab that has just loaded: on a first
272
+ * connect its values are the device profile; otherwise it is about to adopt
273
+ * the account's values, and what it held before is not news. `user` is a
274
+ * person changing something.
275
+ */
276
+ async function reportUi(raw, reason) {
277
+ const { values } = cleanUiValues(raw);
278
+ if (reason === "initial") {
279
+ if (!s.initialUpload) return view();
280
+ s.initialUpload = false;
281
+ s.local = { ...s.local, ...values };
282
+ if (Object.keys(values).length) s.pending = { values: { ...values }, since: new Date(now()).toISOString() };
283
+ await changed();
284
+ await save();
285
+ return view();
286
+ }
287
+ const base = resolvedBase();
288
+ const pending = { ...(s.pending?.values ?? {}) };
289
+ let edits = 0;
290
+ for (const [k, v] of Object.entries(values)) {
291
+ if (base[k] === v) delete pending[k];
292
+ else { pending[k] = v; edits++; }
293
+ }
294
+ s.local = { ...s.local, ...values };
295
+ // An edit is the person engaging with this account: it is saved, and the
296
+ // question about uploading everything stops being asked.
297
+ if (edits) s.askUpload = false;
298
+ s.pending = Object.keys(pending).length ? { values: pending, since: s.pending?.since ?? new Date(now()).toISOString() } : null;
299
+ await changed();
300
+ if (s.pending) await save();
301
+ return view();
302
+ }
303
+
304
+ /** A tab put revision `revision` on screen. `skipped` names what it could
305
+ * not apply — a theme this version does not have — which still counts as
306
+ * processed. */
307
+ async function applied(revision, skipped) {
308
+ if (!Number.isInteger(revision) || revision < 0 || revision > s.base.revision) return view();
309
+ if (s.apply && s.apply.revision <= revision) {
310
+ s.local = { ...s.local, ...s.apply.values };
311
+ s.apply = null;
312
+ }
313
+ s.appliedRevision = Math.max(s.appliedRevision ?? -1, revision);
314
+ s.skipped = skipped && typeof skipped.theme === "string" ? { theme: skipped.theme.slice(0, 40) } : null;
315
+ await changed();
316
+ return view();
317
+ }
318
+
319
+ /** The conflict, answered. */
320
+ function resolve(action) {
321
+ return serial(async () => {
322
+ if (!s.conflict) return view();
323
+ const latest = s.conflict.latest;
324
+ if (action === "use-latest") {
325
+ s.pending = null;
326
+ if (s.conflict.target === "own") s.own = latest;
327
+ else { s.base = latest; if (s.mode === "independent") s.own = latest; }
328
+ s.conflict = null;
329
+ const values = resolvedBase();
330
+ if (Object.keys(values).length) s.apply = { revision: s.base.revision, values };
331
+ else s.appliedRevision = s.base.revision;
332
+ await changed();
333
+ return view();
334
+ }
335
+ if (action === "reapply") {
336
+ // Save mine over rN: the latest revision becomes the base, the draft
337
+ // goes on top of it.
338
+ if (s.conflict.target === "own") s.own = latest;
339
+ else { s.base = latest; if (s.mode === "independent") s.own = latest; }
340
+ s.conflict = null;
341
+ await changed();
342
+ return null;
343
+ }
344
+ return view();
345
+ }).then(async out => {
346
+ if (out !== null) return out;
347
+ await save();
348
+ return view();
349
+ });
350
+ }
351
+
352
+ /** The join preview: this device's values against the shared profile's. */
353
+ async function preview() {
354
+ const res = await client.get("/v1/device/settings?include=shared", { token: token() });
355
+ if (unauthorized(res)) return { error: "revoked" };
356
+ if (!res.ok) return { error: res.network ? "offline" : `status_${res.status}` };
357
+ const shared = keptProfile(res.body?.shared);
358
+ const local = shownValues();
359
+ const differences = [];
360
+ if (shared) {
361
+ for (const key of new Set([...Object.keys(local), ...Object.keys(shared.values)])) {
362
+ const a = Object.hasOwn(local, key) ? local[key] : null;
363
+ const b = Object.hasOwn(shared.values, key) ? shared.values[key] : null;
364
+ if (a !== b) differences.push({ key, local: a, shared: b });
365
+ }
366
+ }
367
+ return {
368
+ local,
369
+ shared: shared ? { revision: shared.revision, values: shared.values, updatedBy: shared.updatedBy } : null,
370
+ differences,
371
+ };
372
+ }
373
+
374
+ /** Join or leave shared settings — only ever from this deck. */
375
+ function setMode(body) {
376
+ return serial(async () => {
377
+ let request;
378
+ const shown = shownValues();
379
+ // `schema` is optional on this body and 1 by default (SettingsModeRequest
380
+ // in ccdeck-api); said anyway, so the values are read as this deck means them.
381
+ if (body?.mode === "shared" && body.join === "use-shared") {
382
+ request = { mode: "shared", join: "use-shared", schema: UI_SCHEMA };
383
+ } else if (body?.mode === "shared" && body.join === "publish") {
384
+ const rev = Number.isInteger(body.previewRevision) && body.previewRevision >= 0 ? body.previewRevision : 0;
385
+ request = { mode: "shared", join: "publish", sharedBaseRevision: rev, schema: UI_SCHEMA, values: shown };
386
+ } else if (body?.mode === "independent") {
387
+ request = { mode: "independent", schema: UI_SCHEMA, values: shown };
388
+ } else {
389
+ return { error: "bad_mode" };
390
+ }
391
+ const res = await client.post("/v1/device/settings/mode", request, { token: token() });
392
+ if (unauthorized(res)) return { error: "revoked" };
393
+ if (res.status === 409) return { error: res.error ?? "conflict", latest: keptProfile(res.body?.latest) };
394
+ if (!res.ok || !takeDocument(res.body)) return { error: res.network ? "offline" : `status_${res.status}` };
395
+ s.pending = null;
396
+ s.conflict = null;
397
+ if (request.join === "use-shared") {
398
+ const values = resolvedBase();
399
+ if (Object.keys(values).length) s.apply = { revision: s.base.revision, values };
400
+ else s.appliedRevision = s.base.revision;
401
+ } else {
402
+ // Publishing and leaving both wrote what this device shows.
403
+ s.appliedRevision = s.base.revision;
404
+ s.apply = null;
405
+ }
406
+ s.askUpload = false;
407
+ s.initialUpload = false;
408
+ await changed();
409
+ return { ok: true };
410
+ });
411
+ }
412
+
413
+ /** "Save this deck's settings to <email>": the deck's values, uploaded to a
414
+ * different account because somebody asked. */
415
+ async function upload(values) {
416
+ const clean = cleanUiValues(values).values;
417
+ s.local = { ...s.local, ...clean };
418
+ const all = { ...shownValues() };
419
+ s.askUpload = false;
420
+ if (Object.keys(all).length) s.pending = { values: all, since: new Date(now()).toISOString() };
421
+ await changed();
422
+ await save();
423
+ return view();
424
+ }
425
+
426
+ /** What /api/account says about the sync. */
427
+ function view() {
428
+ return {
429
+ mode: s.mode,
430
+ overrides: [...s.overrides],
431
+ profileId: s.profileId,
432
+ savedRevision: s.base.revision,
433
+ appliedRevision: s.appliedRevision,
434
+ // What a tab that has just loaded takes on when nothing is waiting to be
435
+ // applied: the account's values with this deck's unsaved edits over
436
+ // them, so a reload while offline does not undo an edit still pending.
437
+ adopt: { revision: s.base.revision, values: { ...resolvedBase(), ...(s.pending?.values ?? {}) } },
438
+ pending: s.pending ? { since: s.pending.since, keys: Object.keys(s.pending.values) } : null,
439
+ conflict: s.conflict ? {
440
+ latest: { revision: s.conflict.latest.revision, values: s.conflict.latest.values, updatedBy: s.conflict.latest.updatedBy },
441
+ mine: s.pending?.values ?? {},
442
+ } : null,
443
+ apply: s.apply ? { revision: s.apply.revision, values: { ...s.apply.values } } : null,
444
+ askUploadForNewAccount: s.askUpload,
445
+ initialUpload: s.initialUpload,
446
+ saving: s.saving,
447
+ skipped: s.skipped,
448
+ };
449
+ }
450
+
451
+ return {
452
+ pull,
453
+ save,
454
+ reportUi,
455
+ applied,
456
+ resolve,
457
+ preview,
458
+ setMode,
459
+ upload,
460
+ view,
461
+ /** What the status frame reports. */
462
+ binding: () => (s.profileId ? { profileId: s.profileId, appliedRevision: s.appliedRevision } : null),
463
+ /** A frame's answer: a newer revision is pulled, and whatever is pending is
464
+ * tried again — every successful frame is a sign the API is reachable. */
465
+ async onControl(settings) {
466
+ const newer = settings && typeof settings.revision === "number"
467
+ && (settings.profileId !== s.profileId || settings.revision > s.base.revision);
468
+ if (newer) await pull();
469
+ if (s.pending && !s.conflict) await save();
470
+ },
471
+ state: () => s,
472
+ };
473
+ }