sideby 0.16.1 → 0.18.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 (128) hide show
  1. package/README.md +7 -3
  2. package/ai-tasks.json +90 -0
  3. package/dist/build.json +1 -1
  4. package/dist/src/cli/commands.d.ts +25 -1
  5. package/dist/src/cli/commands.js +802 -15
  6. package/dist/src/cli/json-schemas.js +252 -1
  7. package/dist/src/cli/main.js +143 -4
  8. package/dist/src/core/after-install.d.ts +54 -0
  9. package/dist/src/core/after-install.js +78 -0
  10. package/dist/src/core/ask.d.ts +222 -0
  11. package/dist/src/core/ask.js +465 -0
  12. package/dist/src/core/attachments.d.ts +50 -0
  13. package/dist/src/core/attachments.js +442 -0
  14. package/dist/src/core/autostart.d.ts +118 -0
  15. package/dist/src/core/autostart.js +302 -0
  16. package/dist/src/core/brand-mark.d.ts +49 -11
  17. package/dist/src/core/brand-mark.js +116 -38
  18. package/dist/src/core/config.d.ts +102 -0
  19. package/dist/src/core/config.js +289 -11
  20. package/dist/src/core/desktop-app.d.ts +1 -1
  21. package/dist/src/core/desktop-app.js +2 -2
  22. package/dist/src/core/edit-settings.d.ts +24 -0
  23. package/dist/src/core/edit-settings.js +97 -0
  24. package/dist/src/core/handoff-brief.d.ts +4 -2
  25. package/dist/src/core/handoff-brief.js +6 -1
  26. package/dist/src/core/handoff-chain.d.ts +24 -0
  27. package/dist/src/core/handoff-chain.js +2 -0
  28. package/dist/src/core/handoff-run.d.ts +4 -3
  29. package/dist/src/core/handoff-run.js +14 -9
  30. package/dist/src/core/launch.d.ts +17 -4
  31. package/dist/src/core/launch.js +32 -24
  32. package/dist/src/core/local-build.d.ts +17 -5
  33. package/dist/src/core/local-build.js +61 -23
  34. package/dist/src/core/lock.d.ts +30 -0
  35. package/dist/src/core/lock.js +143 -0
  36. package/dist/src/core/probe.d.ts +78 -0
  37. package/dist/src/core/probe.js +127 -0
  38. package/dist/src/core/quota-levels.d.ts +6 -1
  39. package/dist/src/core/quota-levels.js +16 -5
  40. package/dist/src/core/same-login.d.ts +9 -4
  41. package/dist/src/core/same-login.js +9 -4
  42. package/dist/src/core/secret-file.d.ts +26 -0
  43. package/dist/src/core/secret-file.js +126 -7
  44. package/dist/src/core/task-spec.d.ts +95 -0
  45. package/dist/src/core/task-spec.js +209 -0
  46. package/dist/src/core/terminal.d.ts +93 -0
  47. package/dist/src/core/terminal.js +376 -0
  48. package/dist/src/core/update.d.ts +34 -12
  49. package/dist/src/core/update.js +96 -84
  50. package/dist/src/desktop/icon.js +12 -15
  51. package/dist/src/families/claude/ai-task.d.ts +8 -0
  52. package/dist/src/families/claude/ai-task.js +38 -0
  53. package/dist/src/families/claude/handoff-hook.js +4 -4
  54. package/dist/src/families/claude/index.js +6 -0
  55. package/dist/src/families/claude/quota-cache.d.ts +24 -7
  56. package/dist/src/families/claude/quota-cache.js +72 -21
  57. package/dist/src/families/codex/handoff-hook.js +4 -4
  58. package/dist/src/families/codex/index.js +16 -0
  59. package/dist/src/families/codex/login-key.d.ts +8 -0
  60. package/dist/src/families/codex/login-key.js +33 -0
  61. package/dist/src/families/grok/handoff-hook.js +4 -4
  62. package/dist/src/families/grok/index.js +4 -0
  63. package/dist/src/families/login-keys.d.ts +6 -0
  64. package/dist/src/families/login-keys.js +6 -0
  65. package/dist/src/families/pi/index.js +5 -0
  66. package/dist/src/handoff/hook.js +51 -30
  67. package/dist/src/handoff/levels.d.ts +24 -0
  68. package/dist/src/handoff/levels.js +70 -0
  69. package/dist/src/handoff/messages.d.ts +6 -3
  70. package/dist/src/handoff/messages.js +20 -7
  71. package/dist/src/handoff/reader.d.ts +6 -3
  72. package/dist/src/menubar/agent.d.ts +3 -0
  73. package/dist/src/menubar/agent.js +21 -0
  74. package/dist/src/menubar/script.d.ts +8 -0
  75. package/dist/src/menubar/script.js +457 -0
  76. package/dist/src/menubar/snapshot.d.ts +115 -0
  77. package/dist/src/menubar/snapshot.js +255 -0
  78. package/dist/src/menubar/strings.d.ts +87 -0
  79. package/dist/src/menubar/strings.js +88 -0
  80. package/dist/src/panel/background.js +15 -21
  81. package/dist/src/panel/handler.d.ts +41 -2
  82. package/dist/src/panel/handler.js +394 -10
  83. package/dist/src/panel/i18n.d.ts +205 -2
  84. package/dist/src/panel/i18n.js +441 -35
  85. package/dist/src/panel/page-logic.d.ts +301 -0
  86. package/dist/src/panel/page-logic.js +532 -0
  87. package/dist/src/panel/page-script.js +1135 -185
  88. package/dist/src/panel/page-styles.js +111 -32
  89. package/dist/src/panel/page.d.ts +12 -0
  90. package/dist/src/panel/page.js +7 -0
  91. package/dist/src/panel/server.d.ts +16 -2
  92. package/dist/src/panel/server.js +41 -13
  93. package/dist/src/plugins/check.d.ts +47 -0
  94. package/dist/src/plugins/check.js +544 -0
  95. package/dist/src/plugins/scaffold.d.ts +21 -0
  96. package/dist/src/plugins/scaffold.js +123 -0
  97. package/dist/src/quota/statusline-tap.js +1 -1
  98. package/dist/src/runtime.d.ts +19 -1
  99. package/dist/src/runtime.js +53 -14
  100. package/dist/src/types.d.ts +33 -0
  101. package/package.json +4 -3
  102. package/schemas/ask-choices.json +168 -0
  103. package/schemas/ask-print.json +87 -0
  104. package/schemas/ask.json +180 -0
  105. package/schemas/autostart.json +165 -0
  106. package/schemas/config-get.json +132 -0
  107. package/schemas/config-set.json +107 -0
  108. package/schemas/config.json +90 -7
  109. package/schemas/edit.json +119 -0
  110. package/schemas/error.json +4 -0
  111. package/schemas/families.json +4 -0
  112. package/schemas/key.json +93 -0
  113. package/schemas/list.json +4 -0
  114. package/schemas/local.json +1 -1
  115. package/schemas/menubar-snapshot.json +646 -0
  116. package/schemas/menubar-start.json +112 -0
  117. package/schemas/menubar.json +165 -0
  118. package/schemas/plugins-check.json +113 -0
  119. package/schemas/plugins-new.json +87 -0
  120. package/schemas/terminal.json +152 -0
  121. package/schemas/try.json +109 -0
  122. package/schemas/update.json +4 -0
  123. package/skills/sideby/SKILL.md +16 -6
  124. package/skills/sideby/references/accounts.md +1 -1
  125. package/skills/sideby/references/ai-tasks.md +126 -0
  126. package/skills/sideby/references/handoff.md +3 -1
  127. package/skills/sideby/references/panel.md +20 -0
  128. package/skills/sideby/references/update.md +1 -1
@@ -1,39 +1,58 @@
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 { aliasArgsOf, aliasIssue, attentionReasons, attentionWhy, cacheHitRate, canLeaveLocal, fixPrompt, formatDuration, handoffChangeOf, handoffHintAccount, inDisplayOrder, loginClusters, loginKey, maskEmail, matchesQuery, mergeDaily, newAccountDir, nextReset, panelFixes, panelHint, panelLang, passedWindow, pinnedIn, quotaPressure, remoteControlSummary, remoteControlTodo, reorder, sortAccounts, suggestAlias, suggestName, switchFailure, updatedAge, windowState, withPinned, } from './page-logic.js';
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';
4
4
  const LOGIC = [
5
+ aiTaskAccounts,
6
+ askBridge,
7
+ askBridged,
8
+ askCopy,
9
+ quotaAskable,
10
+ stripSecrets,
11
+ taskFindings,
5
12
  aliasArgsOf,
6
13
  aliasIssue,
7
14
  attentionReasons,
8
15
  attentionWhy,
16
+ autostartNote,
9
17
  cacheHitRate,
18
+ fileSize,
10
19
  fixPrompt,
20
+ foldSkips,
11
21
  formatDuration,
12
22
  handoffChangeOf,
13
23
  handoffHintAccount,
24
+ handoffTaskFacts,
14
25
  inDisplayOrder,
15
26
  loginClusters,
16
27
  loginKey,
17
28
  maskEmail,
18
29
  matchesQuery,
30
+ menuPlacement,
19
31
  mergeDaily,
20
32
  newAccountDir,
21
33
  nextReset,
22
34
  canLeaveLocal,
35
+ codeSwapOutcome,
36
+ runCodeSwap,
23
37
  switchFailure,
24
38
  panelFixes,
25
39
  panelHint,
26
40
  panelLang,
41
+ panelMigration,
42
+ panelPrefs,
27
43
  passedWindow,
28
44
  quotaPressure,
29
45
  remoteControlSummary,
30
46
  remoteControlTodo,
31
47
  reorder,
48
+ rowBadge,
32
49
  sortAccounts,
33
50
  suggestAlias,
34
51
  suggestName,
35
52
  updatedAge,
36
53
  pinnedIn,
54
+ widthFollower,
55
+ widthTier,
37
56
  windowState,
38
57
  withPinned,
39
58
  ]
@@ -56,6 +75,9 @@ const MAIN = String.raw `
56
75
  const AUTO_MS = 20000
57
76
  const FAST_MS = 5000
58
77
  const FAST_FOR_MS = 3 * 60000
78
+ // After the layout follows a width into another band, how long the width must hold still before a later crossing
79
+ // in the same gesture is applied (page-logic.ts, widthFollower).
80
+ const WIDTH_SETTLE_MS = 90
59
81
  const S = {
60
82
  state: null, loadError: null, loading: false, loadedAt: 0, history: null,
61
83
  report: null, checking: false, fixing: false, checkError: null, checkRetry: null, fixes: null,
@@ -82,6 +104,8 @@ const MAIN = String.raw `
82
104
  if (raw.hideEmail === true) p.hideEmail = true
83
105
  if (typeof raw.ahHintAt === 'number') p.ahHintAt = raw.ahHintAt
84
106
  if (raw.rcHide === true) p.rcHide = true
107
+ if (raw.mbHintDone === true) p.mbHintDone = true
108
+ if (raw.cfgDone === true) p.cfgDone = true
85
109
  if (typeof raw.family === 'string') p.family = raw.family
86
110
  if (raw.collapsed && typeof raw.collapsed === 'object')
87
111
  for (const k of Object.keys(raw.collapsed)) if (raw.collapsed[k] === true) p.collapsed[k] = true
@@ -92,7 +116,16 @@ const MAIN = String.raw `
92
116
  function savePrefs() { try { localStorage.setItem(PREFS_KEY, JSON.stringify(prefs)) } catch {} }
93
117
  // A host lang other than auto wins over the saved choice (which stays saved) and hides the switch.
94
118
  const LANG_FIXED = BOOT.lang === 'en' || BOOT.lang === 'zh'
95
- let lang = panelLang(BOOT.lang, prefs.lang, navigator.language)
119
+ // Theme and language live in config panel.* (spec §3.29), so the CLI and an AI assistant can change them too. A
120
+ // choice this browser saved before is written there once (cfgDone), then config is the only source. A read-only
121
+ // Panel cannot write config and keeps the browser's choice.
122
+ const CFG = !BOOT.readOnly
123
+ let cfgPanel = Object.assign({}, BOOT.panel || {})
124
+ let cfgSaving = 0
125
+ const cfgMigrate = CFG && !prefs.cfgDone ? panelMigration(cfgPanel, { theme: prefs.theme, lang: prefs.lang }) : null
126
+ if (cfgMigrate) Object.assign(cfgPanel, cfgMigrate)
127
+ function viewPrefs() { return panelPrefs(cfgPanel, { theme: prefs.theme, lang: prefs.lang }, CFG) }
128
+ let lang = panelLang(BOOT.lang, viewPrefs().language, navigator.language)
96
129
 
97
130
  // ---------- text ----------
98
131
  function t(key, vars) {
@@ -270,6 +303,7 @@ const MAIN = String.raw `
270
303
  terminal: 'M4 17l6-5-6-5M12 19h8',
271
304
  key: 'M15 9a3 3 0 1 0-.01 0M12.9 11.1L4 20M7 17l2 2M9.5 14.5l2 2',
272
305
  folder: 'M3 6h6l2 2h10v11H3z',
306
+ file: 'M14 3H6v18h12V7zM14 3v4h4M9 13h6M9 17h6',
273
307
  check: 'M9 12l2 2 4-4M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z',
274
308
  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',
275
309
  x: 'M6 6l12 12M18 6L6 18',
@@ -278,6 +312,8 @@ const MAIN = String.raw `
278
312
  swap: 'M7 4 3 8l4 4M3 8h14M17 20l4-4-4-4M21 16H7',
279
313
  // Lucide "pin" (ISC license)
280
314
  pin: 'M12 17v5M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z',
315
+ // Lucide "link" (ISC license)
316
+ link: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71',
281
317
  bot: 'M6 9h12a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2zM12 5v4M9.5 13.5v1M14.5 13.5v1',
282
318
  grid: 'M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z',
283
319
  list: 'M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01',
@@ -285,6 +321,8 @@ const MAIN = String.raw `
285
321
  clock: 'M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 7v5l3 2',
286
322
  mail: 'M3 6h18v12H3zM3 7l9 6 9-6',
287
323
  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
+ image: 'M3 5h18v14H3zM3 16l5-5 4 4 3-3 6 6M15 9h.01',
325
+ film: 'M3 5h18v14H3zM7 5v14M17 5v14M3 9h4M3 15h4M17 9h4M17 15h4',
288
326
  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',
289
327
  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',
290
328
  }
@@ -553,24 +591,39 @@ const MAIN = String.raw `
553
591
 
554
592
  // ---------- floating panels: menus and popovers ----------
555
593
  // One shared base for everything that floats next to a button: it is placed under (or above) its anchor, kept
556
- // inside the window, closed by a click outside, Escape, a resize or a scroll, and only one is open at a time.
594
+ // inside the window, closed by a click outside, Escape or a resize, and only one is open at a time. One taller than
595
+ // the room it gets scrolls inside itself (menuPlacement), and that scroll never closes it; a scroll of the page
596
+ // moves it along with its anchor and closes it only when the anchor leaves the window.
557
597
  // openMenu() fills it with menu items; openPopover() with any content that render() returns (re-run by refreshPopover()).
558
- const menu = { el: null, anchor: null, kind: null, render: null }
598
+ // returnTo: where focus goes back on close when that is not the anchor (a right-click menu's point).
599
+ const menu = { el: null, anchor: null, kind: null, render: null, align: 'end', returnTo: null }
600
+ function placeFloat() {
601
+ const el = menu.el
602
+ const r = menu.anchor.getBoundingClientRect()
603
+ if (r.bottom < 0 || r.top > window.innerHeight) { closeMenu(); return }
604
+ // Its full height, not the capped one: a menu that got more room grows back.
605
+ const height = el.scrollHeight + el.offsetHeight - el.clientHeight
606
+ const p = menuPlacement(r, { width: el.offsetWidth, height }, { width: window.innerWidth, height: window.innerHeight }, menu.align)
607
+ el.style.setProperty('left', p.left + 'px')
608
+ el.style.setProperty('top', p.top + 'px')
609
+ el.style.setProperty('max-height', p.maxHeight + 'px')
610
+ if (menu.kind === 'settings') settingsFit()
611
+ }
559
612
  function openFloat(anchor, el, kind, align) {
560
613
  closeMenu()
561
614
  document.body.append(el)
562
- const r = anchor.getBoundingClientRect()
563
- const w = el.offsetWidth
564
- const hgt = el.offsetHeight
565
- const x = align === 'start' ? r.left : r.right - w
566
- const left = Math.max(8, Math.min(window.innerWidth - w - 8, x))
567
- const top = r.bottom + 4 + hgt > window.innerHeight - 8 && r.top - hgt - 4 > 8 ? r.top - hgt - 4 : r.bottom + 4
568
- el.style.setProperty('left', left + 'px')
569
- el.style.setProperty('top', top + 'px')
570
615
  anchor.setAttribute('aria-expanded', 'true')
571
616
  menu.el = el
572
617
  menu.anchor = anchor
573
618
  menu.kind = kind
619
+ menu.align = align
620
+ placeFloat()
621
+ // The wheel over it never scrolls the page behind: overscroll-behavior covers a menu that scrolls, this one that
622
+ // does not or has reached its end.
623
+ el.addEventListener('wheel', (e) => {
624
+ const end = e.deltaY < 0 ? el.scrollTop <= 0 : el.scrollTop + el.clientHeight >= el.scrollHeight - 1
625
+ if (end) e.preventDefault()
626
+ }, { passive: false })
574
627
  }
575
628
  function openMenu(anchor, items, label) {
576
629
  const el = h('div', { class: 'menu', role: 'menu', 'aria-label': label },
@@ -586,7 +639,7 @@ const MAIN = String.raw `
586
639
  // A popover: a small panel of text and buttons, lighter than a dialog. A second click on its anchor closes it.
587
640
  function openPopover(anchor, kind, label, render, align = 'start') {
588
641
  if (menu.anchor === anchor) { closeMenu(true); return }
589
- const el = h('div', { class: 'menu popover', role: 'dialog', 'aria-label': label })
642
+ const el = h('div', { class: 'menu popover pop-' + kind, role: 'dialog', 'aria-label': label })
590
643
  el.addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.preventDefault(); closeMenu(true) } })
