sideby 0.19.0 → 0.20.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 (161) hide show
  1. package/README.md +7 -4
  2. package/ai-tasks.json +28 -0
  3. package/dist/build.json +1 -1
  4. package/dist/src/cli/commands.d.ts +22 -1
  5. package/dist/src/cli/commands.js +815 -21
  6. package/dist/src/cli/format.d.ts +4 -0
  7. package/dist/src/cli/format.js +42 -4
  8. package/dist/src/cli/json-schemas.js +334 -4
  9. package/dist/src/cli/main.js +159 -13
  10. package/dist/src/core/accounts.d.ts +6 -0
  11. package/dist/src/core/accounts.js +12 -0
  12. package/dist/src/core/autostart.d.ts +11 -0
  13. package/dist/src/core/autostart.js +32 -5
  14. package/dist/src/core/browser-profiles.d.ts +23 -2
  15. package/dist/src/core/browser-profiles.js +148 -37
  16. package/dist/src/core/claude-settings-file.d.ts +18 -0
  17. package/dist/src/core/claude-settings-file.js +52 -3
  18. package/dist/src/core/config.d.ts +5 -0
  19. package/dist/src/core/config.js +12 -1
  20. package/dist/src/core/edit-settings.d.ts +7 -0
  21. package/dist/src/core/edit-settings.js +10 -5
  22. package/dist/src/core/file-memo.js +26 -4
  23. package/dist/src/core/history-group.d.ts +28 -0
  24. package/dist/src/core/history-group.js +47 -0
  25. package/dist/src/core/history-index.d.ts +145 -0
  26. package/dist/src/core/history-index.js +447 -0
  27. package/dist/src/core/history-project.d.ts +13 -0
  28. package/dist/src/core/history-project.js +87 -0
  29. package/dist/src/core/history.d.ts +210 -0
  30. package/dist/src/core/history.js +952 -0
  31. package/dist/src/core/inbound.d.ts +62 -0
  32. package/dist/src/core/inbound.js +215 -0
  33. package/dist/src/core/launch.d.ts +9 -1
  34. package/dist/src/core/launch.js +58 -24
  35. package/dist/src/core/live-sessions-copy.d.ts +5 -0
  36. package/dist/src/core/live-sessions-copy.js +46 -0
  37. package/dist/src/core/live-sessions-procs.d.ts +89 -0
  38. package/dist/src/core/live-sessions-procs.js +296 -0
  39. package/dist/src/core/live-sessions-title.d.ts +28 -0
  40. package/dist/src/core/live-sessions-title.js +80 -0
  41. package/dist/src/core/live-sessions.d.ts +68 -0
  42. package/dist/src/core/live-sessions.js +163 -0
  43. package/dist/src/core/login-check.d.ts +15 -0
  44. package/dist/src/core/login-check.js +32 -0
  45. package/dist/src/core/messages.d.ts +83 -0
  46. package/dist/src/core/messages.js +433 -0
  47. package/dist/src/core/project-categories.d.ts +14 -0
  48. package/dist/src/core/project-categories.js +48 -0
  49. package/dist/src/core/quota-fetch.d.ts +3 -3
  50. package/dist/src/core/quota-fetch.js +5 -5
  51. package/dist/src/core/quota-levels.d.ts +5 -0
  52. package/dist/src/core/quota-levels.js +5 -0
  53. package/dist/src/core/remote-control.d.ts +2 -0
  54. package/dist/src/core/remote-control.js +34 -59
  55. package/dist/src/core/run-link.d.ts +76 -0
  56. package/dist/src/core/run-link.js +245 -0
  57. package/dist/src/core/same-login.d.ts +4 -3
  58. package/dist/src/core/same-login.js +10 -7
  59. package/dist/src/core/session-select.d.ts +31 -0
  60. package/dist/src/core/session-select.js +44 -0
  61. package/dist/src/families/browser.d.ts +7 -18
  62. package/dist/src/families/browser.js +19 -8
  63. package/dist/src/families/claude/deliver.d.ts +2 -0
  64. package/dist/src/families/claude/deliver.js +43 -0
  65. package/dist/src/families/claude/history.d.ts +2 -0
  66. package/dist/src/families/claude/history.js +192 -0
  67. package/dist/src/families/claude/live-sessions.d.ts +13 -0
  68. package/dist/src/families/claude/live-sessions.js +117 -0
  69. package/dist/src/families/claude/messaging.d.ts +69 -0
  70. package/dist/src/families/claude/messaging.js +165 -0
  71. package/dist/src/families/claude/mod.d.ts +26 -0
  72. package/dist/src/families/claude/mod.js +105 -0
  73. package/dist/src/families/claude/session-files.d.ts +21 -0
  74. package/dist/src/families/claude/session-files.js +54 -0
  75. package/dist/src/families/codex/deliver.d.ts +5 -0
  76. package/dist/src/families/codex/deliver.js +76 -0
  77. package/dist/src/families/codex/history.d.ts +7 -0
  78. package/dist/src/families/codex/history.js +174 -0
  79. package/dist/src/families/codex/index.js +2 -0
  80. package/dist/src/families/codex/live-sessions.d.ts +12 -0
  81. package/dist/src/families/codex/live-sessions.js +193 -0
  82. package/dist/src/families/codex/quota.d.ts +3 -0
  83. package/dist/src/families/codex/quota.js +123 -0
  84. package/dist/src/families/codex/rate-limits.js +2 -0
  85. package/dist/src/families/codex/rollout.js +1 -1
  86. package/dist/src/families/grok/browser.d.ts +3 -0
  87. package/dist/src/families/grok/browser.js +5 -0
  88. package/dist/src/families/grok/history.d.ts +2 -0
  89. package/dist/src/families/grok/history.js +157 -0
  90. package/dist/src/families/grok/live-sessions.d.ts +4 -0
  91. package/dist/src/families/grok/live-sessions.js +80 -0
  92. package/dist/src/families/grok/login-key.d.ts +14 -0
  93. package/dist/src/families/grok/login-key.js +37 -0
  94. package/dist/src/families/history.d.ts +20 -0
  95. package/dist/src/families/history.js +81 -0
  96. package/dist/src/families/live-sessions.d.ts +26 -0
  97. package/dist/src/families/live-sessions.js +9 -0
  98. package/dist/src/families/login-keys.js +5 -1
  99. package/dist/src/families/messaging.d.ts +27 -0
  100. package/dist/src/families/messaging.js +6 -0
  101. package/dist/src/families/pi/history.d.ts +2 -0
  102. package/dist/src/families/pi/history.js +124 -0
  103. package/dist/src/families/pi/live-sessions.d.ts +2 -0
  104. package/dist/src/families/pi/live-sessions.js +70 -0
  105. package/dist/src/families/shared/history-text.d.ts +65 -0
  106. package/dist/src/families/shared/history-text.js +261 -0
  107. package/dist/src/menubar/hotkey.d.ts +86 -0
  108. package/dist/src/menubar/hotkey.js +159 -0
  109. package/dist/src/menubar/script.d.ts +2 -0
  110. package/dist/src/menubar/script.js +118 -22
  111. package/dist/src/menubar/snapshot.d.ts +8 -4
  112. package/dist/src/menubar/snapshot.js +45 -13
  113. package/dist/src/menubar/strings.d.ts +24 -6
  114. package/dist/src/menubar/strings.js +24 -6
  115. package/dist/src/panel/handler.d.ts +69 -0
  116. package/dist/src/panel/handler.js +686 -15
  117. package/dist/src/panel/i18n.d.ts +304 -3
  118. package/dist/src/panel/i18n.js +669 -67
  119. package/dist/src/panel/orca.d.ts +48 -0
  120. package/dist/src/panel/orca.js +153 -0
  121. package/dist/src/panel/page-logic.d.ts +255 -13
  122. package/dist/src/panel/page-logic.js +483 -1
  123. package/dist/src/panel/page-script.js +2265 -207
  124. package/dist/src/panel/page-styles.js +404 -32
  125. package/dist/src/panel/page.js +1 -0
  126. package/dist/src/plugins/account-script.js +61 -27
  127. package/dist/src/plugins/check.js +16 -4
  128. package/dist/src/plugins/loader.d.ts +8 -1
  129. package/dist/src/plugins/loader.js +72 -7
  130. package/dist/src/runtime.d.ts +5 -0
  131. package/dist/src/runtime.js +27 -5
  132. package/dist/src/types.d.ts +116 -1
  133. package/dist/testing/index.d.ts +5 -0
  134. package/dist/testing/index.js +5 -0
  135. package/mods/claude/.claude-plugin/plugin.json +7 -0
  136. package/mods/claude/hooks/hooks.json +1 -0
  137. package/mods/claude/hooks/register.js +261 -0
  138. package/package.json +5 -2
  139. package/schemas/autostart.json +74 -1
  140. package/schemas/browser-set.json +110 -0
  141. package/schemas/browser.json +22 -2
  142. package/schemas/config.json +26 -1
  143. package/schemas/history-index.json +209 -0
  144. package/schemas/history-projects.json +133 -0
  145. package/schemas/history-show.json +275 -0
  146. package/schemas/history.json +410 -0
  147. package/schemas/menubar-hotkey.json +139 -0
  148. package/schemas/menubar-snapshot.json +36 -2
  149. package/schemas/menubar.json +74 -1
  150. package/schemas/messages-inbound.json +258 -0
  151. package/schemas/messages.json +164 -0
  152. package/schemas/send.json +165 -0
  153. package/schemas/sessions-copy.json +113 -0
  154. package/schemas/sessions-open-run.json +97 -0
  155. package/schemas/sessions.json +237 -0
  156. package/skills/sideby/SKILL.md +10 -5
  157. package/skills/sideby/references/accounts.md +11 -0
  158. package/skills/sideby/references/ai-tasks.md +17 -1
  159. package/skills/sideby/references/panel.md +6 -4
  160. package/skills/sideby/references/quota.md +2 -2
  161. package/skills/sideby/references/sessions.md +79 -0
