sideby 0.19.1 → 0.21.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 (159) 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/history-group.d.ts +28 -0
  23. package/dist/src/core/history-group.js +47 -0
  24. package/dist/src/core/history-index.d.ts +145 -0
  25. package/dist/src/core/history-index.js +447 -0
  26. package/dist/src/core/history-project.d.ts +13 -0
  27. package/dist/src/core/history-project.js +87 -0
  28. package/dist/src/core/history.d.ts +210 -0
  29. package/dist/src/core/history.js +952 -0
  30. package/dist/src/core/inbound.d.ts +62 -0
  31. package/dist/src/core/inbound.js +215 -0
  32. package/dist/src/core/launch.d.ts +9 -1
  33. package/dist/src/core/launch.js +58 -24
  34. package/dist/src/core/live-sessions-copy.d.ts +5 -0
  35. package/dist/src/core/live-sessions-copy.js +46 -0
  36. package/dist/src/core/live-sessions-procs.d.ts +89 -0
  37. package/dist/src/core/live-sessions-procs.js +296 -0
  38. package/dist/src/core/live-sessions-title.d.ts +28 -0
  39. package/dist/src/core/live-sessions-title.js +80 -0
  40. package/dist/src/core/live-sessions.d.ts +68 -0
  41. package/dist/src/core/live-sessions.js +163 -0
  42. package/dist/src/core/login-check.d.ts +15 -0
  43. package/dist/src/core/login-check.js +32 -0
  44. package/dist/src/core/messages.d.ts +83 -0
  45. package/dist/src/core/messages.js +433 -0
  46. package/dist/src/core/project-categories.d.ts +14 -0
  47. package/dist/src/core/project-categories.js +48 -0
  48. package/dist/src/core/quota-fetch.d.ts +3 -3
  49. package/dist/src/core/quota-fetch.js +5 -5
  50. package/dist/src/core/quota-levels.d.ts +5 -0
  51. package/dist/src/core/quota-levels.js +5 -0
  52. package/dist/src/core/remote-control.d.ts +2 -0
  53. package/dist/src/core/remote-control.js +34 -59
  54. package/dist/src/core/run-link.d.ts +76 -0
  55. package/dist/src/core/run-link.js +245 -0
  56. package/dist/src/core/same-login.d.ts +4 -3
  57. package/dist/src/core/same-login.js +10 -7
  58. package/dist/src/core/session-select.d.ts +31 -0
  59. package/dist/src/core/session-select.js +44 -0
  60. package/dist/src/families/browser.d.ts +7 -18
  61. package/dist/src/families/browser.js +19 -8
  62. package/dist/src/families/claude/deliver.d.ts +2 -0
  63. package/dist/src/families/claude/deliver.js +43 -0
  64. package/dist/src/families/claude/history.d.ts +2 -0
  65. package/dist/src/families/claude/history.js +192 -0
  66. package/dist/src/families/claude/live-sessions.d.ts +13 -0
  67. package/dist/src/families/claude/live-sessions.js +117 -0
  68. package/dist/src/families/claude/messaging.d.ts +69 -0
  69. package/dist/src/families/claude/messaging.js +165 -0
  70. package/dist/src/families/claude/mod.d.ts +26 -0
  71. package/dist/src/families/claude/mod.js +105 -0
  72. package/dist/src/families/claude/session-files.d.ts +21 -0
  73. package/dist/src/families/claude/session-files.js +54 -0
  74. package/dist/src/families/codex/deliver.d.ts +5 -0
  75. package/dist/src/families/codex/deliver.js +76 -0
  76. package/dist/src/families/codex/history.d.ts +7 -0
  77. package/dist/src/families/codex/history.js +174 -0
  78. package/dist/src/families/codex/index.js +2 -0
  79. package/dist/src/families/codex/live-sessions.d.ts +12 -0
  80. package/dist/src/families/codex/live-sessions.js +193 -0
  81. package/dist/src/families/codex/quota.d.ts +3 -0
  82. package/dist/src/families/codex/quota.js +123 -0
  83. package/dist/src/families/codex/rate-limits.js +2 -0
  84. package/dist/src/families/codex/rollout.js +1 -1
  85. package/dist/src/families/grok/browser.d.ts +3 -0
  86. package/dist/src/families/grok/browser.js +5 -0
  87. package/dist/src/families/grok/history.d.ts +2 -0
  88. package/dist/src/families/grok/history.js +157 -0
  89. package/dist/src/families/grok/live-sessions.d.ts +4 -0
  90. package/dist/src/families/grok/live-sessions.js +80 -0
  91. package/dist/src/families/grok/login-key.d.ts +14 -0
  92. package/dist/src/families/grok/login-key.js +37 -0
  93. package/dist/src/families/history.d.ts +20 -0
  94. package/dist/src/families/history.js +81 -0
  95. package/dist/src/families/live-sessions.d.ts +26 -0
  96. package/dist/src/families/live-sessions.js +9 -0
  97. package/dist/src/families/login-keys.js +5 -1
  98. package/dist/src/families/messaging.d.ts +27 -0
  99. package/dist/src/families/messaging.js +6 -0
  100. package/dist/src/families/pi/history.d.ts +2 -0
  101. package/dist/src/families/pi/history.js +124 -0
  102. package/dist/src/families/pi/live-sessions.d.ts +2 -0
  103. package/dist/src/families/pi/live-sessions.js +70 -0
  104. package/dist/src/families/shared/history-text.d.ts +65 -0
  105. package/dist/src/families/shared/history-text.js +261 -0
  106. package/dist/src/menubar/hotkey.d.ts +86 -0
  107. package/dist/src/menubar/hotkey.js +159 -0
  108. package/dist/src/menubar/script.d.ts +2 -0
  109. package/dist/src/menubar/script.js +118 -22
  110. package/dist/src/menubar/snapshot.d.ts +8 -4
  111. package/dist/src/menubar/snapshot.js +45 -13
  112. package/dist/src/menubar/strings.d.ts +24 -6
  113. package/dist/src/menubar/strings.js +24 -6
  114. package/dist/src/panel/handler.d.ts +69 -0
  115. package/dist/src/panel/handler.js +686 -15
  116. package/dist/src/panel/i18n.d.ts +305 -3
  117. package/dist/src/panel/i18n.js +622 -18
  118. package/dist/src/panel/orca.d.ts +48 -0
  119. package/dist/src/panel/orca.js +153 -0
  120. package/dist/src/panel/page-logic.d.ts +260 -13
  121. package/dist/src/panel/page-logic.js +497 -1
  122. package/dist/src/panel/page-script.js +2309 -204
  123. package/dist/src/panel/page-styles.js +398 -32
  124. package/dist/src/panel/page.js +1 -0
  125. package/dist/src/plugins/check.js +16 -4
  126. package/dist/src/plugins/loader.d.ts +8 -1
  127. package/dist/src/plugins/loader.js +72 -7
  128. package/dist/src/runtime.d.ts +5 -0
  129. package/dist/src/runtime.js +27 -5
  130. package/dist/src/types.d.ts +116 -1
  131. package/dist/testing/index.d.ts +5 -0
  132. package/dist/testing/index.js +5 -0
  133. package/mods/claude/.claude-plugin/plugin.json +7 -0
  134. package/mods/claude/hooks/hooks.json +1 -0
  135. package/mods/claude/hooks/register.js +261 -0
  136. package/package.json +5 -2
  137. package/schemas/autostart.json +74 -1
  138. package/schemas/browser-set.json +110 -0
  139. package/schemas/browser.json +22 -2
  140. package/schemas/config.json +26 -1
  141. package/schemas/history-index.json +209 -0
  142. package/schemas/history-projects.json +133 -0
  143. package/schemas/history-show.json +275 -0
  144. package/schemas/history.json +410 -0
  145. package/schemas/menubar-hotkey.json +139 -0
  146. package/schemas/menubar-snapshot.json +36 -2
  147. package/schemas/menubar.json +74 -1
  148. package/schemas/messages-inbound.json +258 -0
  149. package/schemas/messages.json +164 -0
  150. package/schemas/send.json +165 -0
  151. package/schemas/sessions-copy.json +113 -0
  152. package/schemas/sessions-open-run.json +97 -0
  153. package/schemas/sessions.json +237 -0
  154. package/skills/sideby/SKILL.md +10 -5
  155. package/skills/sideby/references/accounts.md +11 -0
  156. package/skills/sideby/references/ai-tasks.md +17 -1
  157. package/skills/sideby/references/panel.md +6 -4
  158. package/skills/sideby/references/quota.md +2 -2
  159. package/skills/sideby/references/sessions.md +79 -0
@@ -1,7 +1,9 @@
1
1
  // The Panel page's inline script. Plain browser JavaScript in a string (no template literals inside, so String.raw
2
2
  // keeps it verbatim); the pure helpers from page-logic.ts are prepended so the tested code is the code that runs.
3
- import { aiTaskAccounts, aliasArgsOf, aliasIssue, askBridge, askBridged, askCopy, attentionReasons, attentionWhy, autostartNote, cacheHitRate, canLeaveLocal, codeSwapOutcome, fileSize, fixPrompt, foldSkips, formatDuration, handoffChangeOf, handoffHintAccount, handoffTaskFacts, inDisplayOrder, loginClusters, loginKey, maskEmail, matchesQuery, menuPlacement, mergeDaily, newAccountDir, nextReset, panelFixes, panelHint, panelLang, panelMigration, panelPrefs, passedWindow, pinnedIn, quotaAskable, quotaPressure, remoteControlSummary, remoteControlTodo, reorder, rowBadge, runCodeSwap, sortAccounts, stripSecrets, suggestAlias, suggestName, switchFailure, taskFindings, updatedAge, widthFollower, widthTier, windowState, withPinned, } from './page-logic.js';
3
+ import { quotaIsStale } from '../core/quota-levels.js';
4
+ import { aiTaskAccounts, aliasArgsOf, aliasIssue, askBridge, askBridged, askCopy, attentionReasons, attentionWhy, autostartNote, cacheHitRate, canLeaveLocal, categoryOrder, codeSwapOutcome, fileSize, fixPrompt, foldSkips, foldToolCalls, formatDuration, handoffChangeOf, handoffHintAccount, handoffTaskFacts, highlightParts, histFilters, historyEmpty, historyWhen, hotkeyFromKey, hotkeyPressKind, inDisplayOrder, loginClusters, loginKey, maskEmail, matchesQuery, mdBlocks, mdInline, menuPlacement, mergeDaily, mergeUsage, messageChip, messageNews, newAccountDir, nextReset, panelFixes, panelHint, panelLang, panelMigration, panelPrefs, passedWindow, pinnedIn, quotaAskable, quotaPressure, remoteControlSummary, remoteControlTodo, reorder, rowBadge, runCodeSwap, sendBlock, sendFileProblem, sendResultView, sessionAge, sessionLabelParts, shortCwd, shortSessionLabel, sortAccounts, sortSessions, steadyOrder, stripSecrets, suggestAlias, suggestName, switchFailure, tailInView, taskFindings, updatedAge, widthFollower, widthTier, windowState, withPinned, } from './page-logic.js';
4
5
  const LOGIC = [
6
+ quotaIsStale,
5
7
  aiTaskAccounts,
6
8
  askBridge,
7
9
  askBridged,
@@ -14,11 +16,18 @@ const LOGIC = [
14
16
  attentionReasons,
15
17
  attentionWhy,
16
18
  autostartNote,
19
+ hotkeyFromKey,
20
+ hotkeyPressKind,
17
21
  cacheHitRate,
22
+ categoryOrder,
18
23
  fileSize,
19
24
  fixPrompt,
20
25
  foldSkips,
21
26
  formatDuration,
27
+ foldToolCalls,
28
+ highlightParts,
29
+ historyEmpty,
30
+ historyWhen,
22
31
  handoffChangeOf,
23
32
  handoffHintAccount,
24
33
  handoffTaskFacts,
@@ -29,6 +38,9 @@ const LOGIC = [
29
38
  matchesQuery,
30
39
  menuPlacement,
31
40
  mergeDaily,
41
+ mergeUsage,
42
+ messageChip,
43
+ messageNews,
32
44
  newAccountDir,
33
45
  nextReset,
34
46
  canLeaveLocal,
@@ -46,9 +58,22 @@ const LOGIC = [
46
58
  remoteControlTodo,
47
59
  reorder,
48
60
  rowBadge,
61
+ sendBlock,
62
+ sendFileProblem,
63
+ sendResultView,
64
+ sessionAge,
65
+ sessionLabelParts,
66
+ shortCwd,
67
+ shortSessionLabel,
49
68
  sortAccounts,
69
+ sortSessions,
70
+ steadyOrder,
71
+ histFilters,
72
+ mdBlocks,
73
+ mdInline,
50
74
  suggestAlias,
51
75
  suggestName,
76
+ tailInView,
52
77
  updatedAge,
53
78
  pinnedIn,
54
79
  widthFollower,
@@ -64,16 +89,19 @@ const MAIN = String.raw `
64
89
  const WARN = BOOT.warn
65
90
  const FAIL = BOOT.fail
66
91
  // Quota data older than this is greyed and marked with its age.
67
- const STALE_MS = 60 * 60000
68
92
  // Findings listed before the rest fold behind a button.
69
93
  const FINDINGS_SHOWN = 5
70
94
  const NAME_RE = /^[a-z0-9][a-z0-9-]{0,31}$/
71
95
  const SVG_NS = 'http://www.w3.org/2000/svg'
72
- const REDUCED = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches
96
+ // Follows the system setting live, so turning on "Reduce motion" with the page open stops the scripted motion too.
97
+ const REDUCED_MQ = window.matchMedia ? window.matchMedia('(prefers-reduced-motion: reduce)') : null
98
+ let REDUCED = Boolean(REDUCED_MQ && REDUCED_MQ.matches)
99
+ if (REDUCED_MQ && REDUCED_MQ.addEventListener) REDUCED_MQ.addEventListener('change', (e) => { REDUCED = e.matches })
73
100
  // Auto refresh: the state reloads every AUTO_MS while the page is visible, and every FAST_MS for FAST_FOR_MS after
74
101
  // quota is turned on, so the first numbers show up soon after a status line reports them.
75
102
  const AUTO_MS = 20000
76
103
  const FAST_MS = 5000
104
+ const PENDING_MS = 1500
77
105
  const FAST_FOR_MS = 3 * 60000
78
106
  // After the layout follows a width into another band, how long the width must hold still before a later crossing
79
107
  // in the same gesture is applied (page-logic.ts, widthFollower).
@@ -87,13 +115,15 @@ const MAIN = String.raw `
87
115
  silent: false, lastTry: 0, pending: false, fastUntil: 0, fastFamily: null,
88
116
  }
89
117
  // View state that is not saved: the search text, the attention filter, the Health check filter.
90
- const ui = { query: '', attention: false, allFindings: false, healthRef: null, checkingRef: null, desktopRef: null, browserRef: null, appBusy: null, appRemove: null, appNew: null, highlight: null, fade: true, loginRefs: new Map(), order: { families: [], units: {} }, drag: null, arrange: null }
118
+ const ui = { query: '', attention: false, allFindings: false, healthRef: null, checkingRef: null, desktopRef: null, browserRef: null, appBusy: null, appRemove: null, copied: null, appNew: null, highlight: null, fade: true, loginRefs: new Map(), order: { families: [], units: {} }, drag: null, arrange: null }
91
119
  const $ = (id) => document.getElementById(id)
92
120
 
93
121
  // ---------- preferences ----------
94
122
  // Kept in localStorage, which can be missing or throw (private windows, blocked storage): every access is guarded
95
123
  // and the defaults apply.
96
124
  const PREFS_KEY = 'sideby.panel.v2'
125
+ const HIST_GROUPS = ['project', 'category', 'day', 'account', 'family', 'none']
126
+ const HIST_FOLD_MAX = 200
97
127
  const CHOICES = { view: ['list', 'cards'], sort: ['pressure', 'name', 'recent', 'manual'], quota: ['used', 'left'], theme: ['system', 'light', 'dark'], lang: ['en', 'zh'] }
98
128
  const prefs = loadPrefs()
99
129
  function loadPrefs() {
@@ -104,13 +134,29 @@ const MAIN = String.raw `
104
134
  if (raw.hideEmail === true) p.hideEmail = true
105
135
  if (typeof raw.ahHintAt === 'number') p.ahHintAt = raw.ahHintAt
106
136
  if (raw.rcHide === true) p.rcHide = true
137
+ if (raw.inbHide === true) p.inbHide = true
107
138
  if (raw.mbHintDone === true) p.mbHintDone = true
108
139
  if (raw.cfgDone === true) p.cfgDone = true
140
+ if (typeof raw.setSec === 'string') p.setSec = raw.setSec
109
141
  if (typeof raw.family === 'string') p.family = raw.family
110
142
  if (raw.collapsed && typeof raw.collapsed === 'object')
111
143
  for (const k of Object.keys(raw.collapsed)) if (raw.collapsed[k] === true) p.collapsed[k] = true
112
144
  if (raw.open && typeof raw.open === 'object')
113
145
  for (const k of Object.keys(raw.open)) if (raw.open[k] === true) p.open[k] = true
146
+ // History: how the list is grouped, and per grouping the groups the user folded.
147
+ if (HIST_GROUPS.includes(raw.histGroup)) p.histGroup = raw.histGroup
148
+ p.histFold = {}
149
+ if (raw.histFold && typeof raw.histFold === 'object')
150
+ for (const g of HIST_GROUPS) {
151
+ const keys = raw.histFold[g] && typeof raw.histFold[g] === 'object' ? Object.keys(raw.histFold[g]).filter((k) => raw.histFold[g][k] === true).slice(0, HIST_FOLD_MAX) : []
152
+ if (keys.length) { p.histFold[g] = {}; for (const k of keys) p.histFold[g][k] = true }
153
+ }
154
+ // The categories of the side list, in the order the user dragged them to.
155
+ p.histCatOrder = Array.isArray(raw.histCatOrder) ? raw.histCatOrder.filter((c) => typeof c === 'string' && c).slice(0, HIST_FOLD_MAX) : []
156
+ // The categories folded in the side list.
157
+ p.histCatFold = {}
158
+ if (raw.histCatFold && typeof raw.histCatFold === 'object')
159
+ for (const k of Object.keys(raw.histCatFold).filter((k) => raw.histCatFold[k] === true).slice(0, HIST_FOLD_MAX)) p.histCatFold[k] = true
114
160
  return p
115
161
  }
116
162
  function savePrefs() { try { localStorage.setItem(PREFS_KEY, JSON.stringify(prefs)) } catch {} }
@@ -134,6 +180,7 @@ const MAIN = String.raw `
134
180
  if (vars) s = s.replace(/\{(\w+)\}/g, (m, k) => (Object.hasOwn(vars, k) ? String(vars[k]) : m))
135
181
  return s
136
182
  }
183
+ function colon() { return t('punct.colon') }
137
184
  function tn(key, n, vars) { return t(key + (n === 1 ? '.one' : '.other'), Object.assign({ n }, vars)) }
138
185
  // A message whose placeholders are nodes, such as a code span inside a sentence.
139
186
  function tx(key, vars) {
@@ -183,6 +230,19 @@ const MAIN = String.raw `
183
230
  el.replaceChildren()
184
231
  add(el, kids)
185
232
  }
233
+ // Re-renders el without the jolt of a rebuild: the focused control keeps focus (matched by data-key), and an element
234
+ // marked data-enter that was not there before grows in, so a row that appears does not snap the layout open.
235
+ // A first render (el empty) animates nothing; the container itself has its own entrance.
236
+ function swapKids(el, kids) {
237
+ const before = new Set([...el.querySelectorAll('[data-enter]')].map((x) => x.getAttribute('data-enter')))
238
+ const shown = el.childNodes.length > 0
239
+ const active = document.activeElement
240
+ const focusKey = active && el.contains(active) ? active.getAttribute('data-key') : null
241
+ setKids(el, kids)
242
+ if (shown && !REDUCED)
243
+ for (const x of el.querySelectorAll('[data-enter]')) if (!before.has(x.getAttribute('data-enter'))) x.classList.add('enter')
244
+ if (focusKey) { const again = el.querySelector('[data-key="' + CSS.escape(focusKey) + '"]'); if (again) again.focus() }
245
+ }
186
246
  function add(el, kid) {
187
247
  if (kid === null || kid === undefined || kid === false) return
188
248
  if (Array.isArray(kid)) { for (const k of kid) add(el, k); return }
@@ -291,6 +351,7 @@ const MAIN = String.raw `
291
351
  refresh: 'M20 11a8 8 0 1 0-2.3 5.7M20 4v7h-7',
292
352
  search: 'M11 18a7 7 0 1 0 0-14 7 7 0 0 0 0 14zM20 20l-4.2-4.2',
293
353
  chevron: 'M9 6l6 6-6 6',
354
+ chevronLeft: 'M15 6l-6 6 6 6',
294
355
  more: 'M5 12h.01M12 12h.01M19 12h.01',
295
356
  grip: 'M9 6h.01M9 12h.01M9 18h.01M15 6h.01M15 12h.01M15 18h.01',
296
357
  plus: 'M12 5v14M5 12h14',
@@ -305,6 +366,7 @@ const MAIN = String.raw `
305
366
  folder: 'M3 6h6l2 2h10v11H3z',
306
367
  file: 'M14 3H6v18h12V7zM14 3v4h4M9 13h6M9 17h6',
307
368
  check: 'M9 12l2 2 4-4M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z',
369
+ tick: 'M5 12.5l4.5 4.5L19 7.5',
308
370
  userPlus: 'M15 19a6 6 0 0 0-12 0M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM19 8v6M16 11h6',
309
371
  x: 'M6 6l12 12M18 6L6 18',
310
372
  arrowUp: 'M12 19V5M5 12l7-7 7 7',
@@ -322,8 +384,11 @@ const MAIN = String.raw `
322
384
  mail: 'M3 6h18v12H3zM3 7l9 6 9-6',
323
385
  globe: 'M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM3 12h18M12 3c2.5 2.5 3.8 5.5 3.8 9s-1.3 6.5-3.8 9c-2.5-2.5-3.8-5.5-3.8-9S9.5 5.5 12 3z',
324
386
  image: 'M3 5h18v14H3zM3 16l5-5 4 4 3-3 6 6M15 9h.01',
387
+ // Lucide "send" (ISC license)
388
+ send: 'M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11zM21.854 2.147l-10.94 10.939',
325
389
  film: 'M3 5h18v14H3zM7 5v14M17 5v14M3 9h4M3 15h4M17 9h4M17 15h4',
326
390
  eye: 'M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z',
391
+ alert: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 8v5M12 16h.01',
327
392
  eyeOff: 'M3 3l18 18M10.6 5.1A10.8 10.8 0 0 1 12 5c6.5 0 10 7 10 7a17.6 17.6 0 0 1-3.2 4.2M6.6 6.6A17.4 17.4 0 0 0 2 12s3.5 7 10 7a10.4 10.4 0 0 0 5.4-1.6M9.9 9.9a3 3 0 0 0 4.2 4.2',
328
393
  }
329
394
  function icon(name, cls) {
@@ -445,27 +510,40 @@ const MAIN = String.raw `
445
510
  void item.el.offsetWidth
446
511
  item.el.classList.add('bump')
447
512
  } else {
448
- item = { text, ms, key: opts.key || null }
513
+ // "keep": a toast that asks the user to act; three newer ones push out the others first.
514
+ item = { text, ms, key: opts.key || null, keep: Boolean(opts.keep) }
449
515
  const action = opts.action ? h('button', { class: 'toast-action', type: 'button', onclick: () => { dismiss(item); opts.action.run() } }, opts.action.label) : null
450
516
  item.el = h('div', { class: 'toast toast-' + kind, role: kind === 'fail' ? 'alert' : null },
451
517
  h('span', { class: 'toast-dot', 'aria-hidden': 'true' }),
452
518
  h('span', { class: 'toast-text' }, text),
453
519
  action,
454
520
  h('button', { class: 'toast-x', type: 'button', 'aria-label': t('toast.dismiss'), onclick: () => dismiss(item) }, icon('x')))
455
- item.el.addEventListener('mouseenter', () => clearTimeout(item.timer))
456
- item.el.addEventListener('mouseleave', () => { item.timer = setTimeout(() => dismiss(item), 2500) })
521
+ // Hovering holds the toast; leaving gives back the time it had left, and at least 2.5 s to move away.
522
+ item.el.addEventListener('mouseenter', () => { clearTimeout(item.timer); item.left = Math.max(0, item.until - Date.now()) })
523
+ item.el.addEventListener('mouseleave', () => { if (!item.gone) { item.until = Date.now() + Math.max(2500, item.left || 0); item.timer = setTimeout(() => dismiss(item), item.until - Date.now()) } })
457
524
  toasts.push(item)
458
525
  $('toasts').append(item.el)
459
526
  if (dlg.el && dlg.el.open) raiseToasts()
460
- while (toasts.length > 3) dismiss(toasts[0])
527
+ while (toasts.length > 3) dismiss(toasts.find((x) => !x.keep && x !== item) || toasts[0])
461
528
  }
529
+ item.until = Date.now() + ms
462
530
  item.timer = setTimeout(() => dismiss(item), ms)
463
531
  }
464
532
  function dismiss(item) {
533
+ if (item.gone) return
534
+ item.gone = true
465
535
  clearTimeout(item.timer)
466
536
  const i = toasts.indexOf(item)
467
537
  if (i >= 0) toasts.splice(i, 1)
468
- item.el.remove()
538
+ if (REDUCED || document.hidden) { item.el.remove(); return }
539
+ // It folds away as it fades, so the toasts beside it slide into place instead of jumping.
540
+ item.el.style.height = item.el.getBoundingClientRect().height + 'px'
541
+ item.el.classList.add('toast-out')
542
+ item.el.style.setProperty('pointer-events', 'none')
543
+ // Removed once the fold has played, even when the browser starts it late; the timer covers one that never ends.
544
+ const done = () => item.el.remove()
545
+ item.el.addEventListener('animationend', (e) => { if (e.animationName === 'toast-out') done() })
546
+ setTimeout(done, 1000)
469
547
  }
470
548
 
471
549
  // ---------- small parts ----------
@@ -509,10 +587,6 @@ const MAIN = String.raw `
509
587
  for (const [v, u] of units) if (n >= v) return (n / v).toFixed(n / v >= 100 ? 0 : 1).replace(/\.0$/, '') + u
510
588
  return String(Math.round(n))
511
589
  }
512
- function isStale(iso, now) {
513
- const ts = Date.parse(iso)
514
- return Number.isFinite(ts) && now - ts > STALE_MS
515
- }
516
590
 
517
591
  function family(id) { return (S.state && S.state.families.find((f) => f.id === id)) || { id, title: id, bin: id, installUrl: '', installed: false } }
518
592
  function famTitle(a) { return a.familyTitle || family(a.family).title }
@@ -575,7 +649,17 @@ const MAIN = String.raw `
575
649
  const body = btn.nextElementSibling
576
650
  if (!body) return
577
651
  body.parentElement.classList.add('is-open')
578
- const r = btn.getBoundingClientRect()
652
+ placeTip(body, btn.getBoundingClientRect())
653
+ }
654
+ function hideTip(btn) { if (btn.parentElement) btn.parentElement.classList.remove('is-open') }
655
+ document.addEventListener('pointerover', (e) => { const b = e.target.closest && e.target.closest('.tip-btn'); if (b) showTip(b) })
656
+ document.addEventListener('pointerout', (e) => { const b = e.target.closest && e.target.closest('.tip-btn'); if (b && !b.contains(e.relatedTarget)) hideTip(b) })
657
+ document.addEventListener('focusin', (e) => { if (e.target.classList && e.target.classList.contains('tip-btn')) showTip(e.target) })
658
+ document.addEventListener('focusout', (e) => { if (e.target.classList && e.target.classList.contains('tip-btn')) hideTip(e.target) })
659
+ // An icon button with data-tip shows its text at once on hover and keyboard focus, in the same bubble as a "?"
660
+ // (a title shows only after a delay, and not on focus). One bubble serves all of them; it never takes a click.
661
+ let hoverTip = null
662
+ function placeTip(body, r) {
579
663
  const w = body.offsetWidth
580
664
  const hgt = body.offsetHeight
581
665
  const left = Math.max(8, Math.min(window.innerWidth - w - 8, r.left + r.width / 2 - w / 2))
@@ -583,11 +667,22 @@ const MAIN = String.raw `
583
667
  body.style.setProperty('left', left + 'px')
584
668
  body.style.setProperty('top', top + 'px')
585
669
  }
586
- function hideTip(btn) { if (btn.parentElement) btn.parentElement.classList.remove('is-open') }
587
- document.addEventListener('pointerover', (e) => { const b = e.target.closest && e.target.closest('.tip-btn'); if (b) showTip(b) })
588
- document.addEventListener('pointerout', (e) => { const b = e.target.closest && e.target.closest('.tip-btn'); if (b && !b.contains(e.relatedTarget)) hideTip(b) })
589
- document.addEventListener('focusin', (e) => { if (e.target.classList && e.target.classList.contains('tip-btn')) showTip(e.target) })
590
- document.addEventListener('focusout', (e) => { if (e.target.classList && e.target.classList.contains('tip-btn')) hideTip(e.target) })
670
+ function showDataTip(el) {
671
+ const text = el.getAttribute('data-tip')
672
+ if (!text || el === menu.anchor) return
673
+ if (!hoverTip) { hoverTip = h('span', { class: 'tip-body tip-float', role: 'tooltip', 'aria-hidden': 'true' }); document.body.append(hoverTip) }
674
+ hoverTip.textContent = text
675
+ hoverTip.classList.add('is-shown')
676
+ placeTip(hoverTip, el.getBoundingClientRect())
677
+ }
678
+ function hideDataTip() { if (hoverTip) hoverTip.classList.remove('is-shown') }
679
+ // Any other target hides it, also after a refresh replaced the button under the pointer.
680
+ document.addEventListener('pointerover', (e) => { const b = e.target.closest && e.target.closest('[data-tip]'); if (b) showDataTip(b); else hideDataTip() })
681
+ document.addEventListener('pointerout', (e) => { const b = e.target.closest && e.target.closest('[data-tip]'); if (b && !b.contains(e.relatedTarget)) hideDataTip() })
682
+ document.addEventListener('focusin', (e) => { if (e.target.matches && e.target.matches('[data-tip]:focus-visible')) showDataTip(e.target) })
683
+ document.addEventListener('focusout', (e) => { if (e.target.matches && e.target.matches('[data-tip]')) hideDataTip() })
684
+ document.addEventListener('pointerdown', hideDataTip, true)
685
+ window.addEventListener('scroll', hideDataTip, true)
591
686
 
592
687
  // ---------- floating panels: menus and popovers ----------
593
688
  // One shared base for everything that floats next to a button: it is placed under (or above) its anchor, kept
@@ -607,7 +702,6 @@ const MAIN = String.raw `
607
702
  el.style.setProperty('left', p.left + 'px')
608
703
  el.style.setProperty('top', p.top + 'px')
609
704
  el.style.setProperty('max-height', p.maxHeight + 'px')
610
- if (menu.kind === 'settings') settingsFit()
611
705
  }
612
706
  function openFloat(anchor, el, kind, align) {
613
707
  closeMenu()
@@ -625,14 +719,42 @@ const MAIN = String.raw `
625
719
  if (end) e.preventDefault()
626
720
  }, { passive: false })
627
721
  }
722
+ // An item with sub (a list of items) shows that list in the same menu, with a way back, so a long group such as
723
+ // the copy commands takes one line until it is wanted.
724
+ function menuKids(el, items, from) {
725
+ return items.filter(Boolean).map((it) => it === '-' ? h('div', { class: 'menu-sep', role: 'separator' })
726
+ : it.header ? h('div', { class: 'menu-head', role: 'presentation' }, it.header)
727
+ : h('button', { class: 'menu-item' + (it.back ? ' menu-back' : it.sub ? ' menu-sub' : ''), type: 'button', role: 'menuitem', tabindex: '-1', disabled: it.disabled, 'aria-haspopup': it.sub && !it.back ? 'true' : null, 'data-from': it === from ? '' : null, onclick: () => {
728
+ if (it.sub) {
729
+ // Back lands on the item that opened the list; a list opens on its first item.
730
+ swapKids(el, menuKids(el, it.sub, it.back ? it.from : null))
731
+ el.scrollTop = 0
732
+ placeFloat()
733
+ menuScrollHint(el)
734
+ const next = el.querySelector('[data-from]') || el.querySelector('.menu-item:not(:disabled)')
735
+ if (next) next.focus()
736
+ return
737
+ }
738
+ closeMenu(true)
739
+ it.run()
740
+ } },
741
+ icon(it.icon), h('span', { class: 'menu-label' }, it.label), it.hint ? h('code', { class: 'menu-hint', title: it.hint }, it.hint.length > 24 ? '…' + it.hint.slice(-23) : it.hint) : null, it.sub && !it.back ? icon('chevron') : null))
742
+ }
743
+ // A menu taller than its room fades at the edge that has more, so it is plain that it scrolls.
744
+ function menuScrollHint(el) {
745
+ const set = () => {
746
+ el.classList.toggle('more-below', el.scrollTop + el.clientHeight < el.scrollHeight - 1)
747
+ el.classList.toggle('more-above', el.scrollTop > 1)
748
+ }
749
+ set()
750
+ if (!el._hint) { el._hint = true; el.addEventListener('scroll', set, { passive: true }) }
751
+ }
628
752
  function openMenu(anchor, items, label) {
629
- const el = h('div', { class: 'menu', role: 'menu', 'aria-label': label },
630
- items.filter(Boolean).map((it) => it === '-' ? h('div', { class: 'menu-sep', role: 'separator' })
631
- : it.header ? h('div', { class: 'menu-head', role: 'presentation' }, it.header)
632
- : h('button', { class: 'menu-item', type: 'button', role: 'menuitem', tabindex: '-1', disabled: it.disabled, onclick: () => { closeMenu(true); it.run() } },
633
- icon(it.icon), h('span', { class: 'menu-label' }, it.label), it.hint ? h('code', { class: 'menu-hint', title: it.hint }, it.hint.length > 24 ? '…' + it.hint.slice(-23) : it.hint) : null)))
753
+ const el = h('div', { class: 'menu', role: 'menu', 'aria-label': label })
754
+ setKids(el, menuKids(el, items, null))
634
755
  el.addEventListener('keydown', menuKeys)
635
756
  openFloat(anchor, el, 'menu', 'end')
757
+ menuScrollHint(el)
636
758
  const first = el.querySelector('.menu-item:not(:disabled)')
637
759
  if (first) first.focus()
638
760
  }