591
644
  setKids(el, render())
592
645
  openFloat(anchor, el, kind, align)
@@ -595,25 +648,71 @@ const MAIN = String.raw `
595
648
  if (first) first.focus()
596
649
  }
597
650
  function refreshPopover(kind) {
598
- if (menu.el && menu.kind === kind && menu.render) setKids(menu.el, menu.render())
651
+ if (menu.el && menu.kind === kind && menu.render) { setKids(menu.el, menu.render()); placeFloat() }
599
652
  }
600
653
  function closeMenu(restore) {
601
654
  if (!menu.el) return
602
655
  menu.el.remove()
603
656
  menu.anchor.setAttribute('aria-expanded', 'false')
604
- if (restore && menu.anchor.isConnected) menu.anchor.focus()
657
+ const back = menu.returnTo || menu.anchor
658
+ if (restore && back.isConnected) back.focus()
659
+ if (menu.anchor.classList.contains('ctx-anchor')) menu.anchor.remove()
605
660
  menu.el = null
606
661
  menu.anchor = null
607
662
  menu.kind = null
608
663
  menu.render = null
664
+ menu.returnTo = null
665
+ }
666
+ // Right-click on an account row or card (spec §3.27) opens the row's "…" menu at the pointer; the ContextMenu key
667
+ // and Shift+F10 open it at the focused element in the row. Inputs, links, buttons and selected text keep the
668
+ // browser's own menu. Each row carries its opener as el.sidebyMenu(anchor).
669
+ let kbMenuAt = 0
670
+ 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
674
+ }
675
+ function openContextMenu(target, x, y, back) {
676
+ const pt = h('span', { class: 'ctx-anchor', 'aria-hidden': 'true', css: { left: x + 'px', top: y + 'px' } })
677
+ document.body.append(pt)
678
+ target.sidebyMenu(pt)
679
+ if (menu.anchor !== pt) { pt.remove(); return }
680
+ // Opens to the right of the point, or to its left where the right edge is too near, as system menus do.
681
+ menu.align = x + menu.el.offsetWidth + 8 > window.innerWidth ? 'end' : 'start'
682
+ menu.returnTo = back && back !== document.body && target.contains(back) ? back : target.querySelector('.more')
683
+ placeFloat()
684
+ }
685
+ function onContextMenu(e) {
686
+ if (Date.now() - kbMenuAt < 600) { e.preventDefault(); return }
687
+ if (ui.arrange || !e.target.closest || e.target.closest('input, textarea, select, a, button, [contenteditable], .tip')) return
688
+ if (window.getSelection && String(window.getSelection())) return
689
+ const target = menuTarget(e.target)
690
+ if (!target) return
691
+ e.preventDefault()
692
+ openContextMenu(target, e.clientX, e.clientY, document.activeElement)
693
+ }
694
+ function onMenuKey(e) {
695
+ if (e.key !== 'ContextMenu' && !(e.key === 'F10' && e.shiftKey)) return
696
+ if (menu.el || (dlg.el && dlg.el.open) || ui.arrange) return
697
+ const at = document.activeElement
698
+ // Text fields and links keep the browser's own menu, as with the mouse; the row's own buttons open the row menu.
699
+ if (at && at.closest && at.closest('input, textarea, select, a, [contenteditable]')) return
700
+ const target = menuTarget(at)
701
+ if (!target) return
702
+ e.preventDefault()
703
+ kbMenuAt = Date.now()
704
+ const r = (at && at !== document.body ? at : target).getBoundingClientRect()
705
+ openContextMenu(target, r.left, r.bottom, at)
609
706
  }
610
707
  function menuKeys(e) {
611
708
  const items = Array.from(menu.el.querySelectorAll('.menu-item:not(:disabled)'))
612
709
  const i = items.indexOf(document.activeElement)
613
- if (e.key === 'ArrowDown') items[(i + 1) % items.length].focus()
614
- else if (e.key === 'ArrowUp') items[(i - 1 + items.length) % items.length].focus()
615
- else if (e.key === 'Home') items[0].focus()
616
- else if (e.key === 'End') items[items.length - 1].focus()
710
+ // A menu that scrolls inside keeps the focused item in sight; focus() alone does not always scroll it there.
711
+ const go = (it) => { it.focus({ preventScroll: true }); it.scrollIntoView({ block: 'nearest' }) }
712
+ if (e.key === 'ArrowDown') go(items[(i + 1) % items.length])
713
+ else if (e.key === 'ArrowUp') go(items[(i - 1 + items.length) % items.length])
714
+ else if (e.key === 'Home') go(items[0])
715
+ else if (e.key === 'End') go(items[items.length - 1])
617
716
  else if (e.key === 'Escape') closeMenu(true)
618
717
  else if (e.key === 'Tab') { closeMenu(true); return }
619
718
  else return
@@ -621,7 +720,28 @@ const MAIN = String.raw `
621
720
  }
622
721
  document.addEventListener('pointerdown', (e) => { if (menu.el && !menu.el.contains(e.target) && !menu.anchor.contains(e.target)) closeMenu() })
623
722
  window.addEventListener('resize', () => closeMenu())
624
- window.addEventListener('scroll', () => closeMenu(), { passive: true })
723
+ // Layout bands: the page's narrow-screen rules hang on the root's data-width (set before the first paint by the
724
+ // head script), not on media queries, so a width that slides across a breakpoint (a dragged window, a Portal's
725
+ // sidebar opening around this frame) changes the layout as it crosses, as one short cross-fade, not once per frame.
726
+ function applyWidthTier(tier) {
727
+ const root = document.documentElement
728
+ const set = () => { root.dataset.width = tier }
729
+ if (REDUCED || document.hidden || !document.startViewTransition) return set()
730
+ root.classList.add('vt-width')
731
+ document.startViewTransition(set).finished.finally(() => root.classList.remove('vt-width'))
732
+ }
733
+ let widthFollow = null
734
+ function followWidth(width) {
735
+ if (!widthFollow) {
736
+ const timers = { set: (fn, ms) => setTimeout(fn, ms), clear: (id) => clearTimeout(id) }
737
+ const shown = document.documentElement.dataset.width || widthTier(window.innerWidth)
738
+ widthFollow = widthFollower(shown, widthTier, applyWidthTier, WIDTH_SETTLE_MS, timers)
739
+ }
740
+ widthFollow(width)
741
+ }
742
+ window.addEventListener('resize', () => followWidth(window.innerWidth))
743
+ // Capture also sees the scroll of an inner scroller (a dialog, a list); the menu's own scroll is left alone.
744
+ window.addEventListener('scroll', (e) => { if (menu.el && !menu.el.contains(e.target)) placeFloat() }, { passive: true, capture: true })
625
745
 
626
746
  // What one directory does: start it, its short commands, its desktop app, its folder, model, tuning, Health.
627
747
  function dirCopies(a) {
@@ -640,27 +760,44 @@ const MAIN = String.raw `
640
760
  return [
641
761
  a.modelInfo && a.modelInfo.settable ? { icon: 'terminal', label: t('menu.model'), run: () => openModel(a) } : null,
642
762
  family(a.family).tuning ? { icon: 'check', label: t('menu.tune'), run: () => openTune(a) } : null,
763
+ settingsItem(a),
643
764
  { icon: 'check', label: t('menu.check'), disabled: S.checking || S.fixing || Boolean(ui.checkingRef), run: () => checkAccount(a.ref) },
644
765
  ]
645
766
  }
767
+ // The directory's own Host settings file, opened in the user's editor (spec §3.30); it starts a program, so a
768
+ // read-only Panel has no such item.
769
+ function settingsItem(a) {
770
+ const file = family(a.family).settingsFile
771
+ if (!file || !a.dir || BOOT.readOnly) return null
772
+ return { icon: 'file', label: t('menu.editSettings', { file }), hint: a.dir + '/' + file, run: () => editSettings(a, file) }
773
+ }
774
+ async function editSettings(a, file) {
775
+ try {
776
+ const r = await api('/api/account/edit-settings', { account: a.ref })
777
+ toast(t('edit.opened', { ref: a.ref, file }))
778
+ if (r.sharedWith && r.sharedWith.length) toast(t('edit.shared', { names: r.sharedWith.map(refName).join(', ') }), { kind: 'info', duration: 8000 })
779
+ } catch (e) { toast(t('edit.failed', { ref: a.ref, file, msg: e.message }), { kind: 'fail' }) }
780
+ }
646
781
  // What the login does, whichever directory: the browser, signing in, the email, a new account like it.
647
782
  function loginItems(a) {
648
783
  return [
649
784
  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,
650
786
  a.kind !== 'api' ? { icon: 'key', label: t('menu.copyLogin'), hint: 'sideby login ' + a.ref, run: () => copyText('sideby login ' + a.ref) } : null,
787
+ keyable(a) ? { icon: 'key', label: t('menu.enterKey'), run: () => openKey(a) } : null,
651
788
  a.identity && a.identity.email ? { icon: 'mail', label: t('menu.copyEmail'), hint: emailText(a.identity.email), run: () => copyText(a.identity.email) } : null,
652
789
  ]
653
790
  }
654
791
  function likeItem(a) { return BOOT.readOnly ? null : { icon: 'userPlus', label: t('menu.like'), run: () => openCreate({ family: a.family, api: a.kind === 'api' }) } }
655
792
  // Grouped by what the user wants to do: open, copy, manage.
656
793
  function accountMenu(a, anchor) {
657
- const [browser, login, email] = loginItems(a)
794
+ const [browser, signInItem, login, key, email] = loginItems(a)
658
795
  const opens = [deskItem(a), browser].filter(Boolean)
659
796
  const copies = dirCopies(a)
660
797
  const items = [pinItem(a),
661
798
  opens.length ? '-' : null, opens.length ? { header: t('menu.groupOpen') } : null, ...opens,
662
799
  '-', { header: t('menu.groupCopy') }, ...copies, login, email,
663
- '-', { header: t('menu.groupManage') }, ...dirTools(a), likeItem(a)]
800
+ '-', { header: t('menu.groupManage') }, signInItem, key, ...dirTools(a), likeItem(a)]
664
801
  openMenu(anchor, items, t('menu.label', { ref: a.ref }))
665
802
  }
666
803
  // A Same Login row (ADR-0026): pin first, then a section per directory, then what the login shares.
@@ -682,15 +819,19 @@ const MAIN = String.raw `
682
819
  const text = t('row.copyRun', { cmd })
683
820
  return h('button', { class: 'icon-btn row-run', type: 'button', 'aria-label': text, title: text, onclick: (e) => { e.stopPropagation(); copyText(cmd) } }, icon('terminal'))
684
821
  }
685
- // The pin at the end of a row (spec §3.25): one click pins or unpins. A pinned row always shows it, filled; the
686
- // others show it on hover or focus. A read-only Panel shows the mark of a pinned row and no button.
687
- function pinButton(a, label) {
822
+ // 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
+ // pinning and unpinning are in the row's menu and in the arrange mode.
824
+ function pinMark(a) {
825
+ return isPinned(a) ? h('span', { class: 'pin-mark', role: 'img', title: t('pin.mark'), 'aria-label': t('pin.mark') }, icon('pin')) : null
826
+ }
827
+ // Before the name (spec §3.27, 2026-10-18): a pinned row always shows its pin, and a click unpins it; any other
828
+ // row shows a fainter pin in the same place on hover or keyboard focus, and a click pins it. The slot keeps its
829
+ // width when empty, so the name never moves. A read-only Panel shows only the mark.
830
+ function pinSlot(a) {
831
+ if (BOOT.readOnly) return pinMark(a)
688
832
  const on = isPinned(a)
689
- if (BOOT.readOnly) return on ? h('span', { class: 'icon-btn pin-btn row-pin is-on', role: 'img', title: t('pin.mark'), 'aria-label': t('pin.mark') }, icon('pin')) : null
690
- const full = !on && pinnedUnits(a.family) >= PIN_MAX
691
- const text = full ? t('pin.full', { n: PIN_MAX }) : t(on ? 'pin.unpinName' : 'pin.pinName', { name: label, title: family(a.family).title })
692
- return h('button', { class: 'icon-btn pin-btn row-pin' + (on ? ' is-on' : ''), type: 'button', 'aria-pressed': String(on), 'aria-label': text, title: text, 'aria-disabled': full ? 'true' : null,
693
- onclick: (e) => { e.stopPropagation(); if (full) toast(t('pin.full', { n: PIN_MAX })); else togglePin(a) } }, icon('pin'))
833
+ const label = t(on ? 'pin.unpin' : 'pin.pin')
834
+ return h('button', { class: 'pin-slot' + (on ? ' is-on' : ''), type: 'button', 'aria-label': label, title: label, onclick: (e) => { e.stopPropagation(); togglePin(a) } }, icon('pin'))
694
835
  }
695
836
  function pinItem(a) {
696
837
  if (BOOT.readOnly) return null
@@ -765,12 +906,14 @@ const MAIN = String.raw `
765
906
  document.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en'
766
907
  for (const el of document.querySelectorAll('[data-i18n]')) el.textContent = t(el.getAttribute('data-i18n'))
767
908
  $('refresh').setAttribute('aria-label', t('top.refresh'))
909
+ $('ask-ai').setAttribute('aria-label', t('ask.button'))
768
910
  renderSettingsButton()
769
911
  }
770
912
  function applyTheme() {
771
913
  if (BOOT.colorScheme !== 'auto') return
772
- if (prefs.theme === 'system') document.documentElement.removeAttribute('data-theme')
773
- else document.documentElement.setAttribute('data-theme', prefs.theme)
914
+ const theme = viewPrefs().theme
915
+ if (theme === 'system') document.documentElement.removeAttribute('data-theme')
916
+ else document.documentElement.setAttribute('data-theme', theme)
774
917
  }
775
918
  function stat(label, value, sub, extra, opts) {
776
919
  const kids = [h('div', { class: 'stat-text' }, h('div', { class: 'stat-label' }, label), h('div', { class: 'stat-value' }, value), h('div', { class: 'stat-sub' }, sub)), extra]
@@ -867,7 +1010,7 @@ const MAIN = String.raw `
867
1010
  })
868
1011
  const display = h('button', { class: 'btn tb-display', type: 'button', 'aria-haspopup': 'dialog', 'aria-expanded': 'false', title: t('tb.display') }, icon('sliders'), h('span', null, t('tb.display')))
869
1012
  display.addEventListener('click', () => openPopover(display, 'display', t('tb.display'), displayPanel, 'end'))
870
- const create = BOOT.readOnly ? null : h('button', { class: 'btn btn-primary', type: 'button', 'aria-label': t('tb.new'), onclick: () => openCreate(null) }, icon('plus'), h('span', null, t('tb.new')))
1013
+ const create = BOOT.readOnly ? null : h('button', { class: 'btn btn-primary', type: 'button', 'aria-label': t('tb.new'), title: t('tb.new'), onclick: () => openCreate(null) }, icon('plus'), h('span', null, t('tb.new')))
871
1014
  setKids($('toolbar'), [
872
1015
  h('label', { class: 'search' }, icon('search', 'search-ic'), tb.search, h('kbd', { class: 'kbd', 'aria-hidden': 'true' }, '/')),
873
1016
  h('div', { class: 'tools' }, tb.family, tb.sort, display),
@@ -955,7 +1098,7 @@ const MAIN = String.raw `
955
1098
  const setup = setupFor(a.family)
956
1099
  // One setup turns quota on for every account of the Family, so the switch lives in the group header only.
957
1100
  // A check that asks the Host (Grok) and is turned off, or failed (spec §3.26): say why and what to do.
958
- if (q.reason === 'fetch-failed') return h('div', { class: 'q-note q-off' }, h('span', { class: 'muted' }, t('quota.fetchFailed')), tipRaw(t('quota.fetchFailed'), q.detail || ''))
1101
+ if (q.reason === 'fetch-failed') return h('div', { class: 'q-note q-off' }, h('span', { class: 'muted' }, t('quota.fetchFailed')), tipRaw(t('quota.fetchFailed'), q.detail || ''), askWhy(a, q))
959
1102
  if (q.reason === 'not-enabled' && checkOf(a.family)) return h('div', { class: 'q-note q-off' }, h('span', { class: 'muted' }, t('quota.checkOff')), tipRaw(t('quota.checkOff'), q.detail || t('quota.checkOffHint')))
960
1103
  if (q.reason === 'not-enabled') {
961
1104
  const host = famTitle(a)
@@ -966,7 +1109,12 @@ const MAIN = String.raw `
966
1109
  }
967
1110
  if (q.reason === 'api-account') return h('div', { class: 'q-note' }, t('quota.api'), tip('api'))
968
1111
  const text = { 'no-session': 'quota.noSession', 'no-source': 'quota.noSource', unrecognized: 'quota.unrecognized' }[q.reason]
969
- return h('div', { class: 'q-note', title: q.reason === 'no-session' ? t('quota.noSessionHint') : q.detail || null }, text ? t(text) : t('quota.unavailable', { reason: q.reason }))
1112
+ return h('div', { class: 'q-note', title: q.reason === 'no-session' ? t('quota.noSessionHint') : q.detail || null }, text ? t(text) : t('quota.unavailable', { reason: q.reason }), askWhy(a, q))
1113
+ }
1114
+ // "Ask AI why" in a quota cell with no data or an error (spec §3.28).
1115
+ function askWhy(a, q) {
1116
+ if (!quotaAskable(q.reason)) return null
1117
+ 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'))
970
1118
  }
971
1119
  function quotaBlock(a, now, cols) {
972
1120
  const q = a.quota
@@ -980,7 +1128,9 @@ const MAIN = String.raw `
980
1128
  const via = q.fetched ? t('quota.fetchedFrom', { host: famTitle(a), ago: ago(q.observedAt) }) : null
981
1129
  const failed = q.fetchError ? t('quota.lastCheckFailed', { why: q.fetchError }) : null
982
1130
  const title = [from || via || (stale ? null : t('quota.dataFrom', { ago: ago(q.observedAt) })), failed].filter(Boolean).join('\n') || null
983
- return h('div', { class: 'quota' + (stale ? ' is-stale' : ''), title },
1131
+ // --qr: this row's own number of windows, so a narrow list can split the width between them alone (--qn is the
1132
+ // widest Family's, for the wide list's shared columns).
1133
+ return h('div', { class: 'quota' + (stale ? ' is-stale' : ''), title, css: wins.length ? { '--qr': String(cols.length) } : null },
984
1134
  wins.length ? cols.map((c) => {
985
1135
  const w = wins.find((x) => winKey(x) === c)
986
1136
  return w ? meter(w, now, stale, q.observedAt) : noMeter(winTitle(c))
@@ -1003,9 +1153,14 @@ const MAIN = String.raw `
1003
1153
  h('div', { class: 'u-sub' }, rate === null ? tn('usage.sessions', u.sessions) : t('usage.cache', { n: Math.round(rate * 100) }))),
