ccdeck 3.82.4 → 4.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 (145) 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/tui.js +58 -4
  5. package/bin/deck.js +27 -1
  6. package/dist/web/assets/AccountBridge-fp-fsMx-.js +1 -0
  7. package/dist/web/assets/AccountSection-Cu-96Q00.js +1 -0
  8. package/dist/web/assets/BrowserWatchModal-CvUx07C6.js +1 -0
  9. package/dist/web/assets/FeedbackConversations-BgVk0nkA.js +1 -0
  10. package/dist/web/assets/IntegrationModal-CEj5oJg4.js +7 -0
  11. package/dist/web/assets/IntegrationSkeleton-DD7YiFgd.js +1 -0
  12. package/dist/web/assets/RadioPanel-BhnzWRCT.js +1 -0
  13. package/dist/web/assets/StageShell-DmJu3dU1.js +4 -0
  14. package/dist/web/assets/TrafficRadar-C8-ieIw5.js +8 -0
  15. package/dist/web/assets/UsageHistoryModal-BThv9Kja.js +1 -0
  16. package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
  17. package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
  18. package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
  19. package/dist/web/assets/app-DtosBis5.css +1 -0
  20. package/dist/web/assets/app-ZMmmEHxF.js +361 -0
  21. package/dist/web/assets/{index-B-l-VxLm.js → index-zSxC5ueJ.js} +1 -1
  22. package/dist/web/assets/inspector-status-pane-BgQG0bQi.js +1 -0
  23. package/dist/web/assets/screens-DD0uCtat.js +12 -0
  24. package/dist/web/assets/screens-DUniTTbC.css +1 -0
  25. package/dist/web/assets/stage-board-J2rKA9Pg.js +2 -0
  26. package/dist/web/assets/use-account-DvFObI4M.js +1 -0
  27. package/dist/web/assets/xterm-4jYizCpg.js +27 -0
  28. package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
  29. package/dist/web/index.html +16 -6
  30. package/package.json +13 -1
  31. package/release-notes.json +69 -1
  32. package/src/server/account-client.mjs +196 -0
  33. package/src/server/account-connect.mjs +238 -0
  34. package/src/server/account-flag.mjs +106 -0
  35. package/src/server/account-projects.mjs +1 -1
  36. package/src/server/account-service.mjs +532 -0
  37. package/src/server/account-status.mjs +293 -0
  38. package/src/server/account-store.mjs +137 -0
  39. package/src/server/account-sync.mjs +473 -0
  40. package/src/server/account-token-store.mjs +216 -0
  41. package/src/server/account-ui-fields.mjs +126 -0
  42. package/src/server/account-watch.mjs +1 -1
  43. package/src/server/browser-watch-log.mjs +1 -1
  44. package/src/server/browser-watch-store.mjs +1 -1
  45. package/src/server/ccdeck-account-routes.mjs +252 -0
  46. package/src/server/ccusage-install.mjs +2 -2
  47. package/src/server/ccusage-registry.mjs +4 -4
  48. package/src/server/ccusage-session.mjs +11 -0
  49. package/src/server/claude-accounts.mjs +1 -1
  50. package/src/server/claude-recovery.mjs +9 -4
  51. package/src/server/claude-settings-catalog.mjs +6 -6
  52. package/src/server/claude-settings.mjs +1 -1
  53. package/src/server/codex-auto.mjs +1 -1
  54. package/src/server/codex-cost-usage.mjs +7 -2
  55. package/src/server/codex-live-checkpoint.mjs +24 -9
  56. package/src/server/codex-live-engine.mjs +14 -4
  57. package/src/server/codex-live-handoff.mjs +53 -9
  58. package/src/server/codex-names.mjs +49 -0
  59. package/src/server/codex-translate.mjs +1 -1
  60. package/src/server/codex-ultrafast.d.mts +3 -0
  61. package/src/server/codex-ultrafast.mjs +5 -0
  62. package/src/server/codex-watch.mjs +25 -0
  63. package/src/server/command-panel-engine.mjs +300 -0
  64. package/src/server/command-panel-platform.mjs +99 -0
  65. package/src/server/cswap-auto-choice.mjs +1 -1
  66. package/src/server/cswap-auto-loop.mjs +1 -1
  67. package/src/server/cswap-install.mjs +21 -40
  68. package/src/server/deck-home.mjs +6 -0
  69. package/src/server/deck-prefs.mjs +53 -1
  70. package/src/server/detach.mjs +1 -1
  71. package/src/server/engine-download.mjs +277 -0
  72. package/src/server/engine-install.mjs +378 -0
  73. package/src/server/engine-package.mjs +267 -0
  74. package/src/server/event-log.mjs +7 -1
  75. package/src/server/event-pipeline.mjs +29 -1
  76. package/src/server/ghostty-handoff.mjs +81 -0
  77. package/src/server/index.mjs +143 -5
  78. package/src/server/installer.mjs +4 -1
  79. package/src/server/integrations/jira-write-guard.mjs +14 -208
  80. package/src/server/integrations/store.mjs +37 -19
  81. package/src/server/integrations/write-guard.mjs +223 -0
  82. package/src/server/intel-cpu-temperature.mjs +26 -0
  83. package/src/server/lifecycle.mjs +69 -6
  84. package/src/server/log-replay.mjs +4 -0
  85. package/src/server/login-service.mjs +7 -1
  86. package/src/server/macmon.mjs +1 -1
  87. package/src/server/npm-latest.mjs +1 -1
  88. package/src/server/org-telemetry.mjs +1 -1
  89. package/src/server/output-watch.mjs +4 -1
  90. package/src/server/panel-provenance.mjs +390 -0
  91. package/src/server/pinned-build.mjs +14 -0
  92. package/src/server/prefs-refusal.mjs +8 -1
  93. package/src/server/prefs-routes.mjs +60 -11
  94. package/src/server/pro-engine-client.mjs +339 -0
  95. package/src/server/pro-engine-install.mjs +294 -0
  96. package/src/server/pro-engine-terminal.mjs +308 -0
  97. package/src/server/project-discovery.mjs +139 -0
  98. package/src/server/provider-session-name.mjs +58 -0
  99. package/src/server/quota-closes.mjs +1 -1
  100. package/src/server/quota-history.mjs +1 -1
  101. package/src/server/reports.mjs +86 -21
  102. package/src/server/request-gates.mjs +34 -5
  103. package/src/server/restart-note.mjs +1 -1
  104. package/src/server/seed-boundary.mjs +489 -0
  105. package/src/server/session-counts.mjs +244 -0
  106. package/src/server/session-deck-names.mjs +143 -0
  107. package/src/server/session-enrichment.mjs +43 -6
  108. package/src/server/session-name-route.mjs +73 -0
  109. package/src/server/session-summary.mjs +12 -1
  110. package/src/server/session-transcript-routes.mjs +167 -0
  111. package/src/server/swap-log.mjs +1 -1
  112. package/src/server/system-metrics.mjs +57 -0
  113. package/src/server/terminal-bridge.mjs +485 -0
  114. package/src/server/terminal-folder.mjs +61 -0
  115. package/src/server/terminal-js-routes.mjs +752 -0
  116. package/src/server/terminal-routes.mjs +553 -0
  117. package/src/server/terminal-sessions.mjs +759 -0
  118. package/src/server/terminal-socket.mjs +403 -0
  119. package/src/server/terminal-target.mjs +928 -0
  120. package/src/server/thermal-metrics.mjs +13 -9
  121. package/src/server/tmux-control.mjs +1319 -0
  122. package/src/server/tmux-download.mjs +220 -0
  123. package/src/server/tmux.mjs +542 -0
  124. package/src/server/token-redact.mjs +42 -3
  125. package/src/server/tool-audit-report.mjs +44 -6
  126. package/src/server/tool-audit-routes.mjs +12 -1
  127. package/src/server/tool-audit.mjs +42 -8
  128. package/src/server/traffic-radar-monitor.mjs +1 -1
  129. package/src/server/traffic-radar-permission.mjs +1 -1
  130. package/src/server/transcript-gate.mjs +1 -1
  131. package/src/server/transcript-scan.mjs +15 -7
  132. package/src/server/transcript-turns.mjs +154 -0
  133. package/src/server/tui-network.mjs +1 -0
  134. package/src/server/tui-view.mjs +28 -0
  135. package/src/server/utf8-carry.mjs +159 -0
  136. package/src/server/uv-bootstrap.mjs +2 -2
  137. package/src/server/windows-acl.mjs +158 -0
  138. package/src/server/ws-frames.mjs +690 -0
  139. package/dist/web/assets/BrowserWatchModal-CWVooKxD.js +0 -1
  140. package/dist/web/assets/IntegrationModal-DLX43RIK.js +0 -7
  141. package/dist/web/assets/RadioPanel-Cj6PjrvQ.js +0 -1
  142. package/dist/web/assets/TrafficRadar-Bq1YcuHB.js +0 -8
  143. package/dist/web/assets/UsageHistoryModal-CMSCca5_.js +0 -1
  144. package/dist/web/assets/app-BHxsMz3-.js +0 -358
  145. package/dist/web/assets/app-CbXmr9rC.css +0 -1