@@ -644,15 +766,19 @@ const MAIN = String.raw `
644
766
  setKids(el, render())
645
767
  openFloat(anchor, el, kind, align)
646
768
  menu.render = render
647
- const first = el.querySelector('button:not(:disabled), a[href]')
769
+ // A list of choices opens on the one in use, as a native menu does.
770
+ const first = el.querySelector('button[aria-pressed="true"]:not(:disabled)') || el.querySelector('button:not(:disabled), a[href]')
648
771
  if (first) first.focus()
649
772
  }
650
773
  function refreshPopover(kind) {
651
- if (menu.el && menu.kind === kind && menu.render) { setKids(menu.el, menu.render()); placeFloat() }
774
+ if (menu.el && menu.kind === kind && menu.render) { swapKids(menu.el, menu.render()); placeFloat() }
652
775
  }
653
776
  function closeMenu(restore) {
654
777
  if (!menu.el) return
655
- menu.el.remove()
778
+ // It fades out rather than vanishing; it takes no clicks meanwhile, and the next menu does not wait for it.
779
+ const gone = menu.el
780
+ if (REDUCED) gone.remove()
781
+ else { gone.classList.add('float-out'); gone.style.setProperty('pointer-events', 'none'); setTimeout(() => gone.remove(), 120) }
656
782
  menu.anchor.setAttribute('aria-expanded', 'false')
657
783
  const back = menu.returnTo || menu.anchor
658
784
  if (restore && back.isConnected) back.focus()
@@ -663,14 +789,15 @@ const MAIN = String.raw `
663
789
  menu.render = null
664
790
  menu.returnTo = null
665
791
  }
666
- // Right-click on an account row or card (spec §3.27) opens the row's "…" menu at the pointer; the ContextMenu key
792
+ // Right-click on an account row or card, or a Session row (spec §3.27) opens the row's "…" menu at the pointer; the ContextMenu key
667
793
  // and Shift+F10 open it at the focused element in the row. Inputs, links, buttons and selected text keep the
668
794
  // browser's own menu. Each row carries its opener as el.sidebyMenu(anchor).
669
795
  let kbMenuAt = 0
670
796
  function menuTarget(node) {
671
- let el = node && node.closest ? node.closest('.row, .card, .login-dir') : null
672
- while (el && !el.sidebyMenu) el = el.parentElement ? el.parentElement.closest('.row, .card, .login-dir') : null
673
- return el && $('accounts').contains(el) ? el : null
797
+ const rows = '.row, .card, .login-dir, .hist-row, .sess-row'
798
+ let el = node && node.closest ? node.closest(rows) : null
799
+ while (el && !el.sidebyMenu) el = el.parentElement ? el.parentElement.closest(rows) : null
800
+ return el && ($('accounts').contains(el) || $('sessions-page').contains(el)) ? el : null
674
801
  }
675
802
  function openContextMenu(target, x, y, back) {
676
803
  const pt = h('span', { class: 'ctx-anchor', 'aria-hidden': 'true', css: { left: x + 'px', top: y + 'px' } })
@@ -713,6 +840,9 @@ const MAIN = String.raw `
713
840
  else if (e.key === 'ArrowUp') go(items[(i - 1 + items.length) % items.length])
714
841
  else if (e.key === 'Home') go(items[0])
715
842
  else if (e.key === 'End') go(items[items.length - 1])
843
+ // In a sub list, Left and Escape go back; on an item that opens one, Right opens it.
844
+ else if ((e.key === 'ArrowLeft' || e.key === 'Escape') && menu.el.querySelector('.menu-back')) menu.el.querySelector('.menu-back').click()
845
+ else if (e.key === 'ArrowRight' && document.activeElement && document.activeElement.classList.contains('menu-sub')) document.activeElement.click()
716
846
  else if (e.key === 'Escape') closeMenu(true)
717
847
  else if (e.key === 'Tab') { closeMenu(true); return }
718
848
  else return
@@ -782,43 +912,80 @@ const MAIN = String.raw `
782
912
  function loginItems(a) {
783
913
  return [
784
914
  browserFor(a) ? { icon: 'globe', label: t('br.open'), disabled: Boolean(ui.browserRef), run: () => openBrowserDialog(a) } : null,
785
- a.kind !== 'api' && !BOOT.readOnly ? { icon: 'terminal', label: t('menu.signIn'), run: () => signIn(a) } : null,
915
+ a.kind !== 'api' && !BOOT.readOnly ? { icon: 'terminal', label: t(a.login === 'logged-in' ? 'menu.signInAgain' : 'menu.signIn'), run: () => signIn(a) } : null,
786
916
  a.kind !== 'api' ? { icon: 'key', label: t('menu.copyLogin'), hint: 'sideby login ' + a.ref, run: () => copyText('sideby login ' + a.ref) } : null,
787
917
  keyable(a) ? { icon: 'key', label: t('menu.enterKey'), run: () => openKey(a) } : null,
788
918
  a.identity && a.identity.email ? { icon: 'mail', label: t('menu.copyEmail'), hint: emailText(a.identity.email), run: () => copyText(a.identity.email) } : null,
789
919
  ]
790
920
  }
791
921
  function likeItem(a) { return BOOT.readOnly ? null : { icon: 'userPlus', label: t('menu.like'), run: () => openCreate({ family: a.family, api: a.kind === 'api' }) } }
792
- // Grouped by what the user wants to do: open, copy, manage.
793
- function accountMenu(a, anchor) {
922
+ // Grouped by what the user wants to do: open, copy, manage. A Same Login row (ADR-0026) passes its other
923
+ // directories: the menu is the one of the directory the row is named after, and each other directory is one item
924
+ // that opens its own actions in the same menu, so the shared actions appear once.
925
+ function accountMenu(a, anchor, others) {
794
926
  const [browser, signInItem, login, key, email] = loginItems(a)
795
927
  const opens = [deskItem(a), browser].filter(Boolean)
796
- const copies = dirCopies(a)
928
+ // Up to six copy commands: past two they fold into "Copy…", which opens them in the same menu, with "Back".
929
+ // The start command stays one click away (a phone has it only here); the other copies fold when there are many.
930
+ const [run, ...more] = [...dirCopies(a), login, email].filter(Boolean)
931
+ const back = { icon: 'chevronLeft', label: t('menu.back'), back: true, sub: null, from: null }
932
+ const fold = more.length > 2 ? { icon: 'copy', label: t('menu.copyMore'), hint: String(more.length), sub: [back, '-', { header: t('menu.groupCopy') }, ...more] } : null
933
+ back.from = fold
934
+ const dirs = (others || []).map((m) => {
935
+ const up = { icon: 'chevronLeft', label: t('menu.back'), back: true, sub: null, from: null }
936
+ const item = { icon: 'folder', label: m.name, hint: (m.aliases || [])[0], sub: [up, '-', { header: m.name + ((m.aliases || []).length ? ' · ' + m.aliases[0] : '') }, ...dirItems(m), ...dirTools(m)] }
937
+ up.from = item
938
+ return { up, item }
939
+ })
797
940
  const items = [pinItem(a),
798
941
  opens.length ? '-' : null, opens.length ? { header: t('menu.groupOpen') } : null, ...opens,
799
- '-', { header: t('menu.groupCopy') }, ...copies, login, email,
800
- '-', { header: t('menu.groupManage') }, signInItem, key, ...dirTools(a), likeItem(a)]
801
- openMenu(anchor, items, t('menu.label', { ref: a.ref }))
802
- }
803
- // A Same Login row (ADR-0026): pin first, then a section per directory, then what the login shares.
804
- function loginMenu(ms, anchor) {
805
- const items = [pinItem(ms[0])]
806
- for (const m of ms) items.push('-', { header: m.name + ((m.aliases || []).length ? ' · ' + m.aliases[0] : '') }, ...dirItems(m), ...dirTools(m))
807
- items.push('-', ...loginItems(ms[0]), likeItem(ms[0]))
808
- openMenu(anchor, items, t('login.label', { names: ms.map((m) => m.name).join(', ') }))
809
- }
942
+ '-', { header: t('menu.groupCopy') }, run, ...(fold ? [fold] : more),
943
+ '-', { header: t('menu.groupManage') }, signInItem, key, ...dirTools(a), likeItem(a),
944
+ ...(dirs.length ? ['-', { header: t('menu.groupOtherDirs') }, ...dirs.map((d) => d.item)] : [])]
945
+ back.sub = items
946
+ for (const d of dirs) d.up.sub = items
947
+ openMenu(anchor, items, others ? t('login.label', { names: [a, ...others].map((m) => m.name).join(', ') }) : t('menu.label', { ref: a.ref }))
948
+ }
949
+ function loginMenu(ms, anchor) { accountMenu(ms[0], anchor, ms.slice(1)) }
810
950
  function loginMoreButton(ms) {
811
- const b = h('button', { class: 'icon-btn more', type: 'button', 'aria-haspopup': 'menu', 'aria-expanded': 'false', 'aria-label': t('login.label', { names: ms.map((m) => m.name).join(', ') }), title: t('menu.title') }, icon('more'))
951
+ const b = h('button', { class: 'icon-btn more', type: 'button', 'aria-haspopup': 'menu', 'aria-expanded': 'false', 'aria-label': t('login.label', { names: ms.map((m) => m.name).join(', ') }), 'data-tip': t('menu.title') }, icon('more'))
812
952
  b.addEventListener('click', () => { if (menu.anchor === b) closeMenu(); else loginMenu(ms, b) })
813
953
  return b
814
954
  }
955
+ // Next to the terminal button: open this account's desktop app (spec §3.20), or bring it to the front when it runs.
956
+ // A Same Login row is one login, so one click is enough: it brings forward a window that already runs, or opens the
957
+ // directory the row is named after.
958
+ function deskButton(a, ms) {
959
+ const can = (ms || [a]).filter((m) => deskItem(m))
960
+ if (!can.length) return null
961
+ const m = can.find((x) => x.desktopApp.running) || can[0]
962
+ const d = m.desktopApp
963
+ const text = t(d.running ? 'desk.showHint' : 'desk.openHint', { app: d.app, ref: m.ref })
964
+ return h('button', { class: 'icon-btn row-run row-desk' + (d.running ? ' is-open' : ''), type: 'button', disabled: Boolean(ui.desktopRef), 'aria-label': text, 'data-tip': text, onclick: (e) => { e.stopPropagation(); openDesktop(m) } },
965
+ can.some((x) => ui.desktopRef === x.ref) ? spinner() : icon('monitor'))
966
+ }
815
967
  // The most used action, on the row itself: copy the command that starts this account (its short command when it
816
968
  // has one, which is shorter to type).
817
969
  function runButton(a) {
818
970
  const cmd = (a.aliases || [])[0] || 'sideby run ' + a.ref
971
+ // Without its tool the command would not start: the button says so and points at installing it instead.
972
+ if (a.hostInstalled === false) {
973
+ const why = t('row.installFirst', { host: famTitle(a) })
974
+ return h('button', { class: 'icon-btn row-run is-off', type: 'button', 'aria-disabled': 'true', 'aria-label': why, 'data-tip': why, onclick: (e) => { e.stopPropagation(); toast(why, { kind: 'info' }) } }, icon('terminal'))
975
+ }
819
976
  const text = t('row.copyRun', { cmd })
820
- return h('button', { class: 'icon-btn row-run', type: 'button', 'aria-label': text, title: text, onclick: (e) => { e.stopPropagation(); copyText(cmd) } }, icon('terminal'))
977
+ const done = ui.copied === a.ref
978
+ // A copy shows a tick on the button for a moment, where the eye already is; it lives in ui, so a refresh keeps it.
979
+ return h('button', { class: 'icon-btn row-run' + (done ? ' is-done' : ''), type: 'button', 'aria-label': text, 'data-tip': text, onclick: (e) => {
980
+ e.stopPropagation()
981
+ copyText(cmd)
982
+ clearTimeout(ui.copiedTimer)
983
+ ui.copied = a.ref
984
+ renderAccounts()
985
+ ui.copiedTimer = setTimeout(() => { ui.copied = null; renderAccounts() }, 1200)
986
+ } }, icon(done ? 'tick' : 'terminal'))
821
987
  }
988
+
822
989
  // A pinned row (spec §3.25, §3.27) says so with a small muted pin right before its name, and nothing at its end;
823
990
  // pinning and unpinning are in the row's menu and in the arrange mode.
824
991
  function pinMark(a) {
@@ -840,7 +1007,7 @@ const MAIN = String.raw `
840
1007
  return { icon: 'pin', label: full ? t('pin.full', { n: PIN_MAX }) : t(on ? 'pin.unpin' : 'pin.pin'), disabled: full, run: () => togglePin(a) }
841
1008
  }
842
1009
  function moreButton(a) {
843
- const b = h('button', { class: 'icon-btn more', type: 'button', 'aria-haspopup': 'menu', 'aria-expanded': 'false', 'aria-label': t('menu.label', { ref: a.ref }), title: t('menu.title') }, icon('more'))
1010
+ const b = h('button', { class: 'icon-btn more', type: 'button', 'aria-haspopup': 'menu', 'aria-expanded': 'false', 'aria-label': t('menu.label', { ref: a.ref }), 'data-tip': t('menu.title') }, icon('more'))
844
1011
  b.addEventListener('click', () => { if (menu.anchor === b) closeMenu(); else accountMenu(a, b) })
845
1012
  return b
846
1013
  }
@@ -932,7 +1099,7 @@ const MAIN = String.raw `
932
1099
  const date = new Date(d.date + 'T12:00:00')
933
1100
  const day = Number.isFinite(date.getTime()) ? date.toLocaleDateString(locale(), { weekday: 'short', month: 'numeric', day: 'numeric' }) : d.date
934
1101
  // Every day keeps its slot; an empty day shows only a short stub on the baseline, so it reads as a gap in time.
935
- return h('i', { class: (i === daily.length - 1 ? 'today' : '') + (v ? '' : ' zero') || null, title: day + ': ' + tokens(v) },
1102
+ return h('i', { class: (i === daily.length - 1 ? 'today' : '') + (v ? '' : ' zero') || null, title: day + colon() + tokens(v) },
936
1103
  h('b', { css: { height: v && max ? Math.max(10, Math.round((v / max) * 100)) + '%' : null } }))
937
1104
  }))
938
1105
  }
@@ -940,7 +1107,8 @@ const MAIN = String.raw `
940
1107
  const box = $('summary')
941
1108
  if (!S.state) { if (S.loadError) box.hidden = true; return }
942
1109
  const list = S.state.accounts
943
- box.hidden = !list.length
1110
+ // Another page keeps it hidden: a refresh while there must not push that page down (renderPageChrome shows it).
1111
+ box.hidden = !list.length || curPage !== 'accounts'
944
1112
  box.removeAttribute('aria-busy')
945
1113
  if (!list.length) return
946
1114
  const now = Date.now()
@@ -1065,6 +1233,7 @@ const MAIN = String.raw `
1065
1233
  function winKey(w) { return w.name || w.label }
1066
1234
  // The words for a window in labels (5-hour, weekly) instead of 5h and 7d; other labels as they are.
1067
1235
  function winTitle(k) { return k === '5h' || k === '7d' ? t('win.' + k) : k }
1236
+ function winShort(k) { return k === '5h' || k === '7d' ? t('win.' + k + '.short') : k }
1068
1237
  // One group's columns: the windows its accounts report, shortest first; 5h and 7d when none reports any yet.
1069
1238
  function quotaColumns(list) {
1070
1239
  const mins = {}
@@ -1086,16 +1255,17 @@ const MAIN = String.raw `
1086
1255
  const title = [passed ? t('quota.resetNoData', { date: day(passed.since) }) : t('quota.resetsAt', { at: clock(w.resetsAt) }), asOf].filter(Boolean).join(' · ')
1087
1256
  return h('div', { class: 'meter lvl-' + st.level + (stale || passed ? ' lvl-stale' : ''), title },
1088
1257
  h('div', { class: 'm-top' },
1089
- h('span', { class: 'm-label' }, winTitle(winKey(w))),
1258
+ // Cards show the short window name ("5 小时"); the list and its column titles keep the full one.
1259
+ h('span', { class: 'm-label' }, h('span', { class: 'm-full' }, winTitle(winKey(w))), h('span', { class: 'm-short' }, winShort(winKey(w)))),
1090
1260
  h('span', { class: 'm-pct' }, shown + '%', h('span', { class: 'm-unit' }, ' ' + t(left ? 'quota.unitLeft' : 'quota.unitUsed')),
1091
1261
  null),
1092
1262
  h('span', { class: 'm-reset' + (passed ? ' m-passed' : '') }, Number.isFinite(Date.parse(w.resetsAt)) || passed ? reset : '?')),
1093
1263
  h('div', { class: 'bar', role: 'meter', 'aria-label': t(left ? 'quota.meterLeft' : 'quota.meterUsed', { label: winTitle(winKey(w)) }), 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(shown), 'aria-valuetext': t(left ? 'quota.pctLeft' : 'quota.pctUsed', { n: shown }) }, h('span', { css: { width: shown + '%' } })))
1094
1264
  }
1095
1265
  // A column whose window this account does not report right now, such as a 5h window that has not started.
1096
- function noMeter(label) {
1266
+ function noMeter(label, short) {
1097
1267
  return h('div', { class: 'meter meter-none', title: t('quota.missing', { label }) },
1098
- h('div', { class: 'm-top' }, h('span', { class: 'm-label' }, label), h('span', { class: 'm-none', 'aria-label': t('quota.missing', { label }) }, '—')))
1268
+ h('div', { class: 'm-top' }, h('span', { class: 'm-label' }, h('span', { class: 'm-full' }, label), h('span', { class: 'm-short' }, short || label)), h('span', { class: 'm-none', 'aria-label': t('quota.missing', { label }) }, '—')))
1099
1269
  }
1100
1270
  function quotaNote(a, q) {
1101
1271
  const setup = setupFor(a.family)
@@ -1120,10 +1290,12 @@ const MAIN = String.raw `
1120
1290
  return h('button', { class: 'link-btn small q-ask', type: 'button', onclick: (e) => { e.stopPropagation(); openAsk({ task: 'quota', context: { account: a.ref, family: a.family, quotaReason: q.reason + (q.detail ? ': ' + q.detail : ''), version: BOOT.version } }) } }, t('ask.quotaWhy'))
1121
1291
  }
1122
1292
  function quotaBlock(a, now, cols) {
1293
+ // Still reading (a slow plugin or Host): say so where its numbers will appear; the page asks again soon.
1294
+ if (a.pending) return h('div', { class: 'quota' }, h('div', { class: 'q-note' }, spinner(), t('acct.reading', { host: famTitle(a) })))
1123
1295
  const q = a.quota
1124
1296
  if (!q) return h('div', { class: 'quota' }, h('div', { class: 'q-note' }, '—'))
1125
1297
  if (q.status !== 'ok') return h('div', { class: 'quota' }, quotaNote(a, q))
1126
- const stale = isStale(q.observedAt, now)
1298
+ const stale = quotaIsStale(q, now)
1127
1299
  const wins = q.windows || []
1128
1300
  // A reading borrowed from another Account of the same login says where it came from (spec §3.21).
1129
1301
  const from = q.from ? t('quota.sharedFrom', { name: refName(q.from), ago: ago(q.observedAt) }) : null
@@ -1136,10 +1308,10 @@ const MAIN = String.raw `
1136
1308
  return h('div', { class: 'quota' + (stale ? ' is-stale' : ''), title, css: wins.length ? { '--qr': String(cols.length) } : null },
1137
1309
  wins.length ? cols.map((c) => {
1138
1310
  const w = wins.find((x) => winKey(x) === c)
1139
- return w ? meter(w, now, stale, q.observedAt) : noMeter(winTitle(c))
1311
+ return w ? meter(w, now, stale, q.observedAt) : noMeter(winTitle(c), winShort(c))
1140
1312
  }) : h('div', { class: 'q-note' }, t('quota.noWindows')),
1141
1313
  // Old numbers keep their colours and say their age once, under the bars.
1142
- stale && wins.length ? h('div', { class: 'q-asof', title: t('quota.asOf', { ago: ago(q.observedAt) }) }, icon('clock'), t('quota.staleShort', { ago: agoShort(now - Date.parse(q.observedAt)) })) : null)
1314
+ stale && wins.length ? h('div', { class: 'q-asof', title: failed || t('quota.asOf', { ago: ago(q.observedAt) }) }, icon('clock'), q.fetchError ? t('quota.fetchFailed') + ' · ' : '', t('quota.staleShort', { ago: agoShort(now - Date.parse(q.observedAt)) })) : null)
1143
1315
  }
1144
1316
  function usageBlock(a) {
1145
1317
  const u = a.usage
@@ -1149,6 +1321,13 @@ const MAIN = String.raw `
1149
1321
  return h('div', { class: 'usage' }, h('span', { class: 'u-note', title: u.detail || null }, t(key, { n: BOOT.usageDays })))
1150
1322
  }
1151
1323
  const rate = cacheHitRate(u)
1324
+ // A tool whose records name sessions but not tokens (Cursor CLI): say how many, not "0 tokens".
1325
+ if (!u.totalTokens && u.sessions > 0) {
1326
+ return h('div', { class: 'usage', title: t('usage.noTokens', { days: u.days, sessions: u.sessions }) },
1327
+ h('div', { class: 'u-text' },
1328
+ h('span', { class: 'u-num' }, tn('usage.sessions', u.sessions)),
1329
+ h('div', { class: 'u-sub' }, t('usage.noTokenCounts'))))
1330
+ }
1152
1331
  const detail = t('usage.detail', { days: u.days, sessions: u.sessions, input: tokens(u.inputTokens), output: tokens(u.outputTokens), cache: tokens(u.cacheReadTokens + u.cacheWriteTokens) })
1153
1332
  return h('div', { class: 'usage', title: detail },
1154
1333
  h('div', { class: 'u-text' },
@@ -1191,7 +1370,10 @@ const MAIN = String.raw `
1191
1370
  const lvl = reason === 'health-fail' ? 'fail' : 'warn'
1192
1371
  const why = whyOf(subject, Date.now())
1193
1372
  const word = reason === 'health-fail' ? t('att.fix') : reason === 'quota-high' ? t('att.quota') : t('att.check')
1194
- return h('span', { class: 'tag tag-' + lvl + ' att-tag', title: why, 'aria-label': why }, h('span', { class: 'dot dot-' + lvl, 'aria-hidden': 'true' }), word)
1373
+ const dot = h('span', { class: 'dot dot-' + lvl, 'aria-hidden': 'true' })
1374
+ // A health label opens the account's findings, as the health chip of the details does.
1375
+ if (reason !== 'quota-high') return h('button', { class: 'tag tag-' + lvl + ' tag-btn att-tag', type: 'button', title: why + '\n' + t('health.filterHint'), 'aria-label': why, onclick: (e) => { e.stopPropagation(); filterHealth(subject.ref) } }, dot, word)
1376
+ return h('span', { class: 'tag tag-' + lvl + ' att-tag', title: why, 'aria-label': why }, dot, word)
1195
1377
  }
1196
1378
  // The word a directory inside a Same Login's details shows when it needs a fix or a look.
1197
1379
  function attentionDot(a) {
@@ -1228,11 +1410,13 @@ const MAIN = String.raw `
1228
1410
  return h('span', { class: 'login-mark', role: 'img', title: text, 'aria-label': text }, icon('link'))
1229
1411
  }
1230
1412
  // members: the directories of a Same Login shown as this one row (spec §3.21).
1231
- function nameLine(a, members) {
1413
+ // opts.linked: the directories a card marks as one login without speaking for them (its badge stays its own).
1414
+ function nameLine(a, members, opts) {
1415
+ const o = opts || {}
1232
1416
  return h('div', { class: 'ident-name' },
1233
1417
  pinSlot(a),
1234
1418
  h('span', { class: 'name', title: a.name }, a.name),
1235
- loginMark(members),
1419
+ loginMark(o.linked || members),
1236
1420
  aliasText(a),
1237
1421
  statusBadge(a, members))
1238
1422
  }
@@ -1253,8 +1437,15 @@ const MAIN = String.raw `
1253
1437
  // The Browser Sign-in as a line of the details: which Chrome browser user signed in to the account's website.
1254
1438
  function browserItem(a) {
1255
1439
  const b = browserButton(a)
1256
- return b ? h('div', { class: 'rd-item rd-browser' }, h('span', { class: 'rd-label' }, t('row.browser')), b) : null
1257
- }
1440
+ if (!b) return null
1441
+ const chosen = browserChosen(a)
1442
+ return h('div', { class: 'rd-item rd-browser' }, h('span', { class: 'rd-label' }, t('row.browser')),
1443
+ h('div', { class: 'br-line' }, b,
1444
+ chosen ? h('span', { class: 'tag', title: t('br.chosenHint') }, t('br.chosen')) : null,
1445
+ h('button', { class: 'link-btn small', type: 'button', title: t('br.changeHint', { ref: a.ref }), onclick: (e) => { e.stopPropagation(); openBrowserDialog(a) } }, t('br.change'))))
1446
+ }
1447
+ // The browser user the person chose for this account themselves (config browser.choices), if any.
1448
+ function browserChosen(a) { const b = browserInfo(); return (b && b.choices && b.choices[a.ref]) || null }
1258
1449
  function subLine(a) {
1259
1450
  const plan = a.quota && a.quota.status === 'ok' && a.quota.plan
1260
1451
  return h('div', { class: 'ident-sub' }, dots([
@@ -1281,7 +1472,7 @@ const MAIN = String.raw `
1281
1472
  }
1282
1473
  // Browser Sign-ins (spec §3.24): which Chrome browser user signed in to the account's website, read on this
1283
1474
  // computer only. Off: the button explains what turning it on reads. On: it names the browser user, and opens it.
1284
- const BR_URL = { claude: 'claude.ai', codex: 'chatgpt.com', grok: 'grok.com' }
1475
+ const siteOf = (b, family) => String((b.sites && b.sites[family]) || '').replace(/^https:\/\//, '').replace(/\/$/, '')
1285
1476
  function browserInfo() { return S.state && S.state.browser }
1286
1477
  function browserFor(a) {
1287
1478
  const b = browserInfo()
@@ -1307,8 +1498,8 @@ const MAIN = String.raw `
1307
1498
  const first = info.found[0]
1308
1499
  if (!first) return null
1309
1500
  const label = t(info.found.length > 1 ? 'br.signedInMore' : 'br.signedIn', { name: profileLabel(first), n: info.found.length })
1310
- return h('button', { class: 'email-btn br-btn', type: 'button', disabled: busy, title: t('br.hint', { url: BR_URL[a.family], ref: a.ref }), 'aria-label': 'Chrome ' + label + ' (' + a.ref + ')', onclick: (e) => { e.stopPropagation(); if (info.found.length === 1) openBrowser(a, first); else openBrowserDialog(a) } },
1311
- busy ? spinner() : icon('globe', 'br-ico'), label)
1501
+ return h('button', { class: 'email-btn br-btn', type: 'button', disabled: busy, title: t('br.hint', { url: siteOf(info.b, a.family), ref: a.ref }), 'aria-label': 'Chrome ' + label + ' (' + a.ref + ')', onclick: (e) => { e.stopPropagation(); if (info.found.length === 1) openBrowser(a, first); else openBrowserDialog(a) } },
1502
+ busy ? spinner() : icon('globe', 'br-ico'), h('span', { class: 'br-name' }, label))
1312
1503
  }
1313
1504
  async function openBrowser(a, p) {
1314
1505
  if (ui.browserRef) return
@@ -1349,16 +1540,33 @@ const MAIN = String.raw `
1349
1540
  }
1350
1541
  function brProfileRow(a, p) {
1351
1542
  const busy = ui.browserRef === a.ref
1543
+ const chosen = browserChosen(a) === p.dir
1352
1544
  return h('li', { class: 'br-row' },
1353
1545
  h('span', null, h('b', null, profileName(p.name)), p.email ? h('span', { class: 'muted small' }, ' · ' + emailText(p.email)) : null, ' ', h('span', { class: 'muted small mono' }, p.dir), p.changedAt ? h('span', { class: 'muted small' }, ' · ' + t('br.changed', { when: ago(p.changedAt) })) : null),
1354
- h('button', { class: 'btn btn-sm', type: 'button', disabled: Boolean(ui.browserRef), 'aria-busy': busy ? 'true' : null, onclick: () => openBrowser(a, p) }, t('br.openIt')))
1546
+ h('span', { class: 'br-acts' },
1547
+ chosen ? h('span', { class: 'tag', title: t('br.chosenHint') }, t('br.chosen'))
1548
+ : h('button', { class: 'link-btn small', type: 'button', disabled: br.busy, title: t('br.chooseHint', { ref: a.ref }), onclick: () => brChoose(a, p.dir) }, t('br.choose')),
1549
+ h('button', { class: 'btn btn-sm', type: 'button', disabled: Boolean(ui.browserRef), 'aria-busy': busy ? 'true' : null, onclick: () => openBrowser(a, p) }, t('br.openIt'))))
1550
+ }
1551
+ // Remembers the person's own choice for this account, or with null lets sideby find it again; sideby's config only.
1552
+ async function brChoose(a, dir) {
1553
+ br.busy = true
1554
+ br.error = null
1555
+ renderBrowser()
1556
+ try {
1557
+ await api('/api/browser/choose', { account: a.ref, profile: dir })
1558
+ await load({ silent: true })
1559
+ toast(dir ? t('br.chosenDone', { ref: a.ref, name: profileLabel({ dir, name: dir }) }) : t('br.autoDone', { ref: a.ref }))
1560
+ } catch (e) { br.error = e }
1561
+ br.busy = false
1562
+ renderBrowser()
1355
1563
  }
1356
1564
  function renderBrowser() {
1357
1565
  if (!br || dlg.kind !== 'browser') return
1358
1566
  const a = S.state && S.state.accounts.find((x) => x.ref === br.ref)
1359
1567
  const info = a && browserFor(a)
1360
1568
  if (!info) { dlg.el.close(); return }
1361
- const url = BR_URL[a.family]
1569
+ const url = siteOf(info.b, a.family)
1362
1570
  const body = []
1363
1571
  const foot = [h('button', { class: 'btn', type: 'button', disabled: br.busy, onclick: () => dlg.el.close() }, t('btn.close'))]
1364
1572
  if (!info.b.enabled) {
@@ -1370,7 +1578,10 @@ const MAIN = String.raw `
1370
1578
  body.push(h('p', { class: 'note' }, t('br.noChrome')))
1371
1579
  } else {
1372
1580
  const others = info.b.profiles.filter((p) => !info.found.includes(p))
1373
- if (info.found.length) body.push(h('p', { class: 'small' }, t('br.found', { ref: a.ref })), h('ul', { class: 'br-list' }, info.found.map((p) => brProfileRow(a, p))))
1581
+ const chosen = browserChosen(a)
1582
+ body.push(h('p', { class: 'muted small' }, t(chosen ? 'br.chosenIntro' : 'br.chooseIntro', { ref: a.ref })))
1583
+ if (chosen) body.push(h('p', null, h('button', { class: 'btn btn-sm', type: 'button', disabled: br.busy, onclick: () => brChoose(a, null) }, t('br.auto'))))
1584
+ if (info.found.length) body.push(h('p', { class: 'small' }, t(chosen ? 'br.foundChosen' : 'br.found', { ref: a.ref })), h('ul', { class: 'br-list' }, info.found.map((p) => brProfileRow(a, p))))
1374
1585
  else body.push(h('p', { class: 'muted small' }, t(info.b.families.matched.includes(a.family) ? 'br.none' : 'br.noMatch', { ref: a.ref, url })))
1375
1586
  if (others.length) body.push(h('p', { class: 'small' }, t(info.found.length ? 'br.others' : 'br.all')), h('ul', { class: 'br-list' }, others.map((p) => brProfileRow(a, p))))
1376
1587
  body.push(h('p', { class: 'muted small' }, t('br.local')))
@@ -1393,13 +1604,22 @@ const MAIN = String.raw `
1393
1604
  function notes(a) {
1394
1605
  const fam = family(a.family)
1395
1606
  const out = []
1396
- if (a.error) out.push(h('div', { class: 'note note-fail' }, h('b', null, t('acct.readError')), ' ', h('span', null, a.error)))
1607
+ // A read error says why and what to do next: its reason is on screen, the settings file opens from here when the
1608
+ // reason names it, and an AI can fix it.
1609
+ if (a.error) {
1610
+ const item = settingsItem(a)
1611
+ const file = item && a.error.includes(family(a.family).settingsFile) ? item : null
1612
+ out.push(h('div', { class: 'note note-fail note-read' },
1613
+ h('b', null, t('acct.readError')), h('span', { class: 'mono small read-why' }, a.error), h('span', null, t('acct.readErrorNext')),
1614
+ file ? h('button', { class: 'link-btn small', type: 'button', title: file.hint, onclick: (e) => { e.stopPropagation(); file.run() } }, file.label) : null,
1615
+ BOOT.readOnly ? null : h('button', { class: 'link-btn small', type: 'button', onclick: (e) => { e.stopPropagation(); openAsk({ text: t('acct.readErrorAsk', { ref: a.ref, error: a.error }) }) } }, t('acct.readErrorAi'))))
1616
+ }
1397
1617
  if (a.hostInstalled === false) out.push(h('div', { class: 'note note-warn' }, hostNote(fam)))
1398
1618
  return out.length ? h('div', { class: 'row-notes' }, out) : null
1399
1619
  }
1400
1620
  // What a row or card shows depends on more than the account (health, view preferences, language); the
1401
1621
  // fingerprint covers what its click handlers use.
1402
- function rowSig(a) { return sig([a, healthOf(a.ref), isNext(a), ui.desktopRef === a.ref, ui.browserRef === a.ref, browserFor(a), prefs.hideEmail, isOpen(a), loginLead(a), isPinned(a)]) }
1622
+ function rowSig(a) { return sig([a, healthOf(a.ref), isNext(a), ui.desktopRef === a.ref, ui.browserRef === a.ref, ui.copied === a.ref, browserFor(a), prefs.hideEmail, isOpen(a), loginLead(a), isPinned(a)]) }
1403
1623
  // Whether the row sits in a login group (spec §3.21): its first row then shows the quota for all of them.
1404
1624
  function inLogin(a) { return ui.loginRefs.has(a.ref) }
1405
1625
  // The group's first row, which shows the quota for all of them.
@@ -1477,7 +1697,7 @@ const MAIN = String.raw `
1477
1697
  el.dataset.sig = ms ? sig(ms.map(rowSig)) : rowSig(a)
1478
1698
  let detail = rowDetails(el)[0]
1479
1699
  if (open && !detail) {
1480
- detail = ms ? loginDetail(ms) : rowDetail(a, Boolean(emailLine(a)))
1700
+ detail = ms ? loginDetail(ms) : rowDetail(a)
1481
1701
  const more = el.querySelector(':scope > .row-end')
1482
1702
  el.insertBefore(detail, more ? more.nextSibling : null)
1483
1703
  detail.style.opacity = '0'
@@ -1539,8 +1759,8 @@ const MAIN = String.raw `
1539
1759
  h('div', { class: 'ident' }, rowToggle(a), badge(a.family, 'sm'), h('div', { class: 'ident-text' }, nameLine(a), metaLine(email || subLine(a), a))),
1540
1760
  quotaBlock(a, now, cols),
1541
1761
  lastUsed(a),
1542
- h('div', { class: 'row-end' }, runButton(a), moreButton(a)),
1543
- open ? rowDetail(a, Boolean(email)) : null,
1762
+ h('div', { class: 'row-end' }, deskButton(a), runButton(a), moreButton(a)),
1763
+ open ? rowDetail(a) : null,
1544
1764
  notes(a)), (anchor) => accountMenu(a, anchor))
1545
1765
  }
