sideby 0.19.1 → 0.20.0

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