1004
1154
  u.totalTokens ? spark(u.daily) : null)
1005
1155
  }
1006
- function lastUsed(a) {
1156
+ function lastUsed(a, cls = 'last') {
1007
1157
  const at = a.usage && a.usage.status === 'ok' && a.usage.lastActivityAt
1008
- return h('div', { class: 'last', title: at ? t('last.title', { at: clock(at) }) : t('last.unknown') }, at ? ago(at) : h('span', { class: 'faint' }, '—'))
1158
+ return h('div', { class: cls, title: at ? t('last.title', { at: clock(at) }) : t('last.unknown') }, at ? ago(at) : h('span', { class: 'faint' }, '—'))
1159
+ }
1160
+ // The line under a row's name, with a copy of the last use at its end: the medium-width list shows that copy
1161
+ // instead of the column (the styles show one of the two), so the time stays next to the account it belongs to.
1162
+ function metaLine(line, a) {
1163
+ return h('div', { class: 'ident-meta' }, line, lastUsed(a, 'last-inline'))
1009
1164
  }
1010
1165
  function healthChip(a) {
1011
1166
  const hs = healthOf(a.ref)
@@ -1020,53 +1175,82 @@ const MAIN = String.raw `
1020
1175
  return h('button', { class: 'chip chip-btn health' + (lvl ? ' chip-' + lvl : ''), type: 'button', title: t('health.filterHint'), 'aria-label': t('health.chipLabel', { ref: a.ref, status: text }), onclick: () => filterHealth(a.ref) },
1021
1176
  h('span', { class: 'dot' + (lvl ? ' dot-' + lvl : ''), 'aria-hidden': 'true' }), text)
1022
1177
  }
1023
- // A dot after the name when the account needs a look that no tag shows: a fuller quota window or a Health
1024
- // finding. Its reason is on hover; the details say more.
1025
- // Inside a login group the quota warning is the first row's, so another row's dot is only about the row itself.
1026
- function attentionDot(a) {
1178
+ // Who the attention words speak about. Inside a login group the quota warning is the first row's, so another
1179
+ // row's word is only about the row itself.
1180
+ function attentionSubject(a) {
1027
1181
  const lead = loginLead(a)
1028
- const subject = !lead ? a
1182
+ return !lead ? a
1029
1183
  : lead !== a.ref ? Object.assign({}, a, { quota: undefined })
1030
1184
  : Object.assign({}, a, { quota: a.quota && Object.assign({}, a.quota, { from: undefined }) })
1031
- const r = reasonsOf(subject, Date.now())
1032
- const lvl = r.includes('health-fail') ? 'fail' : r.includes('quota-high') || r.includes('health-warn') ? 'warn' : ''
1033
- if (!lvl) return null
1185
+ }
1186
+ // A word, not only a colour (spec §3.8): what kind of look the account needs; the reason is on hover.
1187
+ function attentionWord(subject, reason) {
1188
+ const lvl = reason === 'health-fail' ? 'fail' : 'warn'
1034
1189
  const why = whyOf(subject, Date.now())
1035
- // A word, not only a colour (spec §3.8): what kind of look the account needs; the reason is on hover.
1036
- const word = r.includes('health-fail') ? t('att.fix') : r.includes('quota-high') ? t('att.quota') : t('att.check')
1190
+ const word = reason === 'health-fail' ? t('att.fix') : reason === 'quota-high' ? t('att.quota') : t('att.check')
1037
1191
  return h('span', { class: 'tag tag-' + lvl + ' att-tag', title: why, 'aria-label': why }, h('span', { class: 'dot dot-' + lvl, 'aria-hidden': 'true' }), word)
1038
1192
  }
1193
+ // The word a directory inside a Same Login's details shows when it needs a fix or a look.
1194
+ function attentionDot(a) {
1195
+ const subject = attentionSubject(a)
1196
+ const r = reasonsOf(subject, Date.now())
1197
+ const reason = ['health-fail', 'quota-high', 'health-warn'].find((x) => r.includes(x))
1198
+ return reason ? attentionWord(subject, reason) : null
1199
+ }
1200
+ // The one status badge after the name (spec §3.27): needs a fix, running low, the other attention words, then
1201
+ // recommended, then API. The rest is in the details or on hover.
1202
+ function statusBadge(a, members) {
1203
+ const subject = attentionSubject(a)
1204
+ const next = members ? members.some(isNext) : isNext(a)
1205
+ const k = rowBadge(reasonsOf(subject, Date.now()), { next, api: a.kind === 'api' })
1206
+ if (k === 'health-fail' || k === 'quota-high' || k === 'health-warn') return attentionWord(subject, k)
1207
+ if (k === 'signed-out')
1208
+ return h('button', { class: 'tag tag-fail tag-btn', type: 'button', title: t('acct.signInHint'), 'aria-label': t('acct.signedOutLabel', { ref: a.ref }), onclick: (e) => { e.stopPropagation(); signIn(a) } }, h('span', { class: 'dot dot-fail', 'aria-hidden': 'true' }), t('acct.signedOut'))
1209
+ if (k === 'not-installed') return h('span', { class: 'tag tag-warn' }, t(family(a.family).brokenBin ? 'acct.broken' : 'acct.notInstalled'))
1210
+ if (k === 'next') return nextTag(a)
1211
+ if (k === 'api') return h('span', { class: 'tag tag-warn', title: t('tip.api.body') }, t('acct.api'))
1212
+ return null
1213
+ }
1214
+ // The short command, as quiet text after the name; every alias and its arguments are on hover.
1215
+ function aliasText(a) {
1216
+ const all = a.aliases || []
1217
+ if (!all.length) return null
1218
+ const lines = all.map((x) => { const args = aliasArgsOf(a, x); return x + ' · ' + (args ? t('acct.aliasArgs', { args: args.join(' ') }) : t('acct.alias')) })
1219
+ return h('span', { class: 'alias', title: lines.join('\n') }, all[0])
1220
+ }
1221
+ // A Same Login row (spec §3.21) gets a link mark after the name; what it means is on hover.
1222
+ function loginMark(members) {
1223
+ if (!members || members.length < 2) return null
1224
+ const text = t('login.label', { names: members.map((m) => m.name).join(', ') }) + '\n' + t('login.explain')
1225
+ return h('span', { class: 'login-mark', role: 'img', title: text, 'aria-label': text }, icon('link'))
1226
+ }
1039
1227
  // members: the directories of a Same Login shown as this one row (spec §3.21).
1040
1228
  function nameLine(a, members) {
1041
- const next = members ? members.some(isNext) : isNext(a)
1042
1229
  return h('div', { class: 'ident-name' },
1230
+ pinSlot(a),
1043
1231
  h('span', { class: 'name', title: a.name }, a.name),
1044
- attentionDot(a),
1045
- (a.aliases || []).slice(0, 3).map((x) => {
1046
- const args = aliasArgsOf(a, x)
1047
- return h('span', { class: 'tag tag-alias', title: args ? t('acct.aliasArgs', { args: args.join(' ') }) : t('acct.alias') }, x)
1048
- }),
1049
- members ? h('span', { class: 'tag tag-login', title: t('login.explain') }, t('login.dirs', { n: members.length })) : null,
1050
- a.kind === 'api' ? h('span', { class: 'tag tag-warn', title: t('tip.api.body') }, t('acct.api')) : null,
1051
- next
1052
- ? nextTag(a)
1053
- : null,
1054
- a.login === 'logged-out' && a.kind !== 'api'
1055
- ? h('button', { class: 'tag tag-fail tag-btn', type: 'button', title: t('acct.signInHint'), 'aria-label': t('acct.signedOutLabel', { ref: a.ref }), onclick: () => copyText('sideby login ' + a.ref) }, h('span', { class: 'dot dot-fail', 'aria-hidden': 'true' }), t('acct.signedOut'))
1056
- : null,
1057
- a.hostInstalled === false ? h('span', { class: 'tag tag-warn' }, t(family(a.family).brokenBin ? 'acct.broken' : 'acct.notInstalled')) : null)
1232
+ loginMark(members),
1233
+ aliasText(a),
1234
+ statusBadge(a, members))
1058
1235
  }
1059
1236
  // An organization name as the vendor wrote it, without a trailing comma or full stop it sometimes carries.
1060
1237
  function orgText(org) { return org ? String(org).replace(/[\s,,;;、。]+$/u, '') : '' }
1061
1238
  // The name part of a ref (claude:001 gives 001), as rows show other Accounts of the same Family.
1062
1239
  function refName(ref) { return String(ref).slice(String(ref).indexOf(':') + 1) }
1063
- // Who the account is signed in as, under its name; masked while "Hide emails" is on.
1240
+ // Who the account is signed in as, under its name, in full unless the cell is too narrow; masked while "Hide
1241
+ // emails" is on. The Browser Sign-in is in the details (spec §3.27).
1064
1242
  function emailLine(a) {
1065
1243
  const id = a.identity
1066
- if (!id || (!id.email && !browserButton(a))) return null
1067
- const email = id.email ? emailText(id.email) : ''
1068
- return h('div', { class: 'ident-email', title: [email, orgText(id.org)].filter(Boolean).join(' · ') },
1069
- dots([email ? h('button', { class: 'email email-btn', type: 'button', title: t('menu.copyEmail'), 'aria-label': t('menu.copyEmail') + ' ' + email, onclick: (e) => { e.stopPropagation(); copyText(id.email) } }, email) : null, browserButton(a)]))
1244
+ if (!id || !id.email) return null
1245
+ const email = emailText(id.email)
1246
+ const full = [email, orgText(id.org)].filter(Boolean).join(' · ')
1247
+ return h('div', { class: 'ident-email', title: full },
1248
+ h('button', { class: 'email email-btn', type: 'button', title: full + '\n' + t('menu.copyEmail'), 'aria-label': t('menu.copyEmail') + ' ' + email, onclick: (e) => { e.stopPropagation(); copyText(id.email) } }, email))
1249
+ }
1250
+ // The Browser Sign-in as a line of the details: which Chrome browser user signed in to the account's website.
1251
+ function browserItem(a) {
1252
+ const b = browserButton(a)
1253
+ return b ? h('div', { class: 'rd-item rd-browser' }, h('span', { class: 'rd-label' }, t('row.browser')), b) : null
1070
1254
  }
1071
1255
  function subLine(a) {
1072
1256
  const plan = a.quota && a.quota.status === 'ok' && a.quota.plan
@@ -1237,7 +1421,7 @@ const MAIN = String.raw `
1237
1421
  function foldClick(a) { return foldHit(() => toggleRow(a)) }
1238
1422
  function foldHit(run) {
1239
1423
  return (e) => {
1240
- if (e.target.closest('button, a, input, select, textarea, .tip')) return
1424
+ if (foldSkips(e.target)) return
1241
1425
  const dragged = downAt && Math.hypot(e.clientX - downAt.x, e.clientY - downAt.y) > 4
1242
1426
  if (dragged && window.getSelection && String(window.getSelection())) return
1243
1427
  run()
@@ -1348,14 +1532,16 @@ const MAIN = String.raw `
1348
1532
  if (ui.arrange) return arrangeRow(a, [a])
1349
1533
  const open = isOpen(a)
1350
1534
  const email = emailLine(a)
1351
- return h('div', { class: 'row fold-hit' + (open ? ' row-open' : '') + (a.error ? ' row-error' : ''), role: 'listitem', 'data-ref': a.ref, 'data-key': a.ref, 'data-sig': rowSig(a), onclick: foldClick(a) },
1352
- h('div', { class: 'ident' }, rowToggle(a), badge(a.family, 'sm'), h('div', { class: 'ident-text' }, nameLine(a), email || subLine(a))),
1535
+ return withMenu(h('div', { class: 'row fold-hit' + (open ? ' row-open' : '') + (a.error ? ' row-error' : ''), role: 'listitem', 'data-ref': a.ref, 'data-key': a.ref, 'data-sig': rowSig(a), onclick: foldClick(a) },
1536
+ h('div', { class: 'ident' }, rowToggle(a), badge(a.family, 'sm'), h('div', { class: 'ident-text' }, nameLine(a), metaLine(email || subLine(a), a))),
1353
1537
  quotaBlock(a, now, cols),
1354
1538
  lastUsed(a),
1355
- h('div', { class: 'row-end' }, runButton(a), pinButton(a, a.name), moreButton(a)),
1539
+ h('div', { class: 'row-end' }, runButton(a), moreButton(a)),
1356
1540
  open ? rowDetail(a, Boolean(email)) : null,
1357
- notes(a))
1541
+ notes(a)), (anchor) => accountMenu(a, anchor))
1358
1542
  }
1543
+ // What a right-click on el opens (see openContextMenu).
1544
+ function withMenu(el, open) { el.sidebyMenu = open; return el }
1359
1545
  // Directories signed in as one login (spec §3.21, ADR-0026) are one row: the vendor counts one quota, so the row
1360
1546
  // shows it once, with the email and the newest use; opening it lists each directory with its own short command,
1361
1547
  // last use, tokens, Health, a button that copies its start command and its own menu.
@@ -1385,20 +1571,21 @@ const MAIN = String.raw `
1385
1571
  if (ui.arrange) return arrangeRow(a, ms)
1386
1572
  const open = isOpen(a)
1387
1573
  const email = emailLine(a)
1388
- return h('div', { class: 'row row-login fold-hit' + (open ? ' row-open' : '') + (a.error ? ' row-error' : ''), role: 'listitem', 'aria-label': t('login.label', { names: ms.map((m) => m.name).join(', ') }), 'data-ref': a.ref, 'data-key': loginKey(ms.map((m) => m.ref)), 'data-sig': sig(ms.map(rowSig)), onclick: foldClick(a) },
1389
- h('div', { class: 'ident' }, rowToggle(a), badge(a.family, 'sm'), h('div', { class: 'ident-text' }, nameLine(a, ms), email || subLine(a))),
1574
+ return withMenu(h('div', { class: 'row row-login fold-hit' + (open ? ' row-open' : '') + (a.error ? ' row-error' : ''), role: 'listitem', 'aria-label': t('login.label', { names: ms.map((m) => m.name).join(', ') }), 'data-ref': a.ref, 'data-key': loginKey(ms.map((m) => m.ref)), 'data-sig': sig(ms.map(rowSig)), onclick: foldClick(a) },
1575
+ h('div', { class: 'ident' }, rowToggle(a), badge(a.family, 'sm'), h('div', { class: 'ident-text' }, nameLine(a, ms), metaLine(email || subLine(a), newestOf(ms)))),
1390
1576
  quotaBlock(a, now, cols),
1391
1577
  lastUsed(newestOf(ms)),
1392
- h('div', { class: 'row-end' }, runButton(a), pinButton(a, ms.map((m) => m.name).join(', ')), loginMoreButton(ms)),
1578
+ h('div', { class: 'row-end' }, runButton(a), loginMoreButton(ms)),
1393
1579
  open ? loginDetail(ms) : null,
1394
- notes(a))
1580
+ notes(a)), (anchor) => loginMenu(ms, anchor))
1395
1581
  }
1396
1582
  function loginDetail(ms) {
1397
1583
  return h('div', { class: 'row-detail login-detail' },
1398
1584
  h('p', { class: 'rd-note' }, t('login.explain')),
1585
+ browserItem(ms[0]),
1399
1586
  h('div', { class: 'login-dirs', role: 'list' }, ms.map((m) => {
1400
1587
  const run = 'sideby run ' + m.ref
1401
- return h('div', { class: 'login-dir', role: 'listitem', 'data-ref': m.ref },
1588
+ return withMenu(h('div', { class: 'login-dir', role: 'listitem', 'data-ref': m.ref },
1402
1589
  h('div', { class: 'ld-name' },
1403
1590
  h('span', { class: 'name' }, m.name),
1404
1591
  m.ref !== ms[0].ref ? attentionDot(m) : null,
@@ -1409,7 +1596,7 @@ const MAIN = String.raw `
1409
1596
  usageBlock(m),
1410
1597
  healthChip(m),
1411
1598
  h('button', { class: 'btn btn-sm', type: 'button', title: run, onclick: () => copyText(run) }, icon('terminal'), t('login.copyRun')),
1412
- moreButton(m))
1599
+ moreButton(m)), (anchor) => accountMenu(m, anchor))
1413
1600
  })))
1414
1601
  }
1415
1602
  // What a click on a row opens: how it runs (ref, model and effort, a shared login), its tokens and its Health.
@@ -1422,19 +1609,21 @@ const MAIN = String.raw `
1422
1609
  const same = sameLoginNote(a)
1423
1610
  return h('div', { class: 'row-detail' },
1424
1611
  withSub || same ? h('div', { class: 'rd-item rd-run' }, h('span', { class: 'rd-label' }, t('row.runs')), withSub ? subLine(a) : null, same) : null,
1612
+ browserItem(a),
1425
1613
  h('div', { class: 'rd-item rd-usage' }, h('span', { class: 'rd-label' }, t('col.tokens', { n: BOOT.usageDays })), usageBlock(a)),
1426
1614
  h('div', { class: 'rd-item rd-health' }, h('span', { class: 'rd-label' }, t('col.health')), healthChip(a)))
1427
1615
  }
1428
1616
  // A card shows everything at once; it has room for it.
1429
1617
  function card(a, now, cols) {
1430
- return h('article', { class: 'card' + (a.error ? ' card-error' : ''), 'data-ref': a.ref, 'data-key': a.ref, 'data-sig': rowSig(a), 'aria-label': a.ref },
1618
+ 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 },
1431
1619
  h('header', { class: 'card-head' },
1432
1620
  badge(a.family, 'sm'),
1433
1621
  h('div', { class: 'ident-text' }, nameLine(a), emailLine(a), subLine(a), sameLoginNote(a)),
1434
- h('div', { class: 'row-end' }, pinButton(a, a.name), moreButton(a))),
1622
+ h('div', { class: 'row-end' }, moreButton(a))),
1435
1623
  notes(a),
1624
+ browserItem(a),
1436
1625
  quotaBlock(a, now, cols),
1437
- h('footer', { class: 'card-foot' }, usageBlock(a), h('div', { class: 'card-side' }, lastUsed(a), healthChip(a))))
1626
+ h('footer', { class: 'card-foot' }, usageBlock(a), h('div', { class: 'card-side' }, lastUsed(a), healthChip(a)))), (anchor) => accountMenu(a, anchor))
1438
1627
  }
1439
1628
  // The list's column titles, once per group under its header. Screen readers get each cell's own label instead.
1440
1629
  function colHead(cols, list) {
@@ -1660,7 +1849,7 @@ const MAIN = String.raw `
1660
1849
  fams.length ? h('ul', { class: 'host-list' }, fams.map((f) => h('li', null, badge(f.id, 'sm'), h('span', null, f.title),
1661
1850
  f.installed ? h('span', { class: 'muted small' }, tx('empty.runOnce', { bin: h('code', null, f.bin) })) : f.installCommand ? codeCopy(f.installCommand) : link(t('empty.install'), f.installUrl, 'btn btn-sm')))) : h('p', { class: 'muted small' }, t('empty.noFamilies')),
1662
1851
  BOOT.readOnly ? null : h('button', { class: 'btn btn-primary', type: 'button', onclick: () => openCreate(null) }, icon('plus'), t('empty.create')),
1663
- BOOT.readOnly ? null : h('p', { class: 'muted small' }, t('ai.emptyHint'), ' ', h('button', { class: 'link-btn', type: 'button', onclick: openAi }, t('ai.how'))))
1852
+ BOOT.readOnly ? null : h('p', { class: 'muted small' }, t('ai.emptyHint'), ' ', h('button', { class: 'link-btn', type: 'button', onclick: () => openAsk({ task: 'account', context: { version: BOOT.version } }) }, t('ask.title.account'))))
1664
1853
  }
1665
1854
  function clearFilters() {
1666
1855
  ui.query = ''
@@ -1789,7 +1978,7 @@ const MAIN = String.raw `
1789
1978
  }
1790
1979
  function arrangeBar() {
1791
1980
  return h('div', { class: 'arrange-bar', role: 'region', 'aria-label': t('sort.arrange'), 'data-key': 'arrange-bar', 'data-sig': sig([ordered(), lang]) },
1792
- h('span', { class: 'arrange-text' }, icon('grip'), h('span', null, t('order.bar')), h('button', { class: 'link-btn small', type: 'button', onclick: openAi }, t('ai.orderHint'))),
1981
+ h('span', { class: 'arrange-text' }, icon('grip'), h('span', null, t('order.bar')), h('button', { class: 'link-btn small', type: 'button', onclick: () => openAsk() }, t('ai.orderHint'))),
1793
1982
  h('div', { class: 'arrange-actions' },
1794
1983
  h('button', { class: 'link-btn', type: 'button', title: t('order.resetHint'), disabled: ordered() ? undefined : true, onclick: resetOrder }, t('order.resetButton')),
1795
1984
  h('button', { class: 'btn btn-primary btn-sm', type: 'button', onclick: endArrange }, t('order.done'))))
@@ -1808,13 +1997,15 @@ const MAIN = String.raw `
1808
1997
  const pinLabel = full ? t('pin.full', { n: PIN_MAX }) : t(pinned ? 'pin.unpinName' : 'pin.pinName', { name: label, title: family(fam).title })
1809
1998
  return h('div', { class: 'row row-arrange' + (pinned ? ' is-pinned' : ''), role: 'listitem', 'data-ref': a.ref, 'data-key': 'arr:' + loginKey(ms.map((m) => m.ref)), 'data-sig': sig([ms.map(rowSig), at, lo, hi, full]) },
1810
1999
  h('div', { class: 'ident' }, dragHandle('account', fam, a.name, label), badge(fam, 'sm'), h('div', { class: 'ident-text' }, h('div', { class: 'ident-name' },
2000
+ pinMark(a),
1811
2001
  h('span', { class: 'name', title: a.name }, a.name),
1812
- (a.aliases || []).slice(0, 3).map((x) => h('span', { class: 'tag tag-alias' }, x)),
1813
- ms.length > 1 ? h('span', { class: 'tag tag-login', title: t('login.explain') }, t('login.dirs', { n: ms.length })) : null))),
2002
+ loginMark(ms),
2003
+ aliasText(a)))),
1814
2004
  h('div', { class: 'arrange-tools' },
1815
2005
  h('button', { class: 'icon-btn', type: 'button', 'aria-label': t('order.up', { name: label }), title: t('order.up', { name: label }), disabled: at <= lo ? true : undefined, onclick: () => moveUnit('account', fam, at, at - 1, { focus: a.name, label, button: 'up' }) }, icon('arrowUp')),
1816
2006
  h('button', { class: 'icon-btn', type: 'button', 'aria-label': t('order.down', { name: label }), title: t('order.down', { name: label }), disabled: at >= hi ? true : undefined, onclick: () => moveUnit('account', fam, at, at + 1, { focus: a.name, label, button: 'down' }) }, icon('arrowDown')),
1817
- h('button', { class: 'icon-btn pin-btn', type: 'button', 'aria-pressed': String(pinned), 'aria-label': pinLabel, title: pinLabel, 'aria-disabled': full ? 'true' : null, onclick: () => { if (full) toast(t('pin.full', { n: PIN_MAX })); else togglePin(a) } }, icon('pin'))))
2007
+ // Words, not a lone pin icon at the end of the row: the arrange mode is where the order and the pins are set.
2008
+ h('button', { class: 'btn btn-sm pin-btn', type: 'button', 'aria-pressed': String(pinned), 'aria-label': pinLabel, title: pinLabel, 'aria-disabled': full ? 'true' : null, onclick: () => { if (full) toast(t('pin.full', { n: PIN_MAX })); else togglePin(a) } }, t(pinned ? 'pin.unpin' : 'pin.pin'))))
1818
2009
  }
1819
2010
  // A grip to drag a Family group or an account (a Same Login moves as one) into a new place, or to move it with
1820
2011
  // the arrow keys. Only in the arrange mode.
@@ -2118,10 +2309,11 @@ const MAIN = String.raw `
2118
2309
  h('div', null,
2119
2310
  h('h2', { id: 'h-checkup' }, t('health.title')),
2120
2311
  h('p', { class: 'muted small' }, status, h('span', { class: 'sep', 'aria-hidden': 'true' }, '·'),
2121
- tx('health.lead', { shared: h('span', { class: 'label-tip' }, t('health.sharedTerm'), tip('shared')), drift: h('span', { class: 'label-tip' }, t('health.driftTerm'), tip('drift')) }))),
2312
+ tx('health.lead', { shared: h('span', { class: 'label-tip' }, t('health.sharedTerm'), tip('shared')) }))),
2122
2313
  h('div', { class: 'actions' },
2123
2314
  h('button', { class: 'btn', type: 'button', disabled: busy || !S.state, 'aria-busy': S.checking ? 'true' : null, title: !S.state && !busy ? t('health.waiting') : null, onclick: runCheck }, S.checking ? spinner() : null, S.checking ? t('health.running') : t('health.run')),
2124
- prompt ? h('button', { class: 'btn', type: 'button', title: t('fix.copyAiTitle'), onclick: () => copyText(prompt, t('fix.promptShown')) }, icon('copy'), t('fix.copyAi')) : null,
2315
+ prompt && BOOT.readOnly ? h('button', { class: 'btn', type: 'button', title: t('fix.copyAiTitle'), onclick: () => copyText(prompt, t('fix.promptShown')) }, icon('copy'), t('fix.copyAi')) : null,
2316
+ prompt && !BOOT.readOnly ? h('button', { class: 'btn', type: 'button', title: t('ask.fixTitle'), onclick: () => openAsk({ task: 'fix', context: { findings: taskFindings(forAi(findings)), version: BOOT.version } }) }, icon('bot'), t('ask.title.fix')) : null,
2125
2317
  BOOT.readOnly ? null : h('button', { class: 'btn btn-primary', type: 'button', disabled: busy || !fixable, 'aria-busy': S.fixing ? 'true' : null, title: fixWhy, onclick: runFix },
2126
2318
  S.fixing ? spinner() : null, S.fixing ? t('health.fixing') : t('fix.all') + (fixable ? ' (' + fixable + ')' : ''))))]
2127
2319
  if (ref) out.push(h('div', { class: 'filter-bar' },
@@ -2561,7 +2753,9 @@ const MAIN = String.raw `
2561
2753
  })
2562
2754
  const body = h('form', { id: 'nf-form', class: 'form', novalidate: true, onsubmit: (ev) => { ev.preventDefault(); create() } },
2563
2755
  h('p', { class: 'muted small' }, t('nf.intro')),
2564
- h('fieldset', { class: 'field fam-field' }, h('legend', null, t('nf.tool')), nf.fams.length ? h('div', { class: 'fam-grid' }, cards) : h('p', { class: 'muted small' }, t('empty.noFamilies'))),
2756
+ h('fieldset', { class: 'field fam-field' }, h('legend', null, t('nf.tool')), h('div', { class: 'fam-grid' }, cards,
2757
+ h('button', { class: 'fam-card fam-other', type: 'button', onclick: () => openAsk({ task: 'host', context: { version: BOOT.version } }) }, h('span', { class: 'badge badge-sm badge-logo', 'aria-hidden': 'true' }, icon('plus')),
2758
+ h('span', { class: 'fam-text' }, h('span', { class: 'fam-title' }, t('ask.otherTool')), h('span', { class: 'fam-sub' }, t('ask.otherToolSub')))))),
2565
2759
  h('div', { class: 'field' }, h('label', { class: 'field', for: 'nf-name' }, h('span', null, t('nf.name')), e.name), e.suggest),
2566
2760
  // The first screen asks only for the tool and a name; the rest waits behind "More options".
2567
2761
  h('details', { class: 'more-opts', open: nf.api || Boolean(nf.alias) || Boolean(nf.error) || undefined },
@@ -2570,7 +2764,8 @@ const MAIN = String.raw `
2570
2764
  h('div', { class: 'check-row' }, h('label', { class: 'check' }, e.api, h('span', null, h('b', null, t('nf.api')), h('span', { class: 'muted small' }, t('nf.apiHint')))), tip('api')),
2571
2765
  e.preview),
2572
2766
  e.error,
2573
- e.errNote = nf.error ? errorNote(nf.error, create, nf.error.code === 'create-refused' && !nf.api ? t('nf.refusedApi') : null) : null)
2767
+ e.errNote = nf.error ? errorNote(nf.error, create, nf.error.code === 'create-refused' && !nf.api ? t('nf.refusedApi') : null) : null,
2768
+ h('p', { class: 'small ask-setup' }, h('button', { class: 'link-btn', type: 'button', onclick: () => openAsk({ task: 'account', context: nf.family ? { family: nf.family, version: BOOT.version } : { version: BOOT.version } }) }, icon('bot'), t('ask.setUp'))))
2574
2769
  setKids(el, dialogFrame(t('nf.title'), null, body, [
2575
2770
  h('button', { class: 'btn', type: 'button', onclick: () => el.close() }, t('btn.cancel')),
2576
2771
  e.submit,
@@ -2678,8 +2873,11 @@ const MAIN = String.raw `
2678
2873
  : h('div', { class: 'note note-warn' }, h('span', { class: 'small' }, f.message))),
2679
2874
  h('p', { class: 'muted small' }, t('nf.next')),
2680
2875
  h('ol', { class: 'steps' }, r.nextSteps.map(stepRow)))
2876
+ const made = S.state && S.state.accounts.find((x) => x.ref === r.account.ref)
2877
+ const keyNow = r.account.kind === 'api' || (made && keyable(made)) ? { ref: r.account.ref, family: r.account.family, kind: r.account.kind } : null
2681
2878
  return dialogFrame(t('nf.title'), r.account.family, body, [
2682
2879
  h('button', { class: 'btn', type: 'button', onclick: () => openCreate({ family: r.account.family, api: nf.api }) }, t('nf.another')),
2880
+ keyNow ? h('button', { class: 'btn', type: 'button', onclick: () => openKey(keyNow) }, icon('key'), t('menu.enterKey')) : null,
2683
2881
  h('button', { class: 'btn btn-primary', type: 'button', onclick: () => dlg.el.close() }, t('btn.done')),
2684
2882
  ])
2685
2883
  }
@@ -2782,6 +2980,13 @@ const MAIN = String.raw `
2782
2980
  }
2783
2981
  return { auto: s.auto, sameFamily: s.sameFamily, prepareAt: s.prepareAt, threshold: s.threshold, wait: s.waitIfResetWithinMinutes, countdown: s.countdownSeconds, orders }
2784
2982
  }
2983
+ // "Let AI tune it" (spec §3.29): the AI gets the facts of sideby handoff status --json, as far as the page has them.
2984
+ function askHandoff() {
2985
+ const st = ahState()
2986
+ if (!st) return
2987
+ const status = ah && ah.status ? ah.status : null
2988
+ openAsk({ task: 'handoff', context: { handoff: handoffTaskFacts(st.settings, st.starters, S.state.accounts, Date.now(), status), version: BOOT.version } })
2989
+ }
2785
2990
  async function openHandoff() {
2786
2991
  if (!ahState()) return
2787
2992
  ah = { form: handoffForm(), loading: true }
@@ -2870,7 +3075,8 @@ const MAIN = String.raw `
2870
3075
  const st = ahState()
2871
3076
  if (!st || !ah) return
2872
3077
  const f = ah.form
2873
- const body = [h('p', { class: 'muted small' }, t('ah.intro'))]
3078
+ const body = [h('p', { class: 'muted small' }, t('ah.intro'), ' ',
3079
+ h('button', { class: 'link-btn', type: 'button', onclick: askHandoff }, icon('bot'), t('ask.title.handoff')))]
2874
3080
  if (BOOT.readOnly) body.push(h('p', { class: 'note' }, t('banner.readOnly')))
2875
3081
  body.push(ahCheck('auto', t('ah.auto'), null))
2876
3082
  body.push(ahCheck('sameFamily', t('ah.sameFamily'), t('ah.sameFamilyWarn')))
@@ -3187,6 +3393,7 @@ const MAIN = String.raw `
3187
3393
  const kids = [h('div', { class: 'section-head' },
3188
3394
  h('h2', { id: 'h-handoff' }, t('hp.title')),
3189
3395
  h('div', { class: 'row-actions' },
3396
+ h('button', { class: 'btn btn-sm', type: 'button', onclick: askHandoff }, icon('bot'), t('ask.title.handoff')),
3190
3397
  h('button', { class: 'btn btn-sm', type: 'button', onclick: openHandoff }, t('hp.advanced')),
3191
3398
  h('button', { class: 'btn btn-sm', type: 'button', disabled: hp.loading, onclick: loadHandoffPage }, hp.loading ? spinner() : icon('refresh'), t('top.refresh'))))]
3192
3399
  const on = st.settings.auto
@@ -3331,6 +3538,7 @@ const MAIN = String.raw `
3331
3538
  const out = []
3332
3539
  if (!LANG_FIXED) out.push('lang')
3333
3540
  if (BOOT.colorScheme === 'auto') out.push('theme')
3541
+ out.push('startup')
3334
3542
  if (S.state && S.state.accounts.length && !BOOT.readOnly) out.push('order')
3335
3543
  out.push('ai')
3336
3544
  if (S.state && rcSummary()) out.push('rc')
@@ -3345,59 +3553,230 @@ const MAIN = String.raw `
3345
3553
  const warn = secs.includes('rc') && rcSummary() === 'on'
3346
3554
  setKids(b, [icon('gear'), h('span', { class: 'hide-sm' }, t('set.button')), warn ? h('span', { class: 'dot set-dot', 'aria-hidden': 'true' }) : null])
3347
3555
  b.setAttribute('aria-label', t('set.button') + (warn ? ': ' + t('set.rcOn') : ''))
3348
- refreshPopover('settings')
3556
+ refreshSettings()
3349
3557
  if (dlg.kind === 'rc') renderRc()
3350
3558
  }
3351
- function settingsPop() {
3559
+ // The popover and the full settings dialog show the same groups (spec §3.29), top to bottom: Appearance, Startup,
3560
+ // Accounts and quota, Let AI help. leave() closes whichever holds them before a link goes elsewhere; a link that
3561
+ // opens a dialog keeps the dialog element open (opens: true), since one dialog element is shared.
3562
+ function settingsGroups(leave) {
3352
3563
  const secs = settingsSections()
3353
- const out = []
3354
3564
  const seg = (label, opts, cur, pick) => h('div', { class: 'set-row' }, h('span', { class: 'set-label' }, label),
3355
3565
  h('div', { class: 'seg', role: 'group', 'aria-label': label }, opts.map(([v, text]) =>
3356
3566
  h('button', { class: 'seg-btn', type: 'button', 'aria-pressed': String(v === cur), onclick: () => pick(v) }, text))))
3357
- const link = (label, state, cls, run) => h('button', { class: 'menu-item set-link', type: 'button', onclick: () => { closeMenu(); run() } },
3358
- h('span', { class: 'menu-label' }, label), h('span', { class: 'chip chip-sm ' + cls }, state), icon('chevron'))
3359
- if (secs.includes('lang')) out.push(seg(t('set.lang'), [['en', 'English'], ['zh', '中文']], lang, setLang))
3360
- if (secs.includes('theme')) out.push(seg(t('set.theme'), CHOICES.theme.map((v) => [v, t('set.theme.' + v)]), prefs.theme, setTheme))
3361
- if (out.length && (secs.includes('order') || secs.includes('rc') || secs.includes('ah'))) out.push(h('div', { class: 'menu-sep', role: 'separator' }))
3362
- // Everything here can also be asked of an AI assistant through the sideby skill (spec §3.8).
3363
- if (secs.includes('ai')) out.push(link(t('ai.title'), t(skillInstalled() ? 'ai.installed' : 'ai.notInstalled'), skillInstalled() ? 'chip-ok' : '', openAi))
3567
+ const link = (label, state, cls, run, opens) => h('button', { class: 'menu-item set-link', type: 'button', onclick: () => { leave(opens); run() } },
3568
+ h('span', { class: 'menu-label' }, label), state ? h('span', { class: 'chip chip-sm ' + cls }, state) : null, icon('chevron'))
3569
+ const look = []
3570
+ if (secs.includes('lang')) look.push(seg(t('set.lang'), [['en', 'English'], ['zh', '中文']], lang, setLang))
3571
+ if (secs.includes('theme')) look.push(seg(t('set.theme'), CHOICES.theme.map((v) => [v, t('set.theme.' + v)]), viewPrefs().theme, setTheme))
3572
+ const start = [autostartRow('autostart')]
3573
+ // The menu bar switch shows only where it works (macOS); while its state loads it waits, unseen.
3574
+ if (li.menubar.status && li.menubar.status.supported) start.push(autostartRow('menubar'))
3575
+ if (!BOOT.readOnly) start.push(link(t('term.title'), '', '', openTerminals, true))
3576
+ const acct = []
3364
3577
  // The arrange mode (spec §3.25) has a place here too, where people look for "how do I change this".
3365
3578
  if (secs.includes('order')) {
3366
3579
  const pins = Object.values(displayOf().pinned || {}).some((x) => x.length)
3367
- out.push(link(t('set.order'), t(ordered() || pins ? 'set.orderMine' : 'set.orderDefault'), '', () => {
3580
+ acct.push(link(t('set.order'), t(ordered() || pins ? 'set.orderMine' : 'set.orderDefault'), '', () => {
3368
3581
  setPage('accounts')
3369
3582
  startArrange()
3370
3583
  const bar = document.querySelector('#accounts .arrange-bar')
3371
3584
  if (bar) bar.scrollIntoView({ behavior: REDUCED ? 'auto' : 'smooth', block: 'center' })
3372
3585
  }))
3373
3586
  }
3374
- if (secs.includes('rc')) {
3375
- const sum = rcSummary()
3376
- out.push(link(t('rc.button'), t('rc.state.' + sum), sum === 'on' ? 'chip-warn' : sum === 'off' ? 'chip-ok' : '', openRc))
3377
- }
3378
- if (secs.includes('ah')) {
3379
- const on = ahState().settings.auto
3380
- out.push(link(t('ah.button'), on ? t('ah.on') : t('ah.off'), on ? 'chip-ok' : '', () => setPage('handoff')))
3381
- }
3382
3587
  // Quota checks that ask the Host (spec §3.26): one switch per Family, with what it does in plain words.
3383
3588
  if (secs.includes('checks')) {
3384
- if (out.length) out.push(h('div', { class: 'menu-sep', role: 'separator' }))
3385
3589
  for (const c of S.state.quotaChecks) {
3386
3590
  const label = t('set.quotaCheck', { host: c.title })
3387
- out.push(h('div', { class: 'set-row set-check' },
3591
+ acct.push(h('div', { class: 'set-row set-check' },
3388
3592
  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 }))),
3389
3593
  BOOT.readOnly ? h('span', { class: 'chip chip-sm' + (c.on ? ' chip-ok' : '') }, c.on ? t('ah.on') : t('ah.off'))
3390
3594
  : h('div', { class: 'seg', role: 'group', 'aria-label': label }, [[true, t('ah.on')], [false, t('ah.off')]].map(([v, text]) =>
3391
- h('button', { class: 'seg-btn', type: 'button', 'aria-pressed': String(v === c.on), onclick: () => { if (v !== c.on) { closeMenu(); setCheck(c.family, v) } } }, text)))))
3595
+ 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)))))
3392
3596
  }
3393
3597
  }
3598
+ if (secs.includes('rc')) {
3599
+ const sum = rcSummary()
3600
+ acct.push(link(t('rc.button'), t('rc.state.' + sum), sum === 'on' ? 'chip-warn' : sum === 'off' ? 'chip-ok' : '', openRc, true))
3601
+ }
3602
+ if (secs.includes('ah')) {
3603
+ const on = ahState().settings.auto
3604
+ acct.push(link(t('ah.button'), on ? t('ah.on') : t('ah.off'), on ? 'chip-ok' : '', () => setPage('handoff')))
3605
+ }
3606
+ // Everything here can also be asked of an AI assistant through the sideby skill (spec §3.8).
3607
+ const ai = [
3608
+ link(t('ai.title'), t(skillInstalled() ? 'ai.installed' : 'ai.notInstalled'), skillInstalled() ? 'chip-ok' : '', () => openAsk(), true),
3609
+ link(t('ask.plugin'), '', '', () => openAsk({ task: 'plugin', context: { version: BOOT.version } }), true),
3610
+ ]
3611
+ return [
3612
+ { title: t('set.g.look'), items: look },
3613
+ { title: t('set.g.start'), items: start },
3614
+ { title: t('set.g.accounts'), items: acct },
3615
+ { title: t('set.g.ai'), items: ai },
3616
+ ].filter((g) => g.items.length)
3617
+ }
3618
+ function settingsBody(leave) {
3619
+ const out = []
3620
+ settingsGroups(leave).forEach((g, i) => {
3621
+ if (i) out.push(h('div', { class: 'menu-sep set-sep', role: 'separator' }))
3622
+ 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))
3623
+ })
3394
3624
  return out