@@ -1,13 +1,13 @@
1
1
  // HTTP handler for the local Panel. Mountable under any basePath; standalone and embedded use the same rules.
2
2
  import { randomBytes, timingSafeEqual } from 'node:crypto';
3
- import { aliasesByAccount } from '../core/accounts.js';
3
+ import { aliasesByAccount, startArgsOf } from '../core/accounts.js';
4
4
  import { listAppProfiles, openAppProfile, removeAppProfile, } from '../core/app-profiles.js';
5
5
  import { openLoginInTerminal, openPickInTerminal, pickTaskAccount, previewAttachments, promptForTask, setCustomTerminal, setPreferredTerminal, startAiTask, taskContext, terminals, tryAccount, } from '../core/ask.js';
6
- import { MAX_ATTACHMENTS, MAX_UPLOAD_BYTES, removeStaged, stageUpload } from '../core/attachments.js';
6
+ import { ATTACHMENT_LIMITS, MAX_ATTACHMENTS, MAX_UPLOAD_BYTES, removeStaged, stagedAttachments, stageUpload, } from '../core/attachments.js';
7
7
  import { applyAutostart, autostartStatus, PANEL_AGENT, planAutostart, } from '../core/autostart.js';
8
8
  import { FAVICON_SVG, ICON_SVG } from '../core/brand-mark.js';
9
- import { browserReport, openInBrowser, setBrowserSignIns, } from '../core/browser-profiles.js';
10
- import { aliasArgs, aliasRefs, editConfigPanel, editConfigTerminal, editConfigUpdate, } from '../core/config.js';
9
+ import { browserReport, openInBrowser, setBrowserChoice, setBrowserSignIns, } from '../core/browser-profiles.js';
10
+ import { aliasArgs, aliasRefs, editConfigPanel, editConfigTerminal, editConfigUpdate, loadConfig, } from '../core/config.js';
11
11
  import { openDesktopApp, withDesktopApps } from '../core/desktop-app.js';
12
12
  import { editSettings } from '../core/edit-settings.js';
13
13
  import { UserError } from '../core/errors.js';
@@ -15,8 +15,12 @@ import { planHandoff } from '../core/handoff.js';
15
15
  import { applyHandoffEnable, planHandoffEnable } from '../core/handoff-enable.js';
16
16
  import { handoffOverview } from '../core/handoff-overview.js';
17
17
  import { configureHandoff, handoffStatus } from '../core/handoff-status.js';
18
+ import { acceptInbound, inboundGroups, undoInbound, waitingFiles, } from '../core/inbound.js';
19
+ import { listLiveSessions, liveKey, referenceText, sessionCopyText, } from '../core/live-sessions.js';
20
+ import { listMessages, sendMessage } from '../core/messages.js';
18
21
  import { accountModel, setAccountModel } from '../core/model-choice.js';
19
22
  import { tildify } from '../core/paths.js';
23
+ import { openRunBoard, withRuns } from '../core/run-link.js';
20
24
  import { SECRET_VAR_NAME, secretVarFor, setSecret } from '../core/secret-file.js';
21
25
  import { SKILL_INSTALL } from '../core/skill-check.js';
22
26
  import { launchArgs, TERMINALS } from '../core/terminal.js';
@@ -25,7 +29,9 @@ import * as update from '../core/update.js';
25
29
  import { buildId, localBuild, packageVersion } from '../core/version.js';
26
30
  import { HOOK_FAMILIES } from '../handoff/hook.js';
27
31
  import { MENUBAR_AGENT } from '../menubar/agent.js';
32
+ import { hotkeyView, iconView, openMenuBarSettings, readMenubarState, setMenubarHotkey, } from '../menubar/hotkey.js';
28
33
  import { MENUBAR_SCRIPT } from '../menubar/script.js';
34
+ import { orcaTabs, switchOrcaTab, systemOrca } from './orca.js';
29
35
  import { renderPage } from './page.js';
30
36
  import { AI_TASK_KINDS } from './page-logic.js';
31
37
  import { resolveTheme } from './theme.js';
@@ -33,6 +39,14 @@ export const PANEL_VERSION = packageVersion();
33
39
  export const MAX_BODY_BYTES = 64 * 1024;
34
40
  /** Write requests allowed to wait behind the running one; more get 409. */
35
41
  export const MAX_QUEUED_WRITES = 4;