1546
1766
  // What a right-click on el opens (see openContextMenu).
@@ -1578,7 +1798,7 @@ const MAIN = String.raw `
1578
1798
  h('div', { class: 'ident' }, rowToggle(a), badge(a.family, 'sm'), h('div', { class: 'ident-text' }, nameLine(a, ms), metaLine(email || subLine(a), newestOf(ms)))),
1579
1799
  quotaBlock(a, now, cols),
1580
1800
  lastUsed(newestOf(ms)),
1581
- h('div', { class: 'row-end' }, runButton(a), loginMoreButton(ms)),
1801
+ h('div', { class: 'row-end' }, deskButton(a, ms), runButton(a), loginMoreButton(ms)),
1582
1802
  open ? loginDetail(ms) : null,
1583
1803
  notes(a)), (anchor) => loginMenu(ms, anchor))
1584
1804
  }
@@ -1599,6 +1819,7 @@ const MAIN = String.raw `
1599
1819
  usageBlock(m),
1600
1820
  healthChip(m),
1601
1821
  h('button', { class: 'btn btn-sm', type: 'button', title: run, onclick: () => copyText(run) }, icon('terminal'), t('login.copyRun')),
1822
+ useOtherButton(m),
1602
1823
  moreButton(m)), (anchor) => accountMenu(m, anchor))
1603
1824
  })))
1604
1825
  }
@@ -1606,27 +1827,71 @@ const MAIN = String.raw `
1606
1827
  function sameLoginNote(a) {
1607
1828
  if (!a.sameLogin || !a.sameLogin.length || inLogin(a)) return null
1608
1829
  const names = a.sameLogin.map(refName).join(', ')
1609
- return h('div', { class: 'rd-note', title: t('acct.sameLoginHint', { names }) }, t('acct.sameLogin', { names }))
1830
+ return h('div', { class: 'rd-note', title: t('acct.sameLoginHint', { names }) }, t('acct.sameLogin', { names }), ' ', useOtherButton(a))
1831
+ }
1832
+ // Gives one directory of a Same Login a login of its own (spec §3.21 "换个账号登录"): its sign-in, in a terminal.
1833
+ function useOtherButton(a) {
1834
+ return h('button', { class: 'link-btn small ld-other', type: 'button', title: t('login.useOtherHint', { name: a.name }), onclick: (e) => { e.stopPropagation(); signIn(a) } }, t('login.useOther'))
1610
1835
  }
1611
- function rowDetail(a, withSub) {
1836
+ function rowDetail(a) {
1612
1837
  const same = sameLoginNote(a)
1613
- return h('div', { class: 'row-detail' },
1614
- withSub || same ? h('div', { class: 'rd-item rd-run' }, h('span', { class: 'rd-label' }, t('row.runs')), withSub ? subLine(a) : null, same) : null,
1615
- browserItem(a),
1616
- h('div', { class: 'rd-item rd-usage' }, h('span', { class: 'rd-label' }, t('col.tokens', { n: BOOT.usageDays })), usageBlock(a)),
1617
- h('div', { class: 'rd-item rd-health' }, h('span', { class: 'rd-label' }, t('col.health')), healthChip(a)))
1838
+ const b = browserInfo()
1839
+ const signIns = Boolean(b && b.enabled && !BOOT.readOnly)
1840
+ // One panel of four cells: how it runs, its Chrome sign-in, tokens, health. Every row has every cell, so the
1841
+ // cells line up down the list; an account without a Chrome sign-in says so with a dash.
1842
+ return h('div', { class: 'row-detail' + (signIns ? '' : ' rd-nobr') },
1843
+ h('div', { class: 'rd-item rd-run' }, h('span', { class: 'rd-label' }, t('row.runs')), h('div', { class: 'rd-val' }, subLine(a)), same),
1844
+ signIns ? browserItem(a) || h('div', { class: 'rd-item rd-browser' }, h('span', { class: 'rd-label' }, t('row.browser')),
1845
+ h('div', { class: 'br-line' }, h('span', { class: 'rd-none' }, '—'),
1846
+ browserFor(a) ? h('button', { class: 'link-btn small', type: 'button', title: t('br.changeHint', { ref: a.ref }), onclick: (e) => { e.stopPropagation(); openBrowserDialog(a) } }, t('br.pick')) : null)) : null,
1847
+ h('div', { class: 'rd-item rd-usage' }, h('span', { class: 'rd-label' }, t('col.tokens', { n: BOOT.usageDays })), h('div', { class: 'rd-val' }, usageBlock(a))),
1848
+ h('div', { class: 'rd-item rd-health' }, h('span', { class: 'rd-label' }, t('col.health')), h('div', { class: 'rd-val' }, healthChip(a))))
1618
1849
  }
1619
1850
  // A card shows everything at once; it has room for it.
1620
1851
  function card(a, now, cols) {
1852
+ // A Same Login shows as a link mark after the name (its note and "Use another account" are in the menu).
1853
+ const peers = a.sameLogin && a.sameLogin.length ? [a, ...a.sameLogin.map((r) => ({ name: refName(r) }))] : null
1621
1854
  return withMenu(h('article', { class: 'card' + (a.error ? ' card-error' : ''), 'data-ref': a.ref, 'data-key': a.ref, 'data-sig': rowSig(a), 'aria-label': a.ref },
1622
- h('header', { class: 'card-head' },
1623
- badge(a.family, 'sm'),
1624
- h('div', { class: 'ident-text' }, nameLine(a), emailLine(a), subLine(a), sameLoginNote(a)),
1625
- h('div', { class: 'row-end' }, moreButton(a))),
1855
+ h('header', { class: 'card-head' }, badge(a.family, 'sm'), nameLine(a, null, { linked: peers }), h('div', { class: 'row-end' }, moreButton(a))),
1856
+ // The last use follows who it is, as in the medium list; a card without one shows nothing there.
1857
+ h('div', { class: 'card-id' }, h('div', { class: 'ident-meta' }, emailLine(a) || subLine(a), a.usage && a.usage.status === 'ok' && a.usage.lastActivityAt ? lastUsed(a, 'last-inline') : null), emailLine(a) ? subLine(a) : null),
1858
+ notes(a),
1859
+ quotaBlock(a, now, cols),
1860
+ cardBrowser(a),
1861
+ // Tokens on the left, the row's own buttons on the right. A health problem shows in the label after the name
1862
+ // (it opens the same filter), so the foot does not say it again.
1863
+ h('footer', { class: 'card-foot' }, usageBlock(a), h('div', { class: 'card-side' }, deskButton(a), runButton(a)))), (anchor) => accountMenu(a, anchor))
1864
+ }
1865
+ // A Same Login as one card (spec §3.21), as the list shows it as one row: named after its first directory, the
1866
+ // other directories listed under who it is, one quota, the tokens of all of them, one menu for all of them.
1867
+ function loginCard(members, now, cols) {
1868
+ const ms = loginMembers(members)
1869
+ const a = ms[0]
1870
+ const newest = newestOf(ms)
1871
+ const email = emailLine(a)
1872
+ const usage = Object.assign({}, a, { usage: mergeUsage(ms.map((m) => m.usage)) })
1873
+ return withMenu(h('article', { class: 'card card-login' + (a.error ? ' card-error' : ''), 'data-ref': a.ref, 'data-key': loginKey(ms.map((m) => m.ref)), 'data-sig': sig(ms.map(rowSig)), 'aria-label': t('login.label', { names: ms.map((m) => m.name).join(', ') }) },
1874
+ h('header', { class: 'card-head' }, badge(a.family, 'sm'), nameLine(a, ms), h('div', { class: 'row-end' }, loginMoreButton(ms))),
1875
+ h('div', { class: 'card-id' },
1876
+ h('div', { class: 'ident-meta' }, email || subLine(a), newest.usage && newest.usage.status === 'ok' && newest.usage.lastActivityAt ? lastUsed(newest, 'last-inline') : null),
1877
+ email ? subLine(a) : null,
1878
+ h('div', { class: 'card-dirs', title: t('login.explain') }, h('span', { class: 'cd-label' }, t('login.also')),
1879
+ ms.slice(1).map((m) => h('span', { class: 'tag tag-dir', title: 'sideby run ' + m.ref }, m.name, (m.aliases || [])[0] ? h('span', { class: 'alias' }, (m.aliases || [])[0]) : null)))),
1626
1880
  notes(a),
1627
- browserItem(a),
1628
1881
  quotaBlock(a, now, cols),
1629
- h('footer', { class: 'card-foot' }, usageBlock(a), h('div', { class: 'card-side' }, lastUsed(a), healthChip(a)))), (anchor) => accountMenu(a, anchor))
1882
+ cardBrowser(a),
1883
+ h('footer', { class: 'card-foot' }, usageBlock(usage), h('div', { class: 'card-side' }, deskButton(a, ms), runButton(a)))), (anchor) => loginMenu(ms, anchor))
1884
+ }
1885
+ // A card's Chrome sign-in: one line, the browser user as a link that opens the website, then Change.
1886
+ function cardBrowser(a) {
1887
+ const b = browserInfo()
1888
+ if (!b || !b.enabled || BOOT.readOnly || !browserFor(a)) return null
1889
+ const btn = browserButton(a)
1890
+ const chosen = browserChosen(a)
1891
+ return h('div', { class: 'card-br', title: t('row.browser') },
1892
+ btn || h('span', { class: 'br-none' }, icon('globe', 'br-ico'), h('span', null, '—')),
1893
+ chosen ? h('span', { class: 'tag', title: t('br.chosenHint') }, t('br.chosen')) : null,
1894
+ h('button', { class: 'link-btn small', type: 'button', title: t('br.changeHint', { ref: a.ref }), onclick: (e) => { e.stopPropagation(); openBrowserDialog(a) } }, t(btn ? 'br.change' : 'br.pick')))
1630
1895
  }
1631
1896
  // The list's column titles, once per group under its header. Screen readers get each cell's own label instead.
1632
1897
  function colHead(cols, list) {
@@ -1656,7 +1921,7 @@ const MAIN = String.raw `
1656
1921
  const label = a.name + ' · ' + whyOf(a, now)
1657
1922
  return h('button', { class: 'tag tag-warn tag-btn', type: 'button', title: t('group.attentionShow', { name: a.name }), onclick: () => flashRow(a.ref) }, label)
1658
1923
  }
1659
- const list = needing.map((a) => a.name + ': ' + whyOf(a, now)).join('\n')
1924
+ const list = needing.map((a) => a.name + colon() + whyOf(a, now)).join('\n')
1660
1925
  return h('button', { class: 'tag tag-warn tag-btn', type: 'button', title: list, 'aria-pressed': String(ui.attention), onclick: () => { ui.attention = !ui.attention; renderSummary(); renderAccounts() } }, tn('group.attention', needing.length))
1661
1926
  }
1662
1927
  // ---------- Grok Bot windows (ADR-0019) ----------
@@ -1686,11 +1951,13 @@ const MAIN = String.raw `
1686
1951
  h('button', { class: 'btn btn-sm btn-danger', type: 'button', disabled: busy, onclick: () => removeApp(p) }, t(busy ? 'app.removing' : 'app.removeYes')),
1687
1952
  h('button', { class: 'btn btn-sm btn-ghost', type: 'button', disabled: busy, onclick: () => { ui.appRemove = null; renderAccounts() } }, t('btn.cancel')))
1688
1953
  : h('div', { class: 'row-actions app-actions' },
1689
- h('button', { class: 'btn btn-sm' + (p.running ? '' : ' btn-primary'), type: 'button', disabled: Boolean(ui.appBusy), title: t(p.running ? 'app.showHint' : 'app.openHint', { app: p.app, ref: p.ref }), 'aria-label': t(p.running ? 'app.show' : 'app.openBtn') + ' (' + p.ref + ')', onclick: () => openApp(p.ref) },
1690
- busy ? t('desk.opening', { app: p.app }) : t(p.running ? 'app.show' : 'app.openBtn')),
1954
+ // The same screen button as an account's row end: open the window, or bring it to the front.
1955
+ h('button', { class: 'icon-btn row-run row-desk' + (p.running ? ' is-open' : ''), type: 'button', disabled: Boolean(ui.appBusy), 'data-tip': t(p.running ? 'app.showHint' : 'app.openHint', { app: p.app, ref: p.ref }), 'aria-label': (busy ? t('desk.opening', { app: p.app }) : t(p.running ? 'app.show' : 'app.openBtn')) + ' (' + p.ref + ')', 'aria-busy': busy ? 'true' : null, onclick: () => openApp(p.ref) },
1956
+ busy ? spinner() : icon('monitor')),
1691
1957
  p.isMain ? null : h('button', { class: 'btn btn-sm btn-ghost', type: 'button', disabled: p.running || Boolean(ui.appBusy), title: t(p.running ? 'app.removeRunning' : 'app.removeHint', { app: p.app }), 'aria-label': t('app.remove') + ' (' + p.ref + ')', onclick: () => { ui.appRemove = p.ref; renderAccounts() } }, t('app.remove')))
1692
1958
  return h('div', { class: 'app-row', role: 'listitem', 'data-ref': p.ref, 'data-key': p.ref, 'data-sig': sig([p, busy, asking, Boolean(ui.appBusy)]) },
1693
- h('div', { class: 'ident' }, appBadge(), h('div', { class: 'ident-text' },
1959
+ // A gap where an account row has its open arrow, so the marks and names line up with the accounts above.
1960
+ h('div', { class: 'ident' }, h('span', { class: 'app-gap', 'aria-hidden': 'true' }), appBadge(), h('div', { class: 'ident-text' },
1694
1961
  h('div', { class: 'ident-name' },
1695
1962
  h('span', { class: 'name' }, p.isMain ? t('app.mainName') : p.name),
1696
1963
  p.running ? h('span', { class: 'tag tag-ok' }, h('span', { class: 'dot dot-ok', 'aria-hidden': 'true' }), t('app.isOpen')) : null,
@@ -1821,7 +2088,7 @@ const MAIN = String.raw `
1821
2088
  // The arrange mode shows every group open, as a short list, in either view (spec §3.25).
1822
2089
  const cards = prefs.view === 'cards' && !ui.arrange
1823
2090
  const collapsedNow = collapsed && !ui.arrange
1824
- if (!cards) ui.order.units[fam] = loginClusters(list).map((x) => Array.isArray(x) ? x.map((a) => a.name) : [x.name])
2091
+ ui.order.units[fam] = loginClusters(list).map((x) => Array.isArray(x) ? x.map((a) => a.name) : [x.name])
1825
2092
  const head = h('div', { class: 'group-head', 'data-key': ui.arrange ? 'head-arrange' : 'head' },
1826
2093
  dragHandle('family', fam, fam, info.title),
1827
2094
  h('button', { class: 'group-toggle', type: 'button', disabled: ui.arrange ? true : undefined, 'aria-expanded': String(!collapsedNow), 'aria-controls': bodyId, title: t(collapsed ? 'group.expand' : 'group.collapse'), 'aria-label': t('group.toggle', { title: info.title, count: list.length === total ? String(total) : list.length + ' / ' + total, action: t(collapsed ? 'group.expand' : 'group.collapse') }), onclick: () => toggleGroup(fam, 'g:' + fam) },
@@ -1838,7 +2105,7 @@ const MAIN = String.raw `
1838
2105
  off && setup && setup.plan.status === 'blocked' ? h('span', { class: 'muted small label-tip' }, t('quota.blocked'), tipRaw(t('quota.blocked'), setup.plan.message)) : null,
1839
2106
  ui.arrange ? null : pickHead(fam)))
1840
2107
  const body = collapsedNow ? null : cards
1841
- ? h('div', { class: 'grid', id: bodyId, 'data-key': 'cards', 'data-patch': '' }, list.map((a) => card(a, now, cols)))
2108
+ ? h('div', { class: 'grid', id: bodyId, 'data-key': 'cards', 'data-patch': '' }, loginClusters(list).map((x) => Array.isArray(x) ? loginCard(x, now, cols) : card(x, now, cols)))
1842
2109
  : h('div', { class: 'rows', id: bodyId, role: 'list', 'data-key': ui.arrange ? 'rows-arrange' : 'rows', 'data-patch': '' }, loginClusters(list).map((x) => Array.isArray(x) ? loginRow(x, now, cols) : row(x, now, cols)))
1843
2110
  return h('section', { class: 'group' + (cards ? ' group-cards' : ' group-list') + (collapsedNow ? ' is-collapsed' : '') + (ui.arrange ? ' is-arranging' : ''), 'aria-label': info.title, 'data-key': 'g:' + fam, 'data-fam': fam, 'data-patch': '' },
1844
2111
  head, collapsedNow || cards || ui.arrange ? null : colHead(cols, list), body)
@@ -2170,8 +2437,7 @@ const MAIN = String.raw `
2170
2437
  const apps = appGroups()
2171
2438
  if (!shown.length && !apps.length) { patch(box, noMatch()); return }
2172
2439
  ui.loginRefs = new Map()
2173
- if (prefs.view !== 'cards' || ui.arrange)
2174
- for (const x of loginClusters(shown)) if (Array.isArray(x)) for (const a of x) ui.loginRefs.set(a.ref, loginMembers(x)[0].ref)
2440
+ for (const x of loginClusters(shown)) if (Array.isArray(x)) for (const a of x) ui.loginRefs.set(a.ref, loginMembers(x)[0].ref)
2175
2441
  // Families in the Display Order (spec §3.25) whatever the sort; each group gets the quota columns it uses.
2176
2442
  // Every group is as wide as the one with the most windows, so the columns after them line up.
2177
2443
  ui.order = { families: [], units: {} }
@@ -2296,6 +2562,7 @@ const MAIN = String.raw `
2296
2562
  // With no account there is nothing to check: the empty state is the only thing to do.
2297
2563
  box.hidden = Boolean(S.state && !S.state.accounts.length)
2298
2564
  if (box.hidden) return
2565
+ if (curPage !== 'accounts') box.hidden = true
2299
2566
  const all = findingsNow()
2300
2567
  const ref = ui.healthRef
2301
2568
  const findings = all && ref ? all.filter((f) => f.account === ref) : all
@@ -2332,7 +2599,7 @@ const MAIN = String.raw `
2332
2599
  const failed = S.fixes.filter((f) => !f.ok)
2333
2600
  out.push(h('div', { class: 'fix-result ' + (failed.length ? 'is-warn' : 'is-ok'), role: 'status' },
2334
2601
  S.fixes.length ? t('fix.result', { ok: S.fixes.length - failed.length, n: S.fixes.length }) : t('fix.nothing'),
2335
- failed.length ? h('ul', null, failed.map((f) => h('li', null, h('b', null, f.account + ' · ' + f.item + ': '), f.message))) : null))
2602
+ failed.length ? h('ul', null, failed.map((f) => h('li', null, h('b', null, f.account + ' · ' + f.item + colon()), f.message))) : null))
2336
2603
  }
2337
2604
  if (!findings) {
2338
2605
  if (busy || !S.state) out.push(h('span', { class: 'sk sk-line w70' }), h('span', { class: 'sk sk-line w50' }))
@@ -2388,6 +2655,10 @@ const MAIN = String.raw `
2388
2655
  function showDialog(kind) {
2389
2656
  const el = ensureDialog()
2390
2657
  dlg.kind = kind
2658
+ // A wide dialog is wide before it opens, so it does not open narrow and then stretch.
2659
+ el.classList.toggle('dialog-wide', kind === 'settings' ? el.classList.contains('dialog-wide') : kind === 'history')
2660
+ // A dialog that grows as the user adds to it (screenshots, its result) keeps its top edge and grows downward.
2661
+ el.classList.toggle('dialog-top', kind === 'send')
2391
2662
  if (!el.open) { el.showModal(); raiseToasts() }
2392
2663
  }
2393
2664
 
@@ -2400,9 +2671,20 @@ const MAIN = String.raw `
2400
2671
  // What each card's size menu shows while the user is choosing, by group id; dropped once a change is made.
2401
2672
  const tuneSel = {}
2402
2673
  const tp = { data: null, loading: false, error: null, at: 0 }
2403
- function pageFromHash() { return location.hash === '#tuning' ? 'tuning' : location.hash === '#handoff' ? 'handoff' : 'accounts' }
2674
+ function pageFromHash() { return location.hash === '#tuning' ? 'tuning' : location.hash === '#handoff' ? 'handoff' : location.hash === '#sessions' || location.hash === '#history' || location.hash === '#live' ? 'sessions' : 'accounts' }
2404
2675
  let curPage = pageFromHash()
2405
2676
  function tuneSize(n) { return n === null || n === undefined ? t('tune.hostDefault') : tokens(n) }
2677
+ // "Default" with the size it means, only where that size is documented: Claude models with a native 1M window
2678
+ // compact at about 967K (families/claude/tuning.ts cites the model documentation), which is below their window.
2679
+ // Elsewhere the effective size is the window itself, an estimate, or what was observed, so it stays "Default".
2680
+ function defaultSize(models) {
2681
+ const sizes = [...new Set(models.filter((m) => m.configured === null && m.effective && m.effective < m.contextWindow).map((m) => m.effective))].sort((x, y) => x - y)
2682
+ if (!sizes.length) return t('tune.hostDefault')
2683
+ return sizes.length === 1 ? t('tune.hostDefaultIs', { size: tokens(sizes[0]) }) : t('tune.hostDefaultRange', { lo: tokens(sizes[0]), hi: tokens(sizes[sizes.length - 1]) })
2684
+ }
2685
+ function claudeModels(entries) {
2686
+ return entries.filter((e) => e.tuning.status === 'ok' && e.ref.startsWith('claude:')).flatMap((e) => e.tuning.models)
2687
+ }
2406
2688
  function tuneRedraw() {
2407
2689
  if (dlg.kind === 'tune') renderTune()
2408
2690
  if (curPage === 'tuning') renderTuningPage()
@@ -2464,8 +2746,8 @@ const MAIN = String.raw `
2464
2746
  return h('div', { class: 'tune-confirm' },
2465
2747
  h('p', { class: 'small' }, h('b', null, t('tune.confirmTitle'))),
2466
2748
  h('ul', { class: 'small' },
2467
- h('li', null, t('tune.change') + ': ' + tuneSize(plan.current) + ' → ' + tuneSize(plan.next)),
2468
- h('li', null, t('tune.file') + ': ', h('code', null, plan.file + (plan.creates ? ' ' + t('tune.willCreate') : '')))),
2749
+ h('li', null, t('tune.change') + colon() + tuneSize(plan.current) + ' → ' + tuneSize(plan.next)),
2750
+ h('li', null, t('tune.file') + colon(), h('code', null, plan.file + (plan.creates ? ' ' + t('tune.willCreate') : '')))),
2469
2751
  plan.affected.length > 1 ? h('p', { class: 'note note-warn' }, t('tune.shared', { list: plan.affected.join(', ') })) : null,
2470
2752
  plan.overrides && plan.overrides.length ? h('p', { class: 'note note-warn' }, t('tune.overrides', { list: plan.overrides.map((o) => o.model + ' (' + tokens(o.value) + ')').join(', ') })) : null,
2471
2753
  h('p', { class: 'muted small' }, t('tune.newSessions')),
@@ -2495,7 +2777,7 @@ const MAIN = String.raw `
2495
2777
  const asking = mine && (useUi.step === 'confirm' || busy)
2496
2778
  const rows = [h('p', { class: 'small' }, g.members.length > 1 ? t('tune.groupShared', { list: g.members.join(', ') }) : h('b', { class: 'mono' }, g.members[0]))]
2497
2779
  rows.push(h('div', { class: 'tune-vals' },
2498
- h('div', null, h('span', { class: 'muted small' }, t('tune.now')), h('div', { class: 'tune-num' }, tuneSize(g.current))),
2780
+ h('div', null, h('span', { class: 'muted small' }, t('tune.now')), h('div', { class: 'tune-num' }, g.current === null ? defaultSize(claudeModels(entries)) : tuneSize(g.current))),
2499
2781
  pick ? h('div', null, h('span', { class: 'muted small' }, t('tune.best')), h('div', { class: 'tune-num tune-best' }, tokens(pick.threshold))) : null))
2500
2782
  if (pick && pick.savedPercent !== null) rows.push(h('p', { class: 'small' }, t('tune.saved', { n: Math.round(pick.savedPercent) })))
2501
2783
  if (pick) rows.push(h('p', { class: 'muted small' }, t('tune.basis', { model: pick.model, ref: pick.ref })))
@@ -2527,10 +2809,10 @@ const MAIN = String.raw `
2527
2809
  return h('div', { class: 'tune-model tune-group' }, rows)
2528
2810
  }
2529
2811
  // What was seen for one model: information only, behind a click.
2530
- function tuneModel(m, minCalls) {
2812
+ function tuneModel(m, minCalls, claude) {
2531
2813
  const rows = [h('div', { class: 'tune-head' }, h('b', { class: 'mono' }, m.model), h('span', { class: 'muted small' }, t('tune.calls', { n: m.calls })))]
2532
2814
  rows.push(h('div', { class: 'tune-vals' },
2533
- h('div', null, h('span', { class: 'muted small' }, t('tune.now')), h('div', { class: 'small' }, tuneSize(m.configured))),
2815
+ h('div', null, h('span', { class: 'muted small' }, t('tune.now')), h('div', { class: 'small' }, m.configured === null && claude ? defaultSize([m]) : tuneSize(m.configured))),
2534
2816
  m.suggestion ? h('div', null, h('span', { class: 'muted small' }, t('tune.best')), h('div', { class: 'small' }, tokens(m.suggestion.threshold))) : null))
2535
2817
  if (!m.suggestion) rows.push(h('p', { class: 'muted small' }, t('tune.reason.' + m.reason, { min: minCalls })))
2536
2818
  rows.push(h('p', { class: 'muted small' }, m.compactions.total ? tn('tune.compactions', m.compactions.total, { size: tokens(m.compactions.preTokensP50 || 0) }) : t('tune.noCompactions')))
@@ -2542,7 +2824,7 @@ const MAIN = String.raw `
2542
2824
  for (const e of entries) {
2543
2825
  if (e.tuning.status !== 'ok' || !e.tuning.models.length) continue
2544
2826
  kids.push(h('div', { class: 'tune-acct-head title-logo' }, badge(e.family, 'sm'), h('b', { class: 'mono' }, e.ref)))
2545
- for (const m of e.tuning.models) kids.push(tuneModel(m, minCalls))
2827
+ for (const m of e.tuning.models) kids.push(tuneModel(m, minCalls, e.ref.startsWith('claude:')))
2546
2828
  }
2547
2829
  return kids.length ? h('details', { class: 'tune-details' }, h('summary', null, label), kids) : null
2548
2830
  }
@@ -2594,31 +2876,61 @@ const MAIN = String.raw `
2594
2876
 
2595
2877
  // The page: every account that can tune, on a page of its own. The address ending in #tuning opens it.
2596
2878
  function tuningAvailable() { return Boolean(S.state && S.state.families.some((f) => f.tuning)) }
2597
- function setPage(next) {
2879
+ // Every move to a page counts, so an answer that comes in late never takes the viewer back to a page they left.
2880
+ let navSeq = 0
2881
+ function setPage(next, ready) {
2882
+ const seq = ++navSeq
2883
+ // The Sessions page opens once its first answer is in, at its final size (one read at start usually has it);
2884
+ // meanwhile its tab spins.
2885
+ const first = hs.mode === 'history' ? !hs.data && !hs.error : !sp.data && !sp.error
2886
+ if (next === 'sessions' && first && !sp.opening && !ready) {
2887
+ sp.opening = true
2888
+ renderPageChrome()
2889
+ const read = hs.mode === 'history' ? Promise.all([loadHistory(), loadProjects()]) : loadSessions()
2890
+ read.finally(() => {
2891
+ sp.opening = false
2892
+ if (seq === navSeq) setPage('sessions', true)
2893
+ else renderPageChrome()
2894
+ })
2895
+ return
2896
+ }
2897
+ if (next !== 'sessions') leaveHistory()
2598
2898
  curPage = next
2599
- try { history.replaceState(null, '', next === 'accounts' ? location.pathname + location.search : '#' + next) } catch {}
2899
+ try { history.replaceState(null, '', next === 'accounts' ? location.pathname + location.search : '#' + (next === 'sessions' && hs.mode === 'live' ? 'live' : next)) } catch {}
2600
2900
  renderPageChrome()
2901
+ renderBanners()
2902
+ if (next === 'sessions' && Date.now() - ib.at >= INB_MS) loadInbound()
2601
2903
  }
2602
2904
  // The page tabs, and which sections show; runs with every render, so a reload or a language switch keeps them.
2603
2905
  function renderPageChrome() {
2604
2906
  const nav = $('pages')
2605
2907
  const canTune = tuningAvailable()
2606
2908
  const canHandoff = Boolean(ahState())
2607
- if (S.state && ((curPage === 'tuning' && !canTune) || (curPage === 'handoff' && !canHandoff))) curPage = 'accounts'
2909
+ // Always offered, so the tabs do not change when the last account goes; the page has its own empty state.
2910
+ const canSessions = Boolean(S.state)
2911
+ if (S.state && ((curPage === 'tuning' && !canTune) || (curPage === 'handoff' && !canHandoff) || (curPage === 'sessions' && !canSessions))) curPage = 'accounts'
2608
2912
  const tabs = [['accounts', t('page.accounts')]]
2913
+ if (canSessions) tabs.push(['sessions', t('page.sessions')])
2609
2914
  if (canTune) tabs.push(['tuning', t('page.tuning')])
2610
2915
  if (canHandoff) tabs.push(['handoff', t('page.handoff')])
2611
2916
  nav.hidden = tabs.length < 2
2612
2917
  setKids(nav, h('div', { class: 'seg', role: 'presentation' }, tabs.map(([id, label]) =>
2613
- h('button', { class: 'seg-btn', type: 'button', role: 'tab', 'aria-selected': curPage === id ? 'true' : 'false', onclick: () => setPage(id) }, label))))
2918
+ h('button', { class: 'seg-btn', type: 'button', role: 'tab', 'aria-selected': curPage === id ? 'true' : 'false', 'aria-busy': id === 'sessions' && sp.opening ? 'true' : null, onclick: () => setPage(id) }, id === 'sessions' && sp.opening ? [spinner(), ' '] : null, label,
2919
+ id === 'sessions' && pasteCount() ? h('span', { class: 'seg-badge', 'data-tip': t('msgn.badge', { n: pasteCount() }), 'aria-label': t('msgn.badge', { n: pasteCount() }) }, String(pasteCount())) : null))))
2614
2920
  const away = curPage !== 'accounts' && tabs.some(([id]) => id === curPage)
2615
2921
  // With no account yet the empty state is the whole page: no summary, no health check.
2616
2922
  const none = Boolean(S.state && !S.state.accounts.length)
2617
2923
  for (const id of ['summary', 'accounts-page', 'checkup']) $(id).hidden = away || (none && id !== 'accounts-page')
2618
2924
  const onTune = away && curPage === 'tuning'
2619
2925
  const onHandoff = away && curPage === 'handoff'
2926
+ const onSessions = away && curPage === 'sessions'
2620
2927
  $('tuning-page').hidden = !onTune
2621
2928
  $('handoff-page').hidden = !onHandoff
2929
+ $('sessions-page').hidden = !onSessions
2930
+ if (onSessions) {
2931
+ if (!sp.data && !sp.error) loadSessions()
2932
+ renderSessionsPage()
2933
+ }
2622
2934
  if (onTune) {
2623
2935
  if (!tp.data && !tp.loading && !tp.error) loadTuningPage()
2624
2936
  else renderTuningPage()
@@ -2631,6 +2943,8 @@ const MAIN = String.raw `
2631
2943
  }
2632
2944
  }