3395
3625
  }
3626
+ // Taller than the window, the popover scrolls inside and ends with "More settings…", the same groups in a dialog.
3627
+ function settingsPop() {
3628
+ loadAutostart()
3629
+ return [...settingsBody(() => closeMenu()),
3630
+ h('button', { class: 'menu-item set-more', type: 'button', hidden: true, onclick: () => { closeMenu(); openSettingsDialog() } }, h('span', { class: 'menu-label' }, t('set.more')), icon('chevron'))]
3631
+ }
3632
+ function settingsFit() {
3633
+ const el = menu.el
3634
+ const more = el && el.querySelector('.set-more')
3635
+ if (!more) return
3636
+ more.hidden = true
3637
+ more.hidden = !(el.scrollHeight > el.clientHeight + 1)
3638
+ }
3639
+ function openSettingsDialog() {
3640
+ loadAutostart()
3641
+ showDialog('settings')
3642
+ renderSettingsDialog()
3643
+ }
3644
+ function renderSettingsDialog() {
3645
+ const leave = (opens) => { if (!opens && dlg.kind === 'settings') dlg.el.close() }
3646
+ setKids(dlg.el, dialogFrame(t('set.title'), null, h('div', { class: 'set-dialog' }, settingsBody(leave)),
3647
+ [h('button', { class: 'btn', type: 'button', onclick: () => dlg.el.close() }, t('btn.close'))]))
3648
+ }
3649
+ function refreshSettings() {
3650
+ refreshPopover('settings')
3651
+ if (dlg.kind === 'settings') renderSettingsDialog()
3652
+ }
3653
+
3654
+ // ---------- start at login (spec §3.29, ADR-0029) and the Menu Bar Item (spec §3.31, ADR-0034) ----------
3655
+ // Each switch reads its state when the settings open; moving it shows the file and what will run, and only the
3656
+ // confirmation writes. A read-only Panel shows the state only. mb.* words override as.* for the menu bar.
3657
+ const liState = () => ({ status: null, loading: false, error: null, want: null, plan: null, planning: false, planError: null, busy: false })
3658
+ const li = { autostart: liState(), menubar: liState() }
3659
+ let liKind = 'autostart'
3660
+ function lt(k, key, vars) {
3661
+ const own = (k === 'menubar' ? 'mb.' : 'as.') + key
3662
+ return t(Object.hasOwn(MESSAGES.en, own) ? own : 'as.' + key, vars)
3663
+ }
3664
+ function loadAutostart() {
3665
+ // A failed read is not retried here: the settings re-render after every read, so a retry would loop.
3666
+ for (const k of Object.keys(li)) if (!li[k].status && !li[k].loading && !li[k].error) loadLoginItem(k)
3667
+ }
3668
+ async function loadLoginItem(k) {
3669
+ const st = li[k]
3670
+ st.loading = true
3671
+ try { st.status = await api('/api/' + k); st.error = null } catch (e) { st.error = e }
3672
+ st.loading = false
3673
+ refreshSettings()
3674
+ if (k === 'menubar') renderAll()
3675
+ }
3676
+ function autostartRow(k) {
3677
+ const st = li[k]
3678
+ const s = st.status
3679
+ const n = autostartNote(s, BOOT.readOnly)
3680
+ const label = lt(k, 'label')
3681
+ const hint = [st.error ? lt(k, 'failed', { msg: st.error.message }) : lt(k, n.key.slice(3))]
3682
+ if (n.action === 'fix') hint.push(' ', h('button', { class: 'link-btn small', type: 'button', onclick: () => autostartAsk(true, k) }, lt(k, 'fix')))
3683
+ 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')))
3684
+ let ctl = null
3685
+ if (!s) ctl = st.loading ? spinner() : null
3686
+ 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]) =>
3687
+ h('button', { class: 'seg-btn', type: 'button', 'aria-pressed': String(v === n.on), onclick: () => { if (v !== n.on) autostartAsk(v, k) } }, text)))
3688
+ 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'))
3689
+ return h('div', { class: 'set-row set-check' },
3690
+ h('div', { class: 'set-text' }, h('span', { class: 'set-label' }, label), h('span', { class: 'set-hint' }, hint)), ctl)
3691
+ }
3692
+ async function autostartAsk(on, k) {
3693
+ if (menu.kind === 'settings') closeMenu()
3694
+ liKind = k
3695
+ const st = li[k]
3696
+ st.want = on
3697
+ st.plan = null
3698
+ st.planError = null
3699
+ st.planning = true
3700
+ showDialog('autostart')
3701
+ renderAutostart()
3702
+ try { st.plan = (await api('/api/' + k, { on })).plan } catch (e) { st.planError = e }
3703
+ st.planning = false
3704
+ if (dlg.kind === 'autostart' && liKind === k) renderAutostart()
3705
+ }
3706
+ function renderAutostart() {
3707
+ const k = liKind
3708
+ const st = li[k]
3709
+ const p = st.plan
3710
+ const on = st.want
3711
+ const body = []
3712
+ if (st.planning) body.push(h('p', { class: 'muted' }, spinner(), ' ', lt(k, 'planning')))
3713
+ else if (st.planError) body.push(errorNote(st.planError, () => autostartAsk(on, k)))
3714
+ else if (p && p.blocked) {
3715
+ const own = 'as.block.' + p.blocked.code
3716
+ body.push(h('p', { class: 'note note-fail' }, Object.hasOwn(MESSAGES.en, own) ? t(own) : p.blocked.message))
3717
+ if (['npx-cache', 'temp-dir', 'unsafe-path'].includes(p.blocked.code)) body.push(codeCopy('npm i -g sideby'))
3718
+ if (p.blocked.code === 'foreign') body.push(codeCopy(p.path))
3719
+ } else if (p && !p.changed) body.push(h('p', null, lt(k, on ? 'alreadyOn' : 'alreadyOff')))
3720
+ else if (p && on) {
3721
+ body.push(h('p', null, lt(k, 'writes')), h('code', { class: 'as-code' }, p.path))
3722
+ body.push(h('p', null, lt(k, 'runs')), h('code', { class: 'as-code' }, (p.programArguments || []).join(' ')))
3723
+ body.push(h('p', { class: 'muted small' }, lt(k, 'noWindow')))
3724
+ } else if (p) {
3725
+ body.push(h('p', null, lt(k, 'removes')), h('code', { class: 'as-code' }, p.path))
3726
+ body.push(h('p', { class: 'muted small' }, lt(k, 'offNote')))
3727
+ }
3728
+ 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'))]
3729
+ if (p && p.changed && !p.blocked)
3730
+ 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')))
3731
+ setKids(dlg.el, dialogFrame(lt(k, on ? 'onTitle' : 'offTitle'), null, body, foot))
3732
+ }
3733
+ async function autostartApply() {
3734
+ const k = liKind
3735
+ const st = li[k]
3736
+ const on = st.want
3737
+ st.busy = true
3738
+ dlg.busy = true
3739
+ renderAutostart()
3740
+ let r = null
3741
+ try { r = await api('/api/' + k, { on, confirm: true, programArguments: st.plan.programArguments || [] }) } catch (e) { st.planError = e }
3742
+ st.busy = false
3743
+ dlg.busy = false
3744
+ if (r && r.applied) {
3745
+ st.status = r.status
3746
+ if (dlg.kind === 'autostart') dlg.el.close()
3747
+ toast(lt(k, on ? 'doneOn' : 'doneOff') + (on && !r.loaded ? ' ' + lt(k, 'nextLogin') : ''))
3748
+ refreshSettings()
3749
+ if (k === 'menubar') renderAll()
3750
+ return
3751
+ }
3752
+ if (r) { st.plan = r.plan; if (r.changedSince) toast(lt(k, 'changedSince')) }
3753
+ if (dlg.kind === 'autostart') renderAutostart()
3754
+ }
3396
3755
  function setLang(v) {
3397
3756
  if (LANG_FIXED || v === lang) return
3757
+ if (CFG) { cfgPanel.language = v; saveCfg({ language: v }) } else { prefs.lang = v; savePrefs() }
3758
+ showLang(v)
3759
+ }
3760
+ // Writes config panel.* (spec §3.29). A failure says so; the next state read then shows what config holds.
3761
+ async function saveCfg(patch, quiet) {
3762
+ cfgSaving++
3763
+ try { await api('/api/panel/settings', patch); return true }
3764
+ catch (e) { if (!quiet) toast(t('set.saveFailed', { msg: e.message }), { kind: 'fail' }); return false }
3765
+ finally { cfgSaving-- }
3766
+ }
3767
+ // A theme or language changed elsewhere (the CLI, an AI assistant) shows at the next state read.
3768
+ function adoptPanel(next) {
3769
+ if (!CFG || cfgSaving) return
3770
+ next = next || {}
3771
+ if (next.theme === cfgPanel.theme && next.language === cfgPanel.language) return
3772
+ cfgPanel = Object.assign({}, next)
3773
+ applyTheme()
3774
+ const l = panelLang(BOOT.lang, viewPrefs().language, navigator.language)
3775
+ if (l !== lang) showLang(l)
3776
+ else refreshSettings()
3777
+ }
3778
+ function showLang(v) {
3398
3779
  lang = v
3399
- prefs.lang = lang
3400
- savePrefs()
3401
3780
  renderStatic()
3402
3781
  buildToolbar()
3403
3782
  renderAll()
@@ -3408,32 +3787,23 @@ const MAIN = String.raw `
3408
3787
  else if (dlg.kind === 'browser') renderBrowser()
3409
3788
  else if (dlg.kind === 'update' && up) renderUpdate()
3410
3789
  else if (dlg.kind === 'rc') renderRc()
3790
+ else if (dlg.kind === 'ask' && ak) { if (ak.els.text) ak.text = ak.els.text.value; renderAsk() }
3791
+ else if (dlg.kind === 'key' && ky && ky.step !== 'enter') renderKey()
3792
+ else if (dlg.kind === 'terminal' && tm) renderTerminals()
3793
+ else if (dlg.kind === 'autostart') renderAutostart()
3411
3794
  }
3412
3795
  function setTheme(v) {
3413
- prefs.theme = v
3414
- savePrefs()
3796
+ if (CFG) { cfgPanel.theme = v; saveCfg({ theme: v }) } else { prefs.theme = v; savePrefs() }
3415
3797
  applyTheme()
3416
- refreshPopover('settings')
3798
+ refreshSettings()
3417
3799
  }
3418
3800
  // The sideby Agent Skill: what to say to an AI assistant instead of clicking, and how to install it when needed.
3419
3801
  function skillInstalled() {
3420
3802
  const u = S.state && S.state.update
3421
3803
  return Boolean(u && u.skillUpdate && u.skillUpdate.installed && u.skillUpdate.installed.length)
3422
3804
  }
3423
- const AI_ASKS = ['ai.ask.quota', 'ai.ask.new', 'ai.ask.pin', 'ai.ask.fix', 'ai.ask.handoff', 'ai.ask.rc']
3424
- function openAi() {
3425
- showDialog('ai')
3426
- const asks = AI_ASKS.map((k) => {
3427
- const text = t(k)
3428
- return h('li', null, h('button', { class: 'ai-ask', type: 'button', title: t('ai.copy'), onclick: () => copyText(text) }, icon('copy'), h('span', null, text)))
3429
- })
3430
- setKids(dlg.el, dialogFrame(t('ai.title'), null, h('div', { class: 'form' },
3431
- h('p', null, t('ai.intro')),
3432
- skillInstalled() ? h('p', { class: 'note' }, t('ai.ready')) : h('div', { class: 'field' }, h('p', { class: 'small' }, t('ai.install')), codeCopy(BOOT.skillInstall)),
3433
- h('p', { class: 'small muted' }, t('ai.examples')),
3434
- h('ul', { class: 'ai-asks' }, asks)),
3435
- [h('button', { class: 'btn', type: 'button', onclick: () => dlg.el.close() }, t('btn.close'))]))
3436
- }
3805
+ // Example phrases: a click puts one in the Let AI do it box (spec §3.28).
3806
+ const AI_ASKS = ['ai.ask.quota', 'ai.ask.new', 'ai.ask.api', 'ai.ask.pin', 'ai.ask.fix', 'ai.ask.handoff', 'ai.ask.menubar', 'ai.ask.rc', 'ai.ask.tool']
3437
3807
  function openRc() {
3438
3808
  if (!S.state || !rcSummary()) return
3439
3809
  rc.target = null
@@ -3469,7 +3839,549 @@ const MAIN = String.raw `
3469
3839
  setKids(dlg.el, dialogFrame(t('rc.dialogTitle'), null, body, foot))
3470
3840
  }