42
+ /**
43
+ * Internal, for tests and screenshots: a property under this key of the handler options replaces where the Sessions
44
+ * page reads Live Sessions and their copy texts from (spec §3.32). Not part of the Portal contract (`src/index.ts`
45
+ * does not export it); it may change without notice.
46
+ */
47
+ export const LIVE_SESSIONS_SOURCE = Symbol('sideby.panel.liveSessions');
48
+ /** The longest text "Send to it" takes; the page's text box has the same limit. */
49
+ export const MAX_MESSAGE_TEXT = 8000;
36
50
  function resolveAsk(ask) {
37
51
  if (ask === undefined)
38
52
  return undefined;
@@ -88,6 +102,23 @@ export function bindPanelAutostart(ctx) {
88
102
  autostartOverride = before;
89
103
  };
90
104
  }
105
+ /**
106
+ * The menu bar shortcut as config holds it now (read again: the Panel's Runtime may hold an older config), and what
107
+ * the item last said about its icon.
108
+ */
109
+ async function menubarExtras(rt) {
110
+ const configured = (await loadConfig(rt.paths.configFile).catch(() => rt.config)).menubar?.hotkey;
111
+ const kept = await readMenubarState(rt.paths.stateDir);
112
+ return { hotkey: hotkeyView(configured, kept.hotkey ?? null), icon: iconView(kept.icon, new Date()) };
113
+ }
114
+ /**
115
+ * A login item's state as the page shows it; the menu bar item's carries its shortcut too. Every answer that hands the
116
+ * page a new state goes through here, so turning it on never drops the shortcut row.
117
+ */
118
+ async function loginItemView(rt, agent) {
119
+ const view = autostartView(await autostartStatus(autostartCtx(rt), agent), rt.paths.home);
120
+ return agent === MENUBAR_AGENT && view.supported ? { ...view, ...(await menubarExtras(rt)) } : view;
121
+ }
91
122
  const autostartCtx = (rt) => ({
92
123
  home: rt.paths.home,
93
124
  env: rt.env,
@@ -107,6 +138,7 @@ export function autostartView(s, home) {
107
138
  current: s.current,
108
139
  ...(s.programArguments ? { programArguments: s.programArguments.map(t) } : {}),
109
140
  ...(s.missing ? { missing: s.missing.map(t) } : {}),
141
+ ...(s.loaded === undefined ? {} : { loaded: s.loaded }),
110
142
  };
111
143
  }
112
144
  /** A program argument as the page shows it: the home folder as `~`, and the menu bar script by name only. */
@@ -118,6 +150,14 @@ function autostartPlanView(p, home) {
118
150
  path: tildify(p.path, home),
119
151
  ...(p.programArguments ? { programArguments: p.programArguments.map(shownArg(home)) } : {}),
120
152
  ...(p.blocked ? { blocked: p.blocked } : {}),
153
+ // Only starts the agent again: the file stays as it is (on, current, but launchd let it go).
154
+ ...(p.action === 'on' &&
155
+ p.changed &&
156
+ p.status.state === 'on' &&
157
+ p.status.current &&
158
+ p.status.loaded === false
159
+ ? { restartOnly: true }
160
+ : {}),
121
161
  status: autostartView(p.status, home),
122
162
  };
123
163
  }
@@ -193,7 +233,8 @@ async function localSwitchState(rt, method) {
193
233
  export function handoffByFamily(rt, accounts, now) {
194
234
  const out = {};
195
235
  for (const [id, f] of rt.families) {
196
- const list = accounts.filter((a) => a.family === id);
236
+ // An Account still being read has no Quota yet; it is neither a pick nor an alternative until it has.
237
+ const list = accounts.filter((a) => a.family === id && !a.pending);
197
238
  // Count logins, not directories: a Same Login group (spec §3.21) is one Quota, so it alone is no alternative.
198
239
  const subs = list.filter((a) => a.kind === 'subscription');
199
240
  const logins = subs.filter((a, i) => !subs.slice(0, i).some((b) => a.sameLogin?.includes(b.ref))).length;
@@ -285,6 +326,83 @@ function readBody(req) {
285
326
  });
286
327
  });
287
328
  }