2633
2945
  async function loadTuningPage() {
2946
+ // One read at a time: a second refresh while one runs would end its spinner early.
2947
+ if (tp.loading) return
2634
2948
  tp.loading = true
2635
2949
  tp.error = null
2636
2950
  renderTuningPage()
@@ -2643,7 +2957,7 @@ const MAIN = String.raw `
2643
2957
  if (box.hidden) return
2644
2958
  const kids = [h('div', { class: 'section-head' },
2645
2959
  h('h2', { id: 'h-tuning' }, t('tpage.title')),
2646
- h('button', { class: 'btn btn-sm', type: 'button', disabled: tp.loading, onclick: loadTuningPage }, tp.loading ? spinner() : icon('refresh'), t('top.refresh')))]
2960
+ tp.loading ? spinner() : null)]
2647
2961
  kids.push(h('p', { class: 'muted small' }, t('tune.intro', { days: BOOT.usageDays })))
2648
2962
  const d = tp.data
2649
2963
  if (tp.loading && !d) kids.push(h('p', { class: 'muted' }, spinner(), ' ', t('tune.loading')))
@@ -2659,7 +2973,1565 @@ const MAIN = String.raw `
2659
2973
  }
2660
2974
  setKids(box, kids)
2661
2975
  }
2662
- window.addEventListener('hashchange', () => { curPage = pageFromHash(); renderPageChrome() })
2976
+ window.addEventListener('hashchange', () => {
2977
+ navSeq++
2978
+ curPage = pageFromHash()
2979
+ if (curPage === 'sessions') { const m = location.hash === '#live' ? 'live' : 'history'; if (m !== hs.mode) { hs.mode = m; sp.drawn = '' } }
2980
+ renderPageChrome()
2981
+ })
2982
+
2983
+ // ---------- sessions (spec §3.32, ADR-0039) ----------
2984
+ // What every Account is running now, one row per Live Session, with "Copy for AI" and a menu for the id and the resume
2985
+ // command. Read once at start so the page opens at its final size, then every SESS_MS while it shows. An answer
2986
+ // that draws the same rows draws nothing; a new one waits while a menu or popover of the page is open, and the
2987
+ // focused button keeps focus (swapKids). The "x min ago" texts change in place every second.
2988
+ const SESS_MS = 5000
2989
+ const sp = { data: null, lang: null, loading: null, error: null, at: 0, drawn: '', pending: false, copied: {}, opening: false, msgs: {}, order: [] }
2990
+ function loadSessions() {
2991
+ if (sp.loading) return sp.loading
2992
+ sp.loading = readSessions()
2993
+ return sp.loading
2994
+ }
2995
+ async function readSessions() {
2996
+ const asked = lang
2997
+ try {
2998
+ // The chips of the latest Messages come with the list; when they cannot be read the rows keep the last ones.
2999
+ const seq = ++mn.asked
3000
+ const [data, msgs] = await Promise.all([api('/api/sessions', { lang: asked }), api('/api/sessions/messages', {}).catch(() => null)])
3001
+ sp.data = data; sp.lang = asked; sp.error = null
3002
+ if (msgs && msgs.latest) noteMessages(msgs.latest, seq)
3003
+ if (Date.now() - ib.at >= INB_MS) loadInbound()
3004
+ } catch (e) { sp.error = e }
3005
+ sp.at = Date.now()
3006
+ sp.loading = null
3007
+ renderSessionsPage()
3008
+ }
3009
+ // ---------- receiving Messages (ADR-0045) ----------
3010
+ // Whether each Claude settings file lets its sessions show a Message from another session at once, or holds it for
3011
+ // approval in that terminal (dropped after about 5 minutes). Read with the Sessions list every INB_MS and after a
3012
+ // change. The dialog lists each file, its value now and the change, and only its button writes; the toast carries
3013
+ // the undo.
3014
+ const INB_MS = 60000
3015
+ const ib = { data: null, error: null, loading: null, busy: false, at: 0, bannerEl: undefined }
3016
+ function loadInbound() {
3017
+ if (ib.loading) return ib.loading
3018
+ ib.loading = (async () => {
3019
+ try { ib.data = await api('/api/messages/inbound', {}); ib.error = null } catch (e) { ib.error = e }
3020
+ ib.at = Date.now()
3021
+ ib.loading = null
3022
+ renderBanners()
3023
+ renderSessionsPage()
3024
+ if (dlg.kind === 'inbound' && dlg.el && dlg.el.open) renderInbound()
3025
+ })()
3026
+ return ib.loading
3027
+ }
3028
+ function inboundGroups() { return (ib.data && ib.data.groups) || [] }
3029
+ function inboundTodo() { return inboundGroups().filter((g) => g.state === 'default' || g.state === 'hold') }
3030
+ function inboundWaiting() { return inboundGroups().filter((g) => g.waits).flatMap((g) => g.accounts).map(shortRef) }
3031
+ function inboundShape() { return inboundGroups().length > 0 }
3032
+ const refList = (refs) => refs.join(lang === 'zh' ? '、' : ', ')
3033
+ // Shown above the Sessions page, in both its views. It grows from nothing to its own height when it first
3034
+ // appears and shrinks back when it goes (inboundBannerKept keeps the old one on screen while it leaves).
3035
+ function inboundBanner() {
3036
+ const refs = inboundWaiting()
3037
+ if (curPage !== 'sessions' || !refs.length || prefs.inbHide) return inboundBannerKept()
3038
+ const text = h('div', null, t('inb.banner', { refs: refList(refs) }))
3039
+ const attrs = { class: 'banner banner-warn', role: 'status', 'data-key': 'inb-banner' }
3040
+ if (BOOT.readOnly) return h('div', attrs, text)
3041
+ return h('div', attrs, text,
3042
+ h('div', { class: 'banner-actions' },
3043
+ h('button', { class: 'btn btn-sm btn-primary', type: 'button', onclick: openInbound }, t('inb.go')),
3044
+ h('button', { class: 'btn btn-sm', type: 'button', onclick: () => { prefs.inbHide = true; savePrefs(); renderBanners(); toast(t('inb.hidden')) } }, t('inb.keep'))))
3045
+ }
3046
+ function inboundBannerKept() {
3047
+ const old = $('banners').querySelector('[data-key="inb-banner"]')
3048
+ if (!old || old.dataset.leaving || matchMedia('(prefers-reduced-motion: reduce)').matches) return null
3049
+ old.dataset.leaving = '1'
3050
+ old.style.pointerEvents = 'none'
3051
+ old.animate(bannerFrames(old).reverse(), { duration: 180, easing: 'ease-in-out', fill: 'forwards' })
3052
+ setTimeout(renderBanners, 180)
3053
+ return old
3054
+ }
3055
+ // From nothing to the banner's measured height, padding, border and margin, so nothing below it jumps.
3056
+ function bannerFrames(el) {
3057
+ const cs = getComputedStyle(el)
3058
+ const full = { height: el.offsetHeight + 'px', paddingTop: cs.paddingTop, paddingBottom: cs.paddingBottom, marginTop: cs.marginTop, marginBottom: cs.marginBottom, borderTopWidth: cs.borderTopWidth, borderBottomWidth: cs.borderBottomWidth, opacity: 1, boxSizing: 'border-box', overflow: 'hidden' }
3059
+ const none = { ...full, height: '0px', paddingTop: '0px', paddingBottom: '0px', marginTop: '0px', marginBottom: '0px', borderTopWidth: '0px', borderBottomWidth: '0px', opacity: 0 }
3060
+ return [none, full]
3061
+ }
3062
+ function growInboundBanner() {
3063
+ const el = $('banners').querySelector('[data-key="inb-banner"]:not([data-leaving])')
3064
+ if (el === ib.bannerEl) return
3065
+ // A banner already there when the page opened just shows; one that arrives later grows in.
3066
+ if (el && ib.bannerEl !== undefined && !matchMedia('(prefers-reduced-motion: reduce)').matches)
3067
+ el.animate(bannerFrames(el), { duration: 180, easing: 'ease-out' })
3068
+ ib.bannerEl = el
3069
+ }
3070
+ // Opens at its final size: the files are read first when they are not in yet.
3071
+ async function openInbound() {
3072
+ if (!ib.data) await loadInbound()
3073
+ showDialog('inbound')
3074
+ renderInbound()
3075
+ if (Date.now() - ib.at >= 5000) loadInbound()
3076
+ }
3077
+ function inboundChip(g) {
3078
+ if (g.state === 'accept') return ['ok', 'inb.state.accept']
3079
+ if (g.state === 'hold') return ['warn', 'inb.state.hold']
3080
+ if (g.state === 'default') return g.waits ? ['warn', 'inb.state.defaultWaits'] : ['', 'inb.state.default']
3081
+ if (g.state === 'refuse') return ['', 'inb.state.refuse']
3082
+ return ['fail', 'inb.state.cannot']
3083
+ }
3084
+ function renderInbound() {
3085
+ const groups = inboundGroups()
3086
+ const todo = inboundTodo()
3087
+ const body = [h('p', { class: 'small' }, t('inb.explain'))]
3088
+ if (!ib.data) body.push(errorNote(ib.error || new Error(t('inb.none')), () => loadInbound()))
3089
+ else if (!groups.length) body.push(h('p', { class: 'muted small' }, t('inb.none')))
3090
+ else {
3091
+ body.push(h('ul', { class: 'rc-list' }, groups.map((g) => {
3092
+ const [tone, key] = inboundChip(g)
3093
+ return h('li', { class: 'rc-row' },
3094
+ h('div', null, h('code', null, g.file), ' ', h('span', { class: 'chip chip-sm' + (tone ? ' chip-' + tone : '') }, t(key))),
3095
+ h('div', { class: 'muted small' }, t('rc.usedBy', { refs: refList(g.accounts.map(shortRef)) })),
3096
+ g.reason ? h('div', { class: 'muted small' }, g.reason) : null,
3097
+ !BOOT.readOnly && todo.includes(g) ? h('div', { class: 'small rc-change' }, t('inb.change', { from: g.state === 'hold' ? '"hold"' : t('inb.notSet') })) : null)
3098
+ })))
3099
+ if (BOOT.readOnly) body.push(h('p', { class: 'small' }, t('inb.readOnly')))
3100
+ else if (todo.length) body.push(h('p', { class: 'small muted' }, t('inb.confirmNote')))
3101
+ else if (groups.every((g) => g.state === 'accept')) body.push(h('p', { class: 'small muted' }, t('inb.allSet')))
3102
+ }
3103
+ const foot = [h('button', { class: 'btn', type: 'button', disabled: ib.busy, onclick: () => dlg.el.close() }, t('btn.close'))]
3104
+ if (!BOOT.readOnly && groups.some((g) => g.undo)) foot.push(h('button', { class: 'btn', type: 'button', disabled: ib.busy, onclick: inboundUndo }, t('inb.undo')))
3105
+ if (!BOOT.readOnly && todo.length) foot.push(h('button', { class: 'btn btn-primary', type: 'button', disabled: ib.busy, 'aria-busy': ib.busy ? 'true' : null, onclick: inboundAccept }, ib.busy ? spinner() : null, t('inb.accept')))
3106
+ setKids(dlg.el, dialogFrame(t('inb.title'), null, body, foot))
3107
+ }
3108
+ function inboundBusy(v) {
3109
+ ib.busy = v
3110
+ if (dlg.kind === 'inbound' && dlg.el && dlg.el.open) renderInbound()
3111
+ }
3112
+ async function inboundAccept() {
3113
+ inboundBusy(true)
3114
+ try {
3115
+ const r = await api('/api/messages/inbound/accept', {})
3116
+ if (r.ok) {
3117
+ if (dlg.kind === 'inbound' && dlg.el.open) dlg.el.close()
3118
+ toast(t('inb.done'), { kind: 'ok', key: 'inb', action: { label: t('toast.undo'), run: inboundUndo }, duration: 12000 })
3119
+ } else toast(t('inb.failed', { msg: r.message }), { kind: 'fail' })
3120
+ } catch (e) { toast(t('inb.failed', { msg: e.message }), { kind: 'fail' }) }
3121
+ inboundBusy(false)
3122
+ await loadInbound()
3123
+ }
3124
+ async function inboundUndo() {
3125
+ inboundBusy(true)
3126
+ try {
3127
+ const r = await api('/api/messages/inbound/undo', {})
3128
+ if (r.ok && dlg.kind === 'inbound' && dlg.el.open) dlg.el.close()
3129
+ toast(r.ok ? t('inb.undone') : r.message, { kind: r.ok ? 'ok' : 'fail', key: 'inb' })
3130
+ } catch (e) { toast(t('toast.undoFailed', { msg: e.message }), { kind: 'fail' }) }
3131
+ inboundBusy(false)
3132
+ await loadInbound()
3133
+ }
3134
+ // ---------- message notices (spec §3.32) ----------
3135
+ // A Message that reaches a Session, is read there, or waits for a paste shows as a toast on every page, with "Show"
3136
+ // leading to the Sessions page. The Sessions list reads the Messages with every refresh; any other page reads them
3137
+ // every MSG_MS while it shows. The first answer is only the baseline, so opening the Panel announces nothing old.
3138
+ const MSG_MS = 10000
3139
+ // "asked" numbers each reading and "applied" is the newest one used, so an answer that comes back late never
3140
+ // replaces a newer one; "own" holds the ids this Panel sent, never announced.
3141
+ const mn = { base: null, at: 0, loading: false, asked: 0, applied: 0, own: new Set() }
3142
+ // Running Sessions whose latest Message waits for a paste, for the count on the Sessions tab.
3143
+ function pasteCount() {
3144
+ if (!sp.data) return 0
3145
+ return sp.data.sessions.filter((s) => sp.msgs[s.sessionId] && sp.msgs[s.sessionId].status === 'paste-needed').length
3146
+ }
3147
+ function noteMessages(latest, seq) {
3148
+ if (seq < mn.applied) return
3149
+ mn.applied = seq
3150
+ const news = messageNews(mn.base, latest)
3151
+ const count = pasteCount()
3152
+ mn.base = latest
3153
+ mn.at = Date.now()
3154
+ sp.msgs = latest
3155
+ if (pasteCount() !== count) renderPageChrome()
3156
+ sendSeen()
3157
+ // The send dialog already says what happened to the Message it shows.
3158
+ const shown = sd && sd.result && dlg.kind === 'send' && dlg.el && dlg.el.open ? sd.result.message.id : null
3159
+ for (const n of news) {
3160
+ if (n.id === shown || (n.kind === 'new' && mn.own.has(n.id))) continue
3161
+ if (n.kind === 'approve') {
3162
+ // Held until the user approves it in that terminal; the way out is to receive directly from now on.
3163
+ toast(t('msgn.approve', { to: n.to || t('msgn.aSession') }), { kind: 'info', key: 'msg-' + n.sessionId, keep: true, duration: 12000, action: BOOT.readOnly ? null : { label: t('inb.go'), run: openInbound } })
3164
+ continue
3165
+ }
3166
+ const key = n.kind === 'read' ? 'msgn.read' : n.kind === 'paste' ? 'msgn.paste' : n.from ? 'msgn.newFrom' : 'msgn.new'
3167
+ const there = curPage === 'sessions' && hs.mode !== 'history'
3168
+ const line = n.kind === 'paste' ? latest[n.sessionId].pasteText : null
3169
+ toast(t(key, { to: n.to || t('msgn.aSession'), from: n.from }), {
3170
+ kind: n.kind === 'read' ? 'ok' : n.kind === 'paste' ? 'info' : 'accent',
3171
+ key: 'msg-' + n.sessionId,
3172
+ keep: n.kind === 'paste',
3173
+ // Long enough to reach the button; hovering holds it. A paste waits for the user on every page.
3174
+ duration: there && !line ? 0 : 12000,
3175
+ action: line ? { label: t('send.copyLine'), run: () => copyPasteLine(n.sessionId, line) } : there ? null : { label: t('msgn.show'), run: () => showSession(n.sessionId) },
3176
+ })
3177
+ }
3178
+ }
3179
+ // A browser that refuses the clipboard gets the Session's row instead, with the line selected in its popover.
3180
+ function copyPasteLine(sessionId, line) {
3181
+ navigator.clipboard.writeText(line).then(() => toast(t('toast.copied', { text: line })), () => showSession(sessionId, true))
3182
+ }
3183
+ // "Show": the Sessions page, scrolled to the Session's row, which lights up once. A list still loading is
3184
+ // waited for; "paste" also opens the row's paste popover.
3185
+ function showSession(sessionId, paste) {
3186
+ mn.show = { sessionId, paste: Boolean(paste) }
3187
+ if (curPage === 'sessions') setSessMode('live'); else { hs.mode = 'live'; setPage('sessions') }
3188
+ revealSession()
3189
+ }
3190
+ function revealSession() {
3191
+ const want = mn.show
3192
+ if (!want || curPage !== 'sessions' || hs.mode === 'history') return
3193
+ const row = $('sessions-page').querySelector('[data-session="' + CSS.escape(want.sessionId) + '"]')
3194
+ if (!row) { if (sp.data && !sp.loading) mn.show = null; return }
3195
+ mn.show = null
3196
+ row.scrollIntoView({ block: 'center', behavior: REDUCED ? 'auto' : 'smooth' })
3197
+ row.classList.remove('flash')
3198
+ void row.offsetWidth
3199
+ row.classList.add('flash')
3200
+ const chip = want.paste ? row.querySelector('.sess-msg-paste') : null
3201
+ if (chip) chip.click()
3202
+ }
3203
+ // A Message this Panel sent is known before the next reading, so it is not announced as a new one.
3204
+ function ownMessage(sessionId, m) {
3205
+ mn.own.add(m.id)
3206
+ const count = pasteCount()
3207
+ sp.msgs = Object.assign({}, sp.msgs, { [sessionId]: m })
3208
+ if (pasteCount() !== count) renderPageChrome()
3209
+ if (mn.base) mn.base = Object.assign({}, mn.base, { [sessionId]: m })
3210
+ }
3211
+ function messagesTick() {
3212
+ if (document.visibilityState !== 'visible' || !S.state || conn.lost || mn.loading || Date.now() - mn.at < MSG_MS) return
3213
+ // The Sessions list reads them itself.
3214
+ if (curPage === 'sessions' && hs.mode !== 'history' && !$('sessions-page').hidden) return
3215
+ mn.loading = true
3216
+ const seq = ++mn.asked
3217
+ api('/api/sessions/messages', {})
3218
+ .then((r) => { if (r && r.latest) noteMessages(r.latest, seq) })
3219
+ .catch(() => {})
3220
+ .finally(() => { mn.loading = false; mn.at = Date.now() })
3221
+ }
3222
+ function sessionsMenuOpen() { return Boolean(menu.el && menu.anchor && $('sessions-page').contains(menu.returnTo || menu.anchor)) }
3223
+ function sessAgeText(s) {
3224
+ const a = sessionAge(s, Date.now())
3225
+ return a ? t(a.key, { n: a.n }) : ''
3226
+ }
3227
+ function renderSessionAges() {
3228
+ if (!sp.data || $('sessions-page').hidden) return
3229
+ const byId = {}
3230
+ for (const s of sp.data.sessions) byId[s.sessionId] = s
3231
+ for (const el of $('sessions-page').querySelectorAll('[data-age]')) {
3232
+ const s = byId[el.getAttribute('data-age')]
3233
+ const text = s ? sessAgeText(s) : ''
3234
+ if (el.textContent !== text) el.textContent = text
3235
+ }
3236
+ }
3237
+ // Copies, then says so where the click was; a browser that refuses gets the text selected in a popover to copy by hand.
3238
+ async function sessCopy(anchor, text, done) {
3239
+ let ok = true
3240
+ try { await navigator.clipboard.writeText(text) } catch {
3241
+ const ta = h('textarea', { css: { position: 'fixed', opacity: '0' } })
3242
+ ta.value = text
3243
+ document.body.append(ta)
3244
+ ta.select()
3245
+ try { ok = document.execCommand('copy') } catch { ok = false }
3246
+ ta.remove()
3247
+ }
3248
+ if (ok) { done(); return }
3249
+ const keys = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent) ? '⌘C' : 'Ctrl+C'
3250
+ openPopover(anchor, 'sess-copy', t('spage.copyFailTitle'), () => {
3251
+ const area = h('textarea', { class: 'sess-copy-text mono', readonly: true, rows: '4', 'aria-label': t('spage.copyFailTitle') })
3252
+ area.value = text
3253
+ setTimeout(() => { if (area.isConnected) { area.focus(); area.select() } }, 0)
3254
+ return [h('p', { class: 'small' }, t('spage.copyFail', { keys })), area]
3255
+ })
3256
+ }
3257
+ function copyForAi(btn, s) {
3258
+ sessCopy(btn, s.copy.reference, () => {
3259
+ sp.copied[s.sessionId] = Date.now() + 2000
3260
+ btn.classList.add('is-copied')
3261
+ btn.replaceChildren(icon('check'), h('span', null, t('spage.copied')))
3262
+ toast(t('spage.copiedToast'), { key: 'sess-copy' })
3263
+ // The row may have been drawn again meanwhile: put back whichever button stands for this Session now.
3264
+ setTimeout(() => {
3265
+ delete sp.copied[s.sessionId]
3266
+ const now = document.querySelector('[data-key="sess-copy-' + s.sessionId + '"]')
3267
+ if (!now) return
3268
+ now.classList.remove('is-copied')
3269
+ now.replaceChildren(icon('copy'), h('span', null, t('spage.copyAi')))
3270
+ }, 2000)
3271
+ })
3272
+ }
3273
+ // Orca brings the tab forward itself; only a refusal needs words here.
3274
+ async function jumpToOrca(s) {
3275
+ try { await api('/api/sessions/orca', { sessionId: s.sessionId }) } catch (e) {
3276
+ toast(e.message, { kind: 'fail' })
3277
+ loadSessions()
3278
+ }
3279
+ }
3280
+ // The Run an orchestrator ties the Session to (spec §3.32 step 2b). A page cannot open a file:// board, so the
3281
+ // server opens it: the page sends only the Session id. Opening starts a program, so a read-only Panel hides it.
3282
+ async function openRunBoard(s) {
3283
+ try { await api('/api/sessions/run', { sessionId: s.sessionId }) } catch (e) {
3284
+ toast(e.message, { kind: 'fail' })
3285
+ loadSessions()
3286
+ }
3287
+ }
3288
+ function runChip(s) {
3289
+ const run = s.run
3290
+ if (!run || !run.title || BOOT.readOnly) return null
3291
+ const others = run.others || []
3292
+ const tip = [run.laneTitle ? t('spage.runTipLane', { lane: run.laneTitle }) : t('spage.runTip')]
3293
+ if (others.length) tip.push(t('spage.runOthers', { runs: others.map((o) => o.title + (o.laneTitle ? ' · ' + o.laneTitle : '')).join('; ') }))
3294
+ return h('button', { class: 'chip chip-btn chip-accent sess-run', type: 'button', 'data-key': 'sess-run-' + s.sessionId, 'data-tip': tip.join(' '), onclick: () => openRunBoard(s) },
3295
+ h('span', { class: 'sess-run-title' }, t('spage.run', { title: run.title })),
3296
+ others.length ? h('span', { class: 'sess-run-more' }, '+' + others.length) : null)
3297
+ }
3298
+ function sessionRow(s) {
3299
+ const p = sessionLabelParts(s)
3300
+ const copied = (sp.copied[s.sessionId] || 0) > Date.now()
3301
+ const status = ['needs-you', 'busy', 'idle'].includes(s.status) ? s.status : 'unknown'
3302
+ const more = h('button', { class: 'icon-btn more', type: 'button', 'aria-haspopup': 'menu', 'aria-expanded': 'false', 'data-key': 'sess-more-' + s.sessionId, 'aria-label': t('spage.more', { label: s.label || p.account }), 'data-tip': t('menu.title') }, icon('more'))
3303
+ const liveMenu = (a) => openMenu(a, [
3304
+ s.orca && !BOOT.readOnly ? { icon: 'link', label: t('spage.jump'), run: () => jumpToOrca(s) } : null,
3305
+ s.orca && !BOOT.readOnly ? '-' : null,
3306
+ { icon: 'copy', label: t('spage.copyAi'), run: () => copyForAi(copyBtn, s) },
3307
+ BOOT.readOnly ? null : { icon: 'send', label: t('spage.send'), run: () => openSend(s) },
3308
+ '-',
3309
+ { icon: 'copy', label: t('spage.copyId'), hint: p.id, run: () => sessCopy(more, s.copy.id, () => toast(t('toast.copied', { text: p.id }))) },
3310
+ { icon: 'terminal', label: t('spage.copyResume'), run: () => sessCopy(more, s.copy.resume, () => toast(t('toast.copied', { text: s.copy.resume }))) },
3311
+ ], t('spage.more', { label: s.label || p.account }))
3312
+ more.addEventListener('click', () => liveMenu(more))
3313
+ const copyBtn = h('button', { class: 'btn btn-sm btn-primary sess-copy' + (copied ? ' is-copied' : ''), type: 'button', 'data-key': 'sess-copy-' + s.sessionId },
3314
+ icon(copied ? 'check' : 'copy'), h('span', null, t(copied ? 'spage.copied' : 'spage.copyAi')))
3315
+ copyBtn.addEventListener('click', () => copyForAi(copyBtn, s))
3316
+ const sendBtn = BOOT.readOnly ? null : h('button', { class: 'btn btn-sm sess-send', type: 'button', 'data-key': 'sess-send-' + s.sessionId, 'aria-label': t('spage.sendTo', { label: s.label || p.account }), onclick: () => openSend(s) }, icon('send'), h('span', null, t('spage.send')))
3317
+ const msg = sp.msgs[s.sessionId]
3318
+ const chip = messageChip(msg && msg.status, msg && msg.needsApproval)
3319
+ const cwd = shortCwd(s.cwd)
3320
+ return withMenu(h('div', { class: 'sess-row sess-' + status, 'data-enter': s.sessionId, 'data-session': s.sessionId },
3321
+ badge(s.family, 'sm'),
3322
+ h('div', { class: 'sess-main' },
3323
+ h('div', { class: 'sess-label' },
3324
+ h('b', null, p.account),
3325
+ p.title ? h('span', { class: 'sess-title' }, p.title) : null,
3326
+ h('span', { class: 'mono sess-id' }, p.id)),
3327
+ h('div', { class: 'sess-sub muted small' },
3328
+ h('span', { class: 'sess-status' }, h('span', { class: 'dot sess-dot', 'aria-hidden': 'true' }), t('spage.status.' + status)),
3329
+ chip ? msgChip(chip, msg, s) : null,
3330
+ s.guessed ? h('span', { class: 'chip sess-guessed', tabindex: '0', 'data-tip': t('spage.guessedTip') }, t('spage.guessed')) : null,
3331
+ runChip(s),
3332
+ h('span', { class: 'sess-cwd' + (cwd ? ' mono' : ''), title: s.cwd && cwd !== s.cwd ? s.cwd : null }, cwd || t('spage.noCwd')),
3333
+ h('span', { class: 'sess-age', 'data-age': s.sessionId }, sessAgeText(s)))),
3334
+ h('div', { class: 'sess-actions' }, copyBtn, sendBtn, more)), liveMenu)
3335
+ }
3336
+ // The latest Message's state on a row. One that waits for a paste opens what to paste and why, so the line is never
3337
+ // only in the dialog that sent it.
3338
+ function msgChip(chip, msg, s) {
3339
+ const cls = 'chip chip-sm chip-' + chip.tone + ' sess-msg'
3340
+ // Waiting for approval: why, and the way to receive the next ones directly (ADR-0045).
3341
+ if (chip.key === 'send.chip.approve') {
3342
+ const btn = h('button', { class: cls + ' sess-msg-paste', type: 'button', 'aria-haspopup': 'dialog', 'data-key': 'sess-msg-' + s.sessionId }, t(chip.key), icon('chevron'))
3343
+ btn.addEventListener('click', () => openPopover(btn, 'sess-paste', t(chip.key), () => {
3344
+ const go = h('button', { class: 'btn btn-sm btn-primary', type: 'button', disabled: BOOT.readOnly }, t('inb.go'))
3345
+ go.addEventListener('click', () => { closeMenu(false); openInbound() })
3346
+ return [msg.note ? h('p', { class: 'small muted' }, msg.note) : null, h('div', { class: 'pop-actions' }, go)]
3347
+ }))
3348
+ return btn
3349
+ }
3350
+ if (chip.tone !== 'warn' || !msg.pasteText) return h('span', { class: cls, tabindex: '0', 'data-tip': t('send.chipTip') }, t(chip.key))
3351
+ const btn = h('button', { class: cls + ' sess-msg-paste', type: 'button', 'aria-haspopup': 'dialog', 'data-key': 'sess-msg-' + s.sessionId }, t(chip.key), icon('chevron'))
3352
+ btn.addEventListener('click', () => openPopover(btn, 'sess-paste', t('send.chip.paste'), () => {
3353
+ const area = h('textarea', { class: 'sess-copy-text mono', readonly: true, rows: '3', 'aria-label': t('send.copyLine') })
3354
+ area.value = msg.pasteText
3355
+ const copy = h('button', { class: 'btn btn-sm btn-primary', type: 'button' }, icon('copy'), h('span', null, t('send.copyLine')))
3356
+ copy.addEventListener('click', () => sessCopy(copy, msg.pasteText, () => { closeMenu(true); toast(t('toast.copied', { text: msg.pasteText })) }))
3357
+ return [msg.note ? h('p', { class: 'small muted' }, msg.note) : null, area, h('div', { class: 'pop-actions' }, copy)]
3358
+ }))
3359
+ return btn
3360
+ }
3361
+ function renderSessionsPage() {
3362
+ const box = $('sessions-page')
3363
+ if (box.hidden) return
3364
+ if (hs.mode === 'history') { renderHistoryPage(); return }
3365
+ // The copy texts come in the Panel's language: a switch reads them again.
3366
+ if (sp.data && sp.lang !== lang && !sp.loading) { loadSessions(); return }
3367
+ const d = sp.data
3368
+ // Rows already on screen keep their places; only a Session that needs the user moves up.
3369
+ const list = d ? steadyOrder(sp.order || [], d.sessions) : []
3370
+ sp.order = list.map((s) => s.sessionId)
3371
+ // Everything a row shows except its age, which renderSessionAges keeps current in place.
3372
+ const shape = JSON.stringify([lang, hs.opening, !d && !sp.error, sp.error ? sp.error.message : '', d ? d.problems : [],
3373
+ list.map((s) => [s.sessionId, s.account, s.accountLabel, s.family, s.title, s.label, s.status, s.cwd, s.guessed, s.copy, Boolean(s.orca), s.run || null, sp.msgs[s.sessionId] ? sp.msgs[s.sessionId].status + (sp.msgs[s.sessionId].needsApproval ? '+approve' : '') : '']), inboundShape()])
3374
+ if (shape === sp.drawn) { sp.pending = false; renderSessionAges(); revealSession(); return }
3375
+ if (sessionsMenuOpen()) { sp.pending = true; return }
3376
+ sp.pending = false
3377
+ sp.drawn = shape
3378
+ // No Refresh of its own: the list renews itself every few seconds, and the header's Refresh reads it too.
3379
+ const kids = [h('div', { class: 'section-head' }, h('h2', { id: 'h-sessions' }, t('spage.title')), modeSeg())]
3380
+ kids.push(h('p', { class: 'muted small' }, t('spage.intro')))
3381
+ if (sp.error) kids.push(errorNote(sp.error, () => loadSessions()))
3382
+ if (!d && !sp.error) kids.push(h('div', { class: 'group-list sess-list', 'aria-busy': 'true' }, [0, 1, 2].map(() => h('div', { class: 'sk-row' }, h('span', { class: 'sk sk-badge' }), h('span', { class: 'sk sk-title' }), h('span', { class: 'sk sk-bar' })))))
3383
+ // With no account yet the way to a session is to add one first.
3384
+ if (d && !list.length && !sp.error) kids.push(h('div', { class: 'empty empty-sm sess-empty' }, S.state && !S.state.accounts.length
3385
+ ? [h('p', null, t('spage.emptyNoAccounts')), BOOT.readOnly ? null : h('button', { class: 'btn btn-primary', type: 'button', onclick: () => openCreate(null) }, icon('plus'), t('empty.create'))]
3386
+ : h('p', null, t('spage.empty'))))
3387
+ if (list.length) kids.push(h('div', { class: 'group-list sess-list', role: 'list' }, list.map((s) => { const r = sessionRow(s); r.setAttribute('role', 'listitem'); return r })))
3388
+ if (d) for (const problem of d.problems) kids.push(h('p', { class: 'note note-warn small' }, t('spage.problem', { problem })))
3389
+ // The example names an Account that is on the list, the one at the top; with none, it asks in general.
3390
+ const example = list.length ? t('spage.askOne', { name: sessionLabelParts(list[0]).account }) : t('spage.askAny')
3391
+ kids.push(h('p', { class: 'muted small sess-ask' }, t('spage.askHint', { example }),
3392
+ inboundGroups().length ? [' ', h('button', { class: 'link-btn small', type: 'button', onclick: openInbound }, t('inb.link'))] : null))
3393
+ swapKids(box, kids)
3394
+ revealSession()
3395
+ }
3396
+ // While the page shows: a new answer every SESS_MS, a held one once its menu closed, and the ages every second.
3397
+ function sessionsTick() {
3398
+ if (curPage !== 'sessions' || $('sessions-page').hidden || document.visibilityState !== 'visible') return
3399
+ if (hs.mode === 'history') { historyTick(); return }
3400
+ if (sp.pending && !sessionsMenuOpen()) renderSessionsPage()
3401
+ else renderSessionAges()
3402
+ if (!sp.loading && !conn.lost && Date.now() - sp.at >= SESS_MS) loadSessions()
3403
+ }
3404
+
3405
+ // ---------- session history (spec §3.33, ADR-0042) ----------
3406
+ // Every past Session of every Account, from the History Index the server builds in the background; read the first
3407
+ // time "History" is picked, which waits on its tab until the first answer is in so the view opens at its final
3408
+ // size. The search box and filters are made once and kept, so typing (and an input method) is never interrupted;
3409
+ // each part under them is drawn again only when what it shows changed. A newer request makes older answers be
3410
+ // ignored. While the index is still being built the list renews every HIST_TICK_MS, then every HIST_IDLE_MS.
3411
+ const HIST_PAGE = 50
3412
+ const HIST_TICK_MS = 2000
3413
+ const HIST_IDLE_MS = 30000
3414
+ const HIST_CLIP = 3000
3415
+ const HIST_KEEP = 500
3416
+ // The filters live in this tab's session storage, so a reload keeps them and a new tab starts clean.
3417
+ const HIST_FILTERS_KEY = 'sideby.historyFilters'
3418
+ function savedHistFilters() { try { return histFilters(JSON.parse(sessionStorage.getItem(HIST_FILTERS_KEY) || 'null')) } catch { return histFilters(null) } }
3419
+ function saveHistFilters() {
3420
+ try { sessionStorage.setItem(HIST_FILTERS_KEY, JSON.stringify({ q: hs.q, since: hs.since, family: hs.family, account: hs.account, project: hs.project, category: hs.category, scripts: hs.scripts })) } catch {}
3421
+ }
3422
+ const hs = Object.assign({ mode: location.hash === '#live' ? 'live' : 'history', opening: false, group: prefs.histGroup || 'project', cats: null, tools: false,
3423
+ data: null, error: null, loading: false, more: false, moreFailed: false, seq: 0, at: 0, projects: null, projError: null, projSeq: 0, tool: null, els: null, srcOpen: false, debounce: 0, clearing: false }, savedHistFilters())
3424
+ function histWords() { return hs.q.split(/\s+/).filter(Boolean) }
3425
+ function histParams(extra) {
3426
+ return Object.assign({ q: hs.q, since: hs.since, family: hs.family, account: hs.account || undefined, project: hs.project, category: hs.category || undefined, scripts: hs.scripts, lang }, extra || {})
3427
+ }
3428
+ function histKey() { return JSON.stringify([hs.q, hs.since, hs.family, hs.account, hs.project, hs.category, hs.scripts]) }
3429
+ // The grouping the list is asked for: one picked Project needs no project headers, and the categories only
3430
+ // group when a plugin gives them (a category picked on the side is grouped by its Projects).
3431
+ function histGroupNow() {
3432
+ const g = hs.group
3433
+ if (g === 'category') return hs.category || !hs.cats ? 'project' : 'category'
3434
+ if (g === 'project' && hs.project) return 'none'
3435
+ if ((g === 'family' && histFamilies().length < 2) || (g === 'account' && histAccounts().length < 2)) return 'project'
3436
+ return g
3437
+ }
3438
+ function histFamilies() { return S.state ? S.state.families.filter((f) => S.state.accounts.some((a) => a.family === f.id)) : [] }
3439
+ function histAccounts() { return S.state ? S.state.accounts.filter((a) => !hs.family || a.family === hs.family) : [] }
3440
+ function histFold(by) { return prefs.histFold[by] || (prefs.histFold[by] = {}) }
3441
+ function fullWhen(iso) {
3442
+ const d = new Date(iso)
3443
+ return Number.isFinite(d.getTime()) ? d.toLocaleString(locale(), { dateStyle: 'medium', timeStyle: 'short' }) : ''
3444
+ }
3445
+ function whenText(iso) {
3446
+ const w = historyWhen(iso, Date.now())
3447
+ if (!w) return ''
3448
+ if (w.key !== 'time.on') return t(w.key, { n: w.n })
3449
+ const d = new Date(iso)
3450
+ const date = d.toLocaleDateString(locale(), d.getFullYear() === new Date().getFullYear() ? { month: 'short', day: 'numeric' } : { dateStyle: 'medium' })
3451
+ return t(w.key, { date })
3452
+ }
3453
+ // A snippet that only repeats the title (ellipses and spacing aside) adds nothing under it.
3454
+ function sameText(a, b) {
3455
+ const norm = (x) => String(x || '').replace(/…/g, '').replace(/\s+/g, ' ').trim().toLowerCase()
3456
+ return norm(a) === norm(b) || (norm(b).length > 0 && norm(b).startsWith(norm(a)))
3457
+ }
3458
+ function highlighted(text, words) {
3459
+ return words.length ? highlightParts(text, words).map((p) => p.hit ? h('mark', null, p.text) : p.text) : text
3460
+ }
3461
+ // quiet: a renewal the user did not ask for: the list stays as it is (not dimmed, not busy) until the answer.
3462
+ // after: the rows already loaded past an unfolded group, kept when the answer stops short of them (a page has at
3463
+ // most HIST_KEEP rows), so folding or opening a group never drops the groups below it back behind "Show more".
3464
+ // With a key, only once the answer holds all of that group's rows; the rest then follow in the same order.
3465
+ async function loadHistory(more, keep, quiet, after) {
3466
+ if (more && (hs.more || hs.loading || !hs.data)) return
3467
+ const seq = ++hs.seq
3468
+ if (more) hs.more = true
3469
+ else if (quiet) hs.bg = true
3470
+ else hs.loading = true
3471
+ if (!quiet) renderHistoryParts()
3472
+ const offset = more ? hs.data.sessions.length : 0
3473
+ const limit = more ? HIST_PAGE : Math.max(HIST_PAGE, Math.min(HIST_KEEP, keep || 0))
3474
+ try {
3475
+ const by = more ? hs.data._by : histGroupNow()
3476
+ const folded = Object.keys(histFold(by))
3477
+ const r = await api('/api/history', histParams({ offset, limit, group: by, collapsed: by === 'none' || !folded.length ? undefined : folded }))
3478
+ if (seq !== hs.seq) return
3479
+ r._by = by
3480
+ // Sessions that moved up while paging (one was updated) are not shown twice.
3481
+ if (more) {
3482
+ const seen = new Set(hs.data.sessions.map((x) => x.account + '\0' + x.sessionId))
3483
+ r.sessions = hs.data.sessions.concat(r.sessions.filter((x) => !seen.has(x.account + '\0' + x.sessionId)))
3484
+ }
3485
+ if (after && r.groups) {
3486
+ const g = after.key === undefined ? null : r.groups.find((x) => x.key === after.key)
3487
+ if (!g || r.sessions.filter((x) => (x.group || '') === after.key).length >= g.sessions) {
3488
+ const seen = new Set(r.sessions.map((x) => x.account + '\0' + x.sessionId))
3489
+ r.sessions = r.sessions.concat(after.rows.filter((x) => !seen.has(x.account + '\0' + x.sessionId)))
3490
+ }
3491
+ }
3492
+ hs.data = r
3493
+ hs.error = null
3494
+ hs.moreFailed = false
3495
+ } catch (e) {
3496
+ if (seq !== hs.seq) return
3497
+ // A renewal that failed keeps what is shown; the next one tries again.
3498
+ if (quiet) {
3499
+ hs.bg = false
3500
+ hs.at = Date.now()
3501
+ // A group that was opening stays folded, and says why.
3502
+ const opening = hs.data && hs.data.groups ? hs.data.groups.filter((g) => g.opening) : []
3503
+ if (opening.length) {
3504
+ for (const g of opening) { g.opening = false; g.collapsed = true; histFold(hs.data._by)[g.key] = true }
3505
+ savePrefs()
3506
+ toast(e.message, { kind: 'fail' })
3507
+ renderHistoryParts()
3508
+ }
3509
+ return
3510
+ }
3511
+ // A page that failed is not asked again by itself: the button at the end tries again.
3512
+ if (more) { hs.moreFailed = true; toast(e.message, { kind: 'fail' }) } else hs.error = e
3513
+ }
3514
+ hs.loading = false
3515
+ hs.more = false
3516
+ hs.bg = false
3517
+ hs.at = Date.now()
3518
+ renderHistoryParts()
3519
+ const grow = hs.growing
3520
+ if (grow && hs.data && hs.data._by === grow.by && !(hs.data.groups || []).some((x) => x.key === grow.key && (x.collapsed || x.opening))) {
3521
+ hs.growing = null
3522
+ growOpened(grow.by, grow.key)
3523
+ }
3524
+ if (!more && !quiet && hs.tools && hs.q && curPage === 'sessions' && hs.mode === 'history') startToolScan()
3525
+ moreIfTailShows()
3526
+ }
3527
+ async function loadProjects() {
3528
+ const seq = ++hs.projSeq
3529
+ try {
3530
+ const r = await api('/api/history/projects', { since: hs.since, family: hs.family, account: hs.account || undefined, scripts: hs.scripts })
3531
+ if (seq !== hs.projSeq) return
3532
+ hs.projects = r.projects.filter((p) => p.project)
3533
+ const had = Boolean(hs.cats)
3534
+ hs.cats = r.categories || null
3535
+ hs.projError = null
3536
+ // A grouping that waited for the categories asks again once it knows whether there are any.
3537
+ if (had !== Boolean(hs.cats) && hs.group === 'category' && hs.data && hs.data._by !== histGroupNow()) historyChanged(false)
3538
+ } catch (e) { if (seq === hs.projSeq) hs.projError = e }
3539
+ renderHistorySide()
3540
+ }
3541
+ // A filter changed: the list starts again from the top; the projects only follow the filters they depend on.
3542
+ function historyChanged(projectsToo) {
3543
+ stopToolScan()
3544
+ // The next answer replaces the whole list: it fades in at its own height instead of each row growing in.
3545
+ hs.swap = true
3546
+ saveHistFilters()
3547
+ loadHistory()
3548
+ if (projectsToo) loadProjects()
3549
+ if (hs.els) hs.els.main.scrollTop = 0
3550
+ }
3551
+
3552
+ // "Also search tool output" (ADR-0042): the server reads the session files at that moment and keeps nothing.
3553
+ // One scan at a time; a change of words or filters stops it, and so does leaving History.
3554
+ async function startToolScan() {
3555
+ const key = histKey()
3556
+ if (hs.tool && hs.tool.key === key) return
3557
+ stopToolScan()
3558
+ if (!hs.tools || !hs.q) { renderHistoryParts(); return }
3559
+ const skip = hs.data ? hs.data.sessions.map((s) => s.account + '\u0000' + s.sessionId) : []
3560
+ const tool = { key, job: null, hits: [], done: 0, total: 0, finished: false, error: null, timer: 0 }
3561
+ hs.tool = tool
3562
+ renderHistoryParts()
3563
+ try {
3564
+ const r = await api('/api/history/tools', histParams({ skip }))
3565
+ if (hs.tool !== tool) { api('/api/history/tools', { job: r.job, cancel: true }).catch(() => {}); return }
3566
+ tool.job = r.job
3567
+ pollToolScan(tool)
3568
+ } catch (e) {
3569
+ if (hs.tool !== tool) return
3570
+ tool.error = e
3571
+ tool.finished = true
3572
+ renderHistoryParts()
3573
+ }
3574
+ }
3575
+ async function pollToolScan(tool) {
3576
+ if (hs.tool !== tool) return
3577
+ try {
3578
+ const r = await api('/api/history/tools', { job: tool.job, lang })
3579
+ if (hs.tool !== tool) return
3580
+ tool.hits = r.hits
3581
+ tool.done = r.done
3582
+ tool.total = r.total
3583
+ tool.finished = r.finished
3584
+ if (r.error) tool.error = { message: r.error }
3585
+ } catch (e) {
3586
+ if (hs.tool !== tool) return
3587
+ tool.error = e
3588
+ tool.finished = true
3589
+ }
3590
+ renderHistoryParts()
3591
+ if (curPage !== 'sessions' || hs.mode !== 'history') { stopToolScan(); return }
3592
+ if (!tool.finished) tool.timer = setTimeout(() => pollToolScan(tool), 600)
3593
+ }
3594
+ // Leaving History: answers still on their way are dropped, a typed search waiting to start does not start.
3595
+ function leaveHistory() {
3596
+ stopToolScan()
3597
+ clearTimeout(hs.debounce)
3598
+ if (hs.loading || hs.more || hs.bg) { hs.seq++; hs.loading = false; hs.more = false; hs.bg = false }
3599
+ hs.projSeq++
3600
+ }
3601
+ function stopToolScan() {
3602
+ const tool = hs.tool
3603
+ hs.tool = null
3604
+ if (!tool) return
3605
+ clearTimeout(tool.timer)
3606
+ if (tool.job && !tool.finished) api('/api/history/tools', { job: tool.job, cancel: true }).catch(() => {})
3607
+ }
3608
+
3609
+ // History / Running, at the head of the Sessions page; History is the one it opens on.
3610
+ function modeSeg() {
3611
+ return h('div', { class: 'seg sess-mode', role: 'tablist', 'aria-label': t('hist.modeLabel') }, [['history', t('hist.mode.history')], ['live', t('hist.mode.live')]].map(([id, label]) =>
3612
+ h('button', { class: 'seg-btn', type: 'button', role: 'tab', 'data-key': 'sess-mode-' + id, 'aria-selected': hs.mode === id ? 'true' : 'false', 'aria-busy': id === 'history' && hs.opening ? 'true' : null, onclick: () => setSessMode(id) },
3613
+ id === 'history' && hs.opening ? [spinner(), ' '] : null, label)))
3614
+ }
3615
+ function setSessMode(m) {
3616
+ if (hs.mode === m || hs.opening) return
3617
+ if (m === 'history' && !hs.data && !hs.error) {
3618
+ hs.opening = true
3619
+ sp.drawn = ''
3620
+ renderSessionsPage()
3621
+ Promise.all([loadHistory(), loadProjects()]).finally(() => {
3622
+ hs.opening = false
3623
+ sp.drawn = ''
3624
+ if (curPage === 'sessions') setSessMode('history')
3625
+ else renderSessionsPage()
3626
+ })
3627
+ return
3628
+ }
3629
+ hs.mode = m
3630
+ sp.drawn = ''
3631
+ try { history.replaceState(null, '', '#' + (m === 'live' ? 'live' : 'sessions')) } catch {}
3632
+ if (m === 'live') { leaveHistory(); loadSessions() }
3633
+ renderSessionsPage()
3634
+ if (m === 'history' && hs.els) hs.els.q.focus()
3635
+ }
3636
+
3637
+ // The parts made once: the toolbar, the project list and the places the lists are drawn into.
3638
+ function historyEls() {
3639
+ if (hs.els) return hs.els
3640
+ const e = {}
3641
+ e.q = h('input', { type: 'search', class: 'search-input', autocomplete: 'off', spellcheck: 'false', 'data-key': 'hist-q', value: hs.q || null })
3642
+ e.q.addEventListener('input', () => {
3643
+ clearTimeout(hs.debounce)
3644
+ hs.debounce = setTimeout(() => {
3645
+ const q = e.q.value.trim()
3646
+ if (q === hs.q) return
3647
+ hs.q = q
3648
+ historyChanged(false)
3649
+ }, 150)
3650
+ })
3651
+ e.q.addEventListener('keydown', (ev) => {
3652
+ if (ev.key !== 'Escape') return
3653
+ ev.preventDefault()
3654
+ if (e.q.value) { e.q.value = ''; clearTimeout(hs.debounce); hs.q = ''; historyChanged(false) } else e.q.blur()
3655
+ })
3656
+ e.since = h('select', { class: 'tb-select' })
3657
+ e.since.addEventListener('change', () => { hs.since = e.since.value; historyChanged(true) })
3658
+ e.family = h('select', { class: 'tb-select' })
3659
+ e.family.addEventListener('change', () => {
3660
+ hs.family = e.family.value
3661
+ // An Account of another AI would match nothing: it is dropped before the lists are asked for again.
3662
+ if (hs.account && S.state && !S.state.accounts.some((a) => a.ref === hs.account && (!hs.family || a.family === hs.family))) hs.account = ''
3663
+ relabelHistory(e)
3664
+ historyChanged(true)
3665
+ })
3666
+ e.account = h('select', { class: 'tb-select' })
3667
+ e.account.addEventListener('change', () => { hs.account = e.account.value; historyChanged(true) })
3668
+ e.tools = h('input', { type: 'checkbox' })
3669
+ e.tools.addEventListener('change', () => {
3670
+ hs.tools = e.tools.checked
3671
+ if (hs.tools) startToolScan()
3672
+ else { stopToolScan(); renderHistoryParts() }
3673
+ })
3674
+ e.scripts = h('input', { type: 'checkbox' })
3675
+ e.scripts.addEventListener('change', () => { hs.scripts = e.scripts.checked; historyChanged(true) })
3676
+ e.toolsText = h('span')
3677
+ e.scriptsText = h('span')
3678
+ e.displayText = h('span')
3679
+ e.display = h('button', { class: 'btn btn-sm hist-display', type: 'button', 'aria-haspopup': 'dialog', 'aria-expanded': 'false', 'data-key': 'hist-display' }, icon('sliders'), e.displayText)
3680
+ e.display.addEventListener('click', () => openPopover(e.display, 'hist-display', t('hist.display'), displayKids, 'end'))
3681
+ e.toolsLabel = h('label', { class: 'hist-check', tabindex: null }, e.tools, e.toolsText)
3682
+ e.scriptsLabel = h('label', { class: 'hist-check' }, e.scripts, e.scriptsText)
3683
+ e.search = h('label', { class: 'search hist-search' }, icon('search', 'search-ic'), e.q)
3684
+ e.head = h('div', { class: 'section-head' })
3685
+ e.intro = h('p', { class: 'muted small' })
3686
+ e.side = h('nav', { class: 'hist-side', ondragover: onCatDragOver, ondrop: onCatDrop })
3687
+ e.status = h('div', { class: 'hist-status' })
3688
+ e.list = h('div', { class: 'hist-list' })
3689
+ e.tail = h('div', { class: 'hist-tail' })
3690
+ e.toolBox = h('div', { class: 'hist-toolbox' })
3691
+ e.sources = h('div', { class: 'hist-sources-box' })
3692
+ e.ask = h('p', { class: 'muted small sess-ask' })
3693
+ e.main = h('div', { class: 'hist-main' }, e.status, e.list, e.tail, e.toolBox)
3694
+ e.root = h('div', { class: 'hist' },
3695
+ h('div', { class: 'toolbar hist-bar' }, e.search, h('div', { class: 'tools' }, e.since, e.family, e.account), h('div', { class: 'hist-checks' }, e.toolsLabel, e.scriptsLabel, e.display)),
3696
+ h('div', { class: 'hist-grid' }, e.side, e.main))
3697
+ // The list loads its next page when its end scrolls into view; the button is there for keyboards.
3698
+ if ('IntersectionObserver' in window) new IntersectionObserver((xs) => { if (xs.some((x) => x.isIntersecting)) moreIfTailShows() }, { rootMargin: '200px' }).observe(e.tail)
3699
+ hs.els = e
3700
+ return e
3701
+ }
3702
+ function hasMore() { return Boolean(hs.data && hs.data.sessions.length < hs.data.total) }
3703
+ function moreIfTailShows() {
3704
+ const e = hs.els
3705
+ if (!e || !hasMore() || hs.loading || hs.more || hs.moreFailed || !e.tail.isConnected) return
3706
+ const box = e.main.getBoundingClientRect()
3707
+ const at = e.tail.getBoundingClientRect()
3708
+ if (tailInView(at.top, box.bottom, window.innerHeight || document.documentElement.clientHeight)) loadHistory(true)
3709
+ }
3710
+ // Texts and choices that follow the Panel's language and the accounts there are; set only when they changed.
3711
+ function relabelHistory(e) {
3712
+ const set = (el, k, v) => { if (el.getAttribute(k) !== v) el.setAttribute(k, v) }
3713
+ set(e.q, 'placeholder', t('hist.searchPh'))
3714
+ set(e.q, 'aria-label', t('hist.search'))
3715
+ set(e.since, 'aria-label', t('hist.since'))
3716
+ set(e.family, 'aria-label', t('hist.family'))
3717
+ set(e.toolsLabel, 'data-tip', t('hist.toolsTip'))
3718
+ set(e.scriptsLabel, 'data-tip', t('hist.scriptsTip'))
3719
+ if (e.toolsText.textContent !== t('hist.tools')) e.toolsText.textContent = t('hist.tools')
3720
+ if (e.scriptsText.textContent !== t('hist.scripts')) e.scriptsText.textContent = t('hist.scripts')
3721
+ const shown = t('hist.display') + (hs.group === 'none' ? '' : colon() + groupName(hs.group))
3722
+ if (e.displayText.textContent !== shown) e.displayText.textContent = shown
3723
+ const sinceKey = lang + hs.since
3724
+ if (e.since._k !== sinceKey) {
3725
+ e.since._k = sinceKey
3726
+ e.since.replaceChildren(...['today', '7d', '30d', 'all'].map((v) => h('option', { value: v }, t('hist.since.' + v, { n: parseInt(v, 10) }))))
3727
+ e.since.value = hs.since
3728
+ }
3729
+ const fams = S.state ? S.state.families.filter((f) => S.state.accounts.some((a) => a.family === f.id)) : []
3730
+ const famKey = lang + fams.map((f) => f.id).join(',')
3731
+ if (e.family._k !== famKey) {
3732
+ e.family._k = famKey
3733
+ e.family.replaceChildren(h('option', { value: '' }, t('hist.allFamilies')), ...fams.map((f) => h('option', { value: f.id }, f.title)))
3734
+ if (hs.family && !fams.some((f) => f.id === hs.family)) hs.family = ''
3735
+ e.family.value = hs.family
3736
+ }
3737
+ e.family.hidden = fams.length < 2 && !hs.family
3738
+ set(e.account, 'aria-label', t('hist.account'))
3739
+ const accts = S.state ? S.state.accounts.filter((a) => !hs.family || a.family === hs.family) : []
3740
+ const acctKey = lang + accts.map((a) => a.ref + ' ' + (a.aliases || [])[0]).join(',')
3741
+ if (e.account._k !== acctKey) {
3742
+ e.account._k = acctKey
3743
+ e.account.replaceChildren(h('option', { value: '' }, t('hist.allAccounts')), ...accts.map((a) => h('option', { value: a.ref }, (a.aliases || [])[0] ? a.aliases[0] + ' · ' + a.ref : a.ref)))
3744
+ if (hs.account && !accts.some((a) => a.ref === hs.account)) hs.account = ''
3745
+ e.account.value = hs.account
3746
+ }
3747
+ e.account.hidden = accts.length < 2 && !hs.account
3748
+ e.tools.checked = hs.tools
3749
+ e.scripts.checked = hs.scripts
3750
+ }
3751
+ // Draws el again only when what it shows changed, so a renewal with the same answer redraws nothing.
3752
+ function drawIf(el, key, kids) {
3753
+ if (el._drawn === key) return
3754
+ el._drawn = key
3755
+ swapKids(el, kids())
3756
+ }
3757
+ // drawIf for a long list: groups and rows that did not change stay the same elements, so folding one group or a
3758
+ // quiet renewal does not rebuild thousands of rows; a row that was not there before grows in.
3759
+ function patchIf(el, key, kids) {
3760
+ if (el._drawn === key) return
3761
+ el._drawn = key
3762
+ const shown = el.childNodes.length > 0
3763
+ const before = new Set([...el.querySelectorAll('[data-enter]')].map((x) => x.getAttribute('data-enter')))
3764
+ for (const x of el.querySelectorAll('.enter')) x.classList.remove('enter')
3765
+ for (const x of el.querySelectorAll('.fade-in')) x.classList.remove('fade-in')
3766
+ patch(el, kids())
3767
+ if (!shown || REDUCED) return
3768
+ const fresh = [...el.querySelectorAll('[data-enter]')].filter((x) => !before.has(x.getAttribute('data-enter')))
3769
+ // A few new rows grow in; a batch fades in at once, since many small motions in a row stutter.
3770
+ for (const x of fresh) x.classList.add(fresh.length > 6 ? 'fade-in' : 'enter')
3771
+ }
3772
+ function renderHistoryPage() {
3773
+ const box = $('sessions-page')
3774
+ const e = historyEls()
3775
+ relabelHistory(e)
3776
+ if (!box.contains(e.root)) {
3777
+ setKids(box, [e.head, e.intro, e.root, e.sources, e.ask])
3778
+ e.head._drawn = null
3779
+ }
3780
+ drawIf(e.head, JSON.stringify([lang, hs.mode, hs.opening]), () => [h('h2', { id: 'h-sessions' }, t('spage.title')), modeSeg()])
3781
+ if (e.intro.textContent !== t('hist.intro')) e.intro.textContent = t('hist.intro')
3782
+ const ask = t('spage.askHint', { example: t('hist.askEx') })
3783
+ if (e.ask.textContent !== ask) e.ask.textContent = ask
3784
+ // With no Account there is nothing to search or filter: only the note saying how to start is shown.
3785
+ const none = Boolean(S.state && !S.state.accounts.length)
3786
+ e.root.classList.toggle('hist-none', none)
3787
+ e.ask.hidden = none
3788
+ if (!hs.data && !hs.loading && !hs.error) { hs.swap = true; loadHistory(); loadProjects() }
3789
+ renderHistorySide()
3790
+ renderHistoryParts()
3791
+ }
3792
+ function renderHistorySide() {
3793
+ const e = hs.els
3794
+ if (!e || !e.root.isConnected) return
3795
+ const list = hs.projects
3796
+ const shown = list && list.map((p) => [p.project, p.name, p.sessions, p.gone, p.category])
3797
+ drawIf(e.side, JSON.stringify([lang, hs.project, hs.category, shown, hs.cats, prefs.histCatOrder, hs.projError ? hs.projError.message : '']), () => {
3798
+ const total = list ? list.reduce((n, p) => n + p.sessions, 0) : 0
3799
+ const item = (project, name, count, gone, tip) => h('button', { class: 'hist-proj', type: 'button', 'data-key': 'hist-p-' + project, 'aria-pressed': hs.project === project && !(project === '' && hs.category) ? 'true' : 'false', title: tip || null, onclick: () => pickProject(project) },
3800
+ h('span', { class: 'hist-proj-name' }, name),
3801
+ gone ? h('span', { class: 'hist-proj-gone', 'aria-label': t('hist.gone'), title: t('hist.goneTip') }, icon('folder')) : null,
3802
+ h('span', { class: 'hist-proj-n' }, count === null ? '' : String(count)))
3803
+ if (hs.projError) return [h('h3', { class: 'hist-side-h' }, t('hist.projects')), errorNote(hs.projError, loadProjects)]
3804
+ if (!list) return [h('h3', { class: 'hist-side-h' }, t('hist.projects')), [0, 1, 2, 3].map(() => h('span', { class: 'sk sk-title hist-sk' }))]
3805
+ const proj = (p) => item(p.project, p.name, p.sessions, p.gone, p.project + (p.gone ? ' · ' + t('hist.gone') : ''))
3806
+ const all = item('', t('hist.allProjects'), total)
3807
+ if (!hs.cats) return [h('h3', { class: 'hist-side-h' }, t('hist.projects')), h('div', { class: 'hist-projs' }, all, list.map(proj))]
3808
+ // With a plugin's categories: each category heads its Projects, in the order the user dragged them to, else
3809
+ // of their latest Session; a category heading folds them. Projects without one come last.
3810
+ const cats = new Map()
3811
+ for (const p of list) { const c = p.category || ''; if (!cats.has(c)) cats.set(c, []); cats.get(c).push(p) }
3812
+ const order = categoryOrder([...cats.keys()], prefs.histCatOrder)
3813
+ hs.catNames = order.filter(Boolean)
3814
+ return [h('h3', { class: 'hist-side-h' }, groupName('category')), h('div', { class: 'hist-projs' }, all,
3815
+ order.map((c) => {
3816
+ const ps = cats.get(c)
3817
+ const n = ps.reduce((x, p) => x + p.sessions, 0)
3818
+ const name = c || t('hist.noCategory')
3819
+ const folded = Boolean(prefs.histCatFold[c])
3820
+ const bodyId = 'hcat-' + order.indexOf(c)
3821
+ // The whole heading folds the category, so a click anywhere on it opens or closes its Projects.
3822
+ // A named category also moves: dragged, or with Alt and the arrow keys. Projects without one stay last.
3823
+ const head = h('button', { class: 'hist-proj hist-cat', type: 'button', 'data-key': 'hist-cf-' + c, 'aria-expanded': String(!folded), 'aria-controls': bodyId,
3824
+ 'aria-label': t('group.toggle', { title: name, count: String(n), action: t(folded ? 'hist.unfoldOne' : 'hist.fold') }),
3825
+ draggable: c ? 'true' : null, title: c ? t('hist.catMove') : null,
3826
+ ondragstart: c ? (ev) => {
3827
+ hs.catDrag = { from: hs.catNames.indexOf(c), to: null }
3828
+ ev.dataTransfer.effectAllowed = 'move'
3829
+ try { ev.dataTransfer.setData('text/plain', c) } catch {}
3830
+ requestAnimationFrame(() => grp.classList.add('is-dragging'))
3831
+ } : null,
3832
+ ondragend: c ? () => endCatDrag() : null,
3833
+ onkeydown: c ? (ev) => {
3834
+ const step = { ArrowUp: -1, ArrowDown: 1 }[ev.key]
3835
+ if (!ev.altKey || !step) return
3836
+ ev.preventDefault()
3837
+ const from = hs.catNames.indexOf(c)
3838
+ moveCategory(from, Math.max(0, Math.min(hs.catNames.length - 1, from + step)), c)
3839
+ } : null },
3840
+ icon('chevron', 'chev'), h('span', { class: 'hist-proj-name' }, name), h('span', { class: 'hist-proj-n' }, String(n)))
3841
+ const grp = h('div', { class: 'hist-catgrp' + (folded ? ' is-folded' : ''), role: 'group', 'aria-label': name, 'data-cat': c },
3842
+ h('div', { class: 'hist-cathead' }, head),
3843
+ h('div', { class: 'hist-catbody', id: bodyId }, h('div', { class: 'hist-catps' }, ps.map(proj))))
3844
+ head.addEventListener('click', () => foldCategory(c, grp, head, name, n))
3845
+ return grp
3846
+ }))]
3847
+ })
3848
+ }
3849
+ // Dragging a category over the side list marks where it would land: before the category under the pointer, or after
3850
+ // it past its middle. Projects without a category stay last, so nothing lands after them.
3851
+ function onCatDragOver(ev) {
3852
+ const d = hs.catDrag
3853
+ const grp = d && ev.target.closest && ev.target.closest('.hist-catgrp[data-cat]')
3854
+ if (!grp) return
3855
+ ev.preventDefault()
3856
+ ev.dataTransfer.dropEffect = 'move'
3857
+ const c = grp.getAttribute('data-cat')
3858
+ const r = grp.getBoundingClientRect()
3859
+ const after = c !== '' && ev.clientY > r.top + r.height / 2
3860
+ const at = (c === '' ? hs.catNames.length : hs.catNames.indexOf(c)) + (after ? 1 : 0)
3861
+ clearDropMarks()
3862
+ grp.classList.add(after ? 'drop-after' : 'drop-before')
3863
+ // Dropped after itself means one place earlier once it is taken out.
3864
+ d.to = Math.min(hs.catNames.length - 1, at > d.from ? at - 1 : at)
3865
+ }
3866
+ function onCatDrop(ev) {
3867
+ const d = hs.catDrag
3868
+ if (!d || d.to === null) return
3869
+ ev.preventDefault()
3870
+ endCatDrag()
3871
+ moveCategory(d.from, d.to)
3872
+ }
3873
+ function endCatDrag() {
3874
+ hs.catDrag = null
3875
+ clearDropMarks()
3876
+ for (const el of document.querySelectorAll('.hist-catgrp.is-dragging')) el.classList.remove('is-dragging')
3877
+ }
3878
+ // The new order is kept in this browser, with the other preferences; the focus follows a category moved by keys.
3879
+ function moveCategory(from, to, focus) {
3880
+ if (from < 0 || from === to) return
3881
+ prefs.histCatOrder = reorder(hs.catNames, hs.catNames.map((c) => [c]), from, to).slice(0, HIST_FOLD_MAX)
3882
+ savePrefs()
3883
+ renderHistorySide()
3884
+ const el = focus && hs.els && hs.els.side.querySelector('[data-key="' + CSS.escape('hist-cf-' + focus) + '"]')
3885
+ if (el) el.focus()
3886
+ }
3887
+ // A category in the side list folds in place (CSS eases its height); the list is not drawn again for it.
3888
+ function foldCategory(c, grp, chev, name, n) {
3889
+ const folded = !prefs.histCatFold[c]
3890
+ if (folded) {
3891
+ if (Object.keys(prefs.histCatFold).length >= HIST_FOLD_MAX) delete prefs.histCatFold[Object.keys(prefs.histCatFold)[0]]
3892
+ prefs.histCatFold[c] = true
3893
+ } else delete prefs.histCatFold[c]
3894
+ savePrefs()
3895
+ grp.classList.toggle('is-folded', folded)
3896
+ chev.setAttribute('aria-expanded', String(!folded))
3897
+ chev.setAttribute('aria-label', t('group.toggle', { title: name, count: String(n), action: t(folded ? 'hist.unfoldOne' : 'hist.fold') }))
3898
+ }
3899
+ function pickProject(p) {
3900
+ if (hs.project === p && !hs.category) return
3901
+ hs.project = p
3902
+ hs.category = ''
3903
+ renderHistorySide()
3904
+ historyChanged(false)
3905
+ }
3906
+ // ---------- grouping the list ----------
3907
+ // A "Display" popover by the filters picks how the list is grouped; a group folds from its header and stays
3908
+ // folded in this browser. The server pages through the groups in order and counts folded ones without their rows.
3909
+ function groupName(by) {
3910
+ return by === 'category' && hs.cats && hs.cats.label ? hs.cats.label : t('hist.by.' + by)
3911
+ }
3912
+ function groupChoices() {
3913
+ return HIST_GROUPS.filter((g) => (g !== 'category' || hs.cats) && (g !== 'family' || histFamilies().length > 1) && (g !== 'account' || histAccounts().length > 1))
3914
+ }
3915
+ function displayKids() {
3916
+ const fold = histFold(histGroupNow())
3917
+ const folded = Object.keys(fold).length
3918
+ return [
3919
+ h('b', null, t('hist.groupBy')),
3920
+ h('div', { class: 'hist-opts', role: 'group', 'aria-label': t('hist.groupBy') }, groupChoices().map((g) =>
3921
+ h('button', { class: 'hist-opt', type: 'button', 'aria-pressed': String(hs.group === g), 'data-key': 'hist-by-' + g, onclick: () => setHistGroup(g) },
3922
+ h('span', { class: 'hist-opt-ck', 'aria-hidden': 'true' }, hs.group === g ? icon('check') : null),
3923
+ h('span', null, groupName(g))))),
3924
+ hs.cats ? h('p', { class: 'muted small' }, t('hist.catsFrom', { label: groupName('category'), plugin: hs.cats.from })) : null,
3925
+ folded && histGroupNow() !== 'none' ? h('div', { class: 'popover-actions' }, h('button', { class: 'btn btn-sm', type: 'button', onclick: unfoldAll }, t('hist.unfold', { n: folded }))) : null,
3926
+ ]
3927
+ }
3928
+ function setHistGroup(g) {
3929
+ if (hs.group === g) return
3930
+ hs.group = g
3931
+ prefs.histGroup = g
3932
+ savePrefs()
3933
+ refreshPopover('hist-display')
3934
+ if (hs.els) relabelHistory(hs.els)
3935
+ historyChanged(false)
3936
+ }
3937
+ function unfoldAll() {
3938
+ prefs.histFold[histGroupNow()] = {}
3939
+ savePrefs()
3940
+ refreshPopover('hist-display')
3941
+ historyChanged(false)
3942
+ }
3943
+ function groupTitle(by, g) {
3944
+ if (by === 'day') return t('hist.day.' + g.key, { n: g.key === 'week' ? 7 : 30 })
3945
+ if (!g.key) return t(by === 'project' ? 'hist.noProject' : by === 'category' ? 'hist.noCategory' : 'hist.other')
3946
+ return g.label
3947
+ }
3948
+ // The groups as headers over their rows. A group shows once a row of it is loaded; a folded one shows in its
3949
+ // place among them (or at the end once everything is loaded), so paging never shuffles the headers.
3950
+ function historyGroups(d, words) {
3951
+ const by = d._by
3952
+ const rows = new Map()
3953
+ for (const s of d.sessions) { const k = s.group || ''; if (!rows.has(k)) rows.set(k, []); rows.get(k).push(s) }
3954
+ let last = -1
3955
+ d.groups.forEach((g, i) => { if (rows.has(g.key)) last = i })
3956
+ const all = !hasMore()
3957
+ return d.groups.filter((g, i) => rows.has(g.key) || g.opening || (g.collapsed && (all || i < last))).map((g, i) => {
3958
+ const open = !g.collapsed
3959
+ const title = groupTitle(by, g)
3960
+ const bodyId = 'hg-' + i
3961
+ const list = rows.get(g.key) || []
3962
+ const btn = h('button', { class: 'group-toggle hist-gtoggle', type: 'button', 'data-key': 'hist-g-' + by + '-' + g.key, 'aria-expanded': String(open), 'aria-controls': open && list.length ? bodyId : null,
3963
+ 'aria-label': t('group.toggle', { title, count: String(g.sessions), action: t(open ? 'hist.fold' : 'hist.unfoldOne') }), title: by === 'project' && g.key ? g.key : null },
3964
+ icon('chevron', 'chev'), by === 'family' && g.key ? badge(g.key, 'sm') : null,
3965
+ h('span', { class: 'hist-gtitle' }, title),
3966
+ g.opening ? spinner() : h('span', { class: 'group-count' }, String(g.sessions)))
3967
+ // patch keeps this button across redraws, so the group is looked up when clicked, never kept from this draw.
3968
+ btn.addEventListener('click', () => {
3969
+ const cur = hs.data && hs.data._by === by && hs.data.groups.find((x) => x.key === g.key)
3970
+ if (cur) toggleHistGroup(by, cur, btn)
3971
+ })
3972
+ return h('section', { class: 'hist-group' + (open ? '' : ' is-folded'), 'data-key': 'hg-' + by + '-' + g.key, 'aria-label': title, 'data-patch': '' },
3973
+ h('div', { class: 'hist-ghead', 'data-key': 'hgh' }, btn),
3974
+ open && list.length ? h('div', { class: 'group-list hist-rows', role: 'list', id: bodyId, 'data-key': 'hgr', 'data-patch': '' }, list.map((s) => historyRow(s, words, by === 'project' || Boolean(hs.project)))) : null)
3975
+ })
3976
+ }
3977
+ // Folding eases the group's rows away and drops them from the list at once; the list is then asked again quietly,
3978
+ // so the next page starts at the right place. Unfolding asks for the group's rows, with a spinner in its header.
3979
+ function toggleHistGroup(by, g, btn) {
3980
+ const d = hs.data
3981
+ if (!d || d._by !== by) return
3982
+ const fold = histFold(by)
3983
+ if (g.collapsed) {
3984
+ delete fold[g.key]
3985
+ savePrefs()
3986
+ g.collapsed = false
3987
+ g.opening = true
3988
+ hs.growing = { by, key: g.key }
3989
+ renderHistoryParts()
3990
+ loadHistory(false, d.sessions.length + g.sessions, true, { key: g.key, rows: d.sessions })
3991
+ return
3992
+ }
3993
+ if (Object.keys(fold).length >= HIST_FOLD_MAX) delete fold[Object.keys(fold)[0]]
3994
+ fold[g.key] = true
3995
+ savePrefs()
3996
+ const done = () => {
3997
+ if (hs.data !== d) return
3998
+ d.sessions = d.sessions.filter((s) => (s.group || '') !== g.key)
3999
+ d.total = Math.max(0, d.total - g.sessions)
4000
+ g.collapsed = true
4001
+ renderHistoryParts()
4002
+ loadHistory(false, d.sessions.length, true, { rows: d.sessions })
4003
+ }
4004
+ const sec = btn.closest('.hist-group')
4005
+ const body = sec && sec.querySelector('.hist-rows')
4006
+ const head = sec && sec.querySelector('.hist-ghead')
4007
+ if (!body || !head || !moving()) { done(); return }
4008
+ btn.setAttribute('aria-expanded', 'false')
4009
+ const from = sec.getBoundingClientRect().height
4010
+ const to = head.getBoundingClientRect().height
4011
+ sec.style.overflow = 'hidden'
4012
+ const a = sec.animate([{ height: from + 'px' }, { height: to + 'px' }], { duration: FOLD_MS, easing: EASE, fill: 'forwards' })
4013
+ body.animate([{ opacity: 1 }, { opacity: 0 }], { duration: FOLD_MS * 0.7, easing: 'ease-out', fill: 'forwards' })
4014
+ a.finished.then(() => {
4015
+ body.remove()
4016
+ a.cancel()
4017
+ sec.style.overflow = ''
4018
+ done()
4019
+ }, () => {})
4020
+ }
4021
+ // An opened group grows from its header to its rows once they are drawn, as one motion; its rows do not grow
4022
+ // in one by one (125 small motions stutter).
4023
+ function growOpened(by, key) {
4024
+ const e = hs.els
4025
+ const sec = e && e.list.querySelector('.hist-group[data-key="' + CSS.escape('hg-' + by + '-' + key) + '"]')
4026
+ const body = sec && sec.querySelector('.hist-rows')
4027
+ const head = sec && sec.querySelector('.hist-ghead')
4028
+ if (!body || !head || !moving()) return
4029
+ for (const x of body.querySelectorAll('.enter')) x.classList.remove('enter')
4030
+ const from = head.getBoundingClientRect().height
4031
+ const to = sec.getBoundingClientRect().height
4032
+ sec.style.overflow = 'hidden'
4033
+ const a = sec.animate([{ height: from + 'px' }, { height: to + 'px' }], { duration: FOLD_MS, easing: EASE })
4034
+ body.animate([{ opacity: 0 }, { opacity: 1 }], { duration: FOLD_MS, easing: 'ease-out' })
4035
+ a.finished.then(() => { sec.style.overflow = '' }, () => {})
4036
+ }
4037
+ // One list for the row's "…" button and its right-click menu (spec §3.27), in the order of how often each is used.
4038
+ // at is the row's own "…" button: a right-click menu opens at a point that is gone once the menu closes.
4039
+ function historyItems(at, s) {
4040
+ return [
4041
+ { icon: 'eye', label: t('hist.open'), run: () => openHistoryView(s, at) },
4042
+ { icon: 'terminal', label: t('hist.continue'), run: () => sessCopy(at, s.continueCommand, () => toast(t('hist.copiedContinue'), { key: 'hist-copy' })) },
4043
+ '-',
4044
+ { icon: 'copy', label: t('spage.copyAi'), run: () => sessCopy(at, s.reference, () => toast(t('spage.copiedToast'))) },
4045
+ { icon: 'copy', label: t('spage.copyId'), hint: s.sessionId.slice(0, 8), run: () => sessCopy(at, s.sessionId, () => toast(t('toast.copied', { text: s.sessionId.slice(0, 8) }))) },
4046
+ ]
4047
+ }
4048
+ function historyMenu(anchor, s, at) {
4049
+ openMenu(anchor, historyItems(at || anchor, s), t('hist.more', { title: s.title || t('hist.untitled') }))
4050
+ }
4051
+ // The button itself says it copied; a toast would only repeat it far from where the user looks.
4052
+ function copyContinue(btn, s) {
4053
+ sessCopy(btn, s.continueCommand, () => {
4054
+ toast(t('hist.copiedContinue'), { key: 'hist-copy' })
4055
+ btn.classList.add('is-copied')
4056
+ setKids(btn, [icon('check'), h('span', null, t('spage.copied'))])
4057
+ setTimeout(() => { btn.classList.remove('is-copied'); setKids(btn, [icon('terminal'), h('span', null, t('hist.continueShort'))]) }, 1500)
4058
+ })
4059
+ }
4060
+ // The project name is left out where the group heading or the picked project already says it (noProject).
4061
+ function historyRow(s, words, noProject) {
4062
+ const title = s.title || t('hist.untitled')
4063
+ const k = s.account + '-' + s.sessionId
4064
+ const open = h('button', { class: 'hist-open', type: 'button', tabindex: '-1', 'data-key': 'hist-open-' + k, 'aria-label': t('hist.openLabel', { title }) }, highlighted(title, words))
4065
+ open.addEventListener('click', () => openHistoryView(s, open))
4066
+ const more = h('button', { class: 'icon-btn more', type: 'button', 'aria-haspopup': 'menu', 'aria-expanded': 'false', 'data-key': 'hist-more-' + k, 'aria-label': t('hist.more', { title }), 'data-tip': t('menu.title') }, icon('more'))
4067
+ more.addEventListener('click', () => historyMenu(more, s))
4068
+ const view = h('button', { class: 'btn btn-sm hist-view', type: 'button', 'data-key': 'hist-view-' + k, 'aria-label': t('hist.openLabel', { title }) }, icon('eye'), h('span', null, t('hist.viewShort')))
4069
+ view.addEventListener('click', () => openHistoryView(s, view))
4070
+ const cont = h('button', { class: 'btn btn-sm hist-cont', type: 'button', 'data-key': 'hist-cont-' + k, 'aria-label': t('hist.continueFor', { title }), 'data-tip': t(s.cwdGone ? 'hist.continueGoneTip' : 'hist.continueTip') }, icon('terminal'), h('span', null, t('hist.continueShort')))
4071
+ cont.addEventListener('click', () => copyContinue(cont, s))
4072
+ const row = h('div', { class: 'hist-row' + (s.live ? ' is-live' : ''), role: 'listitem', 'data-key': 'hr-' + k, 'data-sig': sig([s.continueCommand, s.reference, s.cwd, s.updatedAt, Boolean(noProject)]), 'data-enter': 'h-' + k },
4073
+ badge(s.family, 'sm'),
4074
+ h('div', { class: 'hist-body' },
4075
+ h('div', { class: 'hist-line' }, open,
4076
+ s.live ? h('span', { class: 'hist-live', tabindex: '0', 'data-tip': t('hist.liveTip') }, h('span', { class: 'hist-dot', 'aria-hidden': 'true' }), t('hist.live')) : null),
4077
+ h('div', { class: 'hist-meta muted small' }, h('div', { class: 'hist-mi-wrap' }, metaItems([
4078
+ h('b', null, s.accountLabel),
4079
+ s.projectName && !noProject ? h('span', { class: 'hist-pname', title: s.cwd || s.project }, s.projectName) : null,
4080
+ s.cwdGone ? h('span', { class: 'chip chip-sm hist-gone', tabindex: '0', 'data-tip': t('hist.goneTip') }, t('hist.gone')) : null,
4081
+ s.branch ? h('span', { class: 'mono hist-branch' }, s.branch) : null,
4082
+ tn('hist.msgs', s.messages),
4083
+ s.children ? h('span', { class: 'chip chip-sm', tabindex: '0', 'data-tip': t('hist.kidsTip') }, tn('hist.kids', s.children)) : null,
4084
+ s.script ? h('span', { class: 'chip chip-sm' }, t('hist.script')) : null,
4085
+ h('span', { class: 'hist-age', 'data-hage': s.updatedAt, title: fullWhen(s.updatedAt) }, whenText(s.updatedAt)),
4086
+ ]))),
4087
+ s.snippet && !sameText(s.snippet, s.title) ? h('div', { class: 'hist-snip' }, highlighted(s.snippet, words))
4088
+ : s.preview ? h('div', { class: 'hist-snip' }, s.preview) : null),
4089
+ h('div', { class: 'sess-actions' }, view, cont, more))
4090
+ // A click on the row's empty space reads the conversation too; text being selected stays a selection.
4091
+ row.addEventListener('click', (ev) => {
4092
+ if (ev.target.closest('button, a, input, .chip, .hist-live') || String(window.getSelection ? window.getSelection() : '')) return
4093
+ openHistoryView(s, open)
4094
+ })
4095
+ return withMenu(row, (a) => historyMenu(a, s, more))
4096
+ }
4097
+ // Each item carries its own leading dot; the dots of items that start a line fall outside the box and are clipped.
4098
+ function metaItems(parts) {
4099
+ return parts.filter((p) => p !== null && p !== undefined && p !== false && p !== '').map((p) => h('span', { class: 'hist-mi' }, p))
4100
+ }
4101
+ function rowsShape(list) {
4102
+ return list.map((s) => [s.account, s.sessionId, s.title, s.updatedAt, s.messages, s.children, s.live, s.snippet, s.preview, s.projectName, s.cwdGone, s.branch, s.script])
4103
+ }
4104
+ // Everything under the toolbar: the count and index state, the rows, the end of the list, tool output and sources.
4105
+ function renderHistoryParts() {
4106
+ const e = hs.els
4107
+ if (!e || !e.root.isConnected) return
4108
+ // A row's menu stays open: the redraw waits until it closes (historyTick draws it then).
4109
+ if (menu.el && menu.anchor && menu.kind !== 'hist-display' && e.root.contains(menu.returnTo || menu.anchor)) { hs.pending = true; return }
4110
+ hs.pending = false
4111
+ const d = hs.data
4112
+ if (d && d.state !== 'building') hs.indexed = true
4113
+ const words = histWords()
4114
+ e.list.classList.toggle('is-loading', Boolean(hs.loading && d))
4115
+ e.list.classList.toggle('is-long', Boolean(d && d.sessions.length > 60))
4116
+ if (hs.loading && d) { if (!e.list.style.minHeight) e.list.style.minHeight = e.list.offsetHeight + 'px' }
4117
+ else e.list.style.minHeight = ''
4118
+ e.list.setAttribute('aria-busy', hs.loading ? 'true' : 'false')
4119
+ drawIf(e.status, JSON.stringify([lang, d ? [d.sessions.length, d.total, d.state, d.progress, d.problems] : null, hs.error ? hs.error.message : '']), () => {
4120
+ const out = []
4121
+ if (hs.error) out.push(errorNote(hs.error, () => loadHistory()))
4122
+ if (!d) return out
4123
+ if (d.total) out.push(h('p', { class: 'muted small hist-count' }, tn('hist.shown', d.total, { shown: d.sessions.length })))
4124
+ // Only the first build gets the note: a later renewal that reads a few changed files would make the list jump.
4125
+ if (d.state === 'building' && !hs.indexed) out.push(h('p', { class: 'note small hist-building' }, spinner(), ' ', d.progress.total ? t('hist.building', { done: d.progress.done, total: d.progress.total }) : t('hist.buildingStart')))
4126
+ if (d.state === 'off') out.push(h('p', { class: 'note small' }, t('hist.indexOff')))
4127
+ for (const p of d.problems) out.push(h('p', { class: 'note note-warn small' }, p))
4128
+ return out
4129
+ })
4130
+ patchIf(e.list, JSON.stringify([lang, words, d ? rowsShape(d.sessions) : null, d ? [d.total, d.state, d.sources.length, d.sources.reduce((n, x) => n + x.sessions, 0), d._by, d.groups || null, hasMore()] : null, hs.since, hs.tools, hs.project, hs.category, Boolean(hs.error)]), () => {
4131
+ if (!d) return hs.error ? [] : h('div', { class: 'group-list', 'aria-busy': 'true' }, [0, 1, 2, 3, 4].map(() => h('div', { class: 'sk-row' }, h('span', { class: 'sk sk-badge' }), h('span', { class: 'sk sk-title' }), h('span', { class: 'sk sk-bar' }))))
4132
+ const empty = historyEmpty({ q: hs.q, since: hs.since, state: d.state, total: d.total, tools: hs.tools, project: hs.project || hs.category, accounts: d.sources.length, stored: d.sources.reduce((n, x) => n + x.sessions, 0), unreadable: !!hs.family && d.sources.some((x) => x.family === hs.family) && d.sources.filter((x) => x.family === hs.family).every((x) => x.reason === 'unsupported') })
4133
+ // Every match in a folded group: the folded headers are the list.
4134
+ if (empty && !(d.groups && d.groups.length)) return h('div', { class: 'empty empty-sm hist-empty' },
4135
+ h('p', null, t(empty.key, { q: hs.q })),
4136
+ empty.widen || empty.tools || empty.accounts || empty.everywhere ? h('div', { class: 'hist-ways' },
4137
+ empty.everywhere ? h('button', { class: 'btn btn-sm btn-primary', type: 'button', onclick: () => pickProject('') }, t('hist.everywhere')) : null,
4138
+ empty.accounts ? h('button', { class: 'btn btn-sm btn-primary', type: 'button', onclick: () => { location.hash = '' } }, t('hist.goAccounts')) : null,
4139
+ empty.widen ? h('button', { class: 'btn btn-sm', type: 'button', onclick: () => { hs.since = 'all'; e.since.value = 'all'; historyChanged(true) } }, t('hist.widen')) : null,
4140
+ empty.tools ? h('button', { class: 'btn btn-sm', type: 'button', onclick: () => { hs.tools = true; e.tools.checked = true; startToolScan() } }, t('hist.tools')) : null) : null)
4141
+ if (d.groups && d.groups.length) return historyGroups(d, words)
4142
+ return h('div', { class: 'group-list hist-rows', role: 'list', 'data-key': 'hrows', 'data-patch': '' }, d.sessions.map((s) => historyRow(s, words, Boolean(hs.project))))
4143
+ })
4144
+ if (hs.swap && !hs.loading) {
4145
+ hs.swap = false
4146
+ for (const x of e.list.querySelectorAll('.enter')) x.classList.remove('enter')
4147
+ if (!REDUCED) { e.list.classList.remove('swap-in'); void e.list.offsetWidth; e.list.classList.add('swap-in') }
4148
+ }
4149
+ drawIf(e.tail, JSON.stringify([lang, hasMore(), hs.more, hs.moreFailed, d ? d.total : 0, hs.since]), () => {
4150
+ if (!d || !d.total) return []
4151
+ if (hasMore()) return h('button', { class: 'btn btn-sm hist-more', type: 'button', 'data-key': 'hist-more-page', disabled: hs.more, onclick: () => { hs.moreFailed = false; loadHistory(true) } }, hs.more ? [spinner(), ' '] : null, t(hs.moreFailed ? 'hist.retryMore' : 'hist.loadMore'))
4152
+ const older = hs.since !== 'all' ? h('button', { class: 'btn btn-sm hist-more', type: 'button', onclick: () => { hs.since = 'all'; e.since.value = 'all'; historyChanged(true) } }, t('hist.older')) : null
4153
+ return [d.total > HIST_PAGE ? h('p', { class: 'muted small' }, t('hist.end')) : null, older].filter(Boolean)
4154
+ })
4155
+ const tool = hs.tool
4156
+ drawIf(e.toolBox, JSON.stringify([lang, words, tool ? [tool.key, rowsShape(tool.hits), tool.done, tool.total, tool.finished, tool.error ? tool.error.message : ''] : null, hs.tools, Boolean(hs.q)]), () => {
4157
+ if (!hs.tools) return []
4158
+ if (!hs.q) return h('p', { class: 'muted small' }, t('hist.toolsNeedWords'))
4159
+ if (!tool) return []
4160
+ const head = h('div', { class: 'hist-tool-head' },
4161
+ h('h3', null, t('hist.toolsHead')),
4162
+ tool.finished ? h('span', { class: 'muted small' }, tool.total ? tn('hist.toolsDone', tool.total) : '')
4163
+ : h('span', { class: 'muted small hist-tool-prog' }, spinner(), ' ', tool.total ? t('hist.toolsProgress', { done: tool.done, total: tool.total }) : t('hist.toolsStarting')),
4164
+ tool.finished ? null : h('button', { class: 'btn btn-sm', type: 'button', onclick: () => { stopToolScan(); renderHistoryParts() } }, t('hist.toolsStop')))
4165
+ if (tool.finished && !tool.error && !tool.hits.length) return h('p', { class: 'muted small' }, t('hist.toolsNone'))
4166
+ const out = [head]
4167
+ if (tool.error) out.push(errorNote(tool.error, () => { hs.tool = null; startToolScan() }))
4168
+ if (tool.hits.length) out.push(h('div', { class: 'group-list hist-rows', role: 'list' }, tool.hits.map((s) => historyRow(s, words))))
4169
+ else if (tool.finished && !tool.error) out.push(h('p', { class: 'muted small' }, t('hist.toolsNone')))
4170
+ return out
4171
+ })
4172
+ drawIf(e.sources, JSON.stringify([lang, d ? d.sources : null, hs.clearing]), () => {
4173
+ if (!d || !d.sources.length) return []
4174
+ const sessions = d.sources.reduce((n, x) => n + x.sessions, 0)
4175
+ const details = h('details', { class: 'hist-sources', open: hs.srcOpen },
4176
+ h('summary', null, t('hist.sources'), h('span', { class: 'muted' }, ' · ' + t('hist.sourcesSum', { accounts: d.sources.length, sessions }))),
4177
+ h('table', { class: 'hist-src' },
4178
+ h('thead', null, h('tr', null, h('th', null, t('hist.src.account')), h('th', { class: 'num' }, t('hist.src.sessions')), h('th', null, t('hist.src.note')))),
4179
+ h('tbody', null, d.sources.map((x) => h('tr', null,
4180
+ h('td', null, h('span', { class: 'title-logo' }, badge(x.family, 'sm'), x.accountLabel)),
4181
+ h('td', { class: 'num' }, String(x.sessions)),
4182
+ h('td', { class: 'muted' }, [x.failed ? tn('hist.src.failed', x.failed) : null, x.note ? (x.failed ? ' · ' : '') + (x.reason && x.reason !== 'unreadable' ? t('hist.src.' + x.reason) : x.note) : null]))))),
4183
+ BOOT.readOnly ? null : h('p', { class: 'hist-clear' },
4184
+ h('button', { class: 'btn btn-sm', type: 'button', disabled: hs.clearing, 'data-tip': t('hist.clearTip'), onclick: clearHistoryIndex }, hs.clearing ? [spinner(), ' '] : null, t('hist.clear'))))
4185
+ details.addEventListener('toggle', () => { hs.srcOpen = details.open })
4186
+ return details
4187
+ })
4188
+ }
4189
+ async function clearHistoryIndex() {
4190
+ hs.clearing = true
4191
+ renderHistoryParts()
4192
+ try {
4193
+ await api('/api/history/index', { clear: true })
4194
+ toast(t('hist.cleared'))
4195
+ historyChanged(true)
4196
+ } catch (e) { toast(e.message, { kind: 'fail' }) }
4197
+ hs.clearing = false
4198
+ renderHistoryParts()
4199
+ }
4200
+ // While History shows: the ages every second, and a renewal while the index is built, then now and then.
4201
+ function historyTick() {
4202
+ const e = hs.els
4203
+ if (!e || !e.root.isConnected) return
4204
+ for (const el of e.root.querySelectorAll('[data-hage]')) {
4205
+ const text = whenText(el.getAttribute('data-hage'))
4206
+ if (el.textContent !== text) el.textContent = text
4207
+ }
4208
+ if (hs.pending) renderHistoryParts()
4209
+ const d = hs.data
4210
+ if (!d || hs.loading || hs.more || hs.bg || conn.lost) return
4211
+ const every = d.state === 'building' ? HIST_TICK_MS : HIST_IDLE_MS
4212
+ // Deep in a long list, a renewal would cut what is loaded; the filters and the search still start it again.
4213
+ if (Date.now() - hs.at < every || d.sessions.length > HIST_KEEP) return
4214
+ // The project list follows every renewal: a Session coming back into the time range changes its counts
4215
+ // without changing the total. It redraws only when what it shows changed.
4216
+ Promise.resolve(loadHistory(false, d.sessions.length, true)).then(loadProjects)
4217
+ }
4218
+
4219
+ // ---------- reading one past session ----------
4220
+ // Read only. The newest 200 messages first, older ones on request; a run of tool calls is one line. The dialog
4221
+ // opens once the messages are in, at its final size, scrolled to the end.
4222
+ const hv = { data: null, open: {}, loading: false }
4223
+ async function openHistoryView(s, btn) {
4224
+ if (hv.loading) return
4225
+ hv.loading = true
4226
+ if (btn) { btn.setAttribute('aria-busy', 'true'); btn.prepend(spinner()) }
4227
+ try {
4228
+ hv.data = await api('/api/history/show', { id: s.sessionId, account: s.account, lang })
4229
+ } catch (e) {
4230
+ // A record removed since the list was read: say so plainly and drop it from the list.
4231
+ if (e.code === 'session-gone') { toast(t('hist.gonefile'), { kind: 'fail' }); loadHistory(false, hs.data ? hs.data.sessions.length : 0, true) }
4232
+ else toast(e.message, { kind: 'fail' })
4233
+ return
4234
+ } finally {
4235
+ hv.loading = false
4236
+ if (btn) { btn.removeAttribute('aria-busy'); const sp = btn.querySelector('.spin'); if (sp) sp.remove() }
4237
+ }
4238
+ hv.open = {}
4239
+ ensureDialog()
4240
+ renderHistoryView()
4241
+ showDialog('history')
4242
+ const box = dlg.el.querySelector('.hv-msgs')
4243
+ if (box) box.scrollTop = box.scrollHeight
4244
+ }
4245
+ async function historyEarlier(btn) {
4246
+ const d = hv.data
4247
+ if (!d || d.before === undefined || hv.loading) return
4248
+ hv.loading = true
4249
+ btn.disabled = true
4250
+ try {
4251
+ const r = await api('/api/history/show', {
4252
+ id: d.session.sessionId,
4253
+ account: d.session.account,
4254
+ before: d.before,
4255
+ lang,
4256
+ })
4257
+ const box = dlg.el.querySelector('.hv-msgs')
4258
+ const fromEnd = box ? box.scrollHeight - box.scrollTop : 0
4259
+ hv.data = Object.assign({}, r, { messages: r.messages.concat(d.messages) })
4260
+ if (r.before === undefined) delete hv.data.before
4261
+ renderHistoryView()
4262
+ const again = dlg.el.querySelector('.hv-msgs')
4263
+ if (again) again.scrollTop = again.scrollHeight - fromEnd
4264
+ } catch (e) { toast(e.message, { kind: 'fail' }); btn.disabled = false }
4265
+ hv.loading = false
4266
+ }
4267
+ // Markdown in a reply, built as nodes (never as HTML), so a transcript cannot add markup or scripts to the page.
4268
+ function mdSpans(text) {
4269
+ return mdInline(text).map((x) => x.t === 'text' ? x.text
4270
+ : x.t === 'code' ? h('code', null, x.text)
4271
+ : x.t === 'b' ? h('strong', null, mdSpans(x.text))
4272
+ : x.t === 'i' ? h('em', null, mdSpans(x.text))
4273
+ : h('a', { href: x.href, target: '_blank', rel: 'noopener noreferrer' }, x.text))
4274
+ }
4275
+ function mdNodes(text) {
4276
+ const cell = (tag, c, align) => h(tag, { css: align ? { 'text-align': align } : null }, mdSpans(c))
4277
+ return mdBlocks(text).map((b) => {
4278
+ if (b.type === 'code') return h('pre', { class: 'hv-code' }, h('code', null, b.text))
4279
+ if (b.type === 'h') return h('p', { class: 'hv-h' }, mdSpans(b.text))
4280
+ if (b.type === 'quote') return h('blockquote', null, mdSpans(b.text))
4281
+ if (b.type === 'list') return h(b.ordered ? 'ol' : 'ul', null, b.items.map((it) => h('li', null, mdSpans(it))))
4282
+ if (b.type === 'hr') return h('hr', null)
4283
+ if (b.type === 'table') return h('div', { class: 'hv-table' }, h('table', null,
4284
+ h('thead', null, h('tr', null, b.head.map((c, k) => cell('th', c, b.align[k])))),
4285
+ h('tbody', null, b.rows.map((r) => h('tr', null, r.map((c, k) => cell('td', c, b.align[k])))))))
4286
+ return h('p', null, mdSpans(b.text))
4287
+ })
4288
+ }
4289
+ function messageBlock(m) {
4290
+ if (m.role === 'tools') {
4291
+ const names = [...new Set(m.tools)]
4292
+ const shown = names.slice(0, 6).join(', ') + (names.length > 6 ? ', …' : '')
4293
+ return h('div', { class: 'hv-tools muted small' }, icon('terminal'), h('span', null, t('hv.tools', { tools: shown })))
4294
+ }
4295
+ const long = m.text.length > HIST_CLIP && !hv.open[m.n]
4296
+ const show = long ? m.text.slice(0, HIST_CLIP) + '…' : m.text
4297
+ return h('div', { class: 'hv-msg hv-' + m.role },
4298
+ h('div', { class: 'hv-who small' }, h('b', null, m.role === 'user' ? t('hv.you') : t('hv.ai')), m.at ? h('span', { class: 'muted', title: fullWhen(m.at) }, whenText(m.at)) : null),
4299
+ m.role === 'user' ? h('div', { class: 'hv-text' }, show) : h('div', { class: 'hv-text hv-md' }, mdNodes(show)),
4300
+ long ? h('button', { class: 'btn btn-sm btn-ghost hv-all', type: 'button', onclick: () => { hv.open[m.n] = true; const box = dlg.el.querySelector('.hv-msgs'); const top = box ? box.scrollTop : 0; renderHistoryView(); const again = dlg.el.querySelector('.hv-msgs'); if (again) again.scrollTop = top } }, t('hv.showAll')) : null)
4301
+ }
4302
+ function renderHistoryView() {
4303
+ const d = hv.data
4304
+ const s = d.session
4305
+ const msgs = foldToolCalls(d.messages)
4306
+ const earlier = d.before !== undefined ? h('button', { class: 'btn btn-sm hv-earlier', type: 'button' }, t('hv.earlier')) : null
4307
+ if (earlier) earlier.addEventListener('click', () => historyEarlier(earlier))
4308
+ const body = [
4309
+ h('p', { class: 'muted small hv-meta' }, dots([
4310
+ h('b', null, s.accountLabel),
4311
+ s.projectName ? h('span', { title: s.cwd || s.project }, s.projectName) : null,
4312
+ s.cwdGone ? t('hist.gone') : null,
4313
+ s.branch ? h('span', { class: 'mono' }, s.branch) : null,
4314
+ s.model ? h('span', { class: 'mono' }, s.model) : null,
4315
+ tn('hist.msgs', s.messages),
4316
+ h('span', { title: fullWhen(s.updatedAt) }, whenText(s.updatedAt)),
4317
+ ])),
4318
+ h('div', { class: 'hv-msgs', tabindex: '0', 'aria-label': t('hv.messages') },
4319
+ earlier || h('p', { class: 'muted small hv-start' }, t('hv.firstShown')),
4320
+ msgs.length ? msgs.map(messageBlock) : h('p', { class: 'muted' }, t('hv.empty'))),
4321
+ h('p', { class: 'muted small' }, t('hv.readOnly')),
4322
+ ]
4323
+ const ai = h('button', { class: 'btn', type: 'button' }, icon('copy'), h('span', null, t('spage.copyAi')))
4324
+ ai.addEventListener('click', () => sessCopy(ai, s.reference, () => toast(t('spage.copiedToast'))))
4325
+ const cont = h('button', { class: 'btn btn-primary', type: 'button', 'data-tip': t(s.cwdGone ? 'hist.continueGoneTip' : 'hist.continueTip') }, icon('terminal'), h('span', null, t('hist.continue')))
4326
+ cont.addEventListener('click', () => copyContinue(cont, s))
4327
+ setKids(dlg.el, dialogFrame(s.title || t('hist.untitled'), s.family, body, [ai, cont]))
4328
+ }
4329
+
4330
+ // ---------- send to a session (spec §3.32 step 2) ----------
4331
+ // "Send to it": a few words and up to 5 screenshots for one Live Session. The text box is made once per opening and
4332
+ // kept across every redraw of the dialog, so a language switch keeps what is typed; the Sessions list renewing behind
4333
+ // it never touches the dialog. Screenshots upload at once, images only, so a refusal is named right away.
4334
+ let sd = null
4335
+ const MOD_KEY = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent) ? '⌘' : 'Ctrl+'
4336
+ function sendName(s) { const p = sessionLabelParts(s); return p.title ? p.account + ' · ' + p.title : p.account }
4337
+ function openSend(s) {
4338
+ if (BOOT.readOnly) return
4339
+ closeMenu()
4340
+ const text = h('textarea', { id: 'sd-text', class: 'ask-text', rows: '4', maxlength: '8000', placeholder: t('send.ph'), 'aria-label': t('send.textLabel'), 'aria-describedby': 'sd-keys' })
4341
+ text.addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); sendNow() } })
4342
+ text.addEventListener('input', () => { if (sd && sd.empty) { sd.empty = false; renderSend() } })
4343
+ sd = { s, files: [], notes: [], busy: false, empty: false, result: null, error: null, els: { text, files: h('div', { class: 'ask-files-wrap' }) } }
4344
+ showDialog('send')
4345
+ hookDrops()
4346
+ const mine = sd
4347
+ dlg.onClose = () => {
4348
+ mine.files.forEach((f) => { if (f.xhr) f.xhr.abort() })
4349
+ // Screenshots never sent are freed now; the server clears any that are left after a day anyway.
4350
+ const ids = mine.files.filter((f) => f.id && !f.sent).map((f) => f.id)
4351
+ if (ids.length) api('/api/ask/attach/remove', { ids }).catch(() => {})
4352
+ if (sd === mine) sd = null
4353
+ }
4354
+ renderSend()
4355
+ text.focus()
4356
+ }
4357
+ function renderSend() {
4358
+ if (!sd || dlg.kind !== 'send') return
4359
+ const el = dlg.el
4360
+ const name = sendName(sd.s)
4361
+ const focused = document.activeElement === sd.els.text
4362
+ const body = []
4363
+ const foot = []
4364
+ if (sd.result) {
4365
+ body.push(sendResult(name))
4366
+ foot.push(h('button', { class: 'btn', type: 'button', onclick: sendAgain }, t('send.again')))
4367
+ // When a line waits to be pasted, "Copy this line" is the one primary action.
4368
+ const v = sendResultView(sd.result.message, Boolean(sd.result.orca))
4369
+ const paste = ((v.kind === 'paste' || v.kind === 'stored') && v.pasteText) || (v.kind === 'approve' && !BOOT.readOnly)
4370
+ foot.push(h('button', { class: paste ? 'btn' : 'btn btn-primary', type: 'button', onclick: () => el.close() }, t('btn.close')))
4371
+ } else {
4372
+ const uploading = sd.files.some((f) => f.status === 'uploading')
4373
+ body.push(h('p', { class: 'muted small' }, t('send.intro')))
4374
+ body.push(h('div', { class: 'field' }, sd.els.text,
4375
+ sd.empty ? h('p', { class: 'field-error', role: 'status' }, t('send.empty')) : h('p', { class: 'small muted', id: 'sd-keys' }, t('send.keys', { keys: MOD_KEY + 'Enter' }))))
4376
+ body.push(sendAttachField())
4377
+ if (sd.error) body.push(errorNote(sd.error, sd.error.retryable ? sendNow : null))
4378
+ foot.push(h('button', { class: 'btn', type: 'button', disabled: sd.busy, onclick: () => el.close() }, t('btn.cancel')))
4379
+ foot.push(h('button', { class: 'btn btn-primary send-go', type: 'button', disabled: sd.busy, 'aria-busy': sd.busy ? 'true' : null, onclick: sendNow },
4380
+ sd.busy ? spinner() : icon('send'), t(sd.busy ? (uploading ? 'send.waiting' : 'send.sending') : 'send.send')))
4381
+ }
4382
+ setKids(el, dialogFrame(t('send.title', { name }), sd.s.family, body, foot))
4383
+ if (focused) sd.els.text.focus()
4384
+ }
4385
+ function sendAttachField() {
4386
+ const input = h('input', { type: 'file', multiple: true, accept: 'image/png,image/jpeg,image/gif,image/webp', class: 'sr-only', tabindex: '-1', 'aria-hidden': 'true' })
4387
+ input.addEventListener('change', () => { sendAddFiles(Array.from(input.files || [])); input.value = '' })
4388
+ renderSendFiles()
4389
+ return h('div', { class: 'field ask-attach' },
4390
+ h('div', { class: 'ask-attach-row' },
4391
+ h('button', { class: 'btn btn-sm', type: 'button', disabled: sd.busy, onclick: () => input.click() }, icon('image'), t('send.attach')),
4392
+ h('span', { class: 'small muted' }, t('send.attachHint', { keys: MOD_KEY + 'V' })), input),
4393
+ sd.els.files)
4394
+ }
4395
+ function renderSendFiles() {
4396
+ const box = sd && sd.els.files
4397
+ if (!box) return
4398
+ const tiles = sd.files.map((f) => {
4399
+ let face
4400
+ if (f.status === 'uploading') face = h('div', { class: 'ask-file-face' }, spinner())
4401
+ else if (f.status === 'error') face = h('div', { class: 'ask-file-face' }, icon('alert'))
4402
+ else if (f.thumb) face = h('img', { class: 'ask-file-img', src: f.thumb, alt: f.name })
4403
+ else face = h('div', { class: 'ask-file-face' }, icon('image'))
4404
+ return h('li', { class: 'ask-file' + (f.status === 'error' ? ' is-error' : ''), 'data-enter': 'sd-' + f.key },
4405
+ face,
4406
+ h('span', { class: 'ask-file-name small', title: f.name }, f.name),
4407
+ h('span', { class: 'small muted' }, fileSize(f.bytes || f.size)),
4408
+ f.status === 'error' && f.file ? h('button', { class: 'icon-btn ask-file-retry', type: 'button', disabled: sd.busy, 'aria-label': t('send.retry', { name: f.name }), 'data-tip': t('send.retry', { name: f.name }), onclick: () => sendRetryFile(f) }, icon('refresh')) : null,
4409
+ h('button', { class: 'icon-btn ask-file-x', type: 'button', disabled: sd.busy, 'aria-label': t('send.remove', { name: f.name }), onclick: () => sendRemoveFile(f) }, icon('x')))
4410
+ })
4411
+ swapKids(box, [
4412
+ tiles.length ? h('ul', { class: 'ask-files', 'aria-label': t('send.attach') }, tiles) : null,
4413
+ sd.files.filter((f) => f.status === 'error').map((f) => h('p', { class: 'field-error' }, f.error)),
4414
+ sd.notes.map((n) => h('p', { class: 'field-error' }, n)),
4415
+ ])
4416
+ }
4417
+ function sendAddFiles(list) {
4418
+ if (!sd || sd.result || sd.busy || !list.length) return
4419
+ sd.notes = []
4420
+ for (const file of list) {
4421
+ const name = file.name || 'image'
4422
+ // A screenshot whose upload broke still holds its place, as it can go up again.
4423
+ const why = sendFileProblem(file, sd.files.filter((f) => f.status !== 'error' || f.file).length)
4424
+ if (why === 'send.max') { sd.notes.push(t(why, { name })); continue }
4425
+ const f = { key: Math.random().toString(36).slice(2), name, size: file.size, bytes: 0, status: why ? 'error' : 'uploading', id: null, thumb: null, error: why ? t(why, { name }) : '', xhr: null, done: null, sent: false }
4426
+ sd.files.push(f)
4427
+ if (!why) f.done = sendUpload(f, file, sd)
4428
+ }
4429
+ renderSendFiles()
4430
+ }
4431
+ // A screenshot whose upload broke (not one refused for its type or size) can go up again as it is.
4432
+ function sendRetryFile(f) {
4433
+ if (!sd || sd.busy || !f.file) return
4434
+ const file = f.file
4435
+ Object.assign(f, { status: 'uploading', error: '', file: null })
4436
+ if (sd.error && sd.error.blocked) sd.error = null
4437
+ f.done = sendUpload(f, file, sd)
4438
+ renderSend()
4439
+ }
4440
+ function sendRemoveFile(f) {
4441
+ if (f.xhr) f.xhr.abort()
4442
+ if (f.id) api('/api/ask/attach/remove', { ids: [f.id] }).catch(() => {})
4443
+ sd.files = sd.files.filter((x) => x !== f)
4444
+ sd.notes = []
4445
+ // The note that held the send back goes once nothing failed is left.
4446
+ if (sd.error && sd.error.blocked && !sendBlock(sd.files)) { sd.error = null; renderSend() } else renderSendFiles()
4447
+ }
4448
+ async function sendUpload(f, file, mine) {
4449
+ const path = '/api/sessions/attach'
4450
+ let r = await askPost(file, () => {}, (x) => { f.xhr = x }, path)
4451
+ if (r.status === 403 && r.data && r.data.code === 'bad-token') {
4452
+ try { await refreshToken(); r = await askPost(file, () => {}, (x) => { f.xhr = x }, path) } catch {}
4453
+ }
4454
+ f.xhr = null
4455
+ if (r.status === -1 || sd !== mine) return
4456
+ if (r.status === 200 && r.data && r.data.id) {
4457
+ f.id = r.data.id
4458
+ f.bytes = r.data.bytes
4459
+ f.thumb = await thumbnail(file)
4460
+ f.status = 'ready'
4461
+ } else {
4462
+ f.status = 'error'
4463
+ f.error = t(r.status === 413 ? 'send.tooBig' : r.status === 415 ? 'send.notImage' : r.status === 507 ? 'send.full' : 'send.failed', { name: f.name })
4464
+ // Kept for "try again" only when sending the same file again can work.
4465
+ if (r.status !== 413 && r.status !== 415) f.file = file
4466
+ }
4467
+ if (sd === mine && dlg.kind === 'send') renderSendFiles()
4468
+ }
4469
+ async function sendNow() {
4470
+ if (!sd || sd.busy || sd.result) return
4471
+ const mine = sd
4472
+ const text = sd.els.text.value.trim()
4473
+ if (!text && !sd.files.length) { sd.empty = true; renderSend(); sd.els.text.focus(); return }
4474
+ sd.busy = true
4475
+ sd.error = null
4476
+ dlg.busy = true
4477
+ renderSend()
4478
+ try {
4479
+ // A screenshot that already failed stops the send at once; then it waits for the ones still uploading, so the
4480
+ // message carries every one the person added, and checks again.
4481
+ const early = sendBlock(mine.files)
4482
+ if (early) throw Object.assign(new Error(t(early.key, { names: early.names })), { blocked: true })
4483
+ const pending = sd.files.filter((f) => f.status === 'uploading' && f.done).map((f) => f.done)
4484
+ if (pending.length) { await Promise.all(pending); if (sd === mine) renderSend() }
4485
+ // A screenshot that failed stops the send: the text and the failed tiles stay for a retry or a removal.
4486
+ const block = sendBlock(mine.files)
4487
+ if (block) throw Object.assign(new Error(t(block.key, { names: block.names })), { blocked: true })
4488
+ const ready = mine.files.filter((f) => f.status === 'ready')
4489
+ if (!text && !ready.length) throw new Error(t('send.empty'))
4490
+ const r = await api('/api/sessions/send', { sessionId: mine.s.sessionId, text, attachments: ready.map((f) => f.id), lang })
4491
+ ready.forEach((f) => { f.sent = true })
4492
+ mine.result = r
4493
+ ownMessage(mine.s.sessionId, { id: r.message.id, status: r.message.status, sentAt: r.message.sentAt, to: r.message.to, ...(r.message.status === 'paste-needed' ? { pasteText: r.message.pasteText } : {}), ...(r.message.note ? { note: r.message.note } : {}) })
4494
+ renderSessionsPage()
4495
+ } catch (e) { mine.error = e }
4496
+ dlg.busy = false
4497
+ mine.busy = false
4498
+ if (sd === mine) renderSend()
4499
+ }
4500
+ // A newer answer about the Message the dialog shows (it was read) shows there too.
4501
+ function sendSeen() {
4502
+ if (!sd || !sd.result || dlg.kind !== 'send') return
4503
+ const m = sd.result.message
4504
+ const now = sp.msgs[sd.s.sessionId]
4505
+ if (now && now.id === m.id && (now.status !== m.status || Boolean(now.needsApproval) !== Boolean(m.needsApproval))) { m.status = now.status; m.needsApproval = now.needsApproval; m.note = now.note; renderSend() }
4506
+ }
4507
+ function sendResult(name) {
4508
+ const r = sd.result
4509
+ const v = sendResultView(r.message, Boolean(r.orca))
4510
+ const out = []
4511
+ if (v.kind === 'done') out.push(h('div', { class: 'note note-ok', role: 'status' }, icon('tick'), h('span', null, t(v.key, { name }))))
4512
+ else out.push(h('div', { class: 'note' + (v.kind === 'paste' || v.kind === 'approve' ? ' note-warn' : ''), role: 'status' }, h('b', null, t(v.key, { name })), v.reason ? h('span', { class: 'note-line' }, v.reason) : null))
4513
+ if (v.hint) out.push(h('p', { class: 'note note-warn small' }, v.hint))
4514
+ if (v.kind === 'approve' && !BOOT.readOnly)
4515
+ out.push(h('div', { class: 'pop-actions' }, h('button', { class: 'btn btn-sm btn-primary', type: 'button', onclick: openInbound }, t('inb.go'))))
4516
+ if ((v.kind === 'paste' || v.kind === 'stored') && v.pasteText) {
4517
+ const copy = h('button', { class: 'btn btn-sm btn-primary', type: 'button' }, icon('copy'), t('send.copyLine'))
4518
+ copy.addEventListener('click', () => sessCopy(copy, v.pasteText, () => toast(t('send.copied', { name }))))
4519
+ out.push(h('div', { class: 'send-line' }, h('code', { class: 'send-line-text' }, v.pasteText),
4520
+ h('div', { class: 'send-line-actions' }, copy,
4521
+ v.jump ? h('button', { class: 'btn btn-sm', type: 'button', onclick: () => jumpToOrca(sd.s) }, icon('link'), t('send.jump')) : null)))
4522
+ }
4523
+ return out
4524
+ }
4525
+ function sendAgain() {
4526
+ if (!sd) return
4527
+ sd.result = null
4528
+ sd.error = null
4529
+ sd.files = []
4530
+ sd.notes = []
4531
+ sd.els.text.value = ''
4532
+ renderSend()
4533
+ sd.els.text.focus()
4534
+ }
2663
4535
 