@@ -0,0 +1,106 @@
1
+ // Whether this deck has a ccdeck account at all — the switch, the two vetoes
2
+ // and the API it would talk to.
3
+ //
4
+ // HIDDEN, AND OFF. The account (Settings › Account, the status frames, the
5
+ // settings sync) is built and not released: nothing about it is public until
6
+ // its owner says so. Off has to mean ABSENT, the way the terminal panel's flag
7
+ // means it on its branch: every /api/account* route answers the 404 an /api
8
+ // path with no route answers, /api/prefs says `accountOn: false`, none of the
9
+ // account modules is imported and no request goes to the API. This file is the
10
+ // one piece that is always loaded, because it is what decides — and it imports
11
+ // nothing but the product's name, does nothing as it loads and touches no file,
12
+ // so loading it costs a deck with the account off nothing.
13
+ //
14
+ // TWO WAYS ON, TWO WAYS OFF, AND OFF WINS. The launch variable turns it on for
15
+ // one run; `account: true` in prefs.json turns it on for good — deck-owned and
16
+ // hand-edited, never written by a page (not in PAGE_FIELDS while hidden). The
17
+ // vetoes are whoever launched the deck saying no for this machine, which a
18
+ // stored switch must not overrule: AGENTS_DECK_NO_ACCOUNT, and
19
+ // AGENTS_DECK_NO_INSTALL, which the README promises "turns off everything but
20
+ // the quota reads". AGENTS_DECK_NO_REPORTS is NOT a veto: reports are on by
21
+ // default and nobody asked for them; an account is something somebody connects
22
+ // on purpose, and the two identities are never linked (account-client.mjs).
23
+ //
24
+ // THE VARIABLES ARE UNDOCUMENTED ON PURPOSE. CCDECK_ACCOUNT and
25
+ // CCDECK_ACCOUNT_API stay out of the README and out of the login item while the
26
+ // feature is hidden; readme-order.test.ts names them as a decision, so
27
+ // documenting them later is a decision too. The veto is carried by the login
28
+ // item (login-service.mjs SETTING_VARS), because a veto is always safe to pass
29
+ // on — and stays out of the README's table for the same reason the switch does.
30
+ import { PRODUCT } from "./brand.mjs";
31
+
32
+ /** Set to "1" to switch the account on for this run, whatever prefs.json says. */
33
+ export const ACCOUNT_ENV = "CCDECK_ACCOUNT";
34
+
35
+ /** Set to "1" to keep this deck away from any account, whatever else says so. */
36
+ export const NO_ACCOUNT_ENV = "AGENTS_DECK_NO_ACCOUNT";
37
+
38
+ /** Where the API is, for development: a local ccdeck-api on loopback. */
39
+ export const ACCOUNT_API_ENV = "CCDECK_ACCOUNT_API";
40
+
41
+ /** The API the account talks to. The same host the usage reports go to
42
+ * (reports.mjs REPORTS_API), a different channel on it: nothing the reports
43
+ * send rides here, and nothing sent here rides there. */
44
+ export const ACCOUNT_API_DEFAULT = "https://api.ccdeck.dev";
45
+
46
+ /** Did the machine rule the account out? Asked before anything else, every
47
+ * time: a vetoed deck reads no token and sends nothing. */
48
+ export function accountVetoed(env = process.env) {
49
+ return env[NO_ACCOUNT_ENV] === "1" || env.AGENTS_DECK_NO_INSTALL === "1";
50
+ }
51
+
52
+ /** Is the account feature on, right now? The launch variable or the stored
53
+ * switch, unless the machine vetoed it. Asked on every request rather than
54
+ * once at boot, so the routes and the boot can never disagree about whether
55
+ * the feature exists. Only "1" and only a real `true` count: a truthy string
56
+ * in a hand-edited file is not an answer anybody gave. */
57
+ export function accountOn(prefs, env = process.env) {
58
+ if (accountVetoed(env)) return false;
59
+ return env[ACCOUNT_ENV] === "1" || prefs?.account === true;
60
+ }
61
+
62
+ /** Did anybody ask for the account — the variable or the stored switch —
63
+ * whether or not a veto then said no? What Settings needs to tell "off on this
64
+ * machine" from "not a thing here". */
65
+ export function accountRequested(prefs, env = process.env) {
66
+ return env[ACCOUNT_ENV] === "1" || prefs?.account === true;
67
+ }
68
+
69
+ /** Hosts a development API may sit on: this machine, by any spelling of it. */
70
+ const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]);
71
+
72
+ /**
73
+ * The API base the account talks to, as an origin with no trailing slash.
74
+ *
75
+ * An override is accepted only as `https://…`, or as plain http on this
76
+ * machine's own loopback — a ccdeck-api run with `dotnet run`. Anything else
77
+ * (a LAN address over http, a URL with a path or credentials in it, garbage)
78
+ * is not a development API: it is ignored, said once, and the default is used.
79
+ * A device token must never travel over plain http to another machine.
80
+ */
81
+ export function accountApiBase(env = process.env, warn = warnOnce) {
82
+ const raw = typeof env[ACCOUNT_API_ENV] === "string" ? env[ACCOUNT_API_ENV].trim() : "";
83
+ if (!raw) return ACCOUNT_API_DEFAULT;
84
+ const base = acceptedApiBase(raw);
85
+ if (base) return base;
86
+ warn(`${ACCOUNT_API_ENV} is not an https:// URL or a loopback http:// URL; using ${ACCOUNT_API_DEFAULT}`);
87
+ return ACCOUNT_API_DEFAULT;
88
+ }
89
+
90
+ /** `raw` as an origin, or null when it is not one the account may use. */
91
+ export function acceptedApiBase(raw) {
92
+ let url;
93
+ try { url = new URL(raw); } catch { return null; }
94
+ if (url.username || url.password || url.search || url.hash) return null;
95
+ if (url.pathname !== "/" && url.pathname !== "") return null;
96
+ if (url.protocol === "https:") return url.origin;
97
+ if (url.protocol === "http:" && LOOPBACK.has(url.hostname)) return url.origin;
98
+ return null;
99
+ }
100
+
101
+ let warned = false;
102
+ function warnOnce(message) {
103
+ if (warned) return;
104
+ warned = true;
105
+ console.error(`${PRODUCT}: ${message}`);
106
+ }
@@ -574,7 +574,7 @@ export function createProjectRollup({
574
574
  prune(state.tally, now());
575
575
  const tmp = stateFile + ".tmp";
576
576
  try {
577
- await mkdir(dirname(stateFile), { recursive: true });
577
+ await mkdir(dirname(stateFile), { recursive: true, mode: 0o700 });
578
578
  await writeFile(tmp, JSON.stringify(state), "utf8");
579
579
  // Atomic replace, so a crash never leaves half a file — through the
580
580
  // shared retry ladder, because a bare rename loses to a virus scanner or
@@ -0,0 +1,532 @@
1
+ // The account, as one running thing: account.json, the device token, the
2
+ // connect flow, the status publisher, the settings sync and the session
3
+ // counts, wired together — and the one answer every /api/account route and
4
+ // every `event: account` frame gives (`view`).
5
+ //
6
+ // LOADED ONLY WHEN THE ACCOUNT IS ON. index.mjs imports this through
7
+ // ccdeck-account-routes.mjs with a dynamic import() the first time a route is
8
+ // asked, or at boot when the account is on; with the flag off nothing here is
9
+ // ever evaluated (account-flag-off.test.ts).
10
+ //
11
+ // WHAT NEVER LEAVES THIS PROCESS: the device token, its DPAPI ciphertext and
12
+ // the device code. The view carries where the token is kept and nothing about
13
+ // it; the token is redacted out of every event (token-redact.mjs) and every
14
+ // report (reports.mjs scrub); no log line here names it.
15
+ //
16
+ // FEEDBACK CONVERSATIONS go through the named methods at the end — a list, a
17
+ // thread, a new one, a reply, read — so the page never holds the token and
18
+ // the routes never build an API path. Nothing of a conversation is kept here:
19
+ // each is fetched when the page asks. What is kept is the account's summary,
20
+ // `{ unread, latestAt, mail }`, which every status frame's answer carries and
21
+ // the view hands the page, in memory only, for the Feedback button's dot and
22
+ // for whether the dialog may say replies come by email. A
23
+ // conversation started here carries the deck's version and system and never
24
+ // the reports' fingerprint or a contact: the account is the way back.
25
+ import { dirname, resolve } from "node:path";
26
+ import { fileURLToPath } from "node:url";
27
+ import { accountApiBase } from "./account-flag.mjs";
28
+ import { createAccountClient, FEEDBACK_READ_MAX } from "./account-client.mjs";
29
+ import { cleanDeviceName, createConnectFlow, deckToken, defaultDeviceName } from "./account-connect.mjs";
30
+ import { createStatusPublisher, feedbackSummary, FINAL_401 } from "./account-status.mjs";
31
+ import { DEVICE_TOKEN, emptyAccount, loadAccount, normaliseAccount, saveAccount } from "./account-store.mjs";
32
+ import { createSync, initialSync, normaliseSync } from "./account-sync.mjs";
33
+ import { createTokenStore } from "./account-token-store.mjs";
34
+ import { inApp } from "./app-host.mjs";
35
+ import { PRODUCT } from "./brand.mjs";
36
+ import { deckDataDir } from "./deck-home.mjs";
37
+ import { isGitCheckout } from "./install-layout.mjs";
38
+ import { RUNNING_VERSION } from "./running-version.mjs";
39
+ import { createSessionCounts } from "./session-counts.mjs";
40
+ import { upstreamForm } from "./feedback-form.mjs";
41
+
42
+ const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
43
+ /** How often a token the keychain would not hand over is asked for again. */
44
+ export const LOCKED_RETRY_MS = 60_000;
45
+ const iso = ms => new Date(ms).toISOString();
46
+
47
+ /** The deck as the API is told about it: four tokens, nothing personal. */
48
+ export function deckFacts({ env = process.env, platform = process.platform, arch = process.arch, version = RUNNING_VERSION, checkout = isGitCheckout(PKG_ROOT) } = {}) {
49
+ return {
50
+ version: deckToken(version, 32),
51
+ os: deckToken(platform, 16),
52
+ arch: deckToken(arch, 16),
53
+ channel: inApp(env) ? "desktop" : checkout ? "checkout" : "npm",
54
+ };
55
+ }
56
+
57
+ /** The API's paths for the account's feedback conversations (design 3.3). */
58
+ const THREADS = "/v1/device/feedback/threads";
59
+ const threadPath = id => `${THREADS}/${encodeURIComponent(id)}`;
60
+ /** The two daily limits a 429 names, as opposed to the request policy's. */
61
+ const FEEDBACK_LIMITS = new Set(["too_many_conversations", "too_many_replies"]);
62
+
63
+ /** A 400's field errors as the page may show them: text under field names. */
64
+ function fieldErrors(body) {
65
+ const errors = body?.errors;
66
+ if (!errors || typeof errors !== "object" || Array.isArray(errors)) return {};
67
+ const out = {};
68
+ for (const [field, messages] of Object.entries(errors)) {
69
+ if (Array.isArray(messages)) out[field] = messages.filter(m => typeof m === "string");
70
+ }
71
+ return out;
72
+ }
73
+
74
+ /** Whether two summaries say the same thing (either may be null). */
75
+ const sameSummary = (a, b) => (a === null || b === null ? a === b : a.unread === b.unread && a.latestAt === b.latestAt && a.mail === b.mail);
76
+
77
+ /** Where a machine's page in the console is, from the approval page's origin:
78
+ * the API hands that out (PublicAccounts:AppBaseUrl), so a development API
79
+ * points at its own console. */
80
+ function consoleUrl(appBase, deviceId) {
81
+ return appBase && deviceId ? `${appBase}/machines/${encodeURIComponent(deviceId)}` : null;
82
+ }
83
+
84
+ /**
85
+ * The service. Everything outside it is passed in, with the product's own as
86
+ * defaults; the suite hands it the fake API's address through `env`, a token
87
+ * store that never touches a real keychain, the ring and the tap of a deck it
88
+ * builds, and a clock.
89
+ */
90
+ export function createAccountService({
91
+ env = process.env,
92
+ home = deckDataDir(),
93
+ prefs = () => ({}),
94
+ request = null,
95
+ tokenStore = null,
96
+ tokenStoreOptions = {},
97
+ broadcast = () => {},
98
+ reading = () => ({ cpu: { unknown: "unavailable" }, memory: { unknown: "unavailable" } }),
99
+ ring = () => [],
100
+ connectTap = () => {},
101
+ capture = () => true,
102
+ registerShutdown = () => () => {},
103
+ setRedactions = () => {},
104
+ facts = deckFacts({ env }),
105
+ now = Date.now,
106
+ random = Math.random,
107
+ setTimer = (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; },
108
+ clearTimer = t => clearTimeout(t),
109
+ log = msg => console.error(`${PRODUCT}: ${msg}`),
110
+ /** Whether the account is still on (account-flag.mjs accountOn), asked by
111
+ * the client before every request. */
112
+ enabled = () => true,
113
+ } = {}) {
114
+ const tokens = tokenStore ?? createTokenStore({ env, home, ...tokenStoreOptions });
115
+ const clients = new Map();
116
+ const counts = createSessionCounts({ capture });
117
+
118
+ let record = emptyAccount();
119
+ let token = null;
120
+ let tokenProblem = null; // "keychain-locked" | "token-missing"
121
+ let lockTimer = null;
122
+ let flow = null;
123
+ let publisher = null;
124
+ let sync = null;
125
+ let unregisterShutdown = null;
126
+ let started = false;
127
+ let announced = false;
128
+ /** The account's feedback summary from the last answer that carried one:
129
+ * null before the first frame, and whenever not connected. */
130
+ let feedback = null;
131
+
132
+ function clientFor(apiBase) {
133
+ let c = clients.get(apiBase);
134
+ if (!c) {
135
+ c = createAccountClient({ apiBase, version: facts.version, request, now, enabled });
136
+ clients.set(apiBase, c);
137
+ }
138
+ return c;
139
+ }
140
+
141
+ /** Every change, as one frame: several in one turn are one broadcast. */
142
+ function announce() {
143
+ if (announced) return;
144
+ announced = true;
145
+ queueMicrotask(() => {
146
+ announced = false;
147
+ try { broadcast(view()); } catch { /* a page that went away */ }
148
+ });
149
+ }
150
+
151
+ const suggestedName = () => cleanDeviceName(prefs()?.lan?.name ?? "", "") || defaultDeviceName();
152
+
153
+ function state() {
154
+ if (flow?.state().connecting) return "connecting";
155
+ if (record.deviceId && tokenProblem === "token-missing") return "error";
156
+ if (record.deviceId) return "connected";
157
+ if (record.revokedAt) return "revoked";
158
+ return "disconnected";
159
+ }
160
+
161
+ /** What /api/account answers and `event: account` carries. */
162
+ function view() {
163
+ const st = state();
164
+ const connected = st === "connected";
165
+ const flowState = flow?.state() ?? null;
166
+ return {
167
+ enabled: true,
168
+ vetoed: false,
169
+ state: st,
170
+ connect: flowState?.connect ?? null,
171
+ account: record.email && (connected || st === "revoked" || st === "error") ? { email: record.email } : null,
172
+ device: record.deviceId
173
+ ? { id: record.deviceId, name: record.deviceName, consoleUrl: consoleUrl(record.appBase, record.deviceId) }
174
+ : null,
175
+ suggestedName: suggestedName(),
176
+ // Where the token is, or where a new one would go.
177
+ tokenStorage: record.deviceId ? record.tokenStorage : tokens.backend(),
178
+ status: connected ? (publisher?.status() ?? null) : null,
179
+ sync: connected && sync ? sync.view() : null,
180
+ revokedReason: st === "revoked" ? record.revokedReason : null,
181
+ problem: tokenProblem && record.deviceId ? tokenProblem : (flowState?.problem ?? null),
182
+ feedback: connected ? feedback : null,
183
+ };
184
+ }
185
+
186
+ /** A summary from a frame's answer or a read's: kept, and said, only when it
187
+ * is one and says something new. A malformed one changes nothing; none at
188
+ * all (an API from before conversations) is no summary. */
189
+ function noteFeedback(raw) {
190
+ const next = raw == null ? null : feedbackSummary(raw);
191
+ if (raw != null && !next) return;
192
+ if (sameSummary(next, feedback)) return;
193
+ feedback = next;
194
+ announce();
195
+ }
196
+
197
+ /** Change the record and write it. The change lands in memory at once, so
198
+ * two writers in flight — a sync save and a token rotation — each build on
199
+ * the other's change instead of writing over it; the file writes are queued
200
+ * in the same order (account-store.mjs saveAccount). */
201
+ function persist(mutate) {
202
+ record = normaliseAccount(mutate(record));
203
+ return saveAccount(record, home);
204
+ }
205
+
206
+ function setToken(next, also = []) {
207
+ token = next;
208
+ setRedactions([next, ...also].filter(Boolean));
209
+ }
210
+
211
+ /** Revocation, account deletion, a token the API no longer knows: the deck
212
+ * forgets the device, keeps who it was connected to, and says so. */
213
+ async function ended(reason) {
214
+ if (!record.deviceId) return;
215
+ halt();
216
+ const was = record;
217
+ await tokens.remove(was).catch(() => {});
218
+ setToken(null);
219
+ await persist(() => ({
220
+ ...emptyAccount(),
221
+ email: was.email,
222
+ deviceName: was.deviceName,
223
+ previousAccountId: was.accountId || was.previousAccountId,
224
+ revokedAt: iso(now()),
225
+ revokedReason: reason ?? "device_revoked",
226
+ })).catch(err => log(`could not write account.json: ${err?.code ?? "error"}`));
227
+ announce();
228
+ }
229
+
230
+ /** Stop everything that talks to the API, and keep nothing running. */
231
+ function halt() {
232
+ publisher?.stop();
233
+ publisher = null;
234
+ sync = null;
235
+ feedback = null;
236
+ unregisterShutdown?.();
237
+ unregisterShutdown = null;
238
+ if (lockTimer) clearTimer(lockTimer);
239
+ lockTimer = null;
240
+ }
241
+
242
+ async function rotate() {
243
+ const client = clientFor(record.apiBase);
244
+ const res = await client.post("/v1/device/token/rotate", undefined, { token });
245
+ if (res.status === 401 && FINAL_401.has(res.error)) return ended(res.error);
246
+ const next = res.ok ? res.body?.accessToken : null;
247
+ if (typeof next !== "string" || !DEVICE_TOKEN.test(next)) return;
248
+ // Persisted BEFORE it is used. Both tokens stay valid until the first
249
+ // request made with the new one, so a write that fails here costs nothing:
250
+ // the old token goes on working and the next rotation request tries again.
251
+ setRedactions([token, next]);
252
+ let kept;
253
+ try {
254
+ kept = await tokens.save(next);
255
+ await persist(r => ({ ...r, tokenStorage: kept.tokenStorage, token: kept.token ?? "", tokenCipher: kept.tokenCipher ?? "" }));
256
+ } catch {
257
+ setRedactions([token]);
258
+ return;
259
+ }
260
+ setToken(next);
261
+ }
262
+
263
+ /** The device is connected and its token is in hand: start talking. */
264
+ function begin() {
265
+ tokenProblem = null;
266
+ const client = clientFor(record.apiBase);
267
+ sync = createSync({
268
+ client,
269
+ token: () => token,
270
+ state: normaliseSync(record.sync) ?? initialSync({ accountId: record.accountId, previousAccountId: record.previousAccountId, settings: null }),
271
+ persist: st => persist(r => ({ ...r, sync: st })),
272
+ onChange: announce,
273
+ onUnauthorized: reason => { void ended(reason); },
274
+ now,
275
+ });
276
+ publisher = createStatusPublisher({
277
+ client,
278
+ token: () => token,
279
+ rotate,
280
+ reading,
281
+ counts: at => counts.reading(at),
282
+ binding: () => sync?.binding() ?? null,
283
+ deck: facts,
284
+ onControl: settings => sync?.onControl(settings),
285
+ onFeedback: noteFeedback,
286
+ onRevoked: reason => { void ended(reason); },
287
+ onChange: announce,
288
+ now,
289
+ random,
290
+ setTimer,
291
+ clearTimer,
292
+ log,
293
+ });
294
+ publisher.start();
295
+ unregisterShutdown = registerShutdown(() => publisher?.sendStopping());
296
+ announce();
297
+ }
298
+
299
+ /** Read the token for a device account.json names; retry a locked keychain. */
300
+ async function unlock() {
301
+ if (!record.deviceId) return;
302
+ const got = await tokens.load(record);
303
+ if (got.ok) {
304
+ setToken(got.token);
305
+ begin();
306
+ void sync?.pull().catch(() => {});
307
+ return;
308
+ }
309
+ tokenProblem = got.reason === "locked" ? "keychain-locked" : "token-missing";
310
+ if (tokenProblem === "keychain-locked") {
311
+ lockTimer = setTimer(() => { lockTimer = null; void unlock(); }, LOCKED_RETRY_MS);
312
+ }
313
+ announce();
314
+ }
315
+
316
+ async function start() {
317
+ if (started) return;
318
+ started = true;
319
+ // The counts first and in one turn: the tap and the ring's snapshot are
320
+ // taken together, so no event is missed between them or counted twice.
321
+ connectTap((raw, at) => counts.note(raw, at));
322
+ counts.seed(ring());
323
+ counts.markReady();
324
+ record = await loadAccount(home);
325
+ await unlock();
326
+ }
327
+
328
+ /** The token is here: keep it, write account.json, and start. */
329
+ /** The code each flow was handed, kept past the approval that clears it:
330
+ * the approval page's origin is where this device's console page is. */
331
+ const codes = new WeakMap();
332
+ const codeOf = f => codes.get(f) ?? null;
333
+
334
+ async function approved(tok, name, apiBase, code) {
335
+ const appBase = (() => {
336
+ try { return new URL(code?.verificationUri ?? "").origin; } catch { return ""; }
337
+ })();
338
+ const kept = await tokens.save(tok.accessToken);
339
+ const previousAccountId = record.previousAccountId || record.accountId || "";
340
+ halt();
341
+ // Written first, and only then made this deck's record: from the moment
342
+ // /api/account answers "connected" the sync and the publisher are running,
343
+ // so a page that reports its settings at once is never told the deck is
344
+ // not connected.
345
+ const next = normaliseAccount({
346
+ ...emptyAccount(),
347
+ apiBase,
348
+ appBase,
349
+ accountId: tok.account.id,
350
+ email: tok.account.email,
351
+ deviceId: tok.deviceId,
352
+ deviceName: cleanDeviceName(tok.name, name),
353
+ connectedAt: iso(now()),
354
+ tokenStorage: kept.tokenStorage,
355
+ token: kept.token ?? "",
356
+ tokenCipher: kept.tokenCipher ?? "",
357
+ previousAccountId,
358
+ sync: initialSync({ accountId: tok.account.id, previousAccountId, settings: tok.settings }),
359
+ });
360
+ await saveAccount(next, home);
361
+ record = next;
362
+ setToken(tok.accessToken);
363
+ begin();
364
+ await sync?.pull().catch(() => {});
365
+ }
366
+
367
+ /**
368
+ * One feedback call, made with this deck's token, and its answer as the
369
+ * local routes give it (design 4.4): `{ ok: true, status, body }` with the
370
+ * API's body, or `{ ok: false, reason, … }`. A final 401 ends the device, as
371
+ * a frame's does; a device that ended while the call was out is `revoked`.
372
+ */
373
+ async function feedbackCall(run) {
374
+ const device = record.deviceId;
375
+ if (!device || !token) return { ok: false, reason: "not_connected" };
376
+ const res = await run(clientFor(record.apiBase), token);
377
+ if (res.status === 401 && FINAL_401.has(res.error)) {
378
+ if (record.deviceId === device) await ended(res.error);
379
+ return { ok: false, reason: "revoked" };
380
+ }
381
+ if (record.deviceId !== device) return { ok: false, reason: "revoked" };
382
+ if (res.ok) {
383
+ const body = res.body;
384
+ return body && typeof body === "object" && !Array.isArray(body) ? { ok: true, status: res.status, body } : { ok: false, reason: "unavailable" };
385
+ }
386
+ if (res.status === 400) return { ok: false, reason: "invalid", errors: fieldErrors(res.body) };
387
+ if (res.status === 404 && res.error === "thread_not_found") return { ok: false, reason: "not_found" };
388
+ if (res.status === 413) return { ok: false, reason: "too_large" };
389
+ if (res.status === 429) {
390
+ const out = { ok: false, reason: "too_many" };
391
+ const limited = FEEDBACK_LIMITS.has(res.error);
392
+ if (limited && Number.isInteger(res.body?.limit)) out.limit = res.body.limit;
393
+ if (limited && Number.isInteger(res.body?.retryAfterSec)) out.retryAfterSec = res.body.retryAfterSec;
394
+ else if (res.retryAfterMs) out.retryAfterSec = Math.ceil(res.retryAfterMs / 1000);
395
+ return out;
396
+ }
397
+ // A network failure, a 5xx, the API with accounts switched off (any other
398
+ // 404), a 401 a proxy wrote: nothing the person can put right but wait.
399
+ return { ok: false, reason: "unavailable" };
400
+ }
401
+
402
+ return {
403
+ start,
404
+ view,
405
+ /** Start connecting under `name` (cleaned; the suggestion when empty).
406
+ * Answers once the API has handed out a code or refused; the approval
407
+ * arrives later, as an `event: account`. */
408
+ async connect(name) {
409
+ if (record.deviceId && tokenProblem !== "token-missing") return view();
410
+ const apiBase = accountApiBase(env, log);
411
+ const clean = cleanDeviceName(typeof name === "string" ? name : "", "") || suggestedName();
412
+ flow?.cancel();
413
+ // A device that lost its token connects again as a new device.
414
+ if (record.deviceId) {
415
+ halt();
416
+ record = { ...emptyAccount(), previousAccountId: record.accountId || record.previousAccountId };
417
+ tokenProblem = null;
418
+ }
419
+ const current = createConnectFlow({
420
+ client: clientFor(apiBase),
421
+ facts,
422
+ onApproved: tok => approved(tok, clean, apiBase, codeOf(current)),
423
+ onChange: announce,
424
+ now,
425
+ setTimer,
426
+ clearTimer,
427
+ });
428
+ flow = current;
429
+ await current.start(clean);
430
+ codes.set(current, current.state().connect);
431
+ return view();
432
+ },
433
+ async cancelConnect() {
434
+ flow?.cancel();
435
+ return view();
436
+ },
437
+ async disconnect() {
438
+ flow?.cancel();
439
+ if (!record.deviceId) return view();
440
+ const was = record;
441
+ const client = clientFor(was.apiBase);
442
+ // Tell the API first, while the token still works: the console then
443
+ // shows the machine gone at once. Best effort — offline, the grant stays
444
+ // until somebody removes it there or it expires unused.
445
+ if (token) await client.del("/v1/device", { token, timeout: 3_000 }).catch(() => null);
446
+ halt();
447
+ await tokens.remove(was).catch(() => {});
448
+ setToken(null);
449
+ tokenProblem = null;
450
+ await persist(() => ({
451
+ ...emptyAccount(),
452
+ deviceName: was.deviceName,
453
+ previousAccountId: was.accountId || was.previousAccountId,
454
+ })).catch(err => log(`could not write account.json: ${err?.code ?? "error"}`));
455
+ announce();
456
+ return view();
457
+ },
458
+ async reportUi(body) {
459
+ if (!sync) return null;
460
+ await sync.reportUi(body?.values, body?.reason === "initial" ? "initial" : "user");
461
+ return sync.view();
462
+ },
463
+ async applied(body) {
464
+ if (!sync) return null;
465
+ await sync.applied(body?.revision, body?.skipped);
466
+ return sync.view();
467
+ },
468
+ async preview() {
469
+ return sync ? sync.preview() : null;
470
+ },
471
+ async setMode(body) {
472
+ if (!sync) return null;
473
+ const out = await sync.setMode(body);
474
+ return { ...out, sync: sync?.view() ?? null };
475
+ },
476
+ async resolve(body) {
477
+ if (!sync) return null;
478
+ await sync.resolve(body?.action);
479
+ return sync.view();
480
+ },
481
+ async upload(body) {
482
+ if (!sync) return null;
483
+ if (body?.upload !== true) return sync.view();
484
+ await sync.upload(body?.values);
485
+ return sync.view();
486
+ },
487
+ /** The account's conversations, latest activity first; `before` is the
488
+ * list's own cursor. */
489
+ feedbackThreads({ before } = {}) {
490
+ const query = before ? `&before=${encodeURIComponent(before)}` : "";
491
+ return feedbackCall((client, tok) => client.get(`${THREADS}?limit=50${query}`, { token: tok, maxBody: FEEDBACK_READ_MAX }));
492
+ },
493
+ /** One conversation's latest page, or the page before item `before`. */
494
+ feedbackThread(id, { before } = {}) {
495
+ const query = Number.isInteger(before) ? `?before=${before}` : "";
496
+ return feedbackCall((client, tok) => client.get(`${threadPath(id)}${query}`, { token: tok, maxBody: FEEDBACK_READ_MAX }));
497
+ },
498
+ /** A new conversation: the dialog's kind, title and message, this deck's
499
+ * version and system, and the images as feedback-form.mjs read them —
500
+ * JSON without images, the form with them. Never a contact, never the
501
+ * reports' fingerprint. */
502
+ feedbackCreate({ fields = {}, images = [] } = {}) {
503
+ const kept = { kind: fields.kind, title: fields.title, body: fields.body };
504
+ const deck = { appVersion: facts.version, platform: `${facts.os}-${facts.arch}` };
505
+ return feedbackCall((client, tok) => (images.length > 0
506
+ ? client.postForm(THREADS, upstreamForm({ fields: kept, images }, deck), { token: tok })
507
+ : client.post(THREADS, { ...kept, ...deck }, { token: tok })));
508
+ },
509
+ feedbackReply(id, body) {
510
+ return feedbackCall((client, tok) => client.post(`${threadPath(id)}/replies`, { body }, { token: tok }));
511
+ },
512
+ /** Everything up to `seq` seen; the answer is the account's summary after
513
+ * it, which clears the dot at once rather than at the next frame. */
514
+ async feedbackRead(id, seq) {
515
+ const out = await feedbackCall((client, tok) => client.post(`${threadPath(id)}/read`, { seq }, { token: tok }));
516
+ if (out.ok) noteFeedback(out.body);
517
+ return out;
518
+ },
519
+ noteFeedback,
520
+ /** For the suite and the shutdown path. */
521
+ publisher: () => publisher,
522
+ sync: () => sync,
523
+ counts,
524
+ stop() {
525
+ flow?.cancel();
526
+ halt();
527
+ for (const c of clients.values()) c.close();
528
+ clients.clear();
529
+ connectTap(null);
530
+ },
531
+ };
532
+ }