329
+ // Session History (spec §3.33, ADR-0042): the page's filters, checked here, and the rows it gets with `~` paths and
330
+ // a Session Reference in the Panel's language. The continue command stays as typed, so a paste works anywhere.
331
+ const HISTORY_SINCE = new Set(['today', '7d', '30d', 'all']);
332
+ const HISTORY_GROUPS = new Set(['project', 'category', 'account', 'family', 'day', 'none']);
333
+ function historyQuery(body) {
334
+ const since = optString(body, 'since');
335
+ if (since !== undefined && !HISTORY_SINCE.has(since))
336
+ throw new HttpError(400, '"since" must be today, 7d, 30d or all');
337
+ const num = (key, max) => {
338
+ const v = body[key];
339
+ if (v === undefined || v === null)
340
+ return undefined;
341
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 0 || v > max)
342
+ throw new HttpError(400, `"${key}" must be a whole number from 0 to ${max}`);
343
+ return v;
344
+ };
345
+ const project = optString(body, 'project');
346
+ const q = { scripts: optBool(body, 'scripts') };
347
+ const words = optString(body, 'q');
348
+ if (words !== undefined)
349
+ q.q = words.slice(0, 200);
350
+ if (project !== undefined)
351
+ q.project = project;
352
+ const family = optString(body, 'family');
353
+ if (family !== undefined)
354
+ q.family = family;
355
+ const account = optString(body, 'account');
356
+ if (account !== undefined)
357
+ q.account = account;
358
+ if (since !== undefined)
359
+ q.since = since;
360
+ const limit = num('limit', 500);
361
+ if (limit !== undefined)
362
+ q.limit = Math.max(1, limit);
363
+ const offset = num('offset', 1_000_000);
364
+ if (offset !== undefined)
365
+ q.offset = offset;
366
+ const group = optString(body, 'group');
367
+ if (group !== undefined) {
368
+ if (!HISTORY_GROUPS.has(group))
369
+ throw new HttpError(400, '"group" must be project, category, account, family, day or none');
370
+ q.group = group;
371
+ }
372
+ const category = optString(body, 'category');
373
+ if (category !== undefined)
374
+ q.category = category;
375
+ if (body.collapsed !== undefined) {
376
+ const c = body.collapsed;
377
+ if (!Array.isArray(c) || c.length > 500 || c.some((k) => typeof k !== 'string' || k.length > 1024))
378
+ throw new HttpError(400, '"collapsed" must be a list of at most 500 group keys');
379
+ q.collapsed = c;
380
+ }
381
+ return q;
382
+ }
383
+ /** Project group keys go out with `~` like every path on the page, and come back the same way. */
384
+ const untildify = (p, home) => (p === '~' || p.startsWith('~/') ? home + p.slice(1) : p);
385
+ function historyView(s, home, lang) {
386
+ return {
387
+ ...s,
388
+ cwd: tildify(s.cwd, home),
389
+ project: tildify(s.project, home),
390
+ transcript: tildify(s.transcript, home),
391
+ reference: referenceText({
392
+ accountLabel: s.accountLabel,
393
+ sessionId: s.sessionId,
394
+ title: s.title,
395
+ cwd: s.cwd,
396
+ transcript: s.transcript,
397
+ guessed: false,
398
+ resumeCommand: s.resumeCommand,
399
+ }, lang),
400
+ };
401
+ }
402
+ const TOOL_SCAN_IDLE_MS = 15_000;
403
+ const TOOL_SCAN_MAX_HITS = 100;
404
+ /** The longest one scan of tool output runs, polled or not. */
405
+ const TOOL_SCAN_MAX_MS = 120_000;
288
406
  function optString(body, key) {
289
407
  const v = body[key];
290
408
  if (v === undefined || v === null || v === '')
@@ -351,6 +469,73 @@ async function accountState(rt, account, families) {
351
469
  function rcView(groups, home) {
352
470
  return groups.map((g) => ({ ...g, file: tildify(g.file, home) }));
353
471
  }
472
+ /**
473
+ * How long one state waits for an Account's reads. A slower Account (a plugin reader that hangs, a Host that answers
474
+ * late) is sent as pending, so it does not hold up every other row; its reads go on and the next state picks up the
475
+ * answer. Mutable for tests only.
476
+ */
477
+ export const readBudget = { ms: 2000, hungMs: 60_000 };
478
+ /** An answer kept longer than this is not used: the next state reads the Account again. */
479
+ const KEPT_MS = 30_000;
480
+ /** The Account's state within `readBudget`, or a pending placeholder while its reads go on. */
481
+ async function timedAccountState(rt, account, families, mine) {
482
+ const fam = families.find((f) => f.id === account.family);
483
+ const placeholder = async (extra) => {
484
+ // Its Same Login is known without the slow reads, so its rows stay grouped meanwhile.
485
+ const sameLogin = await rt.sameLogin(account).catch(() => []);
486
+ return {
487
+ ...account,
488
+ familyTitle: fam?.title ?? account.family,
489
+ hostInstalled: fam?.installed ?? false,
490
+ login: 'unknown',
491
+ ...(sameLogin.length ? { sameLogin } : {}),
492
+ ...extra,
493
+ };
494
+ };
495
+ let r = mine.get(account.ref);
496
+ if (r?.done && Date.now() - r.done.at > KEPT_MS)
497
+ r = undefined;
498
+ // A read still going after `readBudget.hungMs` has hung (a plugin reader, a Host that never answers).
499
+ if (r && !r.done && Date.now() - r.started > readBudget.hungMs) {
500
+ // Dropped, so the next state starts a new read; this one says what happened instead of spinning on.
501
+ mine.delete(account.ref);
502
+ return placeholder({
503
+ error: `reading this account took longer than ${Math.round(readBudget.hungMs / 1000)} s; refresh to try again`,
504
+ });
505
+ }
506
+ if (!r) {
507
+ const fresh = { promise: accountState(rt, account, families), started: Date.now() };
508
+ fresh.promise.then((state) => {
509
+ fresh.done = { state, at: Date.now() };
510
+ }, () => undefined);
511
+ mine.set(account.ref, fresh);
512
+ r = fresh;
513
+ }
514
+ const reading = r;
515
+ let timer;
516
+ const late = new Promise((done) => {
517
+ timer = setTimeout(() => done(null), readBudget.ms);
518
+ });
519
+ let state;
520
+ try {
521
+ state = await Promise.race([reading.promise, late]);
522
+ }
523
+ catch (err) {
524
+ if (mine.get(account.ref) === reading)
525
+ mine.delete(account.ref);
526
+ return placeholder({ error: err.message });
527
+ }
528
+ finally {
529
+ clearTimeout(timer);
530
+ }
531
+ if (state) {
532
+ // Only this reading: another request may already have started a newer one.
533
+ if (mine.get(account.ref) === reading)
534
+ mine.delete(account.ref);
535
+ return state;
536
+ }
537
+ return placeholder({ pending: true });
538
+ }
354
539
  async function buildState(rt, opts) {
355
540
  const ctx = rt.readContext();
356
541
  const [families, accounts, history, quotaSetups, remoteControl, upd] = await Promise.all([
@@ -362,10 +547,14 @@ async function buildState(rt, opts) {
362
547
  opts.updates ? updateState(rt, opts.readOnly).catch(() => undefined) : Promise.resolve(undefined),
363
548
  ]);
364
549
  const health = healthByAccount(history);
550
+ // Reads of Accounts that are gone are dropped.
551
+ for (const ref of opts.readings.keys())
552
+ if (!accounts.some((a) => a.ref === ref))
553
+ opts.readings.delete(ref);
365
554
  const aliases = aliasesByAccount(aliasRefs(rt.config.aliases), accounts);
366
555
  // Desktop Apps (spec §3.20): one process listing for every Account, run alongside the per-Account reads.
367
556
  const [states, appProfiles] = await Promise.all([
368
- withDesktopApps(rt, accounts, Promise.all(accounts.map((a) => accountState(rt, a, families)))),
557
+ withDesktopApps(rt, accounts, Promise.all(accounts.map((a) => timedAccountState(rt, a, families, opts.readings)))),
369
558
  listAppProfiles(rt),
370
559
  ]);
371
560
  const list = states.map((st) => {
@@ -551,6 +740,35 @@ function opened(r) {
551
740
  }
552
741
  /** The AI Task upload route; its body is a file, not a JSON object, so it sits outside the route table. */
553
742
  const ATTACH_ROUTE = '/api/ask/attach';
743
+ /** The "Send to it" screenshot upload (spec §3.32 step 2): images only, each at most the image limit. */
744
+ const SEND_ATTACH_ROUTE = '/api/sessions/attach';
745
+ const IMAGE_ONLY = 'Only images can be sent to a session: add a PNG, JPEG, GIF or WebP screenshot.';
746
+ const IMAGE_TOO_BIG = `This image is over ${ATTACHMENT_LIMITS.image / 1024 / 1024} MB; send a smaller screenshot.`;
747
+ /** Stops a stream once it passes `max` bytes, so a file that is no image cannot run on to the larger video limit. */
748
+ async function* capped(source, max, message) {
749
+ let n = 0;
750
+ for await (const chunk of source) {
751
+ n += chunk.length;
752
+ if (n > max)
753
+ throw new HttpError(413, message);
754
+ yield chunk;
755
+ }
756
+ }
757
+ /** The ids of staged uploads a request lists, checked as `/api/ask` checks them. */
758
+ function uploadIds(body) {
759
+ const ids = body.attachments;
760
+ if (ids === undefined)
761
+ return [];
762
+ if (!Array.isArray(ids) ||
763
+ ids.length > MAX_ATTACHMENTS ||
764
+ !ids.every((u) => typeof u === 'string' && /^[a-f0-9]{16}$/.test(u)))
765
+ throw new HttpError(400, `"attachments" must list at most ${MAX_ATTACHMENTS} upload ids`);
766
+ return ids;
767
+ }
768
+ /** A Message as the Panel returns it: its files with `~`. */
769
+ function messageView(m, home) {
770
+ return { ...m, file: tildify(m.file, home), attachments: m.attachments.map((a) => tildify(a, home)) };
771
+ }
554
772
  /** Runs write requests one at a time; a few may wait, the rest are told to retry. */
555
773
  function writeQueue() {
556
774
  let tail = Promise.resolve();
@@ -579,7 +797,55 @@ export function createPanelHandler(opts) {
579
797
  const ask = resolveAsk(opts.ask);
580
798
  const token = randomBytes(32).toString('base64url');
581
799
  const serial = writeQueue();
800
+ const readings = new Map();
582
801
  const getRuntime = typeof opts.runtime === 'function' ? opts.runtime : async () => opts.runtime;
802
+ const sessionsSource = opts[LIVE_SESSIONS_SOURCE];
803
+ const liveSessions = sessionsSource?.list ?? listLiveSessions;
804
+ const copyText = sessionsSource?.copyText ?? sessionCopyText;
805
+ const orcaOf = (rt) => sessionsSource?.orca ?? systemOrca(rt.env);
806
+ const sendTo = sessionsSource?.send ?? sendMessage;
807
+ const messages = sessionsSource?.messages ?? listMessages;
808
+ // Session History loads node:sqlite only when the page first asks for it.
809
+ let historyMod;
810
+ const history = () => (historyMod ??= import('../core/history.js'));
811
+ // Which Sessions run now, for the "running" mark of History rows: read at most every 5 s, given 3 s.
812
+ const LIVE_FIRST_MS = 300;
813
+ let liveMark;
814
+ // Which past Sessions run now. A search never waits for that list once one is known: it answers with the last
815
+ // one while a fresh one is read, and waits at most LIVE_FIRST_MS for the very first.
816
+ const liveIds = async (rt) => {
817
+ if (!liveMark || Date.now() - liveMark.at > 5_000) {
818
+ const ids = (sessionsSource?.list ? sessionsSource.list(rt) : listLiveSessions(rt, { deadlineMs: 3_000 }))
819
+ .then((r) => new Set(r.sessions.map((x) => liveKey(x.account, x.sessionId))))
820
+ .catch(() => new Set());
821
+ const last = liveMark?.last;
822
+ liveMark = { at: Date.now(), ids, ...(last ? { last } : {}) };
823
+ const mark = liveMark;
824
+ void ids.then((v) => {
825
+ mark.last = v;
826
+ });
827
+ }
828
+ if (liveMark.last)
829
+ return liveMark.last;
830
+ let timer;
831
+ const late = new Promise((r) => {
832
+ timer = setTimeout(() => r(new Set()), LIVE_FIRST_MS);
833
+ });
834
+ try {
835
+ return await Promise.race([liveMark.ids, late]);
836
+ }
837
+ finally {
838
+ clearTimeout(timer);
839
+ }
840
+ };
841
+ const toolScans = new Map();
842
+ const dropIdleScans = () => {
843
+ for (const [id, scan] of toolScans)
844
+ if (Date.now() - scan.seen > TOOL_SCAN_IDLE_MS) {
845
+ scan.ctrl.abort();
846
+ toolScans.delete(id);
847
+ }
848
+ };
583
849
  /** The switch of one LaunchAgent sideby writes: the Panel's login item or the Menu Bar Item. */
584
850
  const loginItemRoute = (agent) => ({
585
851
  writes: (body) => body.confirm === true,
@@ -604,7 +870,7 @@ export function createPanelHandler(opts) {
604
870
  changed: r.changed,
605
871
  loaded: r.loaded,
606
872
  ...(r.note ? { note: r.note.split(home).join('~') } : {}),
607
- status: autostartView(await autostartStatus(ctx, agent), home),
873
+ status: await loginItemView(rt, agent),
608
874
  };
609
875
  },
610
876
  });
@@ -898,6 +1164,336 @@ export function createPanelHandler(opts) {
898
1164
  return { ...r, results: r.results.map((x) => ({ ...x, file: tildify(x.file, home) })) };
899
1165
  },
900
1166
  },
1167
+ // Sessions (spec §3.32, ADR-0039): what every Account is running now, read only, with the texts its copy buttons
1168
+ // copy in the Panel's language. Polled every few seconds, so it runs beside the write queue.
1169
+ '/api/sessions': {
1170
+ writes: () => false,
1171
+ queued: false,
1172
+ async run(body) {
1173
+ const lang = body.lang === 'zh' ? 'zh' : 'en';
1174
+ const rt = await getRuntime();
1175
+ const listed = await liveSessions(rt);
1176
+ const home = rt.paths.home;
1177
+ // The Run each Session works for, only where the Session Index and its board file check out (ADR-0041).
1178
+ const [sessions, tabs] = await Promise.all([
1179
+ withRuns(rt.env, home, listed.sessions),
1180
+ orcaTabs(orcaOf(rt), listed.sessions),
1181
+ ]);
1182
+ const problems = listed.problems;
1183
+ return {
1184
+ sessions: sessions.map((s) => ({
1185
+ ...s,
1186
+ ...(s.cwd ? { cwd: tildify(s.cwd, home) } : {}),
1187
+ ...(s.run
1188
+ ? {
1189
+ run: {
1190
+ ...s.run,
1191
+ board: tildify(s.run.board, home),
1192
+ ...(s.run.others
1193
+ ? { others: s.run.others.map((o) => ({ ...o, board: tildify(o.board, home) })) }
1194
+ : {}),
1195
+ },
1196
+ }
1197
+ : {}),
1198
+ ...(tabs.has(s.sessionId) ? { orca: true } : {}),
1199
+ copy: {
1200
+ reference: copyText(s, 'reference', lang),
1201
+ id: copyText(s, 'id', lang),
1202
+ resume: copyText(s, 'resume', lang),
1203
+ },
1204
+ })),
1205
+ problems: problems.map((p) => p.split(home).join('~')),
1206
+ };
1207
+ },
1208
+ },
1209
+ // Session History (spec §3.33): every past Session of every Account, from the History Index sideby keeps in its
1210
+ // own state folder. Read only for the Host folders; it answers from what is built and builds the rest behind.
1211
+ '/api/history': {
1212
+ writes: () => false,
1213
+ queued: false,
1214
+ async run(body) {
1215
+ const lang = body.lang === 'zh' ? 'zh' : 'en';
1216
+ const rt = await getRuntime();
1217
+ const home = rt.paths.home;
1218
+ const h = await history();
1219
+ const q = historyQuery(body);
1220
+ const paths = q.group === 'project';
1221
+ if (paths && q.collapsed)
1222
+ q.collapsed = q.collapsed.map((k) => untildify(k, home));
1223
+ const r = await h.searchHistory(rt, q, { live: await liveIds(rt) });
1224
+ h.syncHistoryInBackground(rt);
1225
+ const key = (k) => (paths ? tildify(k, home) : k);
1226
+ return {
1227
+ ...r,
1228
+ sessions: r.sessions.map((x) => {
1229
+ const v = historyView(x, home, lang);
1230
+ return v.group === undefined ? v : { ...v, group: key(v.group) };
1231
+ }),
1232
+ ...(r.groups ? { groups: r.groups.map((g) => ({ ...g, key: key(g.key) })) } : {}),
1233
+ problems: r.problems.map((p) => p.split(home).join('~')),
1234
+ };
1235
+ },
1236
+ },
1237
+ '/api/history/projects': {
1238
+ writes: () => false,
1239
+ queued: false,
1240
+ async run(body) {
1241
+ const rt = await getRuntime();
1242
+ const home = rt.paths.home;
1243
+ const r = await (await history()).historyProjects(rt, historyQuery(body));
1244
+ return {
1245
+ ...r,
1246
+ projects: r.projects.map((p) => ({ ...p, project: tildify(p.project, home) })),
1247
+ ...(r.problems ? { problems: r.problems.map((p) => p.split(home).join('~')) } : {}),
1248
+ };
1249
+ },
1250
+ },
1251
+ '/api/history/show': {
1252
+ writes: () => false,
1253
+ queued: false,
1254
+ async run(body) {
1255
+ const id = optString(body, 'id');
1256
+ if (!id)
1257
+ throw new HttpError(400, '"id" is required');
1258
+ const before = body.before;
1259
+ if (before !== undefined && (typeof before !== 'number' || !Number.isInteger(before) || before < 0))
1260
+ throw new HttpError(400, '"before" must be a whole number');
1261
+ const lang = body.lang === 'zh' ? 'zh' : 'en';
1262
+ const rt = await getRuntime();
1263
+ const home = rt.paths.home;
1264
+ const account = optString(body, 'account');
1265
+ const r = await (await history()).historyShow(rt, id, {
1266
+ ...(before === undefined ? {} : { before }),
1267
+ ...(account ? { account } : {}),
1268
+ });
1269
+ return { ...r, session: historyView(r.session, home, lang) };
1270
+ },
1271
+ },
1272
+ // "Also search tool output": reads the record files at that moment and keeps nothing (ADR-0042). The page starts
1273
+ // one scan, polls it with its id and stops it; a new scan stops the one before.
1274
+ '/api/history/tools': {
1275
+ writes: () => false,
1276
+ queued: false,
1277
+ async run(body) {
1278
+ dropIdleScans();
1279
+ const lang = body.lang === 'zh' ? 'zh' : 'en';
1280
+ const rt = await getRuntime();
1281
+ const home = rt.paths.home;
1282
+ const job = optString(body, 'job');
1283
+ if (job) {
1284
+ const scan = toolScans.get(job);
1285
+ if (!scan)
1286
+ throw new HttpError(404, 'This search of tool output has stopped; search again.');
1287
+ if (optBool(body, 'cancel')) {
1288
+ scan.ctrl.abort();
1289
+ toolScans.delete(job);
1290
+ return { job, stopped: true };
1291
+ }
1292
+ scan.seen = Date.now();
1293
+ if (scan.finished)
1294
+ toolScans.delete(job);
1295
+ return {
1296
+ job,
1297
+ hits: scan.hits.map((x) => historyView(x, home, lang)),
1298
+ done: scan.done,
1299
+ total: scan.total,
1300
+ finished: scan.finished,
1301
+ ...(scan.error ? { error: scan.error } : {}),
1302
+ };
1303
+ }
1304
+ const q = historyQuery(body);
1305
+ if (!q.q?.trim())
1306
+ throw new HttpError(400, 'Type the words to look for first.');
1307
+ for (const scan of toolScans.values())
1308
+ scan.ctrl.abort();
1309
+ toolScans.clear();
1310
+ const skip = Array.isArray(body.skip)
1311
+ ? new Set(body.skip.filter((x) => typeof x === 'string').slice(0, 500))
1312
+ : undefined;
1313
+ const id = randomBytes(8).toString('hex');
1314
+ const scan = {
1315
+ ctrl: new AbortController(),
1316
+ hits: [],
1317
+ done: 0,
1318
+ total: 0,
1319
+ finished: false,
1320
+ seen: Date.now(),
1321
+ };
1322
+ toolScans.set(id, scan);
1323
+ const h = await history();
1324
+ const started = Date.now();
1325
+ void (async () => {
1326
+ try {
1327
+ for await (const hit of h.scanToolOutput(rt, q, {
1328
+ signal: scan.ctrl.signal,
1329
+ live: await liveIds(rt),
1330
+ ...(skip ? { skip } : {}),
1331
+ onProgress: (done, total) => {
1332
+ scan.done = done;
1333
+ scan.total = total;
1334
+ // A scan stops by itself once the page stops asking, or after TOOL_SCAN_MAX_MS.
1335
+ const now = Date.now();
1336
+ if (now - scan.seen > TOOL_SCAN_IDLE_MS || now - started > TOOL_SCAN_MAX_MS)
1337
+ scan.ctrl.abort();
1338
+ },
1339
+ })) {
1340
+ scan.hits.push(hit.session);
1341
+ if (scan.hits.length >= TOOL_SCAN_MAX_HITS)
1342
+ break;
1343
+ }
1344
+ }
1345
+ catch (err) {
1346
+ scan.error = (err instanceof Error ? err.message : String(err)).split(home).join('~');
1347
+ }
1348
+ scan.finished = true;
1349
+ })();
1350
+ return { job: id, hits: [], done: 0, total: 0, finished: false };
1351
+ },
1352
+ },
1353
+ // How far the History Index is built, and "Delete the index" (it is built again on the next search). Deleting
1354
+ // writes only sideby's own state folder, but a read-only Panel still refuses it.
1355
+ '/api/history/index': {
1356
+ writes: (body) => body.clear === true,
1357
+ queued: false,
1358
+ async run(body) {
1359
+ const rt = await getRuntime();
1360
+ const home = rt.paths.home;
1361
+ const r = await (await history()).historyIndexInfo(rt, { clear: optBool(body, 'clear') });
1362
+ return { ...r, path: tildify(r.path, home) };
1363
+ },
1364
+ },
1365
+ // Brings the Orca tab a Session runs in to the front (ADR-0039). The page sends only the Session id: the handle is
1366
+ // found again here, from the running process and Orca's own list. It starts a program, so a read-only Panel
1367
+ // refuses it (writes defaults to true).
1368
+ '/api/sessions/orca': {
1369
+ queued: false,
1370
+ async run(body) {
1371
+ const id = optString(body, 'sessionId');
1372
+ if (!id)
1373
+ throw new HttpError(400, '"sessionId" is required');
1374
+ const rt = await getRuntime();
1375
+ const session = (await liveSessions(rt)).sessions.find((s) => s.sessionId === id);
1376
+ if (!session)
1377
+ throw new HttpError(404, 'This session is no longer running; refresh the list.');
1378
+ const orca = orcaOf(rt);
1379
+ const handle = (await orcaTabs(orca, [session])).get(id);
1380
+ if (!handle)
1381
+ throw new HttpError(409, 'This session is not in an Orca tab any more; refresh the list.');
1382
+ await switchOrcaTab(orca, handle);
1383
+ return { switched: true };
1384
+ },
1385
+ },
1386
+ // "Send to it" (spec §3.32 step 2): text and the screenshots staged through SEND_ATTACH_ROUTE go to one Live
1387
+ // Session through sendMessage, which keeps the Message as a file before any delivery. The page sends only the
1388
+ // Session id. It writes files, so a read-only Panel refuses it (writes defaults to true); it runs beside the
1389
+ // write queue because a delivery may wait on the Host.
1390
+ // Opens the Run Board of a Session (spec §3.32 step 2b, ADR-0041). The page sends only the Session id: the board
1391
+ // file is found again here, from the Session Index, and checked again. It starts a program, so a read-only Panel
1392
+ // refuses it (writes defaults to true).
1393
+ '/api/sessions/run': {
1394
+ queued: false,
1395
+ async run(body) {
1396
+ const id = optString(body, 'sessionId');
1397
+ if (!id)
1398
+ throw new HttpError(400, '"sessionId" is required');
1399
+ const rt = await getRuntime();
1400
+ const r = await openRunBoard(rt, id);
1401
+ return { opened: true, board: tildify(r.board, rt.paths.home) };
1402
+ },
1403
+ },
1404
+ '/api/sessions/send': {
1405
+ queued: false,
1406
+ async run(body) {
1407
+ const id = optString(body, 'sessionId');
1408
+ if (!id)
1409
+ throw new HttpError(400, '"sessionId" is required');
1410
+ if (body.text !== undefined && typeof body.text !== 'string')
1411
+ throw new HttpError(400, '"text" must be text');
1412
+ const text = (body.text ?? '').trim();
1413
+ if (text.length > MAX_MESSAGE_TEXT)
1414
+ throw new HttpError(400, `The message is over ${MAX_MESSAGE_TEXT} characters; shorten it.`);
1415
+ const ids = uploadIds(body);
1416
+ if (!text && !ids.length)
1417
+ throw new HttpError(400, 'Write a message or add a screenshot first.');
1418
+ const lang = body.lang === 'zh' ? 'zh' : 'en';
1419
+ const rt = await getRuntime();
1420
+ const images = ids.length ? await stagedAttachments(rt.paths, ids) : [];
1421
+ if (images.some((f) => f.kind !== 'image'))
1422
+ throw new HttpError(415, IMAGE_ONLY);
1423
+ const session = (await liveSessions(rt)).sessions.find((s) => s.sessionId === id);
1424
+ if (!session)
1425
+ throw new HttpError(404, 'This session is no longer running; refresh the list.');
1426
+ const receipt = await sendTo(rt, id, { text, images: images.map((f) => f.path), lang });
1427
+ // The Message has its own copies now; the staged ones would only wait a day to be cleared.
1428
+ await removeStaged(rt.paths, ids).catch(() => 0);
1429
+ // Only a Message the user pastes needs the way to the target's tab.
1430
+ const tabs = receipt.status === 'paste-needed'
1431
+ ? await orcaTabs(orcaOf(rt), [session])
1432
+ : new Map();
1433
+ return {
1434
+ message: messageView(receipt, rt.paths.home),
1435
+ ...(tabs.has(id) ? { orca: true } : {}),
1436
+ };
1437
+ },
1438
+ },
1439
+ // The latest Message to each Session, for the chips on the Sessions page; polled with the list, read only.
1440
+ '/api/sessions/messages': {
1441
+ writes: () => false,
1442
+ queued: false,
1443
+ async run() {
1444
+ const latest = {};
1445
+ // Newest first: the first one met for a Session is its latest.
1446
+ for (const m of await messages(await getRuntime(), { limit: 200, persist: !readOnly }))
1447
+ latest[m.toSessionId] ??= {
1448
+ id: m.id,
1449
+ status: m.status,
1450
+ sentAt: m.sentAt,
1451
+ to: m.to,
1452
+ ...(m.from ? { from: m.from } : {}),
1453
+ ...(m.status === 'paste-needed' ? { pasteText: m.pasteText } : {}),
1454
+ ...(m.note ? { note: m.note } : {}),
1455
+ ...(m.needsApproval ? { needsApproval: true } : {}),
1456
+ };
1457
+ return { latest };
1458
+ },
1459
+ },
1460
+ // Receiving Messages (ADR-0045): whether each Claude settings file lets its sessions show a Message at once, and
1461
+ // the same change as `sideby messages inbound accept|undo`; the page shows each file's change before it asks.
1462
+ '/api/messages/inbound': {
1463
+ writes: () => false,
1464
+ queued: false,
1465
+ async run() {
1466
+ const rt = await getRuntime();
1467
+ const accounts = await rt.accounts();
1468
+ const groups = await inboundGroups(accounts, rt.readContext());
1469
+ const waits = await waitingFiles(groups, accounts, startArgsOf(rt.config, accounts));
1470
+ const home = rt.paths.home;
1471
+ return {
1472
+ groups: groups.map((g) => ({
1473
+ ...g,
1474
+ file: tildify(g.file, home),
1475
+ ...(g.reason ? { reason: g.reason.split(home).join('~') } : {}),
1476
+ waits: waits.has(g.file),
1477
+ })),
1478
+ };
1479
+ },
1480
+ },
1481
+ '/api/messages/inbound/accept': {
1482
+ async run() {
1483
+ const rt = await getRuntime();
1484
+ const r = await acceptInbound(await rt.accounts(), rt.readContext());
1485
+ const home = rt.paths.home;
1486
+ return { ...r, results: r.results.map((x) => ({ ...x, file: tildify(x.file, home) })) };
1487
+ },
1488
+ },
1489
+ '/api/messages/inbound/undo': {
1490
+ async run() {
1491
+ const rt = await getRuntime();
1492
+ const r = await undoInbound(await rt.accounts(), rt.readContext());
1493
+ const home = rt.paths.home;
1494
+ return { ...r, results: r.results.map((x) => ({ ...x, file: tildify(x.file, home) })) };
1495
+ },
1496
+ },
901
1497
  // Auto Handoff (spec §3.17): readiness reads only; configure shows the config change unless `confirm`.
902
1498
  '/api/handoff/status': {
903
1499
  writes: () => false,
@@ -990,6 +1586,19 @@ export function createPanelHandler(opts) {
990
1586
  return openInBrowser(rt, await rt.resolve(account), profile);
991
1587
  },
992
1588
  },
1589
+ // Chooses the Chrome browser user of an Account, or with profile null lets sideby find it again (spec §3.24 "手动指定").
1590
+ // It writes sideby's config only.
1591
+ '/api/browser/choose': {
1592
+ async run(body) {
1593
+ const account = optString(body, 'account');
1594
+ if (!account)
1595
+ throw new HttpError(400, '"account" is required');
1596
+ if (body.profile !== null && typeof body.profile !== 'string')
1597
+ throw new HttpError(400, '"profile" must be a browser user folder or null');
1598
+ const rt = await getRuntime();
1599
+ return setBrowserChoice(rt, await rt.resolve(account), body.profile);
1600
+ },
1601
+ },
993
1602
  // Opens a Grok Bot window, creating it when the name is new, or brings it to the front (ADR-0019).
994
1603
  '/api/app-profile/open': {
995
1604
  async run(body) {
@@ -1201,6 +1810,31 @@ export function createPanelHandler(opts) {
1201
1810
  // saw (`programArguments`).
1202
1811
  '/api/autostart': loginItemRoute(PANEL_AGENT),
1203
1812
  '/api/menubar': loginItemRoute(MENUBAR_AGENT),
1813
+ // "Can't see the icon?": System Settings › Menu Bar, where macOS 26 and later ask to allow it.
1814
+ '/api/menubar/settings': {
1815
+ async run() {
1816
+ const rt = await getRuntime();
1817
+ if (!(await openMenuBarSettings(autostartCtx(rt))))
1818
+ throw new UserError('Could not open System Settings; open it yourself and choose Menu Bar');
1819
+ return { opened: true };
1820
+ },
1821
+ },
1822
+ // The shortcut that opens the menu bar item (spec §3.31): `keys` as `sideby menubar hotkey` takes it.
1823
+ '/api/menubar/hotkey': {
1824
+ async run(body) {
1825
+ const keys = optString(body, 'keys');
1826
+ if (!keys)
1827
+ throw new HttpError(400, '"keys" is required, such as "ctrl+opt+s", "off" or "default"');
1828
+ const rt = await getRuntime();
1829
+ const r = await setMenubarHotkey({
1830
+ configFile: rt.paths.configFile,
1831
+ stateDir: rt.paths.stateDir,
1832
+ value: keys,
1833
+ ctx: autostartCtx(rt),
1834
+ });
1835
+ return r;
1836
+ },
1837
+ },
1204
1838
  // Undo for the quota setup above; the Runtime turns a teardown that throws into `{ ok: false, message }`.
1205
1839
  '/api/quota/teardown': {
1206
1840
  async run(body) {
@@ -1235,6 +1869,39 @@ export function createPanelHandler(opts) {
1235
1869
  throw err;
1236
1870
  }
1237
1871
  };
1872
+ // A "Send to it" screenshot: staged like an AI Task attachment, but only an image is kept, and the stream stops at
1873
+ // the image limit whatever the file turns out to be.
1874
+ const receiveImage = async (req) => {
1875
+ const max = ATTACHMENT_LIMITS.image;
1876
+ const declared = Number(req.headers['content-length']);
1877
+ if (Number.isFinite(declared) && declared > max)
1878
+ throw new HttpError(413, IMAGE_TOO_BIG);
1879
+ const rt = await getRuntime();
1880
+ let staged;
1881
+ try {
1882
+ staged = await stageUpload(rt.paths, capped(req.iterator({ destroyOnReturn: false }), max, IMAGE_TOO_BIG));
1883
+ }
1884
+ catch (err) {
1885
+ const code = err.code;
1886
+ if (code === 'attachment-too-large')
1887
+ throw new HttpError(413, IMAGE_TOO_BIG);
1888
+ if (code === 'attachment-type')
1889
+ throw new HttpError(415, IMAGE_ONLY);
1890
+ if (code === 'attachment-quota')
1891
+ throw new HttpError(507, err.message, code);
1892
+ throw err;
1893
+ }
1894
+ if (staged.kind !== 'image') {
1895
+ await removeStaged(rt.paths, [staged.id]);
1896
+ throw new HttpError(415, IMAGE_ONLY);
1897
+ }
1898
+ return { id: staged.id, kind: staged.kind, bytes: staged.bytes };
1899
+ };
1900
+ // Routes whose body is a file rather than a JSON object.
1901
+ const uploads = {
1902
+ [ATTACH_ROUTE]: receiveAttachment,
1903
+ [SEND_ATTACH_ROUTE]: receiveImage,
1904
+ };
1238
1905
  const handle = async (req, res) => {
1239
1906
  let pathname;
1240
1907
  try {
@@ -1322,22 +1989,22 @@ export function createPanelHandler(opts) {
1322
1989
  // Start at login (spec §3.29): its state only; turning it on or off is the POST of the same path.
1323
1990
  if (sub === '/api/autostart' || sub === '/api/menubar') {
1324
1991
  const rt = await getRuntime();
1325
- const agent = sub === '/api/menubar' ? MENUBAR_AGENT : PANEL_AGENT;
1326
- send(res, 200, autostartView(await autostartStatus(autostartCtx(rt), agent), rt.paths.home));
1992
+ send(res, 200, await loginItemView(rt, sub === '/api/menubar' ? MENUBAR_AGENT : PANEL_AGENT));
1327
1993
  return true;
1328
1994
  }
1329
1995
  if (sub === '/api/state') {
1330
- send(res, 200, await buildState(await getRuntime(), { version, build, readOnly, updates }));
1996
+ send(res, 200, await buildState(await getRuntime(), { version, build, readOnly, updates, readings }));
1331
1997
  return true;
1332
1998
  }
1333
- if (Object.hasOwn(routes, sub) || sub === ATTACH_ROUTE)
1999
+ if (Object.hasOwn(routes, sub) || Object.hasOwn(uploads, sub))
1334
2000
  throw new HttpError(405, 'use POST');
1335
2001
  throw new HttpError(404, 'not found');
1336
2002
  }
1337
2003
  if (method !== 'POST')
1338
2004
  throw new HttpError(405, 'method not allowed');
1339
2005
  const route = Object.hasOwn(routes, sub) ? routes[sub] : undefined;
1340
- if (!route && sub !== ATTACH_ROUTE)
2006
+ const upload = Object.hasOwn(uploads, sub) ? uploads[sub] : undefined;
2007
+ if (!route && !upload)
1341
2008
  throw new HttpError(404, 'not found');
1342
2009
  const origin = req.headers.origin;
1343
2010
  if (!origin || origin.toLowerCase() !== `http://${host}`)
@@ -1349,14 +2016,18 @@ export function createPanelHandler(opts) {
1349
2016
  // An upload writes a file: a read-only Panel refuses it before reading a byte.
1350
2017
  if (readOnly)
1351
2018
  throw new HttpError(403, 'this panel is read-only');
1352
- send(res, 200, await receiveAttachment(req));
2019
+ send(res, 200, await upload(req));
1353
2020
  return true;
1354
2021
  }
1355
2022
  const body = (await readBody(req));
1356
2023
  if (readOnly && (route.writes?.(body) ?? true))
1357
2024
  throw new HttpError(403, 'this panel is read-only');
1358
2025
  // Reads that record history (doctor) also run in this queue, so overlapping checks merge in order.
1359
- send(res, 200, await (route.queued === false ? route.run(body) : serial(() => route.run(body))));
2026
+ const result = await (route.queued === false ? route.run(body) : serial(() => route.run(body)));
2027
+ // A change may concern an Account whose read began before it: the next state reads again.
2028
+ if (route.writes?.(body) ?? true)
2029
+ readings.clear();
2030
+ send(res, 200, result);
1360
2031
  return true;
1361
2032
  }
1362
2033
  catch (err) {
@@ -1367,7 +2038,7 @@ export function createPanelHandler(opts) {
1367
2038
  if (err instanceof HttpError) {
1368
2039
  const body = err.code ? { error: err.message, code: err.code } : { error: err.message };
1369
2040
  // A refused body (too big, or an upload stopped early) is left unread: close the connection after answering.
1370
- const unread = err.status === 413 || (sub === ATTACH_ROUTE && !req.readableEnded);
2041
+ const unread = err.status === 413 || (Object.hasOwn(uploads, sub) && !req.readableEnded);
1371
2042
  send(res, err.status, body, unread ? { connection: 'close' } : {});
1372
2043
  if (unread)
1373
2044
  req.resume();