3471
3841
 
3842
+ // ---------- AI Tasks (spec §3.28) ----------
3843
+ // One dialog for every "let AI do it" entry: what to do, then the account and the terminal it will use, then one
3844
+ // button. When nothing can run it, or the panel is read-only, it copies the prompt instead.
3845
+ let ak = null
3846
+ const TERM_NAMES = { terminal: 'Terminal', iterm2: 'iTerm2', ghostty: 'Ghostty', orca: 'Orca', wezterm: 'WezTerm', kitty: 'kitty', alacritty: 'Alacritty', custom: 'Custom' }
3847
+ function termName(id) {
3848
+ const list = ak && ak.terms ? ak.terms.terminals : []
3849
+ const f = list.find((x) => x.id === id)
3850
+ return f ? f.name : TERM_NAMES[id] || id
3851
+ }
3852
+ function askBody() {
3853
+ const body = { task: ak.task, lang }
3854
+ const text = ak.els && ak.els.text ? ak.els.text.value.trim() : ak.text
3855
+ if (text) body.text = text
3856
+ if (ak.context) body.context = ak.context
3857
+ if (ak.account && ak.accountChanged) body.account = ak.account
3858
+ if (ak.terminal && ak.terminalChanged) body.terminal = ak.terminal
3859
+ const ids = ak.files.filter((f) => f.status === 'ready').map((f) => f.id)
3860
+ if (ids.length) body.attachments = ids
3861
+ return body
3862
+ }
3863
+ function openAsk(opts) {
3864
+ opts = opts || {}
3865
+ closeMenu()
3866
+ // In a Portal that offers AI Tasks itself (createPanelHandler's ask bridge), the task goes to its dialog.
3867
+ if (askBridge(BOOT, opts, window)) return
3868
+ 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: {} }
3869
+ showDialog('ask')
3870
+ hookAskDrops()
3871
+ const mine = ak
3872
+ // Uploads still running when the dialog closes are stopped; the server drops staged files it never received.
3873
+ dlg.onClose = () => { mine.files.forEach((f) => { if (f.xhr) f.xhr.abort() }) }
3874
+ renderAsk()
3875
+ if (ak.els.text) ak.els.text.focus()
3876
+ askLoad()
3877
+ }
3878
+ async function askLoad() {
3879
+ const mine = ak
3880
+ const body = askBody()
3881
+ delete body.account
3882
+ try {
3883
+ const [pick, terms] = await Promise.all([
3884
+ api('/api/ask/prompt', body),
3885
+ BOOT.readOnly ? Promise.resolve(null) : api('/api/terminals').catch(() => null),
3886
+ ])
3887
+ if (ak !== mine) return
3888
+ ak.pick = pick.account
3889
+ ak.reason = pick.reason || null
3890
+ if (!ak.accountChanged) ak.account = pick.account
3891
+ ak.terms = terms
3892
+ if (terms && !ak.terminalChanged) ak.terminal = terms.guess.id
3893
+ } catch (e) { if (ak === mine) ak.error = e }
3894
+ if (ak !== mine) return
3895
+ ak.loading = false
3896
+ if (dlg.kind === 'ask') renderAsk()
3897
+ }
3898
+ // Title, placeholder and examples of the dialog for its task (spec §3.28 "每个入口的提示").
3899
+ function askStrings() { return askCopy(ak.task, (k) => Object.hasOwn(MESSAGES.en, k), AI_ASKS) }
3900
+ function askChoices() { return aiTaskAccounts((S.state && S.state.accounts) || []) }
3901
+ function askTaskLine() {
3902
+ if (ak.task === 'free') return null
3903
+ const ctx = ak.context || {}
3904
+ return h('p', { class: 'note' }, t('ask.task.' + ak.task, { n: (ctx.findings || []).length, ref: ctx.account || '' }))
3905
+ }
3906
+ function askTextField() {
3907
+ const e = ak.els
3908
+ const copy = askStrings()
3909
+ e.text = h('textarea', { id: 'ak-text', class: 'ask-text', rows: ak.task === 'free' ? '3' : '2', maxlength: '8000', placeholder: t(copy.placeholder), 'aria-describedby': 'ak-warn' })
3910
+ e.text.value = ak.text
3911
+ e.warn = h('p', { class: 'field-error field-note', id: 'ak-warn', role: 'status' })
3912
+ const warnNow = () => { e.warn.textContent = stripSecrets(e.text.value).removed ? t('ask.keyWarn') : '' }
3913
+ e.text.addEventListener('input', () => { ak.text = e.text.value; warnNow() })
3914
+ warnNow()
3915
+ const label = h('label', { class: 'field', for: 'ak-text' }, h('span', null, t(ak.task === 'free' ? 'ask.what' : 'ask.whatMore')), e.text)
3916
+ const chips = h('div', { class: 'field' }, h('p', { class: 'small muted' }, t('ask.examples')),
3917
+ h('div', { class: 'ask-chips' }, copy.chips.map((k) => h('button', { class: 'chip chip-btn', type: 'button', onclick: () => { e.text.value = t(k); ak.text = e.text.value; warnNow(); e.text.focus() } }, t(k)))))
3918
+ return [h('div', { class: 'field' }, label, e.warn), askAttachField(), chips]
3919
+ }
3920
+
3921
+ // Attachments (spec §3.28 "附件"): pasted, dropped or picked files upload at once, one request each, so a wrong
3922
+ // type or a file that is too big is named right away. The page shows image thumbnails from the file itself as a
3923
+ // data: URL (the CSP allows no blob:); the server decides the type from the first bytes.
3924
+ const ATTACH_MAX = 5
3925
+ const ATTACH_ACCEPT = 'image/png,image/jpeg,image/gif,image/webp,video/mp4,video/quicktime,video/webm'
3926
+ let askHooked = false
3927
+ function hookAskDrops() {
3928
+ if (askHooked) return
3929
+ askHooked = true
3930
+ const el = dlg.el
3931
+ const active = () => dlg.kind === 'ask' && ak && !ak.result && !BOOT.readOnly
3932
+ const hasFiles = (e) => e.dataTransfer && Array.prototype.indexOf.call(e.dataTransfer.types || [], 'Files') >= 0
3933
+ el.addEventListener('paste', (e) => {
3934
+ const files = e.clipboardData ? Array.from(e.clipboardData.files || []) : []
3935
+ if (!active() || !files.length) return
3936
+ // A file copied in Finder also carries its name as text; only the file is wanted.
3937
+ e.preventDefault()
3938
+ askAddFiles(files)
3939
+ })
3940
+ el.addEventListener('dragover', (e) => {
3941
+ if (!active() || !hasFiles(e)) return
3942
+ e.preventDefault()
3943
+ e.dataTransfer.dropEffect = 'copy'
3944
+ el.classList.add('drop-on')
3945
+ })
3946
+ el.addEventListener('dragleave', (e) => { if (e.target === el || !el.contains(e.relatedTarget)) el.classList.remove('drop-on') })
3947
+ el.addEventListener('drop', (e) => {
3948
+ el.classList.remove('drop-on')
3949
+ if (!active() || !hasFiles(e)) return
3950
+ e.preventDefault()
3951
+ askAddFiles(Array.from(e.dataTransfer.files || []))
3952
+ })
3953
+ }
3954
+ function askAttachField() {
3955
+ if (BOOT.readOnly) return null
3956
+ const input = h('input', { type: 'file', multiple: true, accept: ATTACH_ACCEPT, class: 'sr-only', tabindex: '-1', 'aria-hidden': 'true' })
3957
+ input.addEventListener('change', () => { askAddFiles(Array.from(input.files || [])); input.value = '' })
3958
+ ak.els.files = h('div', { class: 'ask-files-wrap' })
3959
+ renderAskFiles()
3960
+ return h('div', { class: 'field ask-attach' },
3961
+ h('div', { class: 'ask-attach-row' },
3962
+ h('button', { class: 'btn btn-sm', type: 'button', onclick: () => input.click() }, icon('image'), t('ask.attach')),
3963
+ h('span', { class: 'small muted' }, t('ask.attachHint')), input),
3964
+ ak.els.files)
3965
+ }
3966
+ function renderAskFiles() {
3967
+ const box = ak && ak.els.files
3968
+ if (!box) return
3969
+ const files = ak.files
3970
+ const tiles = files.map((f) => {
3971
+ const remove = h('button', { class: 'icon-btn ask-file-x', type: 'button', 'aria-label': t('ask.attachRemove', { name: f.name }), onclick: () => askRemoveFile(f) }, icon('x'))
3972
+ let face
3973
+ if (f.status === 'uploading') {
3974
+ f.pctEl = h('span', { class: 'small' }, t('ask.attachUploading', { pct: Math.round(f.progress * 100) }))
3975
+ face = h('div', { class: 'ask-file-face' }, spinner(), f.pctEl)
3976
+ } else if (f.status === 'error') face = h('div', { class: 'ask-file-face' }, icon('x'))
3977
+ else if (f.thumb) face = h('img', { class: 'ask-file-img', src: f.thumb, alt: f.name })
3978
+ else face = h('div', { class: 'ask-file-face' }, icon(f.kind === 'video' ? 'film' : 'image'), f.kind === 'video' ? h('span', { class: 'small' }, t('ask.attachVideo')) : null)
3979
+ return h('li', { class: 'ask-file' + (f.status === 'error' ? ' is-error' : '') },
3980
+ face,
3981
+ h('span', { class: 'ask-file-name small', title: f.name }, f.name),
3982
+ h('span', { class: 'small muted' }, fileSize(f.bytes || f.size)),
3983
+ remove)
3984
+ })
3985
+ const errors = files.filter((f) => f.status === 'error').map((f) => h('p', { class: 'field-error' }, f.error))
3986
+ const live = files.some((f) => f.status !== 'error')
3987
+ setKids(box, [
3988
+ tiles.length ? h('ul', { class: 'ask-files', 'aria-label': t('ask.attach') }, tiles) : null,
3989
+ errors,
3990
+ ak.attachFull ? h('p', { class: 'field-error' }, t('ask.attachMax')) : null,
3991
+ live ? h('p', { class: 'note note-warn small' }, t('ask.attachWarn')) : null,
3992
+ ])
3993
+ }
3994
+ function askAddFiles(list) {
3995
+ if (!ak || !list.length) return
3996
+ ak.attachFull = false
3997
+ for (const file of list) {
3998
+ if (ak.files.filter((f) => f.status !== 'error').length >= ATTACH_MAX) { ak.attachFull = true; break }
3999
+ const f = { key: Math.random(), name: file.name || 'file', size: file.size, bytes: 0, kind: '', status: 'uploading', progress: 0, id: null, thumb: null, error: '', xhr: null, done: null }
4000
+ ak.files.push(f)
4001
+ // Over the largest limit there is no point uploading: the server would refuse it.
4002
+ if (file.size > 200 * 1024 * 1024) { f.status = 'error'; f.error = t('ask.attachTooBig', { name: f.name }); continue }
4003
+ f.done = askUpload(f, file, ak)
4004
+ }
4005
+ renderAskFiles()
4006
+ }
4007
+ function askRemoveFile(f) {
4008
+ if (f.xhr) f.xhr.abort()
4009
+ // Free the staged copy now; if this fails the server clears it after a day anyway.
4010
+ if (f.id) api('/api/ask/attach/remove', { ids: [f.id] }).catch(() => {})
4011
+ ak.files = ak.files.filter((x) => x !== f)
4012
+ ak.attachFull = false
4013
+ renderAskFiles()
4014
+ }
4015
+ function askPost(file, onProgress, xhrOut) {
4016
+ return new Promise((resolve) => {
4017
+ const xhr = new XMLHttpRequest()
4018
+ xhrOut(xhr)
4019
+ xhr.open('POST', BOOT.basePath + '/api/ask/attach')
4020
+ xhr.setRequestHeader('x-sideby-token', token)
4021
+ xhr.setRequestHeader('content-type', file.type || 'application/octet-stream')
4022
+ xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress(e.loaded / e.total) }
4023
+ xhr.onload = () => { let data = null; try { data = JSON.parse(xhr.responseText) } catch {} resolve({ status: xhr.status, data }) }
4024
+ xhr.onerror = () => resolve({ status: 0, data: null })
4025
+ xhr.onabort = () => resolve({ status: -1, data: null })
4026
+ xhr.send(file)
4027
+ })
4028
+ }
4029
+ async function askUpload(f, file, mine) {
4030
+ const progress = (p) => { f.progress = p; if (f.pctEl) f.pctEl.textContent = t('ask.attachUploading', { pct: Math.round(p * 100) }) }
4031
+ let r = await askPost(file, progress, (x) => { f.xhr = x })
4032
+ if (r.status === 403 && r.data && r.data.code === 'bad-token') {
4033
+ try { await refreshToken(); r = await askPost(file, progress, (x) => { f.xhr = x }) } catch {}
4034
+ }
4035
+ f.xhr = null
4036
+ if (r.status === -1 || ak !== mine) return
4037
+ if (r.status === 200 && r.data && r.data.id) {
4038
+ f.id = r.data.id
4039
+ f.kind = r.data.kind
4040
+ f.bytes = r.data.bytes
4041
+ if (f.kind === 'image') f.thumb = await thumbnail(file)
4042
+ f.status = 'ready'
4043
+ } else {
4044
+ f.status = 'error'
4045
+ f.error = t(r.status === 413 ? 'ask.attachTooBig' : r.status === 415 ? 'ask.attachType' : r.status === 507 ? 'ask.attachFull' : 'ask.attachFailed', { name: f.name })
4046
+ }
4047
+ if (ak === mine && dlg.kind === 'ask') renderAskFiles()
4048
+ }
4049
+ // A small JPEG data: URL of an image, drawn on a canvas so a 20 MB screenshot is not kept in the page.
4050
+ function thumbnail(file) {
4051
+ return new Promise((resolve) => {
4052
+ const reader = new FileReader()
4053
+ reader.onerror = () => resolve(null)
4054
+ reader.onload = () => {
4055
+ const img = new Image()
4056
+ img.onerror = () => resolve(null)
4057
+ img.onload = () => {
4058
+ try {
4059
+ const scale = Math.min(1, 192 / Math.max(img.width, img.height))
4060
+ const c = document.createElement('canvas')
4061
+ c.width = Math.max(1, Math.round(img.width * scale))
4062
+ c.height = Math.max(1, Math.round(img.height * scale))
4063
+ c.getContext('2d').drawImage(img, 0, 0, c.width, c.height)
4064
+ resolve(c.toDataURL('image/jpeg', 0.8))
4065
+ } catch { resolve(null) }
4066
+ }
4067
+ img.src = String(reader.result)
4068
+ }
4069
+ reader.readAsDataURL(file)
4070
+ })
4071
+ }
4072
+ // Open and Copy prompt wait for uploads still running, so the task carries every file the person added.
4073
+ async function askUploadsDone() {
4074
+ const pending = ak.files.filter((f) => f.status === 'uploading' && f.done).map((f) => f.done)
4075
+ if (pending.length) await Promise.all(pending)
4076
+ }
4077
+ function askConfirm() {
4078
+ if (BOOT.readOnly) return h('p', { class: 'note' }, t('ask.readOnly'))
4079
+ if (ak.loading) return h('p', { class: 'muted small' }, spinner(), ' ', t('ask.loading'))
4080
+ if (ak.error) return errorNote(ak.error, () => { ak.error = null; ak.loading = true; renderAsk(); askLoad() })
4081
+ const choices = askChoices()
4082
+ const out = []
4083
+ if (!ak.account) {
4084
+ out.push(h('div', { class: 'note note-warn' }, h('span', null, t('ask.noAccount.' + (ak.reason || 'no-accounts'))), h('span', { class: 'note-line' }, t('ask.noAccountHint'))))
4085
+ const main = ak.reason === 'none-signed-in' && S.state ? S.state.accounts.find((a) => a.isMain && a.kind !== 'api') : null
4086
+ if (main) out.push(h('div', null, h('button', { class: 'btn btn-sm', type: 'button', onclick: () => signIn(main) }, icon('key'), t('ask.signInMain', { ref: main.ref }))))
4087
+ }
4088
+ const rows = []
4089
+ if (choices.length) {
4090
+ const sel = h('select', { id: 'ak-account', 'aria-label': t('ask.account') },
4091
+ ak.account ? null : h('option', { value: '' }, t('ask.chooseAccount')),
4092
+ choices.map((a) => h('option', { value: a.ref }, a.ref + (a.kind === 'api' ? ' · API' : ''))))
4093
+ sel.value = ak.account || ''
4094
+ sel.addEventListener('change', () => { ak.account = sel.value || null; ak.accountChanged = Boolean(sel.value); renderAsk() })
4095
+ rows.push(h('label', { class: 'field', for: 'ak-account' }, h('span', null, t('ask.account')), sel))
4096
+ }
4097
+ const installed = ak.terms ? ak.terms.installed : []
4098
+ if (installed.length && ak.account) {
4099
+ const sel = h('select', { id: 'ak-term', 'aria-label': t('ask.terminal') }, installed.map((id) => h('option', { value: id }, termName(id))))
4100
+ sel.value = ak.terminal || installed[0]
4101
+ sel.addEventListener('change', () => { ak.terminal = sel.value; ak.terminalChanged = true; renderAsk() })
4102
+ rows.push(h('label', { class: 'field', for: 'ak-term' }, h('span', null, t('ask.terminal')), sel))
4103
+ }
4104
+ if (rows.length) out.push(h('div', { class: 'ask-pick' }, rows))
4105
+ if (ak.account) {
4106
+ // Families whose AI Tasks start with permission checks on (ADR-0031) say so after the confirm line.
4107
+ const acct = S.state && S.state.accounts.find((x) => x.ref === ak.account)
4108
+ const safe = acct && family(acct.family).aiTaskSafe
4109
+ out.push(h('p', { class: 'small' }, t('ask.confirm', { terminal: termName(ak.terminal || 'terminal'), ref: ak.account }) + (safe ? ' ' + t('ask.safe') : '')))
4110
+ }
4111
+ return out
4112
+ }
4113
+ function askResult() {
4114
+ const r = ak.result
4115
+ const term = termName(r.terminal || ak.terminal || 'terminal')
4116
+ return [
4117
+ h('div', { class: 'note note-warn' }, h('b', null, t('ask.failed', { terminal: term })), h('span', { class: 'note-line' }, t('ask.paste'))),
4118
+ codeCopy(r.command),
4119
+ r.automation ? h('p', { class: 'small' }, t('ask.automation', { terminal: term })) : null,
4120
+ r.reason === 'not-installed' ? h('p', { class: 'small muted' }, t('ask.notInstalled')) : null,
4121
+ !r.automation && r.reason !== 'not-installed' && r.detail ? h('p', { class: 'small muted' }, r.detail) : null,
4122
+ ]
4123
+ }
4124
+ function askYourself() {
4125
+ return h('details', { class: 'more-opts' }, h('summary', null, t('ask.yourself')),
4126
+ h('p', { class: 'small' }, t('ai.intro')),
4127
+ skillInstalled() ? h('p', { class: 'note' }, t('ai.ready')) : h('div', { class: 'field' }, h('p', { class: 'small' }, t('ai.install')), codeCopy(BOOT.skillInstall)))
4128
+ }
4129
+ function renderAsk() {
4130
+ if (!ak) return
4131
+ const el = dlg.el
4132
+ const body = [h('p', { class: 'muted small' }, t('ask.intro')), askTaskLine()]
4133
+ const foot = [h('button', { class: 'btn', type: 'button', disabled: ak.busy, onclick: () => el.close() }, t(ak.result ? 'btn.close' : 'btn.cancel'))]
4134
+ if (ak.result) {
4135
+ body.push(askResult())
4136
+ if (ak.result.removedSecrets) body.push(h('p', { class: 'small muted' }, t('ask.keyRemoved')))
4137
+ } else {
4138
+ body.push(askTextField(), askConfirm(), askYourself())
4139
+ const canOpen = !BOOT.readOnly && !ak.loading && !ak.error && ak.account
4140
+ if (canOpen) {
4141
+ const term = termName(ak.terminal || 'terminal')
4142
+ foot.push(h('button', { class: 'btn btn-primary', type: 'button', disabled: ak.busy, 'aria-busy': ak.busy ? 'true' : null, onclick: askOpen }, ak.busy ? spinner() : icon('terminal'), ak.busy ? t(ak.files.some((f) => f.status === 'uploading') ? 'ask.attachWaiting' : 'ask.opening') : t('ask.open', { terminal: term })))
4143
+ } else if (!ak.loading || BOOT.readOnly) {
4144
+ foot.push(h('button', { class: 'btn btn-primary', type: 'button', disabled: ak.busy, onclick: askCopyPrompt }, icon('copy'), t('ask.copyPrompt')))
4145
+ }
4146
+ }
4147
+ setKids(el, dialogFrame(t(askStrings().title), null, body, foot))
4148
+ }
4149
+ async function askCopyPrompt() {
4150
+ const mine = ak
4151
+ ak.busy = true
4152
+ renderAsk()
4153
+ try {
4154
+ await askUploadsDone()
4155
+ const r = await api('/api/ask/prompt', askBody())
4156
+ await copyText(r.prompt, t('ask.promptShown'))
4157
+ if (r.removedSecrets) toast(t('ask.keyRemoved'), { kind: 'info' })
4158
+ } catch (e) { toast(e.message, { kind: 'fail' }) }
4159
+ if (ak !== mine) return
4160
+ ak.busy = false
4161
+ if (dlg.kind === 'ask') renderAsk()
4162
+ }
4163
+ async function askOpen() {
4164
+ const mine = ak
4165
+ ak.busy = true
4166
+ renderAsk()
4167
+ try {
4168
+ await askUploadsDone()
4169
+ if (ak !== mine) return
4170
+ renderAsk()
4171
+ const r = await api('/api/ask', askBody())
4172
+ if (ak !== mine) return
4173
+ ak.busy = false
4174
+ if (r.opened) {
4175
+ toast(t('ask.opened', { terminal: termName(r.terminal), ref: r.account }))
4176
+ if (r.removedSecrets) toast(t('ask.keyRemoved'), { kind: 'info' })
4177
+ dlg.el.close()
4178
+ return
4179
+ }
4180
+ if (!r.command) {
4181
+ // No account can run it after all: the dialog turns into Copy prompt.
4182
+ ak.account = null
4183
+ ak.reason = r.reason || null
4184
+ renderAsk()
4185
+ return
4186
+ }
4187
+ ak.result = r
4188
+ renderAsk()
4189
+ copyText(r.command, t('ask.copiedCmd'))
4190
+ } catch (e) {
4191
+ if (ak !== mine) return
4192
+ ak.busy = false
4193
+ toast(e.message, { kind: 'fail' })
4194
+ renderAsk()
4195
+ }
4196
+ }
4197
+
4198
+ // Sign in: "sideby login <ref>" in the person's terminal, no AI involved; the command is copied when it cannot open.
4199
+ async function signIn(a) {
4200
+ const cmd = 'sideby login ' + a.ref
4201
+ if (BOOT.readOnly) { copyText(cmd); return }
4202
+ try {
4203
+ const r = await api('/api/login', { account: a.ref })
4204
+ if (r.opened) { toast(t('login.opened', { terminal: TERM_NAMES[r.terminal] || r.terminal, ref: a.ref })); return }
4205
+ await copyText(cmd, cmd)
4206
+ toast(r.automation ? t('login.automation', { terminal: TERM_NAMES[r.terminal] || r.terminal }) : t('login.failed'), { kind: 'info' })
4207
+ } catch (e) {
4208
+ await copyText(cmd, cmd)
4209
+ toast(e.message, { kind: 'fail' })
4210
+ }
4211
+ }
4212
+ function keyable(a) { return !BOOT.readOnly && (a.kind === 'api' || Boolean(family(a.family).keyAlways)) }
4213
+
4214
+ // Enter key (spec §3.28): a password field, saved into the account's proxy.env; then an optional "Try it" that says
4215
+ // what it runs and that it spends a few tokens before it runs.
4216
+ let ky = null
4217
+ function openKey(a) {
4218
+ if (!keyable(a)) return
4219
+ const fam = family(a.family)
4220
+ ky = { ref: a.ref, family: a.family, var: fam.keyVar || '', step: 'enter', busy: false, error: null, saved: null, tried: null, els: {} }
4221
+ showDialog('key')
4222
+ renderKey()
4223
+ if (ky.els.value) ky.els.value.focus()
4224
+ }
4225
+ function renderKey() {
4226
+ if (!ky) return
4227
+ const el = dlg.el
4228
+ const fam = family(ky.family)
4229
+ const body = []
4230
+ const foot = [h('button', { class: 'btn', type: 'button', disabled: ky.busy, onclick: () => el.close() }, t(ky.step === 'enter' ? 'btn.cancel' : 'btn.close'))]
4231
+ if (ky.step === 'enter') {
4232
+ const e = ky.els
4233
+ e.value = h('input', { id: 'ky-value', type: 'password', autocomplete: 'off', spellcheck: 'false', 'aria-describedby': 'ky-err' })
4234
+ e.varInput = h('input', { id: 'ky-var', type: 'text', autocomplete: 'off', autocapitalize: 'characters', spellcheck: 'false', maxlength: '64' })
4235
+ e.varInput.value = ky.var
4236
+ e.err = h('p', { class: 'field-error', id: 'ky-err', role: 'alert' }, ky.error ? ky.error.message : '')
4237
+ e.varInput.addEventListener('input', () => { ky.var = e.varInput.value.trim(); e.label.textContent = t('key.label', { var: ky.var || '?' }) })
4238
+ e.label = h('span', null, t('key.label', { var: ky.var || '?' }))
4239
+ body.push(h('p', { class: 'muted small' }, t('key.intro')),
4240
+ h('form', { id: 'ky-form', class: 'form', novalidate: true, onsubmit: (ev) => { ev.preventDefault(); keySave() } },
4241
+ h('label', { class: 'field', for: 'ky-value' }, e.label, e.value),
4242
+ fam.keyVar ? h('details', { class: 'more-opts' }, h('summary', null, t('key.otherVar')),
4243
+ h('label', { class: 'field', for: 'ky-var' }, h('span', null, t('key.varLabel')), e.varInput), h('p', { class: 'field-hint' }, t('key.varHint')))
4244
+ : h('div', { class: 'field' }, h('p', { class: 'field-hint' }, t('key.noVar')), h('label', { class: 'field', for: 'ky-var' }, h('span', null, t('key.varLabel')), e.varInput)),
4245
+ e.err))
4246
+ foot.push(h('button', { class: 'btn btn-primary', type: 'submit', form: 'ky-form', disabled: ky.busy, 'aria-busy': ky.busy ? 'true' : null }, ky.busy ? spinner() : null, ky.busy ? t('key.saving') : t('key.save')))
4247
+ } else {
4248
+ body.push(h('div', { class: 'created-head', role: 'status' }, h('span', { class: 'check-icon', 'aria-hidden': 'true' }, '✓'), h('span', null, t('key.saved', { var: ky.saved.var, file: ky.saved.path }))))
4249
+ const cmd = fam.tryCommand
4250
+ if (!cmd) body.push(h('p', { class: 'small muted' }, tx('key.cannotTry', { cmd: h('code', null, 'sideby run ' + ky.ref) })))
4251
+ else if (ky.step === 'saved') {
4252
+ body.push(h('p', { class: 'small' }, t('key.tryLead')))
4253
+ foot.push(h('button', { class: 'btn btn-primary', type: 'button', onclick: () => { ky.step = 'confirm'; renderKey() } }, t('key.try')))
4254
+ } else if (ky.step === 'confirm' || ky.step === 'trying') {
4255
+ body.push(h('p', { class: 'small' }, t('key.tryCost')), h('pre', { class: 'diff' }, cmd.map((v) => /^[A-Za-z0-9_./:=-]+$/.test(v) ? v : JSON.stringify(v)).join(' ')))
4256
+ if (ky.step === 'trying') body.push(h('p', { class: 'muted small' }, spinner(), ' ', t('key.trying')))
4257
+ foot.push(h('button', { class: 'btn btn-primary', type: 'button', disabled: ky.step === 'trying', 'aria-busy': ky.step === 'trying' ? 'true' : null, onclick: keyTry }, ky.step === 'trying' ? spinner() : null, t('key.tryRun')))
4258
+ } else if (ky.step === 'tried') {
4259
+ const r = ky.tried
4260
+ if (r.ok) body.push(h('div', { class: 'note' }, t('key.tryOk', { ref: ky.ref })))
4261
+ else {
4262
+ body.push(h('div', { class: 'note note-fail' }, t(r.timedOut ? 'key.tryTimeout' : 'key.tryFail')),
4263
+ h('p', { class: 'small muted' }, t('key.output')),
4264
+ h('pre', { class: 'diff' }, r.output || t('key.noOutput')))
4265
+ foot.push(h('button', { class: 'btn btn-primary', type: 'button', onclick: () => { const ref = ky.ref; const fam = ky.family; openAsk({ task: 'account', context: { account: ref, family: fam }, text: t('key.explainText', { ref, output: r.output || t('key.noOutput') }) }) } }, icon('bot'), t('key.explain')))
4266
+ }
4267
+ }
4268
+ if (ky.error) body.push(errorNote(ky.error, null))
4269
+ }
4270
+ setKids(el, dialogFrame(t('key.title', { ref: ky.ref }), ky.family, body, foot))
4271
+ }
4272
+ async function keySave() {
4273
+ const value = ky.els.value.value
4274
+ const name = ky.var.trim()
4275
+ if (!value.trim()) { ky.els.err.textContent = t('key.empty'); ky.els.value.focus(); return }
4276
+ if (!/^[A-Z][A-Z0-9_]*$/.test(name)) { ky.els.err.textContent = t('key.badVar'); return }
4277
+ const mine = ky
4278
+ ky.busy = true
4279
+ dlg.busy = true
4280
+ ky.error = null
4281
+ renderKey()
4282
+ try {
4283
+ ky.saved = await api('/api/key', { account: ky.ref, var: name, value })
4284
+ ky.step = 'saved'
4285
+ } catch (e) { ky.error = e }
4286
+ dlg.busy = false
4287
+ if (ky !== mine) return
4288
+ ky.busy = false
4289
+ renderKey()
4290
+ if (ky.step === 'enter' && ky.els.value) ky.els.value.focus()
4291
+ }
4292
+ async function keyTry() {
4293
+ const mine = ky
4294
+ ky.step = 'trying'
4295
+ ky.error = null
4296
+ renderKey()
4297
+ try {
4298
+ ky.tried = await api('/api/try', { account: ky.ref })
4299
+ ky.step = 'tried'
4300
+ } catch (e) { ky.error = e; ky.step = 'confirm' }
4301
+ if (ky !== mine || dlg.kind !== 'key') return
4302
+ renderKey()
4303
+ }
4304
+
4305
+ // Preferred terminal and the custom command (spec §3.28): the installed list, "Guess for me" with where the guess
4306
+ // comes from, and a template for any other terminal.
4307
+ let tm = null
4308
+ function openTerminals() {
4309
+ closeMenu()
4310
+ tm = { data: null, busy: false, error: null, draft: null, customOpen: false }
4311
+ showDialog('terminal')
4312
+ renderTerminals()
4313
+ api('/api/terminals').then((d) => { if (tm) { tm.data = d; renderTerminals() } }, (e) => { if (tm) { tm.error = e; renderTerminals() } })
4314
+ }
4315
+ async function termSave(body) {
4316
+ tm.busy = true
4317
+ tm.error = null
4318
+ renderTerminals()
4319
+ try { tm.data = await api('/api/terminal', body); tm.draft = null; toast(t('term.saved')) } catch (e) { tm.error = e }
4320
+ tm.busy = false
4321
+ if (dlg.kind === 'terminal') renderTerminals()
4322
+ }
4323
+ // "Not sure how?": AI writes the custom command, starting from what is typed or saved and what is installed.
4324
+ function termAskAi(d) {
4325
+ const name = (id) => { const f = d.terminals.find((x) => x.id === id); return f ? f.name : id }
4326
+ const typed = tm.draft !== null ? tm.draft.trim() : ''
4327
+ const custom = typed || d.custom || ''
4328
+ const context = { terminals: d.installed.filter((id) => id !== 'custom').map(name), version: BOOT.version }
4329
+ if (custom) context.terminalCustom = custom
4330
+ openAsk({ task: 'terminal', context })
4331
+ }
4332
+ function renderTerminals() {
4333
+ if (!tm) return
4334
+ const body = [h('p', { class: 'muted small' }, t('term.intro'))]
4335
+ const d = tm.data
4336
+ if (!d && !tm.error) body.push(h('p', { class: 'muted small' }, spinner(), ' ', t('term.loading')))
4337
+ if (d) {
4338
+ const name = (id) => { const f = d.terminals.find((x) => x.id === id); return f ? f.name : id }
4339
+ if (!d.installed.length) body.push(h('p', { class: 'note' }, t('term.none')))
4340
+ else {
4341
+ const sel = h('select', { id: 'tm-pick', disabled: tm.busy, 'aria-label': t('term.pick') },
4342
+ h('option', { value: '' }, t('term.auto')),
4343
+ d.installed.map((id) => h('option', { value: id }, name(id))))
4344
+ sel.value = d.preferred && d.installed.includes(d.preferred) ? d.preferred : ''
4345
+ sel.addEventListener('change', () => termSave(sel.value ? { id: sel.value } : {}))
4346
+ body.push(h('label', { class: 'field', for: 'tm-pick' }, h('span', null, t('term.pick')), sel),
4347
+ h('p', { class: 'field-hint' }, t('term.guess.' + d.guess.source, { name: name(d.guess.id) })))
4348
+ }
4349
+ const input = h('input', { id: 'tm-custom', type: 'text', autocomplete: 'off', spellcheck: 'false', placeholder: 'myterm --cwd {cwd} -e {cmd}', disabled: tm.busy })
4350
+ // What was typed stays after a refusal, and so does the open section.
4351
+ input.value = tm.draft !== null ? tm.draft : d.custom || ''
4352
+ input.addEventListener('input', () => { tm.draft = input.value })
4353
+ const more = h('details', { class: 'more-opts', open: tm.customOpen || d.custom ? true : undefined }, h('summary', null, t('term.custom')),
4354
+ h('label', { class: 'field', for: 'tm-custom' }, h('span', null, t('term.custom')), input),
4355
+ h('p', { class: 'field-hint' }, t('term.customHint')),
4356
+ BOOT.readOnly ? null : h('p', { class: 'small' }, h('button', { class: 'link-btn', type: 'button', onclick: () => termAskAi(d) }, icon('bot'), t('term.askAi'))),
4357
+ h('div', { class: 'actions' },
4358
+ h('button', { class: 'btn btn-sm', type: 'button', disabled: tm.busy, onclick: () => termSave({ custom: input.value.trim() }) }, t('term.customSave')),
4359
+ d.custom ? h('button', { class: 'btn btn-sm', type: 'button', disabled: tm.busy, onclick: () => termSave({ custom: '' }) }, t('term.customClear')) : null))
4360
+ more.addEventListener('toggle', () => { tm.customOpen = more.open })
4361
+ body.push(more)
4362
+ }
4363
+ if (tm.error) body.push(errorNote(tm.error, null))
4364
+ setKids(dlg.el, dialogFrame(t('term.title'), null, body, [h('button', { class: 'btn', type: 'button', onclick: () => dlg.el.close() }, t('btn.close'))]))
4365
+ }
4366
+
3472
4367
  // ---------- banners ----------