2664
4536
  // New account. The form is built once per opening so typing keeps focus; only its derived parts re-render.
2665
4537
  let nf = null
@@ -2867,8 +4739,8 @@ const MAIN = String.raw `
2867
4739
  ? h('div', { class: 'created-head' }, h('span', { class: 'check-icon', 'aria-hidden': 'true' }, '✓'), h('span', null, tx('nf.created', { ref: h('b', { class: 'mono' }, r.account.ref) })))
2868
4740
  : h('div', { class: 'created-head' }, h('span', { class: 'warn-icon', 'aria-hidden': 'true' }, '!'), h('span', null, tx('nf.createdProblems', { ref: h('b', { class: 'mono' }, r.account.ref) }))),
2869
4741
  failed.length || r.hookErrors.length ? h('div', { class: 'note note-warn' },
2870
- failed.map((s) => h('span', { class: 'small' }, s.item + ': ' + (s.message || 'failed'))),
2871
- r.hookErrors.map((e) => h('span', { class: 'small' }, 'plugin ' + e.plugin + ': ' + e.message))) : null,
4742
+ failed.map((s) => h('span', { class: 'small' }, s.item + colon() + (s.message || 'failed'))),
4743
+ r.hookErrors.map((e) => h('span', { class: 'small' }, 'plugin ' + e.plugin + colon() + e.message))) : null,
2872
4744
  r.account.dir ? h('p', { class: 'small' }, h('span', { class: 'muted' }, t('nf.dir') + ' '), h('code', null, r.account.dir)) : null,
2873
4745
  r.alias && r.alias.added ? h('div', { class: 'small created-alias' }, h('span', { class: 'muted' }, t('nf.alias') + ' '), codeCopy(r.alias.name), h('span', { class: 'muted' }, ' ' + t('nf.aliasNewShell'))) : null,
2874
4746
  r.alias && r.alias.added ? shellSetupNote() : null,
@@ -3153,7 +5025,7 @@ const MAIN = String.raw `
3153
5025
  // A value from the last session may differ from what a new session starts with; say both.