4368
+ // Offered once on macOS (spec §3.31), when quota shows and the menu bar item is off; "No thanks" is for good.
4369
+ function menubarHint() {
4370
+ if (BOOT.readOnly || prefs.mbHintDone) return null
4371
+ const st = li.menubar
4372
+ if (!st.status) {
4373
+ if (!st.loading && !st.error) loadLoginItem('menubar')
4374
+ return null
4375
+ }
4376
+ if (!st.status.supported || st.status.state !== 'off') return null
4377
+ if (!S.state.accounts.some((a) => a.quota && a.quota.status === 'ok')) return null
4378
+ const done = () => { prefs.mbHintDone = true; savePrefs(); renderBanners() }
4379
+ return h('div', { class: 'banner', role: 'status' },
4380
+ h('div', null, h('b', null, t('mb.hintTitle') + ' '), t('mb.hintBody')),
4381
+ h('div', { class: 'banner-actions' },
4382
+ h('button', { class: 'btn btn-sm btn-primary', type: 'button', onclick: () => { done(); autostartAsk(true, 'menubar') } }, t('mb.hintYes')),
4383
+ h('button', { class: 'btn btn-sm', type: 'button', onclick: done }, t('mb.hintNo'))))
4384
+ }
3473
4385
  function renderBanners() {
3474
4386
  const out = []
3475
4387
  if (S.loadError && S.state) out.push(h('div', { class: 'banner banner-fail', role: 'alert' },
@@ -3483,6 +4395,10 @@ const MAIN = String.raw `
3483
4395
  h('div', { class: 'banner-actions' },
3484
4396
  h('button', { class: 'btn btn-sm btn-primary', type: 'button', onclick: () => setPage('handoff') }, t('ah.setUp')),
3485
4397
  h('button', { class: 'btn btn-sm', type: 'button', onclick: () => { prefs.ahHintAt = Date.now(); savePrefs(); renderBanners() } }, t('ah.dismiss')))))
4398
+ else {
4399
+ const mb = menubarHint()
4400
+ if (mb) out.push(mb)
4401
+ }
3486
4402
  const rcBanner = remoteControlBanner()
3487
4403
  if (rcBanner) out.push(rcBanner)
3488
4404
  const errs = S.state.pluginErrors
@@ -3529,6 +4445,7 @@ const MAIN = String.raw `
3529
4445
  }
3530
4446
  // A read-only Panel never records checks, so keep the result of its own last check over the disk.
3531
4447
  if (!BOOT.readOnly || !S.history) S.history = state.history || null
4448
+ adoptPanel(state.panel)
3532
4449
  } else if (!error.network) S.loadError = error // a lost connection has its own notice
3533
4450
  }