3154
5026
  const line = (label, v, key) => {
3155
5027
  if (!v) return null
3156
- const out = label + ': ' + v.value + ' (' + modelFrom(a, v.from) + ')'
5028
+ const out = label + colon() + v.value + ' (' + modelFrom(a, v.from) + ')'
3157
5029
  const host = mi.host && mi.host[key]
3158
5030
  // 'opus' and 'claude-opus-5-5' name the same model: only a real difference is worth a line.
3159
5031
  return v.from === 'last' && host && !v.value.includes(host)
@@ -3166,7 +5038,7 @@ const MAIN = String.raw `
3166
5038
  mi.settable ? t('md.click') : null,
3167
5039
  ].filter(Boolean).join('\n')
3168
5040
  if (!mi.settable) return h('span', { class: 'mono', title }, text)
3169
- return h('button', { class: 'mono model-btn' + (mi.model && mi.model.from === 'sideby' ? ' model-set' : ''), type: 'button', title, 'aria-label': t('menu.model') + ' ' + a.ref + ': ' + text, onclick: (e) => { e.stopPropagation(); openModel(a) } }, text)
5041
+ return h('button', { class: 'mono model-btn' + (mi.model && mi.model.from === 'sideby' ? ' model-set' : ''), type: 'button', title, 'aria-label': t('menu.model') + ' ' + a.ref + colon() + text, onclick: (e) => { e.stopPropagation(); openModel(a) } }, text)
3170
5042
  }
3171
5043
  function mdAccount() { return S.state && S.state.accounts.find((x) => x.ref === md.ref) }
3172
5044
  function openModel(a) {
@@ -3245,8 +5117,8 @@ const MAIN = String.raw `
3245
5117
  const body = [h('p', { class: 'muted small' }, t('md.intro', { ref: a.ref, host }))]
3246
5118
  if (BOOT.readOnly) body.push(h('p', { class: 'note' }, t('banner.readOnly')))
3247
5119
  body.push(h('div', { class: 'md-now' },
3248
- h('div', null, h('span', { class: 'muted' }, t('md.model') + ': '), now('model')),
3249
- h('div', null, h('span', { class: 'muted' }, t('md.effort') + ': '), now('effort'))))
5120
+ h('div', null, h('span', { class: 'muted' }, t('md.model') + colon()), now('model')),
5121
+ h('div', null, h('span', { class: 'muted' }, t('md.effort') + colon()), now('effort'))))
3250
5122
  body.push(h('div', { class: 'ah-grid' },
3251
5123
  h('label', { class: 'field' }, h('span', null, t('md.model')), f.model, f.list),
3252
5124
  h('label', { class: 'field' }, h('span', null, t('md.effort')), f.effort)))
@@ -3268,6 +5140,8 @@ const MAIN = String.raw `
3268
5140
  // still missing. Turning on is one plan shown first (hp.preview) and one confirmation; no commands to copy.
3269
5141
  const hp = { data: null, plan: null, loading: false, error: null, preview: null, previewing: false, applying: false, failed: null, changed: false, sameFamily: false, sameTouched: false, busyOff: false, askSame: false }
3270
5142
  async function loadHandoffPage() {
5143
+ // One read at a time: a second refresh while one runs would end its spinner early.
5144
+ if (hp.loading) return
3271
5145
  hp.loading = true
3272
5146
  hp.error = null
3273
5147
  renderHandoffPage()
@@ -3333,7 +5207,7 @@ const MAIN = String.raw `
3333
5207
  step.diff ? h('details', { class: 'small' }, h('summary', null, t('hp.showChange')), h('p', { class: 'muted small' }, tx('ah.changes', { file: h('code', null, step.file) })), diffView(step.diff)) : null))))
3334
5208
  }
3335
5209
  function hpManual(plan) {
3336
- return plan.manual.map((m) => h('p', { class: 'note' }, m.id === 'codex-trust' ? t('hp.manual.codexTrust') : (family(m.family).title + ': ' + (m.message || ''))))
5210
+ return plan.manual.map((m) => h('p', { class: 'note' }, m.id === 'codex-trust' ? t('hp.manual.codexTrust') : (family(m.family).title + colon() + (m.message || ''))))
3337
5211
  }
3338
5212
  function hpPreviewCard() {
3339
5213
  const p = hp.preview
@@ -3400,7 +5274,7 @@ const MAIN = String.raw `
3400
5274
  h('div', { class: 'row-actions' },
3401
5275
  h('button', { class: 'btn btn-sm', type: 'button', onclick: askHandoff }, icon('bot'), t('ask.title.handoff')),
3402
5276
  h('button', { class: 'btn btn-sm', type: 'button', onclick: openHandoff }, t('hp.advanced')),
3403
- h('button', { class: 'btn btn-sm', type: 'button', disabled: hp.loading, onclick: loadHandoffPage }, hp.loading ? spinner() : icon('refresh'), t('top.refresh'))))]
5277
+ hp.loading ? spinner() : null))]
3404
5278
  const on = st.settings.auto
3405
5279
  if (hp.loading && !hp.data) kids.push(h('p', { class: 'muted' }, spinner(), ' ', t('hp.loading')))
3406
5280
  if (hp.error) kids.push(errorNote(hp.error, loadHandoffPage))
@@ -3526,6 +5400,10 @@ const MAIN = String.raw `
3526
5400
  btn.disabled = false
3527
5401
  }
3528
5402
  load({ check: true, announce: true })
5403
+ // The page in view reads again too, so the pages need no refresh button of their own.
5404
+ if (curPage === 'sessions') loadSessions()
5405
+ else if (curPage === 'tuning') loadTuningPage()
5406
+ else if (curPage === 'handoff') loadHandoffPage()
3529
5407
  }
3530
5408
  function checkOf(fam) { return S.state && (S.state.quotaChecks || []).find((c) => c.family === fam) }
3531
5409
  async function setCheck(fam, on) {
@@ -3557,27 +5435,58 @@ const MAIN = String.raw `
3557
5435
  b.hidden = !secs.length
3558
5436
  const warn = secs.includes('rc') && rcSummary() === 'on'
3559
5437
  setKids(b, [icon('gear'), h('span', { class: 'hide-sm' }, t('set.button')), warn ? h('span', { class: 'dot set-dot', 'aria-hidden': 'true' }) : null])
3560
- b.setAttribute('aria-label', t('set.button') + (warn ? ': ' + t('set.rcOn') : ''))
5438
+ b.setAttribute('aria-label', t('set.button') + (warn ? colon() + t('set.rcOn') : ''))
3561
5439
  refreshSettings()
3562
5440
  if (dlg.kind === 'rc') renderRc()
3563
5441
  }
3564
- // The popover and the full settings dialog show the same groups (spec §3.29), top to bottom: Appearance, Startup,
3565
- // Accounts and quota, Let AI help. leave() closes whichever holds them before a link goes elsewhere; a link that
3566
- // opens a dialog keeps the dialog element open (opens: true), since one dialog element is shared.
3567
- function settingsGroups(leave) {
3568
- const secs = settingsSections()
3569
- const seg = (label, opts, cur, pick) => h('div', { class: 'set-row' }, h('span', { class: 'set-label' }, label),
5442
+ // The settings live in two places (spec §3.29, 2026-10-20). The header popover holds only what people change
5443
+ // often, one click each and no explanations: language, theme, Auto Handoff, asking an AI, and "All settings…".
5444
+ // Everything else is in the settings dialog, one section at a time, picked in a list at its side; each section
5445
+ // explains itself once. leave() closes whichever holds them before a link goes elsewhere; a link that opens a
5446
+ // dialog keeps the dialog element open (opens: true), since one dialog element is shared.
5447
+ function setSeg(label, opts, cur, pick) {
5448
+ return h('div', { class: 'set-row' }, h('span', { class: 'set-label' }, label),
3570
5449
  h('div', { class: 'seg', role: 'group', 'aria-label': label }, opts.map(([v, text]) =>
3571
5450
  h('button', { class: 'seg-btn', type: 'button', 'aria-pressed': String(v === cur), onclick: () => pick(v) }, text))))
3572
- const link = (label, state, cls, run, opens) => h('button', { class: 'menu-item set-link', type: 'button', onclick: () => { leave(opens); run() } },
5451
+ }
5452
+ function setLink(leave, label, state, cls, run, opens, key) {
5453
+ return h('button', { class: 'menu-item set-link', type: 'button', 'data-enter': key || null, onclick: () => { leave(opens); run() } },
3573
5454
  h('span', { class: 'menu-label' }, label), state ? h('span', { class: 'chip chip-sm ' + cls }, state) : null, icon('chevron'))
3574
- const look = []
3575
- if (secs.includes('lang')) look.push(seg(t('set.lang'), [['en', 'English'], ['zh', '中文']], lang, setLang))
3576
- if (secs.includes('theme')) look.push(seg(t('set.theme'), CHOICES.theme.map((v) => [v, t('set.theme.' + v)]), viewPrefs().theme, setTheme))
3577
- const start = [autostartRow('autostart')]
5455
+ }
5456
+ function lookRows() {
5457
+ const secs = settingsSections()
5458
+ const out = []
5459
+ if (secs.includes('lang')) out.push(setSeg(t('set.lang'), [['en', 'English'], ['zh', '中文']], lang, setLang))
5460
+ if (secs.includes('theme')) out.push(setSeg(t('set.theme'), CHOICES.theme.map((v) => [v, t('set.theme.' + v)]), viewPrefs().theme, setTheme))
5461
+ return out
5462
+ }
5463
+ function ahLink(leave) {
5464
+ if (!settingsSections().includes('ah')) return null
5465
+ const on = ahState().settings.auto
5466
+ return setLink(leave, t('ah.button'), on ? t('ah.on') : t('ah.off'), on ? 'chip-ok' : '', () => setPage('handoff'))
5467
+ }
5468
+ function rcLink(leave) {
5469
+ const sum = rcSummary()
5470
+ return setLink(leave, t('rc.button'), t('rc.state.' + sum), sum === 'on' ? 'chip-warn' : sum === 'off' ? 'chip-ok' : '', openRc, true)
5471
+ }
5472
+ function aiLink(leave) {
5473
+ return setLink(leave, t('ai.title'), t(skillInstalled() ? 'ai.installed' : 'ai.notInstalled'), skillInstalled() ? 'chip-ok' : '', () => openAsk(), true)
5474
+ }
5475
+ // The dialog's sections, in order: General, Menu bar, Accounts, Quota checks, Auto Handoff, Let AI help. Each is
5476
+ // { id, title, items, foot }: foot is the one line that explains the whole section.
5477
+ function settingsGroups(leave) {
5478
+ const secs = settingsSections()
5479
+ const link = (...args) => setLink(leave, ...args)
5480
+ const general = [...lookRows(), autostartRow('autostart')]
5481
+ if (!BOOT.readOnly) general.push(link(t('term.title'), '', '', openTerminals, true))
3578
5482
  // The menu bar switch shows only where it works (macOS); while its state loads it waits, unseen.
3579
- if (li.menubar.status && li.menubar.status.supported) start.push(autostartRow('menubar'))
3580
- if (!BOOT.readOnly) start.push(link(t('term.title'), '', '', openTerminals, true))
5483
+ const bar = []
5484
+ if (li.menubar.status && li.menubar.status.supported) {
5485
+ bar.push(autostartRow('menubar'))
5486
+ const mbs = li.menubar.status
5487
+ if ((mbs.state === 'on' || mbs.state === 'stale') && mbs.hotkey)
5488
+ bar.push(link(t('mb.settings'), mbs.hotkey.enabled ? mbs.hotkey.label : t('hk.unset'), mbs.hotkey.registered === false ? 'chip-warn' : '', openMenubarSettings, true, 'mbset'))
5489
+ }
3581
5490
  const acct = []
3582
5491
  // The arrange mode (spec §3.25) has a place here too, where people look for "how do I change this".
3583
5492
  if (secs.includes('order')) {
@@ -3589,71 +5498,72 @@ const MAIN = String.raw `
3589
5498
  if (bar) bar.scrollIntoView({ behavior: REDUCED ? 'auto' : 'smooth', block: 'center' })
3590
5499
  }))
3591
5500
  }