3534
4451
  S.loading = false
@@ -3614,7 +4531,7 @@ const MAIN = String.raw `
3614
4531
  }
3615
4532
  function openUpdate() {
3616
4533
  if (!BOOT.updates) return
3617
- up = { busy: false, error: null, done: null, changed: false, skillDone: false, skillChanged: false, autoPlan: null, autoBusy: false, waitUntil: 0, checking: false, checked: false }
4534
+ up = { busy: false, error: null, done: null, confirming: null, unknown: null, changed: false, skillDone: false, skillChanged: false, autoPlan: null, autoBusy: false, waitUntil: 0, checking: false, checked: false }
3618
4535
  showDialog('update')
3619
4536
  renderUpdate()
3620
4537
  }
@@ -3624,24 +4541,36 @@ const MAIN = String.raw `
3624
4541
  up.busy = true
3625
4542
  dlg.busy = true
3626
4543
  up.error = null
4544
+ up.unknown = null
3627
4545
  renderUpdate()
3628
- try {
3629
- const r = await api('/api/update', { confirm: true, version: u.latest })
3630
- if (!r.updated) {
3631
- // The registry names another version than the dialog showed: show the new plan and let the person look again.
3632
- Object.assign(S.state.update, { latest: r.latest, available: r.available, command: r.command, canRun: r.canRun, releaseNotes: r.releaseNotes, method: r.method })
3633
- up.changed = true
3634
- } else {
3635
- up.done = r
4546
+ const target = u.latest
4547
+ const free = () => { up.busy = false; dlg.busy = false }
4548
+ await codeSwap({
4549
+ send: () => api('/api/update', { confirm: true, version: target }),
4550
+ landed: () => { const now = updState(); return now ? now.current === target : null },
4551
+ // The answer was cut: say only that it is being confirmed, never "updated", until the state shows it.
4552
+ confirming: () => { free(); up.confirming = target; renderUpdate() },
4553
+ done: (r) => {
4554
+ free()
4555
+ up.confirming = null
4556
+ if (r && !r.updated) {
4557
+ // The registry names another version than the dialog showed: show the new plan and let the person look again.
4558
+ Object.assign(S.state.update, { latest: r.latest, available: r.available, command: r.command, canRun: r.canRun, releaseNotes: r.releaseNotes, method: r.method })
4559
+ up.changed = true
4560
+ renderUpdate()
4561
+ return false
4562
+ }
4563
+ up.done = r || { updated: true, latest: target }
3636
4564
  up.waitUntil = Date.now() + 20000
3637
- updWait()
3638
- }
3639
- } catch (e) { up.error = e }
3640
- up.busy = false
3641
- dlg.busy = false
3642
- renderUpdate()
4565
+ renderUpdate()
4566
+ return true
4567
+ },
4568
+ stuck: () => { up.waitUntil = 0; renderUpdate() },
4569
+ fail: (e) => { free(); up.confirming = null; up.error = e; renderUpdate() },
4570
+ unknown: () => { free(); up.confirming = null; up.unknown = target; renderUpdate() },
4571
+ })
3643
4572
  }