3592
- // Quota checks that ask the Host (spec §3.26): one switch per Family, with what it does in plain words.
5501
+ if (pickFamilies().length) {
5502
+ const names = Object.keys(S.state.pickCommands || {})
5503
+ acct.push(link(t('pk.title'), names.length ? names.join(', ') : t('pk.noneYet'), names.length ? 'chip-ok' : '', () => openPick(null), true))
5504
+ }
5505
+ if (secs.includes('rc')) acct.push(rcLink(leave))
5506
+ // Quota checks that ask the Host (spec §3.26): one switch per Family under one shared explanation.
5507
+ const checks = []
5508
+ let every = 15
3593
5509
  if (secs.includes('checks')) {
3594
5510
  for (const c of S.state.quotaChecks) {
5511
+ every = c.everyMinutes
3595
5512
  const label = t('set.quotaCheck', { host: c.title })
3596
- acct.push(h('div', { class: 'set-row set-check' },
3597
- h('div', { class: 'set-text' }, h('span', { class: 'set-label' }, label), h('span', { class: 'set-hint' }, c.blocked ? c.blocked : t('set.quotaCheckHint', { host: c.title, n: c.everyMinutes }))),
5513
+ checks.push(h('div', { class: 'set-row' + (c.blocked ? ' set-check' : '') },
5514
+ h('div', { class: 'set-text' }, h('span', { class: 'set-label' }, c.title), c.blocked ? h('span', { class: 'set-hint' }, c.blocked) : null),
3598
5515
  BOOT.readOnly ? h('span', { class: 'chip chip-sm' + (c.on ? ' chip-ok' : '') }, c.on ? t('ah.on') : t('ah.off'))
3599
5516
  : h('div', { class: 'seg', role: 'group', 'aria-label': label }, [[true, t('ah.on')], [false, t('ah.off')]].map(([v, text]) =>
3600
5517
  h('button', { class: 'seg-btn', type: 'button', 'aria-pressed': String(v === c.on), onclick: () => { if (v !== c.on) { leave(false); setCheck(c.family, v) } } }, text)))))
3601
5518
  }
3602
5519
  }
3603
- if (pickFamilies().length) {
3604
- const names = Object.keys(S.state.pickCommands || {})
3605
- acct.push(link(t('pk.title'), names.length ? names.join(', ') : t('pk.noneYet'), names.length ? 'chip-ok' : '', () => openPick(null), true))
3606
- }
3607
- if (secs.includes('rc')) {
3608
- const sum = rcSummary()
3609
- acct.push(link(t('rc.button'), t('rc.state.' + sum), sum === 'on' ? 'chip-warn' : sum === 'off' ? 'chip-ok' : '', openRc, true))
3610
- }
3611
- if (secs.includes('ah')) {
3612
- const on = ahState().settings.auto
3613
- acct.push(link(t('ah.button'), on ? t('ah.on') : t('ah.off'), on ? 'chip-ok' : '', () => setPage('handoff')))
3614
- }
3615
5520
  // Everything here can also be asked of an AI assistant through the sideby skill (spec §3.8).
3616
- const ai = [
3617
- link(t('ai.title'), t(skillInstalled() ? 'ai.installed' : 'ai.notInstalled'), skillInstalled() ? 'chip-ok' : '', () => openAsk(), true),
3618
- link(t('ask.plugin'), '', '', () => openAsk({ task: 'plugin', context: { version: BOOT.version } }), true),
3619
- ]
5521
+ const ai = [aiLink(leave), link(t('ask.plugin'), '', '', () => openAsk({ task: 'plugin', context: { version: BOOT.version } }), true)]
3620
5522
  return [
3621
- { title: t('set.g.look'), items: look },
3622
- { title: t('set.g.start'), items: start },
3623
- { title: t('set.g.accounts'), items: acct },
3624
- { title: t('set.g.ai'), items: ai },
5523
+ { id: 'general', title: t('set.g.general'), items: general },
5524
+ { id: 'menubar', title: t('set.g.menubar'), items: bar },
5525
+ { id: 'accounts', title: t('set.g.accounts'), items: acct },
5526
+ { id: 'quota', title: t('set.g.quota'), items: checks, foot: t('set.quotaChecksHint', { n: every }) },
5527
+ { id: 'handoff', title: t('ah.button'), items: [ahLink(leave)].filter(Boolean), foot: t('set.ahHint') },
5528
+ { id: 'ai', title: t('set.g.ai'), items: ai, foot: t('set.aiHint') },
3625
5529
  ].filter((g) => g.items.length)
3626
5530
  }
3627
- function settingsBody(leave) {
3628
- const out = []
3629
- settingsGroups(leave).forEach((g, i) => {
3630
- if (i) out.push(h('div', { class: 'menu-sep set-sep', role: 'separator' }))
3631
- out.push(h('div', { class: 'set-group', role: 'group', 'aria-label': g.title }, h('div', { class: 'set-group-title', 'aria-hidden': 'true' }, g.title), g.items))
3632
- })
3633
- return out
3634
- }
3635
- // Taller than the window, the popover scrolls inside and ends with "More settings…", the same groups in a dialog.
5531
+ // The popover: a few things, no scrolling, then the way to everything else.
3636
5532
  function settingsPop() {
3637
5533
  loadAutostart()
3638
- return [...settingsBody(() => closeMenu()),
3639
- h('button', { class: 'menu-item set-more', type: 'button', hidden: true, onclick: () => { closeMenu(); openSettingsDialog() } }, h('span', { class: 'menu-label' }, t('set.more')), icon('chevron'))]
3640
- }
3641
- function settingsFit() {
3642
- const el = menu.el
3643
- const more = el && el.querySelector('.set-more')
3644
- if (!more) return
3645
- more.hidden = true
3646
- more.hidden = !(el.scrollHeight > el.clientHeight + 1)
5534
+ const leave = () => closeMenu()
5535
+ const look = lookRows()
5536
+ const quick = [ahLink(leave), rcSummary() === 'on' ? rcLink(leave) : null, aiLink(leave)].filter(Boolean)
5537
+ return [
5538
+ look.length ? h('div', { class: 'set-group' }, look) : null,
5539
+ look.length ? h('div', { class: 'menu-sep set-sep', role: 'separator' }) : null,
5540
+ h('div', { class: 'set-group' }, quick),
5541
+ h('button', { class: 'menu-item set-more', type: 'button', onclick: () => { closeMenu(); openSettingsDialog() } }, h('span', { class: 'menu-label' }, t('set.more')), icon('chevron')),
5542
+ ]
3647
5543
  }
3648
- function openSettingsDialog() {
5544
+ function openSettingsDialog(sec) {
3649
5545
  loadAutostart()
5546
+ if (sec) { prefs.setSec = sec; savePrefs() }
3650
5547
  showDialog('settings')
3651
5548
  renderSettingsDialog()
3652
5549
  }
3653
- function renderSettingsDialog() {
5550
+ // The dialog opens on the section last looked at; a list at its side (a row of tabs on a narrow screen) picks another.
5551
+ // switched: the user picked another section, so the new one slides in; a refresh redraws it in place.
5552
+ function renderSettingsDialog(switched) {
3654
5553
  const leave = (opens) => { if (!opens && dlg.kind === 'settings') dlg.el.close() }
3655
- setKids(dlg.el, dialogFrame(t('set.title'), null, h('div', { class: 'set-dialog' }, settingsBody(leave)),
3656
- [h('button', { class: 'btn', type: 'button', onclick: () => dlg.el.close() }, t('btn.close'))]))
5554
+ const groups = settingsGroups(leave)
5555
+ const cur = groups.find((g) => g.id === prefs.setSec) || groups[0]
5556
+ const nav = h('div', { class: 'set-nav', role: 'tablist', 'aria-label': t('set.title') }, groups.map((g) =>
5557
+ h('button', { class: 'set-tab', type: 'button', role: 'tab', id: 'set-tab-' + g.id, 'aria-selected': String(g === cur), 'aria-controls': 'set-pane', onclick: () => { if (prefs.setSec === g.id || g === cur) return; prefs.setSec = g.id; savePrefs(); renderSettingsDialog(true) } }, g.title)))
5558
+ const pane = h('div', { class: 'set-pane' + (switched ? ' view-in' : ''), id: 'set-pane', role: 'tabpanel', 'aria-labelledby': 'set-tab-' + cur.id },
5559
+ h('h3', { class: 'set-pane-title' }, cur.title),
5560
+ cur.foot ? h('p', { class: 'set-foot' }, cur.foot) : null,
5561
+ h('div', { class: 'set-group' }, cur.items))
5562
+ // It stays wide while it fades out; showDialog drops the width when another dialog takes the element.
5563
+ dlg.el.classList.add('dialog-wide')
5564
+ setKids(dlg.el, dialogFrame(t('set.title'), null, h('div', { class: 'set-dialog' }, nav, pane)))
5565
+ // A redraw replaced the list; a section picked from it keeps the focus on its tab.
5566
+ if (switched) { const tab = document.getElementById('set-tab-' + cur.id); if (tab) tab.focus() }
3657
5567
  }
3658
5568
  function refreshSettings() {
3659
5569
  refreshPopover('settings')
@@ -3677,10 +5587,13 @@ const MAIN = String.raw `
3677
5587
  async function loadLoginItem(k) {
3678
5588
  const st = li[k]
3679
5589
  st.loading = true
5590
+ const was = JSON.stringify([st.status, st.error && st.error.message])
3680
5591
  try { st.status = await api('/api/' + k); st.error = null } catch (e) { st.error = e }
3681
5592
  st.loading = false
5593
+ // The same answer again (each open of a dialog reads it anew) redraws nothing: a redraw would close an open list.
5594
+ if (JSON.stringify([st.status, st.error && st.error.message]) === was) return
3682
5595
  refreshSettings()
3683
- if (k === 'menubar') renderAll()
5596
+ if (k === 'menubar') { renderAll(); if (!hk.recording && !hk.busy) refreshHotkey() }
3684
5597
  }
3685
5598
  function autostartRow(k) {
3686
5599
  const st = li[k]
@@ -3688,16 +5601,172 @@ const MAIN = String.raw `
3688
5601
  const n = autostartNote(s, BOOT.readOnly)
3689
5602
  const label = lt(k, 'label')
3690
5603
  const hint = [st.error ? lt(k, 'failed', { msg: st.error.message }) : lt(k, n.key.slice(3))]
3691
- if (n.action === 'fix') hint.push(' ', h('button', { class: 'link-btn small', type: 'button', onclick: () => autostartAsk(true, k) }, lt(k, 'fix')))
5604
+ // The menu bar item: how to bring it back once hidden, and why a running one may not show (Rectangle, Stats).
5605
+ if (k === 'menubar' && s && s.supported && !st.error && n.key === 'as.hint') {
5606
+ if (!n.on) hint.push(' ', lt(k, 'hintOff'))
5607
+ }
5608
+ if (n.action === 'fix') hint.push(' ', h('button', { class: 'link-btn small', type: 'button', onclick: () => autostartAsk(true, k) }, lt(k, n.key === 'as.notRunning' ? 'restart' : 'fix')))
3692
5609
  if (s && s.state === 'foreign') hint.push(' ', h('button', { class: 'link-btn small', type: 'button', title: s.path, onclick: () => copyText(s.path) }, lt(k, 'copyPath')))
5610
+ // Running, but macOS tucked the icon behind « (a full menu bar): say where it went, whatever else the row says.
5611
+ if (k === 'menubar' && s && n.on && s.loaded !== false && s.icon && s.icon.visible === false)
5612
+ hint.push(h('span', { class: 'note-warn-line' }, t('mb.iconHidden'), ' ', BOOT.readOnly ? null : h('button', { class: 'link-btn small', type: 'button', onclick: openMenuBarSettings }, t('mb.openSettings'))))
3693
5613
  let ctl = null
3694
5614
  if (!s) ctl = st.loading ? spinner() : null
3695
5615
  else if (n.toggle) ctl = h('div', { class: 'seg', role: 'group', 'aria-label': label }, [[true, t('ah.on')], [false, t('ah.off')]].map(([v, text]) =>
3696
5616
  h('button', { class: 'seg-btn', type: 'button', 'aria-pressed': String(v === n.on), onclick: () => { if (v !== n.on) autostartAsk(v, k) } }, text)))
3697
5617
  else if (s.supported && s.state !== 'foreign') ctl = h('span', { class: 'chip chip-sm' + (n.on ? ' chip-ok' : '') }, n.on ? t('ah.on') : t('ah.off'))
3698
- return h('div', { class: 'set-row set-check' },
5618
+ return h('div', { class: 'set-row set-check', 'data-enter': 'li-' + k },
3699
5619
  h('div', { class: 'set-text' }, h('span', { class: 'set-label' }, label), h('span', { class: 'set-hint' }, hint)), ctl)
3700
5620
  }
5621
+ async function openMenuBarSettings() {
5622
+ try { await api('/api/menubar/settings', {}) } catch (e) { toast(e.message, { kind: 'fail' }) }
5623
+ }
5624
+
5625
+ // The menu bar item's own dialog (spec §3.31): its shortcut, what hides its icon, and the AI Task that checks it.
5626
+ // The settings popover keeps one row for it, like Preferred terminal, so the popover stays one line per setting.
5627
+ function openMenubarSettings() {
5628
+ hk.recording = false
5629
+ hk.error = ''
5630
+ showDialog('mbset')
5631
+ dlg.onClose = () => { hk.recording = false; hk.error = ''; hk.live = ''; hk.undo = ''; hk.mods = false; hk.custom = false }
5632
+ renderMenubarSettings()
5633
+ // What the page read earlier may be old (the CLI, another tab, an update changed it): read it again now.
5634
+ loadLoginItem('menubar')
5635
+ }
5636
+ function renderMenubarSettings() {
5637
+ const s = li.menubar.status
5638
+ const v = s && s.hotkey
5639
+ const body = []
5640
+ if (v) {
5641
+ body.push(h('div', { class: 'set-row set-check' },
5642
+ h('div', { class: 'set-text' }, h('span', { class: 'set-label' }, t('hk.label')),
5643
+ h('span', { class: 'set-hint' }, hk.error ? h('span', { class: 'note-fail-text' }, hk.error)
5644
+ : hk.custom ? t('hk.customHint')
5645
+ : v.registered === false ? h('span', { class: 'note-fail-text' }, t('hk.taken', { key: v.label }))
5646
+ : v.problem ? t('hk.problem', { key: v.label })
5647
+ : v.enabled ? t('hk.hint', { key: v.label })
5648
+ : hk.undo ? [t('hk.savedOff'), ' ', h('button', { class: 'link-btn small', type: 'button', disabled: hk.busy, onclick: () => saveHotkey(hk.undo) }, t('hk.undo'))]
5649
+ : t('hk.hintOff'))),
5650
+ hotkeyPicker(v)))
5651
+ if (hk.custom) body.push(h('div', { class: 'hk-custom', 'data-enter': 'hk-custom' }, hotkeyField(v)))
5652
+ if (!BOOT.readOnly && !hk.custom) body.push(h('p', { class: 'small', 'data-enter': 'hk-ai' }, h('button', { class: 'link-btn small', type: 'button', onclick: () => { dlg.el.close(); openAsk({ task: 'hotkey', context: { version: BOOT.version } }) } }, icon('bot'), ' ', t('hk.askAi'))))
5653
+ }
5654
+ const key = v && v.enabled ? v.label : ''
5655
+ body.push(h('h3', { class: 'mb-help-title' }, t('mb.cantSee')),
5656
+ h('ol', { class: 'set-help' },
5657
+ h('li', null, t('mb.cantSeeOverflow')),
5658
+ h('li', null, t('mb.cantSeeAllow'), ' ', BOOT.readOnly ? null : h('button', { class: 'link-btn small', type: 'button', onclick: openMenuBarSettings }, t('mb.openSettings'))),
5659
+ h('li', null, t('mb.cantSeeOrganizer'))))
5660
+ if (key) body.push(h('p', { class: 'muted small' }, t('mb.cantSeeKey', { key })))
5661
+ const foot = [h('button', { class: 'btn', type: 'button', onclick: () => dlg.el.close() }, t('btn.close'))]
5662
+ if (!BOOT.readOnly) foot.push(h('button', { class: 'btn btn-primary', type: 'button', onclick: () => { dlg.el.close(); openAsk({ task: 'menubar', context: { version: BOOT.version } }) } }, icon('bot'), t('mb.askAi')))
5663
+ swapKids(dlg.el, dialogFrame(t('mb.settings'), null, body, foot))
5664
+ if (hk.recording) focusRecorder()
5665
+ }
5666
+
5667
+ // The shortcut as a choice, not a recording (spec §3.31): a few checked combinations that work, Off, and Custom…,
5668
+ // which opens the recorder. A browser never sees keys another app holds, so recording stays the exception.
5669
+ const HOTKEY_PRESETS = ['opt+x', 'opt+z', 'opt+cmd+s', 'ctrl+opt+s']
5670
+ const HOTKEY_SIGNS = { ctrl: '⌃', opt: '⌥', shift: '⇧', cmd: '⌘' }
5671
+ function hotkeyLabel(keys) {
5672
+ const parts = keys.split('+')
5673
+ const key = parts.pop()
5674
+ return parts.map((p) => HOTKEY_SIGNS[p] || '').join('') + key.toUpperCase()
5675
+ }
5676
+ function hotkeyPicker(v) {
5677
+ const now = hk.custom ? 'custom' : v.enabled ? v.keys : 'off'
5678
+ if (BOOT.readOnly) return h('span', { class: 'chip chip-sm' }, v.enabled ? v.label : t('hk.unset'))
5679
+ const opts = HOTKEY_PRESETS.map((k) => [k, hotkeyLabel(k) + (k === HOTKEY_PRESETS[0] ? t('hk.isDefault') : '')])
5680
+ if (v.enabled && HOTKEY_PRESETS.indexOf(v.keys) < 0) opts.unshift([v.keys, v.label])
5681
+ opts.push(['off', t('hk.offOption')], ['custom', t('hk.custom')])
5682
+ return h('select', { class: 'hk-select', 'data-key': 'hk-select', 'aria-label': t('hk.label'), disabled: hk.busy,
5683
+ onchange: (e) => {
5684
+ const val = e.target.value
5685
+ hk.error = ''
5686
+ if (val === 'custom') { hk.custom = true; hk.recording = true; hk.live = ''; refreshHotkey(); return }
5687
+ hk.custom = false
5688
+ saveHotkey(val)
5689
+ } },
5690
+ opts.map(([val, text]) => h('option', { value: val, selected: val === now }, text)))
5691
+ }
5692
+
5693
+ // The shortcut recorder (spec §3.31), one field as in macOS Keyboard Shortcuts and KeyboardShortcuts: click it and
5694
+ // press the keys, saved at once; Esc cancels, Delete or its ✕ turns the shortcut off (with Undo). Nothing else
5695
+ // appears around it while recording; a refusal is one red line, gone at the next key.
5696
+ // undo: the shortcut before it was turned off, offered in the row itself (a toast is out of reach behind the modal).
5697
+ // mods: modifiers were held while recording and no letter came yet (see recordUp).
5698
+ // custom: the picker's Custom… is open, showing the recorder below it.
5699
+ const hk = { recording: false, busy: false, error: '', live: '', undo: '', mods: false, custom: false }
5700
+ function hotkeyField(v) {
5701
+ const shown = hk.recording ? (hk.live || t('hk.recording')) : v.enabled ? v.label : t('hk.unset')
5702
+ if (BOOT.readOnly) return h('span', { class: 'chip chip-sm' }, shown)
5703
+ const field = h('button', { class: 'hk-rec' + (hk.recording ? ' recording' : '') + (v.registered === false && !hk.recording ? ' taken' : '') + (!v.enabled && !hk.recording ? ' unset' : ''), type: 'button', 'aria-label': t('hk.label') + colon() + shown, 'aria-pressed': String(hk.recording), disabled: hk.busy,
5704
+ onclick: () => { if (!hk.recording) { hk.recording = true; hk.error = ''; hk.live = ''; refreshHotkey() } },
5705
+ onkeydown: recordKey, onkeyup: recordUp,
5706
+ onblur: () => { if (hk.recording) setTimeout(() => { if (hk.recording && !document.querySelector('.hk-rec:focus')) stopRecording() }, 150) } }, shown)
5707
+ const cancel = h('button', { class: 'link-btn small', type: 'button', onclick: () => { hk.custom = false; stopRecording() } }, t('btn.cancel'))
5708
+ return h('div', { class: 'hk-field' }, field, cancel)
5709
+ }
5710
+ function refreshHotkey() {
5711
+ if (dlg.kind === 'mbset' && dlg.el && dlg.el.open) renderMenubarSettings()
5712
+ }
5713
+ function focusRecorder() { const b = document.querySelector('.hk-rec'); if (b) b.focus() }
5714
+ function stopRecording() { hk.recording = false; hk.live = ''; hk.error = ''; refreshHotkey(); focusRecorder() }
5715
+ // The modifiers held now, as macOS writes them, while the letter is still to come.
5716
+ function hotkeyLive(e) {
5717
+ return (e.ctrlKey ? '⌃' : '') + (e.altKey ? '⌥' : '') + (e.shiftKey ? '⇧' : '') + (e.metaKey ? '⌘' : '')
5718
+ }
5719
+ function recordKey(e) {
5720
+ if (!hk.recording) return
5721
+ const mods = e.ctrlKey || e.altKey || e.shiftKey || e.metaKey
5722
+ // Tab is how a keyboard user leaves: recording stops and focus moves on as usual.
5723
+ if (e.key === 'Tab' && !mods) { hk.recording = false; hk.live = ''; hk.error = ''; refreshHotkey(); return }
5724
+ e.preventDefault()
5725
+ // Esc stops recording only; the next Esc closes the dialog.
5726
+ e.stopPropagation()
5727
+ if (e.key === 'Escape' && !mods) { hk.custom = false; return stopRecording() }
5728
+ if ((e.key === 'Backspace' || e.key === 'Delete') && !mods) return saveHotkey('off')
5729
+ hk.error = ''
5730
+ const keys = hotkeyFromKey(e)
5731
+ // An arrow, an F-key or Space: say at once that only a letter or digit works, rather than seem not to react.
5732
+ if (!keys && hotkeyPressKind(e.code) === 'unsupported') { hk.error = t('hk.err.key'); hk.live = ''; hk.mods = false; refreshHotkey(); return }
5733
+ if (!keys) { hk.live = hotkeyLive(e); hk.mods = Boolean(hk.live); refreshHotkey(); return }
5734
+ hk.mods = false
5735
+ saveHotkey(keys)
5736
+ }
5737
+ // The modifiers came up and no letter reached the page: either none was pressed, or macOS handed the keys to the
5738
+ // app that holds them as its own shortcut (sideby's own included) before the browser saw them. Say both.
5739
+ function recordUp(e) {
5740
+ if (!hk.recording) return
5741
+ hk.live = hotkeyLive(e)
5742
+ if (hk.mods && !hk.live) { hk.mods = false; hk.error = t('hk.err.noKey') }
5743
+ refreshHotkey()
5744
+ }
5745
+ async function saveHotkey(keys) {
5746
+ const before = li.menubar.status && li.menubar.status.hotkey
5747
+ hk.busy = true
5748
+ hk.error = ''
5749
+ refreshHotkey()
5750
+ try {
5751
+ const r = await api('/api/menubar/hotkey', { keys })
5752
+ hk.recording = false
5753
+ hk.custom = false
5754
+ hk.live = ''
5755
+ if (li.menubar.status) li.menubar.status = { ...li.menubar.status, hotkey: r.hotkey }
5756
+ // Off is one click with no question, so the row offers to undo it until something else changes.
5757
+ hk.undo = r.changed && !r.hotkey.enabled && before && before.enabled ? before.keys : ''
5758
+ if (r.changed && r.hotkey.enabled) toast(t('hk.saved', { key: r.hotkey.label }))
5759
+ } catch (e) {
5760
+ const own = 'hk.err.' + (e.code || '')
5761
+ hk.error = Object.hasOwn(MESSAGES.en, own) ? t(own) : e.message
5762
+ hk.live = ''
5763
+ }
5764
+ hk.busy = false
5765
+ refreshHotkey()
5766
+ refreshSettings()
5767
+ if (hk.recording) focusRecorder()
5768
+ }
5769
+
3701
5770
  async function autostartAsk(on, k) {
3702
5771
  if (menu.kind === 'settings') closeMenu()
3703
5772
  liKind = k
@@ -3726,18 +5795,22 @@ const MAIN = String.raw `
3726
5795
  if (['npx-cache', 'temp-dir', 'unsafe-path'].includes(p.blocked.code)) body.push(codeCopy('npm i -g sideby'))
3727
5796
  if (p.blocked.code === 'foreign') body.push(codeCopy(p.path))
3728
5797
  } else if (p && !p.changed) body.push(h('p', null, lt(k, on ? 'alreadyOn' : 'alreadyOff')))
5798
+ else if (p && on && p.restartOnly) body.push(h('p', null, lt(k, 'restartBody')))
5799
+ // What happens, in one sentence; the file and the command it runs sit behind Details, for whoever wants them.
3729
5800
  else if (p && on) {
3730
- body.push(h('p', null, lt(k, 'writes')), h('code', { class: 'as-code' }, p.path))
3731
- body.push(h('p', null, lt(k, 'runs')), h('code', { class: 'as-code' }, (p.programArguments || []).join(' ')))
3732
- body.push(h('p', { class: 'muted small' }, lt(k, 'noWindow')))
5801
+ body.push(h('p', null, lt(k, 'noWindow')))
5802
+ body.push(h('details', { class: 'as-details' }, h('summary', null, t('as.details')),
5803
+ h('p', null, lt(k, 'writes')), h('code', { class: 'as-code' }, p.path),
5804
+ h('p', null, lt(k, 'runs')), h('code', { class: 'as-code' }, (p.programArguments || []).join(' '))))
3733
5805
  } else if (p) {
3734
- body.push(h('p', null, lt(k, 'removes')), h('code', { class: 'as-code' }, p.path))
3735
- body.push(h('p', { class: 'muted small' }, lt(k, 'offNote')))
5806
+ body.push(h('p', null, lt(k, 'offNote')))
5807
+ body.push(h('details', { class: 'as-details' }, h('summary', null, t('as.details')),
5808
+ h('p', null, lt(k, 'removes')), h('code', { class: 'as-code' }, p.path)))
3736
5809
  }
3737
5810
  const foot = [h('button', { class: 'btn', type: 'button', disabled: st.busy, onclick: () => dlg.el.close() }, t(p && p.changed && !p.blocked ? 'btn.cancel' : 'btn.close'))]
3738
5811
  if (p && p.changed && !p.blocked)
3739
- foot.push(h('button', { class: 'btn btn-primary', type: 'button', disabled: st.busy, 'aria-busy': st.busy ? 'true' : null, onclick: autostartApply }, st.busy ? spinner() : null, lt(k, on ? 'turnOn' : 'turnOff')))
3740
- setKids(dlg.el, dialogFrame(lt(k, on ? 'onTitle' : 'offTitle'), null, body, foot))
5812
+ foot.push(h('button', { class: 'btn btn-primary', type: 'button', disabled: st.busy, 'aria-busy': st.busy ? 'true' : null, onclick: autostartApply }, st.busy ? spinner() : null, lt(k, p.restartOnly ? 'restart' : on ? 'turnOn' : 'turnOff')))
5813
+ setKids(dlg.el, dialogFrame(lt(k, p && p.restartOnly ? 'restartTitle' : on ? 'onTitle' : 'offTitle'), null, body, foot))
3741
5814
  }
3742
5815
  async function autostartApply() {
3743
5816
  const k = liKind
@@ -3751,9 +5824,11 @@ const MAIN = String.raw `
3751
5824
  st.busy = false
3752
5825
  dlg.busy = false
3753
5826
  if (r && r.applied) {
5827
+ const restarted = st.plan && st.plan.restartOnly
3754
5828
  st.status = r.status
3755
5829
  if (dlg.kind === 'autostart') dlg.el.close()
3756
- toast(lt(k, on ? 'doneOn' : 'doneOff') + (on && !r.loaded ? ' ' + lt(k, 'nextLogin') : ''))
5830
+ if (restarted) toast(lt(k, r.loaded ? 'doneRestart' : 'restartFailed'), r.loaded ? undefined : { kind: 'fail' })
5831
+ else toast(lt(k, on ? 'doneOn' : 'doneOff') + (on && !r.loaded ? ' ' + lt(k, 'nextLogin') : ''))
3757
5832
  refreshSettings()
3758
5833
  if (k === 'menubar') renderAll()
3759
5834
  return
@@ -3796,11 +5871,14 @@ const MAIN = String.raw `
3796
5871
  else if (dlg.kind === 'browser') renderBrowser()
3797
5872
  else if (dlg.kind === 'update' && up) renderUpdate()
3798
5873
  else if (dlg.kind === 'rc') renderRc()
5874
+ else if (dlg.kind === 'inbound') renderInbound()
3799
5875
  else if (dlg.kind === 'ask' && ak) { if (ak.els.text) ak.text = ak.els.text.value; renderAsk() }
3800
5876
  else if (dlg.kind === 'key' && ky && ky.step !== 'enter') renderKey()
3801
5877
  else if (dlg.kind === 'terminal' && tm) renderTerminals()
3802
5878
  else if (dlg.kind === 'autostart') renderAutostart()
5879
+ else if (dlg.kind === 'mbset') renderMenubarSettings()
3803
5880
  else if (dlg.kind === 'pick' && pk) renderPick()
5881
+ else if (dlg.kind === 'send' && sd) renderSend()
3804
5882
  }
3805
5883
  function setTheme(v) {
3806
5884
  if (CFG) { cfgPanel.theme = v; saveCfg({ theme: v }) } else { prefs.theme = v; savePrefs() }
@@ -3813,7 +5891,7 @@ const MAIN = String.raw `
3813
5891
  return Boolean(u && u.skillUpdate && u.skillUpdate.installed && u.skillUpdate.installed.length)
3814
5892
  }
3815
5893
  // Example phrases: a click puts one in the Let AI do it box (spec §3.28).
3816
- const AI_ASKS = ['ai.ask.quota', 'ai.ask.pick', 'ai.ask.new', 'ai.ask.api', 'ai.ask.pin', 'ai.ask.fix', 'ai.ask.handoff', 'ai.ask.menubar', 'ai.ask.rc', 'ai.ask.tool']
5894
+ const AI_ASKS = ['ai.ask.quota', 'ai.ask.pick', 'ai.ask.new', 'ai.ask.api', 'ai.ask.pin', 'ai.ask.relogin', 'ai.ask.fix', 'ai.ask.handoff', 'ai.ask.session', 'ai.ask.history', 'ai.ask.send', 'ai.ask.inbound', 'ai.ask.menubar', 'ai.ask.rc', 'ai.ask.tool']
3817
5895
  function openRc() {
3818
5896
  if (!S.state || !rcSummary()) return
3819
5897
  rc.target = null
@@ -3877,7 +5955,7 @@ const MAIN = String.raw `
3877
5955
  if (askBridge(BOOT, opts, window)) return
3878
5956
  ak = { task: opts.task || 'free', text: opts.text || '', context: opts.context || null, account: null, accountChanged: false, terminal: null, terminalChanged: false, pick: null, reason: null, terms: null, loading: true, busy: false, result: null, error: null, removed: false, files: [], els: {} }
3879
5957
  showDialog('ask')
3880
- hookAskDrops()
5958
+ hookDrops()
3881
5959
  const mine = ak
3882
5960
  // Uploads still running when the dialog closes are stopped; the server drops staged files it never received.
3883
5961
  dlg.onClose = () => { mine.files.forEach((f) => { if (f.xhr) f.xhr.abort() }) }
@@ -3933,19 +6011,29 @@ const MAIN = String.raw `
3933
6011
  // data: URL (the CSP allows no blob:); the server decides the type from the first bytes.
3934
6012
  const ATTACH_MAX = 5
3935
6013
  const ATTACH_ACCEPT = 'image/png,image/jpeg,image/gif,image/webp,video/mp4,video/quicktime,video/webm'
3936
- let askHooked = false
3937
- function hookAskDrops() {
3938
- if (askHooked) return
3939
- askHooked = true
6014
+ let dropsHooked = false
6015
+ // Which open dialog takes pasted or dropped files now: the AI Task's or "Send to it"'s, until it shows its result.
6016
+ function dropTarget() {
6017
+ if (BOOT.readOnly) return null
6018
+ if (dlg.kind === 'ask' && ak && !ak.result) return askAddFiles
6019
+ if (dlg.kind === 'send' && sd && !sd.result) return sendAddFiles
6020
+ return null
6021
+ }
6022
+ function hookDrops() {
6023
+ if (dropsHooked) return
6024
+ dropsHooked = true
3940
6025
  const el = dlg.el
3941
- const active = () => dlg.kind === 'ask' && ak && !ak.result && !BOOT.readOnly
6026
+ const active = () => Boolean(dropTarget())
3942
6027
  const hasFiles = (e) => e.dataTransfer && Array.prototype.indexOf.call(e.dataTransfer.types || [], 'Files') >= 0
3943
6028
  el.addEventListener('paste', (e) => {
3944
- const files = e.clipboardData ? Array.from(e.clipboardData.files || []) : []
6029
+ const cd = e.clipboardData
6030
+ let files = cd ? Array.from(cd.files || []) : []
6031
+ // Some browsers put a copied screenshot only among the items.
6032
+ if (cd && !files.length) files = Array.from(cd.items || []).filter((i) => i.kind === 'file').map((i) => i.getAsFile()).filter(Boolean)
3945
6033
  if (!active() || !files.length) return
3946
6034
  // A file copied in Finder also carries its name as text; only the file is wanted.
3947
6035
  e.preventDefault()
3948
- askAddFiles(files)
6036
+ dropTarget()(files)
3949
6037
  })
3950
6038
  el.addEventListener('dragover', (e) => {
3951
6039
  if (!active() || !hasFiles(e)) return
@@ -3958,7 +6046,7 @@ const MAIN = String.raw `
3958
6046
  el.classList.remove('drop-on')
3959
6047
  if (!active() || !hasFiles(e)) return
3960
6048
  e.preventDefault()
3961
- askAddFiles(Array.from(e.dataTransfer.files || []))
6049
+ dropTarget()(Array.from(e.dataTransfer.files || []))
3962
6050
  })
3963
6051
  }
3964
6052
  function askAttachField() {
@@ -4022,11 +6110,11 @@ const MAIN = String.raw `
4022
6110
  ak.attachFull = false
4023
6111
  renderAskFiles()
4024
6112
  }
4025
- function askPost(file, onProgress, xhrOut) {
6113
+ function askPost(file, onProgress, xhrOut, path) {
4026
6114
  return new Promise((resolve) => {
4027
6115
  const xhr = new XMLHttpRequest()
4028
6116
  xhrOut(xhr)
4029
- xhr.open('POST', BOOT.basePath + '/api/ask/attach')
6117
+ xhr.open('POST', BOOT.basePath + (path || '/api/ask/attach'))
4030
6118
  xhr.setRequestHeader('x-sideby-token', token)
4031
6119
  xhr.setRequestHeader('content-type', file.type || 'application/octet-stream')
4032
6120
  xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress(e.loaded / e.total) }
@@ -4542,7 +6630,9 @@ const MAIN = String.raw `
4542
6630
  if (name) return h('button', { class: 'btn btn-sm', type: 'button', title: t('pk.startTip', { name, host: family(fam).title }), 'aria-label': t('pk.startTip', { name, host: family(fam).title }), onclick: () => startPick(name) }, icon('terminal'), h('span', { class: 'hide-sm' }, pickStartLabel()), h('code', { class: 'mono' }, name))
4543
6631
  const offer = (S.state.pickOffers || {})[fam]
4544
6632
  if (!offer || BOOT.readOnly) return null
4545
- return h('button', { class: 'link-btn small', type: 'button', onclick: () => openPick(fam) }, offer.name ? [t('pk.offerShort', { name: offer.name }), h('span', { class: 'hide-sm' }, t('pk.offerMore'))] : t('pk.offerNoName'))
6633
+ // Short in the head ("Add cc"); what it does is in its hover text, so several groups do not repeat a sentence.
6634
+ const full = offer.name ? t('pk.offerShort', { name: offer.name }) + t('pk.offerMore') : t('pk.offerNoName')
6635
+ return h('button', { class: 'link-btn small', type: 'button', 'aria-label': full, 'data-tip': full, onclick: () => openPick(fam) }, offer.name ? t('pk.offerShort', { name: offer.name }) : t('pk.offerNoNameShort'))
4546
6636
  }
4547
6637
 
4548
6638
  // ---------- banners ----------
@@ -4577,17 +6667,21 @@ const MAIN = String.raw `
4577
6667
  h('button', { class: 'btn btn-sm btn-primary', type: 'button', onclick: () => setPage('handoff') }, t('ah.setUp')),
4578
6668
  h('button', { class: 'btn btn-sm', type: 'button', onclick: () => { prefs.ahHintAt = Date.now(); savePrefs(); renderBanners() } }, t('ah.dismiss')))))
4579
6669
  else {
4580
- const mb = menubarHint()
6670
+ // About the accounts' quota, so it shows on the Accounts page only.
6671
+ const mb = curPage === 'accounts' ? menubarHint() : null
4581
6672
  if (mb) out.push(mb)
4582
6673
  }
4583
6674
  const rcBanner = remoteControlBanner()
4584
6675
  if (rcBanner) out.push(rcBanner)
6676
+ const inbBanner = inboundBanner()
6677
+ if (inbBanner) out.push(inbBanner)
4585
6678
  const errs = S.state.pluginErrors
4586
6679
  if (errs.length) out.push(h('div', { class: 'banner banner-warn', role: 'status' }, h('div', null,
4587
6680
  h('b', null, tn('banner.plugins', errs.length) + ' '), t('banner.pluginsHint'),
4588
- h('ul', null, errs.map((e) => h('li', null, h('code', null, e.where), ': ', e.message))))))
6681
+ h('ul', null, errs.map((e) => h('li', null, h('code', null, e.where), colon(), e.message))))))
4589
6682
  }
4590
6683
  patch($('banners'), out)
6684
+ growInboundBanner()
4591
6685
  }
4592
6686
 
4593
6687
  // ---------- loading ----------
@@ -4651,10 +6745,17 @@ const MAIN = String.raw `
4651
6745
  function tick() {
4652
6746
  renderUpdated()
4653
6747
  reloadForNewBuild()
6748
+ sessionsTick()
6749
+ messagesTick()
4654
6750
  if (document.visibilityState !== 'visible' || !S.state) return
4655
6751
  if (S.pending && !S.loading && !uiBusy()) { S.pending = false; renderAll() }
4656
6752
  const now = Date.now()
4657
- const every = now < S.fastUntil ? FAST_MS : AUTO_MS
6753
+ // An Account still being read is asked for again soon, so it fills in without waiting for the next round.
6754
+ // For half a minute: the server says "took too long" after a minute, which the normal round then shows.
6755
+ const pending = S.state.accounts.some((a) => a.pending)
6756
+ if (!pending) S.pendingSince = 0
6757
+ else if (!S.pendingSince) S.pendingSince = now
6758
+ const every = pending && now - S.pendingSince < 30_000 ? PENDING_MS : now < S.fastUntil ? FAST_MS : AUTO_MS
4658
6759
  if (!S.loading && !conn.lost && !S.fixing && !S.checking && !dlg.busy && now - S.lastTry >= every) load({ silent: true })
4659
6760
  }
4660
6761
  // Coming back to the page refreshes at once.
@@ -5073,6 +7174,10 @@ const MAIN = String.raw `
5073
7174
  buildToolbar()
5074
7175
  raiseToasts()
5075
7176
  load({ check: true })
7177
+ // The switches' state is read now, not when Settings opens, so the popover opens at its final size.
7178
+ loadAutostart()
7179
+ // The sessions too, so the Sessions page opens with its rows already there.
7180
+ loadSessions()
5076
7181
  setInterval(tick, 1000)
5077
7182
  document.addEventListener('visibilitychange', wake)
5078
7183
  window.addEventListener('focus', wake)