3644
- // The CLI is current and the skill is behind: update the skill alone, as sideby update --yes does.
4573
+ // The CLI is current and the skill is behind: update the skill alone, as sideby update --skill --yes does.
3645
4574
  async function updSkillRun() {
3646
4575
  up.busy = true
3647
4576
  dlg.busy = true
@@ -3713,7 +4642,7 @@ const MAIN = String.raw `
3713
4642
  }
3714
4643
  // The switch between a Local Build and the npm package (ADR-0024), only where the state offers it: the other side,
3715
4644
  // one button. After the switch the page waits for the server to run the new build and reloads into it.
3716
- const vs = { busy: false, to: null, waitUntil: 0, stuck: false, error: null }
4645
+ const vs = { busy: false, to: null, stuck: false, unknown: false, error: null }
3717
4646
  function localSwitchKids(u) {
3718
4647
  const ls = u && u.localSwitch
3719
4648
  if (!ls || BOOT.readOnly) return null
@@ -3723,8 +4652,8 @@ const MAIN = String.raw `
3723
4652
  const l = ls.local
3724
4653
  const build = l ? l.version + '-dev · ' + (l.commit || '?') + (l.dirty ? '+' : '') : ''
3725
4654
  const kids = [h('p', { class: 'muted small' }, toNpm ? t('loc.toNpmHint') : t('loc.toLocalHint', { b: build, at: l.builtAt ? clock(l.builtAt) : '' }))]
3726
- if (vs.stuck) {
3727
- kids.push(h('p', { class: 'small' }, t('loc.stuck')))
4655
+ if (vs.stuck || vs.unknown) {
4656
+ kids.push(h('p', { class: 'small' }, t(vs.stuck ? 'loc.stuck' : 'loc.unconfirmed')))
3728
4657
  kids.push(h('div', { class: 'popover-actions' }, h('button', { class: 'btn btn-sm btn-primary', type: 'button', onclick: () => location.reload() }, icon('refresh'), t('loc.reload'))))
3729
4658
  } else {
3730
4659
  const newer = toNpm && u.available && u.latest
@@ -3743,27 +4672,36 @@ const MAIN = String.raw `
3743
4672
  vs.to = to
3744
4673
  vs.error = null
3745
4674
  vs.stuck = false
4675
+ vs.unknown = false
3746
4676
  renderSwitch()
3747
- try {
3748
- await api('/api/local', { to, confirm: true })
3749
- } catch (e) {
3750
- // A background Panel restarting from the new code may drop this answer, and a Portal moving to it may answer
3751
- // 5xx (spec §3.23): the state then says whether the switch happened. Only a switch that did not is an error.
3752
- const kind = switchFailure(e)
3753
- if (kind === 'fail') { vs.busy = false; vs.error = e; renderSwitch(); return }
3754
- if (kind === 'check') {
3755
- await load({ silent: true })
3756
- const ls = updState() && updState().localSwitch
3757
- if (!ls || ls.running !== to) { vs.busy = false; vs.error = e; renderSwitch(); return }
3758
- }
3759
- }
3760
- vs.waitUntil = Date.now() + 20000
3761
- localWait()
4677
+ await codeSwap({
4678
+ send: () => api('/api/local', { to, confirm: true }),
4679
+ landed: () => { const now = updState(); return now && now.localSwitch ? now.localSwitch.running === to : null },
4680
+ confirming: () => {},
4681
+ done: () => true,
4682
+ stuck: () => { vs.busy = false; vs.stuck = true; renderSwitch() },
4683
+ fail: (e) => { vs.busy = false; vs.error = e; renderSwitch() },
4684
+ unknown: () => { vs.busy = false; vs.unknown = true; renderSwitch() },
4685
+ })
3762
4686
  }
3763
- function localWait() {
3764
- if (S.newBuild) { location.reload(); return }
3765
- if (Date.now() > vs.waitUntil) { vs.busy = false; vs.stuck = true; renderSwitch(); return }
3766
- setTimeout(() => { void load({ silent: true }).then(localWait, localWait) }, 1500)
4687
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
4688
+ // Reads the state; true when this read answered (a cut connection or a load already running leaves the old state).
4689
+ async function readState() {
4690
+ const before = S.loadedAt
4691
+ try { await load({ silent: true }) } catch {}
4692
+ return S.loadedAt !== before
4693
+ }
4694
+ // A request that may swap the server's code (runCodeSwap): each wait is 20 s, read every 1.5 s.
4695
+ function codeSwap(o) {
4696
+ return runCodeSwap(Object.assign({
4697
+ readState,
4698
+ newBuild: () => !!S.newBuild,
4699
+ reload: () => location.reload(),
4700
+ now: () => Date.now(),
4701
+ pause,
4702
+ windowMs: 20000,
4703
+ pollMs: 1500,
4704
+ }, o))
3767
4705
  }
3768
4706
  async function verPopCheck() {
3769
4707
  vp.checking = true
@@ -3792,12 +4730,6 @@ const MAIN = String.raw `
3792
4730
  up.checking = false
3793
4731
  renderUpdate()
3794
4732
  }
3795
- // After an Update the server (or the Portal's worker) comes back with a new build; load() then reloads the page.
3796
- function updWait() {
3797
- if (!up || !up.done || S.newBuild) { if (S.newBuild) location.reload(); return }
3798
- if (Date.now() > up.waitUntil) { renderUpdate(); return }
3799
- setTimeout(() => { void load({ silent: true }).then(updWait) }, 1500)
3800
- }
3801
4733
  async function updAuto(on) {
3802
4734
  up.autoBusy = true
3803
4735
  up.error = null
@@ -3844,19 +4776,27 @@ const MAIN = String.raw `
3844
4776
  return
3845
4777
  }
3846
4778
  body.push(h('p', null, t('upd.current', { v: u.current })))
3847
- if (up.done) {
4779
+ // While an Update runs, is being confirmed or could not be, the dialog offers nothing else to start.
4780
+ const swapping = Boolean(up.done || up.confirming || up.unknown)
4781
+ if (up.confirming) {
4782
+ body.push(h('p', { class: 'muted small' }, spinner(), ' ', t('upd.confirming', { v: up.confirming })))
4783
+ } else if (up.unknown) {
4784
+ body.push(h('p', { class: 'note note-warn' }, t('upd.unconfirmed', { v: up.unknown })))
4785
+ } else if (up.done) {
3848
4786
  body.push(h('p', { class: 'note' }, t('upd.done', { v: up.done.latest })))
3849
4787
  body.push(h('p', { class: 'muted small' }, Date.now() > up.waitUntil ? t('upd.restartHint') : [spinner(), ' ', t('upd.reloading')]))
3850
4788
  if (up.done.skillUpdated) body.push(h('p', { class: 'small' }, t('upd.skillDone')))
4789
+ else if (up.done.skillSyncStarted) body.push(h('p', { class: 'muted small' }, t('upd.skillSyncing')))
3851
4790
  else body.push(...updSkill(u))
3852
4791
  } else if (up.skillDone && !skillOld(u)) {
3853
4792
  body.push(h('p', { class: 'note' }, t('upd.skillDoneOnly')))
3854
- } else if (u.available && isLocal(u) && (leavesLocal(u) || vs.busy || vs.stuck)) {
4793
+ } else if (u.available && isLocal(u) && (leavesLocal(u) || vs.busy || vs.stuck || vs.unknown)) {
3855
4794
  // A Local Build the Panel can leave (ADR-0024): switching to the release is the update, and brings the skill.
3856
4795
  body.push(h('p', null, t('upd.localSwitch', { v: u.latest }), ' ',
3857
4796
  h('a', { href: u.releaseNotes, target: '_blank', rel: 'noopener noreferrer' }, t('upd.notes'))))
3858
4797
  if (vs.busy) body.push(h('p', { class: 'muted small' }, spinner(), ' ', t('upd.reloading')))
3859
4798
  if (vs.stuck) body.push(h('p', { class: 'note' }, t('loc.stuck')))
4799
+ if (vs.unknown) body.push(h('p', { class: 'note note-warn' }, t('loc.unconfirmed')))
3860
4800
  if (vs.error) body.push(errorNote(vs.error, null))
3861
4801
  body.push(updManual([h('p', { class: 'small' }, t('upd.localManual')), codeCopy(u.command)]))
3862
4802
  } else if (u.available && isLocal(u)) {
@@ -3896,11 +4836,11 @@ const MAIN = String.raw `
3896
4836
  body.push(h('p', { class: 'muted small' }, t('upd.latest') + (u.checkedAt ? ' · ' + t('upd.checked', { ago: ago(u.checkedAt) }) : '')))
3897
4837
  } else body.push(h('p', { class: 'muted small' }, t('upd.notYet')))
3898
4838
  // A read-only Panel sends no request and writes nothing, so it cannot check (spec §3.23).
3899
- if (!BOOT.readOnly && !up.done && !u.available && !skillDue(u))
4839
+ if (!BOOT.readOnly && !swapping && !u.available && !skillDue(u))
3900
4840
  body.push(h('p', null, h('button', { class: 'btn btn-sm', type: 'button', disabled: up.checking || up.busy, 'aria-busy': up.checking ? 'true' : null, onclick: updCheck },
3901
4841
  up.checking ? spinner() : icon('refresh'), up.checking ? t('upd.checking') : t('upd.check'))))
3902
- if (!BOOT.readOnly && !up.done && isLocal(u)) body.push(h('p', { class: 'muted small' }, t('upd.autoLocal')))
3903
- else if (!BOOT.readOnly && !up.done) {
4842
+ if (!BOOT.readOnly && !swapping && isLocal(u)) body.push(h('p', { class: 'muted small' }, t('upd.autoLocal')))
4843
+ else if (!BOOT.readOnly && !swapping) {
3904
4844
  const box = h('input', { type: 'checkbox', disabled: up.autoBusy || !u.method.canUpdate })
3905
4845
  box.checked = up.autoPlan ? up.autoPlan.auto : u.auto
3906
4846
  box.addEventListener('change', () => updAuto(box.checked))
@@ -3913,12 +4853,12 @@ const MAIN = String.raw `
3913
4853
  if (up.error) body.push(errorNote(up.error, null))
3914
4854
  const foot = [h('button', { class: 'btn', type: 'button', disabled: up.busy, onclick: () => dlg.el.close() }, t('btn.close'))]
3915
4855
  const primary = (label, run) => h('button', { class: 'btn btn-primary', type: 'button', disabled: up.busy, 'aria-busy': up.busy ? 'true' : null, onclick: run }, up.busy ? spinner() : null, up.busy ? t('upd.updating') : label)
3916
- if (u.available && isLocal(u) && vs.stuck) foot.push(h('button', { class: 'btn btn-primary', type: 'button', onclick: () => location.reload() }, icon('refresh'), t('loc.reload')))
4856
+ if (up.unknown || (u.available && isLocal(u) && (vs.stuck || vs.unknown))) foot.push(h('button', { class: 'btn btn-primary', type: 'button', onclick: () => location.reload() }, icon('refresh'), t('loc.reload')))
3917
4857
  else if (u.available && isLocal(u) && (leavesLocal(u) || vs.busy))
3918
4858
  foot.push(h('button', { class: 'btn btn-primary', type: 'button', disabled: vs.busy, 'aria-busy': vs.busy ? 'true' : null, onclick: () => localSwitchTo('npm') },
3919
4859
  vs.busy ? spinner() : icon('swap'), vs.busy ? t('loc.switching') : t('loc.toNpmV', { v: u.latest })))
3920
- else if (u.available && u.canRun && !BOOT.readOnly && !up.done) foot.push(primary(t('upd.now', { v: u.latest }), updRun))
3921
- else if (skillDue(u) && !BOOT.readOnly && !up.done) foot.push(primary(t('upd.skillNow'), updSkillRun))
4860
+ else if (u.available && u.canRun && !BOOT.readOnly && !swapping) foot.push(primary(t('upd.now', { v: u.latest }), updRun))
4861
+ else if (skillDue(u) && !BOOT.readOnly && !swapping) foot.push(primary(t('upd.skillNow'), updSkillRun))
3922
4862
  setKids(dlg.el, dialogFrame(t('upd.title'), null, body, foot))
3923
4863
  }
3924
4864
 
@@ -3929,6 +4869,9 @@ const MAIN = String.raw `
3929
4869
  $('update').addEventListener('click', openUpdate)
3930
4870
  $('ver-top').addEventListener('click', () => openVerPop($('ver-top')))
3931
4871
  $('refresh').addEventListener('click', refreshAll)
4872
+ $('ask-ai').addEventListener('click', () => openAsk())
4873
+ // In a Portal that offers AI Tasks itself the Portal has the button; opened on its own, the Panel keeps it.
4874
+ $('ask-ai').hidden = askBridged(BOOT, window)
3932
4875
  $('accounts').addEventListener('dragover', onDragOver)
3933
4876
  $('accounts').addEventListener('drop', onDrop)
3934
4877
  // Escape leaves the arrange mode, as "Done" does, unless a menu or dialog takes it first.
@@ -3937,6 +4880,13 @@ const MAIN = String.raw `
3937
4880
  endArrange()
3938
4881
  })
3939
4882
  $('settings').addEventListener('click', () => openPopover($('settings'), 'settings', t('set.button'), settingsPop, 'end'))
4883
+ document.addEventListener('contextmenu', onContextMenu)
4884
+ document.addEventListener('keydown', onMenuKey)
4885
+ // The first load of this version writes this browser's earlier theme and language into config, once (spec §3.29).
4886
+ if (CFG && !prefs.cfgDone) {
4887
+ if (!cfgMigrate) { prefs.cfgDone = true; savePrefs() }
4888
+ else saveCfg(cfgMigrate, true).then((ok) => { if (ok) { prefs.cfgDone = true; savePrefs() } })
4889
+ }
3940
4890
  applyTheme()
3941
4891
  renderStatic()
3942
4892
  buildToolbar()