pisha-server 0.0.0-stage → 0.0.12

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 (129) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/accounts/accounts.js +754 -0
  4. package/accounts/index.js +1 -0
  5. package/accounts/passwords.js +41 -0
  6. package/accounts/totp.js +54 -0
  7. package/boards/boards.js +1087 -0
  8. package/boards/github.js +212 -0
  9. package/boards/index.js +1 -0
  10. package/boards/sync.js +980 -0
  11. package/companies.js +294 -0
  12. package/company-export.js +101 -0
  13. package/company.js +82 -0
  14. package/dashboard/dashboard.js +408 -0
  15. package/dashboard/index.js +1 -0
  16. package/data-upgrade.js +69 -0
  17. package/install/linux.sh +181 -0
  18. package/install/macos.sh +121 -0
  19. package/install/windows.bat +54 -0
  20. package/machines/index.js +3 -0
  21. package/machines/machines.js +910 -0
  22. package/messaging/inbox.js +252 -0
  23. package/messaging/index.js +3 -0
  24. package/messaging/messaging.js +551 -0
  25. package/messaging/plans.js +67 -0
  26. package/observation/index.js +1 -0
  27. package/observation/observation.js +231 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +55 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3303 -0
  34. package/pisha-host.mjs.sig +1 -0
  35. package/platform/acme.js +207 -0
  36. package/platform/basics.js +14 -0
  37. package/platform/config.js +154 -0
  38. package/platform/control.js +93 -0
  39. package/platform/credentials.js +151 -0
  40. package/platform/database.js +251 -0
  41. package/platform/errors.js +13 -0
  42. package/platform/files.js +50 -0
  43. package/platform/http.js +207 -0
  44. package/platform/index.js +58 -0
  45. package/platform/limits.js +122 -0
  46. package/platform/listen.js +183 -0
  47. package/platform/roles.js +6 -0
  48. package/platform/stream.js +19 -0
  49. package/platform/text.js +83 -0
  50. package/platform/ws.js +186 -0
  51. package/routes.js +405 -0
  52. package/server.js +65 -0
  53. package/sessions/index.js +1 -0
  54. package/sessions/sessions.js +533 -0
  55. package/ui/LICENSE-affectui.txt +26 -0
  56. package/ui/addmachine.js +151 -0
  57. package/ui/api.js +20 -0
  58. package/ui/app.js +143 -0
  59. package/ui/attention.js +78 -0
  60. package/ui/back.js +168 -0
  61. package/ui/boards.js +958 -0
  62. package/ui/chat.js +388 -0
  63. package/ui/content.js +157 -0
  64. package/ui/dialogs.js +135 -0
  65. package/ui/doing.js +112 -0
  66. package/ui/dom.js +6 -0
  67. package/ui/ds-base.css +146 -0
  68. package/ui/ds-components.css +229 -0
  69. package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
  70. package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
  71. package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
  72. package/ui/format.js +25 -0
  73. package/ui/i18n.js +2145 -0
  74. package/ui/icons/apple-touch-icon.png +0 -0
  75. package/ui/icons/icon-192.png +0 -0
  76. package/ui/icons/icon-512.png +0 -0
  77. package/ui/icons/maskable-512.png +0 -0
  78. package/ui/icons.js +41 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +105 -0
  81. package/ui/machines.js +261 -0
  82. package/ui/manifest.webmanifest +16 -0
  83. package/ui/mosaic.js +189 -0
  84. package/ui/nav.js +142 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +669 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +180 -0
  89. package/ui/people.js +371 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +173 -0
  93. package/ui/routes.js +47 -0
  94. package/ui/screen-boards.css +241 -0
  95. package/ui/screen-inbox.css +201 -0
  96. package/ui/screen-machines.css +76 -0
  97. package/ui/screen-mosaic.css +26 -0
  98. package/ui/screen-newteam.css +90 -0
  99. package/ui/screen-org.css +119 -0
  100. package/ui/screen-session.css +99 -0
  101. package/ui/screen-signin.css +28 -0
  102. package/ui/screen-team.css +80 -0
  103. package/ui/screen-teams.css +41 -0
  104. package/ui/screen-usage.css +60 -0
  105. package/ui/session.js +42 -0
  106. package/ui/shell.css +122 -0
  107. package/ui/signin.js +120 -0
  108. package/ui/squads.js +371 -0
  109. package/ui/state.js +59 -0
  110. package/ui/stream.js +269 -0
  111. package/ui/styles.css +343 -0
  112. package/ui/team.js +115 -0
  113. package/ui/teams.js +58 -0
  114. package/ui/terminal.js +261 -0
  115. package/ui/theme.js +32 -0
  116. package/ui/timeline.js +163 -0
  117. package/ui/topbar.js +211 -0
  118. package/ui/usage.js +175 -0
  119. package/ui/voice-parse.js +98 -0
  120. package/ui/voice.js +320 -0
  121. package/usage/index.js +1 -0
  122. package/usage/usage.js +127 -0
  123. package/vendor/InterVariable.woff2 +0 -0
  124. package/vendor/LICENSE-inter +92 -0
  125. package/vendor/LICENSE-xterm +21 -0
  126. package/vendor/README.md +8 -0
  127. package/vendor/addon-fit.js +2 -0
  128. package/vendor/xterm.css +218 -0
  129. package/vendor/xterm.js +2 -0
Binary file
Binary file
Binary file
Binary file
package/ui/icons.js ADDED
@@ -0,0 +1,41 @@
1
+ // The dashboard's icons: inline strokes that take the colour of their text.
2
+ // Decorative by default (the label next to them says what they are); a button
3
+ // with only an icon carries its own aria-label.
4
+ const PATHS = {
5
+ inbox: '<path d="M4 13l3-8h10l3 8v6H4z"/><path d="M4 13h5l1.5 2.5h3L15 13h5"/>',
6
+ teams: '<circle cx="12" cy="6" r="2.5"/><circle cx="5" cy="18" r="2.5"/><circle cx="19" cy="18" r="2.5"/><path d="M12 8.5V12M5 15.5V12h14v3.5"/>',
7
+ machines: '<rect x="4" y="5" width="16" height="11" rx="1.5"/><path d="M9 20h6M12 16v4"/>',
8
+ settings: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>',
9
+ search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/>',
10
+ plus: '<path d="M12 5v14M5 12h14"/>',
11
+ chevron: '<path d="m9 6 6 6-6 6"/>',
12
+ close: '<path d="M6 6l12 12M18 6 6 18"/>',
13
+ menu: '<path d="M4 7h16M4 12h16M4 17h16"/>',
14
+ refresh: '<path d="M20 11a8 8 0 1 0-2.4 5.7"/><path d="M20 4v7h-7"/>',
15
+ trash: '<path d="M4 7h16M10 11v6M14 11v6M6 7l1 12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1l1-12M9 7V4h6v3"/>',
16
+ archive: '<rect x="3" y="4" width="18" height="4" rx="1"/><path d="M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M10 12h4"/>',
17
+ logout: '<path d="M15 4h3a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-3M10 17l5-5-5-5M15 12H4"/>',
18
+ enter: '<path d="M9 10 4 15l5 5"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/>',
19
+ more: '<circle cx="5" cy="12" r="1.4"/><circle cx="12" cy="12" r="1.4"/><circle cx="19" cy="12" r="1.4"/>',
20
+ sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>',
21
+ moon: '<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/>',
22
+ usage: '<path d="M4 20h16"/><rect x="5" y="11" width="3" height="6" rx="1"/><rect x="10.5" y="6" width="3" height="11" rx="1"/><rect x="16" y="9" width="3" height="8" rx="1"/>',
23
+ board: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M9 4v16M15 4v16"/><path d="M5.5 8h1.5M11 8h2M11 11h2M17 8h1.5"/>',
24
+ pr: '<circle cx="6" cy="6" r="2.3"/><circle cx="6" cy="18" r="2.3"/><circle cx="18" cy="18" r="2.3"/><path d="M6 8.3v7.4M18 15.7V10a3 3 0 0 0-3-3h-4"/><path d="m13 4.5-2.5 2.5 2.5 2.5"/>',
25
+ // (What an inbox entry is: a permission, someone to approve, a question, news, done.)
26
+ shield: '<path d="M12 3.5 19 6v5.2c0 4.3-2.9 7.9-7 9.3-4.1-1.4-7-5-7-9.3V6z"/><path d="m9.2 12.2 2 2 3.8-4"/>',
27
+ userok: '<circle cx="10" cy="8" r="3.5"/><path d="M3.5 20a6.5 6.5 0 0 1 11.2-4.5M15.5 18l2 2 4-4.2"/>',
28
+ ask: '<path d="M20.5 12a8.5 8.5 0 0 1-12.3 7.6L3.5 20.5l1-4.4A8.5 8.5 0 1 1 20.5 12z"/><path d="M9.7 9.6a2.4 2.4 0 0 1 4.6.9c0 1.6-2.3 2-2.3 3.2"/><path d="M12 16.6h.01"/>',
29
+ info: '<circle cx="12" cy="12" r="8.5"/><path d="M12 11v5.2M12 7.8h.01"/>',
30
+ check: '<path d="M5 12.5l4.5 4.5L19 7.5"/>',
31
+ package: '<path d="M12 3 20 7.5v9L12 21l-8-4.5v-9z"/><path d="M4 7.5 12 12l8-4.5M12 12v9"/>',
32
+ folder: '<path d="M3.5 7a2 2 0 0 1 2-2h4l2 2.5h7a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2z"/>',
33
+ sliders: '<path d="M4 7h10M18 7h2M4 17h4M12 17h8"/><circle cx="16" cy="7" r="2"/><circle cx="10" cy="17" r="2"/>',
34
+ spark: '<path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 15.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z"/>',
35
+ mic: '<rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/>',
36
+ }
37
+
38
+ export const icon = (name, cls = '') => `<svg class="ic ${cls}" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${PATHS[name] ?? ''}</svg>`
39
+
40
+ // The logo, drawn from the symbol in the page.
41
+ export const logo = (cls = 'logo') => `<svg class="${cls}" aria-hidden="true" focusable="false"><use href="#pisha-logo"/></svg>`
package/ui/inbox.js ADDED
@@ -0,0 +1,535 @@
1
+ import { $ } from './dom.js'
2
+ import { T, LOCALE } from './i18n.js'
3
+ import { state, can, sessions, hosts } from './state.js'
4
+ import { esc, now, ago } from './format.js'
5
+ import { sortedSessions, status, agentMark } from './content.js'
6
+ import { setHtml } from './nav.js'
7
+ import { postJson } from './machines.js'
8
+ import { alertBox } from './mosaic.js'
9
+ import { currentRoute } from './router.js'
10
+ import { replaceHash, closeTo } from './back.js'
11
+ import { api } from './api.js'
12
+ import { icon } from './icons.js'
13
+ import { nowPhrase } from './doing.js'
14
+
15
+ // The inbox: everything that waits on you, in one list across the page; the
16
+ // one picked opens on the right, and closes again (✕ or Esc) to the list.
17
+ // Two tabs. Pending: decisions coordinators left (ask_user), permission
18
+ // prompts waiting in a session, names to approve; then what they wanted you
19
+ // to know (tell_user). It is all there, live: what arrives shows on its own.
20
+ // Done: what was answered, put away or closed, newest first, a page at a time
21
+ // from the server, by day, searched by its words or one team's.
22
+ // It says what they wrote and nothing more: what it is about, a ticket or
23
+ // anything else, is theirs.
24
+
25
+ const when = t => new Date(t).toLocaleString(LOCALE, { dateStyle: 'medium', timeStyle: 'short' })
26
+ // (A link only if it really is one: a ref is whatever the session wrote.)
27
+ const refHtml = ref => {
28
+ if (!ref) return ''
29
+ let url = null
30
+ try { url = new URL(ref) } catch {}
31
+ return url && (url.protocol === 'https:' || url.protocol === 'http:')
32
+ ? `<a class="ibx-link" href="${esc(url.href)}" target="_blank" rel="noopener noreferrer">${esc(ref)}</a>`
33
+ : `<code>${esc(ref)}</code>`
34
+ }
35
+ const teamOf = name => {
36
+ const s = sessions.get(name)
37
+ const c = s?.role === 'coordinator' ? name : s?.coordinator
38
+ return c ? state.squadMeta.get(c)?.title || c : ''
39
+ }
40
+ const who = name => {
41
+ const s = sessions.get(name)
42
+ const role = s?.role === 'coordinator' ? 'coord' : s?.role === 'solo' ? 'solo' : 'worker'
43
+ return `<span class="ibx-who"><span class="role ${role}" aria-hidden="true"></span>${agentMark(name)}<span class="sr-only">${esc(T.roleName[s?.role] ?? '')} </span>${esc(name)}</span>`
44
+ }
45
+
46
+ // The version of each question the user has had in front of them: if its
47
+ // coordinator changes it after that, an answer is refused until they read it
48
+ // again (they must never decide on what it no longer thinks).
49
+ const seen = new Map()
50
+ // What they were typing, kept across redraws.
51
+ const drafts = new Map()
52
+ // The option picked for each question, until it is sent (a pick alone sends nothing).
53
+ const picks = new Map()
54
+
55
+ // Why an answer can't be typed in the coordinator's terminal from here (null: it can).
56
+ export function cantAnswer(i) {
57
+ const h = hosts.get(sessions.get(i.session)?.host_id)
58
+ if (!h?.online) return T.inboxNoMachine
59
+ if (!h.info?.answers) return T.inboxOldMachine
60
+ if (h.info.allow_input === false) return T.inboxTypingOff
61
+ return null
62
+ }
63
+
64
+ // What a session waiting for permission wants to run.
65
+ const permWhat = s => { const a = s.activity ?? {}; return a.tool?.name ? [a.tool.name, a.tool.summary].filter(Boolean).join(' · ') : a.waiting ?? '' }
66
+
67
+ // Which tab, and where its list and its entries are.
68
+ const tabOf = r => (r.tab === 'done' || r.tab === 'running' ? r.tab : 'pending')
69
+ const listHash = (r = currentRoute()) => ({ done: '#/inbox/done', running: '#/inbox/running' }[tabOf(r)] ?? '#/inbox')
70
+ const itemHash = (tab, key) => (tab === 'done' ? `#/inbox/done/${key}` : `#/inbox/${key}`)
71
+
72
+ // What waits, in its groups. Each entry: { key, kind, ... }.
73
+ function entries() {
74
+ const open = state.inbox.filter(i => !i.resolved_at)
75
+ const asks = open.filter(i => i.kind === 'ask').map(i => ({ key: `i${i.id}`, kind: 'ask', i, at: i.updated_at ?? i.created_at }))
76
+ // Permission prompts waiting in a session: answered in its terminal.
77
+ const perms = sortedSessions().filter(s => status(s).waiting).map(s => ({ key: `p${s.name}`, kind: 'perm', s, at: (s.activity?.tool?.since ?? s.activity?.since ?? now()) }))
78
+ const approvals = can('manager') ? sortedSessions().filter(s => s.approval_pending).map(s => ({ key: `a${s.name}`, kind: 'approve', s, at: (s.created_at ?? 0) * 1000 })) : []
79
+ const tells = open.filter(i => i.kind === 'tell').map(i => ({ key: `i${i.id}`, kind: 'tell', i, at: i.created_at }))
80
+ const newest = (a, b) => b.at - a.at
81
+ return [
82
+ { id: 'decide', label: T.ibxDecide, list: [...perms.sort(newest), ...asks.sort(newest), ...approvals] },
83
+ { id: 'know', label: T.inboxTell, list: tells.sort(newest) },
84
+ ]
85
+ }
86
+
87
+ // What runs now: each session at work, the longest at it first. (A session
88
+ // waiting on you is in Pending, not here.)
89
+ const BUSY = ['tool', 'working', 'compacting']
90
+ function running() {
91
+ return sortedSessions().filter(s => s.online && BUSY.includes(s.activity?.state))
92
+ .map(s => ({ key: `r${s.name}`, kind: 'running', s, at: s.activity.busy_since ?? s.activity.since ?? now() }))
93
+ .sort((a, b) => a.at - b.at)
94
+ }
95
+
96
+ // A live clock: how long it has waited, or worked (m:ss, then h:mm:ss, then days).
97
+ function clock(ms) {
98
+ const t = Math.max(0, Math.floor(ms / 1000)), h = Math.floor(t / 3600), m = Math.floor(t / 60) % 60, sec = String(t % 60).padStart(2, '0')
99
+ return t >= 86400 ? T.ibxDays(Math.floor(t / 86400)) : h ? `${h}:${String(m).padStart(2, '0')}:${sec}` : `${m}:${sec}`
100
+ }
101
+ const tick = () => { for (const el of $('inbox').querySelectorAll('[data-since]')) el.textContent = clock(now() - Number(el.dataset.since)) }
102
+ setInterval(() => { if (!$('inbox').hidden) tick() }, 1000)
103
+
104
+ // What is done: the pages asked for, and what the live list brings on top of
105
+ // them (closed meanwhile), without what has since been opened again.
106
+ const done = { q: '', team: '', items: [], next: null, loaded: false, loading: false, failed: false, turn: 0 }
107
+ const PAGE = 50
108
+ async function loadDone(more = false) {
109
+ if (more && (done.loading || !done.next)) return
110
+ const turn = ++done.turn
111
+ done.loading = true; done.failed = false
112
+ const qs = new URLSearchParams({ limit: String(PAGE) })
113
+ if (done.team) qs.set('team', done.team)
114
+ if (done.q.trim()) qs.set('q', done.q.trim())
115
+ if (more) qs.set('before', done.next)
116
+ refreshInbox()
117
+ try {
118
+ const r = await api(`/api/inbox/done?${qs}`)
119
+ if (turn !== done.turn) return
120
+ done.items = more ? [...done.items, ...r.items] : r.items
121
+ done.next = r.next_before
122
+ done.loaded = true
123
+ } catch {
124
+ if (turn === done.turn) done.failed = true
125
+ } finally {
126
+ if (turn === done.turn) { done.loading = false; refreshInbox() }
127
+ }
128
+ }
129
+ const newer = (a, b) => a.resolved_at > b.resolved_at || (a.resolved_at === b.resolved_at && a.id > b.id)
130
+ function doneEntries() {
131
+ const open = new Set(state.inbox.filter(i => !i.resolved_at).map(i => i.id))
132
+ const words = done.q.trim().toLowerCase()
133
+ // (Live ones only above where the pages end: below, the next page has them in order.)
134
+ const bottom = done.next ? done.items.at(-1) : null
135
+ const live = state.inbox.filter(i => i.resolved_at && (!done.team || i.session === done.team)
136
+ && (!words || [i.text, i.answer, i.closed_reason].some(t => t?.toLowerCase().includes(words)))
137
+ && (!bottom || newer(i, bottom)))
138
+ const byId = new Map()
139
+ for (const i of [...done.items, ...live]) byId.set(i.id, i)
140
+ return [...byId.values()].filter(i => !open.has(i.id)).sort((a, b) => (newer(a, b) ? -1 : 1))
141
+ .map(i => ({ key: `i${i.id}`, kind: 'done', i, at: i.resolved_at }))
142
+ }
143
+
144
+ // "Today", "Yesterday", then the date: what is done, by the day it was.
145
+ function dayOf(t) {
146
+ const d = new Date(t), today = new Date()
147
+ const start = x => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime()
148
+ const days = Math.round((start(today) - start(d)) / 86400_000)
149
+ if (days === 0) return T.dayToday
150
+ if (days === 1) return T.dayYesterday
151
+ return d.toLocaleDateString(LOCALE, { weekday: 'long', day: 'numeric', month: 'long', ...(d.getFullYear() !== today.getFullYear() ? { year: 'numeric' } : {}) })
152
+ }
153
+
154
+ // What arrived while the list was in view: marked a moment, never moved to.
155
+ const arrived = new Map() // key -> when it first showed
156
+ let listedKeys = null
157
+ const FRESH_MS = 3000
158
+
159
+ function row(e, on, tab = 'pending') {
160
+ const href = itemHash(tab, e.key)
161
+ const fresh = Date.now() - (arrived.get(e.key) ?? 0) < FRESH_MS
162
+ let dot, title, meta
163
+ // (Its mark: what it is, in the colour of what it needs.)
164
+ const mark = { perm: 'shield', approve: 'userok', ask: 'ask', tell: 'info', done: 'check', running: 'spark' }[e.kind] ?? 'info'
165
+ if (e.kind === 'running') {
166
+ const a = e.s.activity ?? {}
167
+ dot = 'info'; title = a.state === 'tool' ? nowPhrase(a.tool) : a.state === 'compacting' ? T.compacting : T.ibxWorkingNow
168
+ meta = [who(e.s.name), esc(teamOf(e.s.name))]
169
+ } else if (e.kind === 'perm') {
170
+ dot = 'warn'; title = T.ibxPermTitle(e.s.name, permWhat(e.s))
171
+ meta = [who(e.s.name), esc(teamOf(e.s.name))]
172
+ } else if (e.kind === 'approve') {
173
+ dot = 'warn'; title = T.ibxApproveTitle(e.s.name)
174
+ meta = [who(e.s.name), esc(T.approveNote)]
175
+ } else {
176
+ const i = e.i
177
+ dot = e.kind === 'ask' ? 'warn' : e.kind === 'tell' ? 'info' : 'ok'
178
+ title = i.text.replace(/\s+/g, ' ')
179
+ meta = [who(i.session), esc(teamOf(i.session)), i.updated_at && e.kind === 'ask' ? `<span class="ibx-upd">${esc(T.inboxUpdated(ago(i.updated_at)))}</span>` : '', tab === 'done' ? esc(ago(e.at)) : '']
180
+ }
181
+ // Its state, as a tag; and, while it waits or works, its clock.
182
+ const st = e.kind === 'done' ? (e.i?.answer != null ? 'answered' : e.i?.dismissed_by ? 'dismissed' : 'closed') : e.kind
183
+ const tone = { perm: 'warn', approve: 'warn', ask: 'warn', tell: 'info', running: 'info' }[st] ?? ''
184
+ const side = `<span class="ibx-side"><span class="tag ${tone}">${st === 'running' ? '<span class="ibx-live" aria-hidden="true"></span>' : ''}${esc(T.ibxTag[st] ?? '')}</span>${tab !== 'done' ? `<time class="ibx-clock" data-since="${Number(e.at)}" title="${esc(when(e.at))}"></time>` : ''}</span>`
185
+ const to = e.kind === 'running' ? `#/s/${encodeURIComponent(e.s.name)}` : href
186
+ return `<li><a href="${to}" class="ibx-item${on ? ' on' : ''}${e.kind === 'done' ? ' done' : ''}${fresh ? ' new' : ''}"${on ? ' aria-current="true"' : ''} data-key="${esc(e.key)}">`
187
+ + `<span class="ibx-mark ${dot}" aria-hidden="true">${icon(mark)}</span><span class="ibx-item-b"><span class="ibx-item-top"><span class="ibx-item-t">${esc(title)}</span>${side}</span><span class="ibx-item-m">${meta.filter(Boolean).join('<span aria-hidden="true">·</span>')}</span></span></a></li>`
188
+ }
189
+
190
+ // Nothing open yet on this company: the three steps to a first team.
191
+ function firstSteps() {
192
+ const machine = hosts.size > 0
193
+ const team = sortedSessions().some(s => s.role === 'coordinator')
194
+ const step = (n, done, now, title, hint, action) => `<li class="fs-step${done ? ' done' : now ? ' now' : ''}"><span class="fs-mark" aria-hidden="true">${done ? '✓' : n}</span><div><b>${esc(title)}</b>${now && hint ? `<p>${esc(hint)}</p>` : ''}${now && action ? action : ''}</div>${done ? `<span class="sr-only">${esc(T.fsDone)}</span>` : ''}</li>`
195
+ return `<div class="fs"><h2 class="fs-title">${esc(T.fsTitle)}</h2><p class="fs-sub">${esc(T.fsSub)}</p>
196
+ <ol class="fs-steps card">
197
+ ${step(1, true, false, T.fsAccount)}
198
+ ${step(2, machine, !machine, T.fsMachine, T.fsMachineHint, can('manager') ? `<button type="button" class="btn primary" data-addmachine>${esc(T.actAddMachine)}</button>` : '')}
199
+ ${step(3, team, machine && !team, T.fsTeam, T.fsTeamHint, can('operator') ? `<button type="button" class="btn primary" data-newteam>${esc(T.newTeam)}</button>` : '')}
200
+ </ol>
201
+ <p class="fs-hint">${T.fsLogin}</p></div>`
202
+ }
203
+
204
+ const emptyState = () => `<div class="empty">${icon('inbox', 'empty-ic')}<b>${esc(T.inboxEmpty)}</b><span>${esc(T.ibxEmptyHint)}</span></div>`
205
+
206
+ // Who left it, as a mail client shows a sender: their mark, name and team,
207
+ // what it is and when; the way to their session on the right.
208
+ function head(name, kind, at, link = true) {
209
+ const s = sessions.get(name)
210
+ const role = s?.role === 'coordinator' ? 'coord' : s?.role === 'solo' ? 'solo' : 'worker'
211
+ return `<header class="ibx-head"><span class="ibx-avatar ${role}" aria-hidden="true"><span class="role ${role}"></span></span>
212
+ <div class="ibx-from"><b>${esc(name)} ${agentMark(name)}</b><span>${[esc(teamOf(name)), esc(kind), at ? `<time title="${esc(when(at))}">${esc(ago(at))}</time>` : ''].filter(Boolean).join('<span aria-hidden="true"> · </span>')}</span></div>
213
+ ${link ? `<a class="btn" href="#/s/${encodeURIComponent(name)}" aria-label="${esc(T.ibxOpenSession)}"><span class="ibx-l">${esc(T.ibxOpenSession)}</span><span class="ibx-s" aria-hidden="true">${esc(T.ibxSessionShort)}</span></a>` : ''}
214
+ <a class="icon-btn ibx-close" href="${listHash()}" aria-label="${esc(T.close)}" title="${esc(T.close)} (Esc)">${icon('close')}</a></header>`
215
+ }
216
+
217
+ function detail(e) {
218
+ if (!e && !sortedSessions().length) return firstSteps()
219
+ if (!e) return emptyState()
220
+ if (e.kind === 'perm') {
221
+ const s = e.s
222
+ return `<article class="ibx-card">${head(s.name, T.ibxPermission, e.at, false)}
223
+ <div class="ibx-body"><h2 class="ibx-q">${esc(T.ibxPermTitle(s.name, ''))}</h2><pre class="ibx-perm">${esc(permWhat(s) || status(s).text)}</pre>
224
+ <p class="ibx-note">${esc(T.ibxPermHint)}</p>
225
+ <div class="ibx-actions"><a class="btn primary ok" href="#/s/${encodeURIComponent(s.name)}">${esc(T.ibxOpenSession)}</a></div></div></article>`
226
+ }
227
+ if (e.kind === 'approve') {
228
+ const s = e.s
229
+ return `<article class="ibx-card">${head(s.name, T.approveNote, e.at, false)}
230
+ <div class="ibx-body"><h2 class="ibx-q">${esc(T.ibxApproveTitle(s.name))}</h2><p class="ibx-note">${esc(T.ibxApproveHint)}</p>
231
+ <div class="ibx-actions"><a class="btn primary ok" href="#/s/${encodeURIComponent(s.name)}">${esc(T.ibxOpenSession)}</a></div></div></article>`
232
+ }
233
+ const i = e.i
234
+ const open = !i.resolved_at
235
+ const ask = i.kind === 'ask'
236
+ if (open && !seen.has(i.id)) seen.set(i.id, i.version)
237
+ const changed = open && seen.get(i.id) !== i.version
238
+ const why = open && ask && can('operator') ? cantAnswer(i) : null
239
+ const answering = open && ask && can('operator') && !why
240
+ // Something it was told can be replied to as well ("update the branches with
241
+ // main"), when it can be typed in its coordinator's terminal; Done still closes it.
242
+ const replying = open && !ask && can('operator') && !cantAnswer(i)
243
+ // The option it recommends: its words, perhaps followed by why ("Keep it: nothing is lost").
244
+ const rec = String(i.recommended ?? '').trim()
245
+ const recIndex = rec ? i.options.findIndex(o => { const t = o.trim().toLowerCase(), r = rec.toLowerCase(); return r === t || (r.startsWith(t) && /^[\s:.,;—–-]/.test(r.slice(t.length))) }) : -1
246
+ const recRest = recIndex >= 0 ? rec.slice(i.options[recIndex].trim().length).replace(/^[\s:.,;—–-]+/, '') : ''
247
+ const recWhy = recRest.charAt(0).toUpperCase() + recRest.slice(1)
248
+ const opts = i.options.map((o, n) => answering
249
+ ? `<button type="button" class="ibx-opt${n === recIndex ? ' rec' : ''}" data-option="${n}" aria-pressed="${picks.get(i.id) === n}"><kbd>${n + 1}</kbd><span>${esc(o)}</span>${n === recIndex ? `<span class="tag">${esc(T.inboxRecommended)}</span>` : ''}</button>`
250
+ : `<li>${esc(o)}${n === recIndex ? ` <span class="tag">${esc(T.inboxRecommended)}</span>` : ''}</li>`).join('')
251
+ const kind = !open ? T.ibxClosedAt : ask ? T.ibxKindAsk : T.inboxTell
252
+ return `<article class="ibx-card${open ? '' : ' closed'}">${head(i.session, kind, i.updated_at ?? i.created_at)}
253
+ <div class="ibx-body">
254
+ ${changed ? `<div class="ibx-changed" data-changed role="status">${esc(T.inboxChangedSince)}</div>` : ''}
255
+ <h2 class="ibx-q${ask ? '' : ' tell'}">${esc(i.text)}</h2>
256
+ ${i.options.length ? (answering ? `<div class="ibx-opts" role="group" aria-label="${esc(T.inboxOptions)}">${opts}</div>` : `<ul class="ibx-optlist">${opts}</ul>`) : ''}
257
+ ${rec && (recIndex < 0 || recWhy) ? `<p class="ibx-rec"><span class="tag">${esc(T.inboxRecommended)}</span> ${esc(recIndex < 0 ? rec : recWhy)}</p>` : ''}
258
+ ${answering ? `<form class="ibx-answer" data-answer="${i.id}"><label class="field"><span>${esc(i.options.length ? T.ibxOwnWordsOr : T.ibxOwnWords)}</span><textarea name="answer" rows="3" maxlength="2000" placeholder="${esc(T.ibxReachesTo(i.session))}"></textarea></label>
259
+ <div class="ibx-actions"><span class="ibx-note">${esc(i.options.length ? T.ibxOptionDetail : T.ibxGoesOn)}</span><span class="row"><button type="button" class="btn danger" data-dismiss="${i.id}">${esc(T.inboxDismiss)}</button><button class="btn primary ok">${esc(T.inboxSend)}</button></span></div></form>` : ''}
260
+ ${replying ? `<form class="ibx-answer" data-answer="${i.id}"><label class="field"><span>${esc(T.ibxReplyTell)}</span><textarea name="answer" rows="2" maxlength="2000" placeholder="${esc(T.ibxReachesTo(i.session))}"></textarea></label>
261
+ <div class="ibx-actions"><span class="ibx-note">${esc(T.ibxReplyTellNote)}</span><span class="row"><button type="button" class="btn ok" data-resolve="${i.id}">${esc(T.inboxResolve)}</button><button class="btn primary ok">${esc(T.inboxSend)}</button></span></div></form>` : ''}
262
+ ${why ? `<p class="ibx-note">${esc(why)}</p>` : ''}
263
+ ${open && !answering && !replying && can('operator') ? `<div class="ibx-actions">${why ? `<a class="btn ok" href="#/s/${encodeURIComponent(i.session)}">${esc(T.inboxAnswer)}</a>` : ''}${ask ? `<button type="button" class="btn danger" data-dismiss="${i.id}">${esc(T.inboxDismiss)}</button>` : `<button type="button" class="btn ok${why ? '' : ' primary'}" data-resolve="${i.id}">${esc(T.inboxResolve)}</button>`}</div>` : ''}
264
+ ${i.answer != null ? `<p class="ibx-result">${esc(T.inboxAnswered(i.answered_by ?? '', i.answer))}</p>` : ''}
265
+ ${i.dismissed_by ? `<p class="ibx-result">${esc(T.inboxDismissed(i.dismissed_by))}</p>` : ''}
266
+ ${i.closed_reason ? `<p class="ibx-result">${esc(T.inboxClosed(i.closed_reason))}</p>` : ''}
267
+ </div>
268
+ <dl class="ibx-facts">
269
+ ${i.ref ? `<dt>${esc(T.ibxRef)}</dt><dd>${refHtml(i.ref)}</dd>` : ''}
270
+ <dt>${esc(T.ibxLeft)}</dt><dd>${esc(when(i.created_at))}</dd>
271
+ ${i.updated_at ? `<dt>${esc(T.ibxChanged)}</dt><dd>${esc(when(i.updated_at))}</dd>` : ''}
272
+ ${i.resolved_at ? `<dt>${esc(T.ibxClosedAt)}</dt><dd>${esc(when(i.resolved_at))}</dd>` : ''}
273
+ </dl></article>`
274
+ }
275
+
276
+ let hadPick = null // the key of the one open at the last draw
277
+
278
+ // The two tabs, in the header: how many wait on the first.
279
+ // (A count that changed rolls in: up when it grows, down when it shrinks.)
280
+ const counted = new Map()
281
+ function tabs(tab, waiting, busy) {
282
+ const a = (t, href, label, n) => {
283
+ const was = counted.get(t)
284
+ counted.set(t, n)
285
+ const roll = was != null && was !== n ? (n > was ? ' up' : ' down') : ''
286
+ return `<a href="${href}"${t === tab ? ' class="on" aria-current="page"' : ''} data-ibxtab="${t}">${esc(label)}${n ? ` <span class="badge soft${roll}" data-n="${n}">${n}</span>` : ''}</a>`
287
+ }
288
+ return `<nav class="seg" aria-label="${esc(T.inbox)}">${a('pending', '#/inbox', T.ibxPending, waiting)}${a('running', '#/inbox/running', T.ibxRunningTab, busy)}${a('done', '#/inbox/done', T.ibxDoneTab, 0)}</nav>`
289
+ }
290
+
291
+ // Running: who is at work now; each opens its session.
292
+ function runningList(list) {
293
+ if (!list.length) return `<div class="empty">${icon('spark', 'empty-ic')}<b>${esc(T.ibxNoneRunning)}</b><span>${esc(T.ibxNoneRunningHint)}</span></div>`
294
+ return `<section class="ibx-group"><ul>${list.map(e => row(e, false, 'running')).join('')}</ul></section>`
295
+ }
296
+
297
+ // Pending: what needs you, then what to know (read all at once, if several).
298
+ function pendingList(groups, picked) {
299
+ return groups.filter(g => g.list.length).map(g => {
300
+ const readAll = g.id === 'know' && g.list.length > 1 && can('operator') ? `<button type="button" class="btn quiet ibx-readall" data-readall>${esc(T.ibxReadAll)}</button>` : ''
301
+ return `<section class="ibx-group"><h2 class="ibx-group-h"><span>${esc(g.label)}</span>${readAll}<span class="badge soft">${g.list.length}</span></h2><ul>${g.list.map(e => row(e, e === picked)).join('')}</ul></section>`
302
+ }).join('')
303
+ }
304
+
305
+ // Done: a search, a team, the days, and more as the list ends.
306
+ function doneList(list, picked) {
307
+ const coords = sortedSessions().filter(x => x.role === 'coordinator')
308
+ if (done.team && !coords.some(c => c.name === done.team)) coords.push({ name: done.team })
309
+ const tools = `<form class="ibx-tools" role="search" data-donefilter>
310
+ <input class="input" type="search" id="ibxQ" name="q" value="${esc(done.q)}" placeholder="${esc(T.ibxSearch)}" aria-label="${esc(T.ibxSearch)}" autocomplete="off" maxlength="100">
311
+ <select class="input" name="team" aria-label="${esc(T.ibxTeam)}"><option value="">${esc(T.ibxAllTeams)}</option>${coords.map(c => `<option value="${esc(c.name)}"${c.name === done.team ? ' selected' : ''}>${esc(state.squadMeta.get(c.name)?.title || c.name)}</option>`).join('')}</select>
312
+ </form>`
313
+ const days = []
314
+ for (const e of list) {
315
+ const day = dayOf(e.at)
316
+ if (days.at(-1)?.day !== day) days.push({ day, list: [] })
317
+ days.at(-1).list.push(e)
318
+ }
319
+ const body = days.map(d => `<section class="ibx-group"><h2 class="ibx-group-h"><span>${esc(d.day)}</span></h2><ul>${d.list.map(e => row(e, e === picked, 'done')).join('')}</ul></section>`).join('')
320
+ const filtered = !!(done.q.trim() || done.team)
321
+ const foot = done.failed ? `<p class="ibx-none">${esc(T.ibxLoadFailed)} <button type="button" class="btn quiet" data-more>${esc(T.tplRetry)}</button></p>`
322
+ : done.next ? `<div class="ibx-more"><button type="button" class="btn" data-more${done.loading ? ' disabled' : ''}>${esc(done.loading ? T.ibxLoading : T.ibxLoadMore)}</button></div>`
323
+ : !done.loaded ? `<p class="ibx-none">${esc(T.ibxLoading)}</p>`
324
+ : list.length ? `<p class="ibx-end">${esc(T.ibxEnd)}</p>`
325
+ : `<p class="ibx-none">${esc(filtered ? T.ibxNoMatch : T.ibxNoDone)}</p>`
326
+ return tools + body + foot
327
+ }
328
+
329
+ // (The next page, as the end of the list comes into view.)
330
+ const moreSeen = typeof IntersectionObserver === 'function'
331
+ ? new IntersectionObserver(es => { if (es.some(x => x.isIntersecting)) void loadDone(true) }, { rootMargin: '200px' })
332
+ : null
333
+
334
+ export function renderInbox() {
335
+ const r = currentRoute()
336
+ const tab = tabOf(r)
337
+ const groups = entries()
338
+ const pending = groups.flatMap(g => g.list)
339
+ const waiting = groups[0].list.length
340
+ if (tab === 'done' && !done.loaded && !done.loading && !done.failed) void loadDone()
341
+ const doneList_ = tab === 'done' ? doneEntries() : []
342
+ const busy = running()
343
+ const all = tab === 'done' ? doneList_ : tab === 'running' ? [] : pending
344
+ // What arrived since the last draw of the list (not on the first).
345
+ const keys = pending.map(e => e.key)
346
+ if (listedKeys) for (const k of keys) if (!listedKeys.has(k) && !arrived.has(k)) arrived.set(k, Date.now())
347
+ listedKeys = new Set(keys)
348
+ for (const [k, t] of arrived) if (Date.now() - t > FRESH_MS * 10) arrived.delete(k)
349
+ // What is picked: only the one in the address; without one, the list has the page.
350
+ // (Pending, one just answered stays open until the next is.)
351
+ const picked = r.item ? (all.find(e => e.key === r.item) ?? (tab === 'pending' ? (() => {
352
+ const i = state.inbox.find(x => `i${x.id}` === r.item)
353
+ return i ? { key: r.item, kind: i.resolved_at ? 'done' : i.kind, i, at: i.resolved_at ?? i.created_at } : null
354
+ })() : null)) : null
355
+ const focus = document.activeElement?.closest?.('#inbox') ? document.activeElement : null
356
+ const focusKey = focus?.closest('[data-key]')?.dataset.key
357
+ const typing = focus?.name === 'answer'
358
+ const searching = focus?.id === 'ibxQ' ? [focus.selectionStart, focus.selectionEnd] : null
359
+ const list = tab === 'done' ? doneList(doneList_, picked) : tab === 'running' ? runningList(busy) : pendingList(groups, picked)
360
+ const fresh = tab === 'pending' && !pending.length && !sortedSessions().length
361
+ const caughtUp = tab === 'pending' && !pending.length
362
+ const pick = !!picked
363
+ // (Where each row was: after the draw, a row that moved glides to its new place.)
364
+ const was = new Map([...$('inbox').querySelectorAll('.ibx-item[data-key]')].map(el => [el.dataset.key, el.getBoundingClientRect().top]))
365
+ setHtml($('inbox'), `<div class="ibx${pick ? ' has-pick' : ''}${fresh ? ' fresh' : ''}${caughtUp && !fresh ? ' none' : ''}" data-tab="${tab}">
366
+ <nav class="ibx-list" aria-label="${esc(T.inbox)}"><div class="ibx-col">${tab === 'pending' ? (caughtUp && !fresh ? '' : list || `<p class="ibx-none">${esc(T.ibxNothingListed)}</p>`) : list}</div></nav>
367
+ <section class="ibx-detail${pick && !hadPick ? ' enter' : ''}" aria-live="polite">${tab === 'done' && !picked ? doneHint() : tab === 'running' ? '' : detail(picked)}</section>
368
+ </div>`)
369
+ tick()
370
+ glide(was)
371
+ const closed = !pick && hadPick
372
+ hadPick = picked?.key ?? null
373
+ setHtml($('topTabs'), tabs(tab, pending.length, busy.length))
374
+ $('topSub').textContent = tab === 'pending' && waiting ? T.ibxWaiting(waiting) : ''
375
+ if (moreSeen) { moreSeen.disconnect(); const m = $('inbox').querySelector('.ibx-more [data-more]'); if (m) moreSeen.observe(m) }
376
+ // Back where the user was: the answer they were typing, the search, the row they were on.
377
+ for (const f of $('inbox').querySelectorAll('[data-answer]')) {
378
+ const input = f.elements.answer
379
+ const d = drafts.get(Number(f.dataset.answer))
380
+ if (d && !input.value) input.value = d
381
+ if (typing && document.activeElement !== input) input.focus()
382
+ }
383
+ const q = $('ibxQ')
384
+ if (q && q.value !== done.q) q.value = done.q
385
+ if (searching && q && document.activeElement !== q) { q.focus(); q.setSelectionRange(...searching) }
386
+ if (focusKey && !typing && !searching && document.activeElement !== focus) $('inbox').querySelector(`[data-key="${CSS.escape(focusKey)}"]`)?.focus()
387
+ // Just closed: the keyboard goes back to its row.
388
+ else if (closed) $('inbox').querySelector(`[data-key="${CSS.escape(closed)}"]`)?.focus({ preventScroll: true })
389
+ }
390
+ // Rows that moved since the last draw glide from where they were (not for who asks for no motion).
391
+ const still = matchMedia('(prefers-reduced-motion: reduce)')
392
+ function glide(was) {
393
+ if (!was.size || still.matches) return
394
+ for (const el of $('inbox').querySelectorAll('.ibx-item[data-key]')) {
395
+ const from = was.get(el.dataset.key)
396
+ if (from == null) continue
397
+ const dy = from - el.getBoundingClientRect().top
398
+ if (Math.abs(dy) > 1) el.animate([{ transform: `translateY(${dy}px)` }, { transform: 'none' }], { duration: 360, easing: 'cubic-bezier(.22, 1, .36, 1)' })
399
+ }
400
+ }
401
+ // (Done, with none open: what the tab is.)
402
+ const doneHint = () => `<div class="empty">${icon('archive', 'empty-ic')}<b>${esc(T.ibxDoneTab)}</b><span>${esc(T.ibxDoneHint)}</span></div>`
403
+ export const refreshInbox = () => { if (currentRoute().view === 'inbox' && !$('inbox').hidden) renderInbox() }
404
+
405
+ // After an answer, the next decision that waits; after a note, the next note.
406
+ // With none left, back to the whole list.
407
+ function next(id) {
408
+ const [decide, know] = entries()
409
+ // (Known by its kind: answered, it may have left the list already.)
410
+ const wasNote = know.list.some(e => e.i?.id === id) || state.inbox.find(x => x.id === id)?.kind === 'tell'
411
+ const list = [...decide.list, ...(wasNote ? know.list : [])].filter(e => e.i?.id !== id)
412
+ if (list.length) replaceHash(`#/inbox/${list[0].key}`); else closeTo('#/inbox')
413
+ }
414
+
415
+ async function answer(id, text) {
416
+ const i = state.inbox.find(x => x.id === id)
417
+ if (!i || !text.trim()) return
418
+ try {
419
+ await postJson('/api/inbox/answer', { id, version: seen.get(id) ?? i.version, answer: text })
420
+ drafts.delete(id)
421
+ picks.delete(id)
422
+ next(id)
423
+ } catch (err) {
424
+ // Changed since they read it: now they have, and it says so.
425
+ if (err.reason === 'changed') seen.set(id, i.version)
426
+ alertBox(err.reason === 'changed' ? T.inboxChangedSince : err.message)
427
+ renderInbox()
428
+ }
429
+ }
430
+ const pickedAsk = () => { const f = $('inbox').querySelector('[data-answer]'); return f ? Number(f.dataset.answer) : null }
431
+ // Picking an option only marks it: it goes with Send (or Ctrl+Enter), along
432
+ // with whatever is typed, before or after. Picked again, it is unmarked.
433
+ function choose(n, { toggle = true } = {}) {
434
+ const id = pickedAsk()
435
+ const i = state.inbox.find(x => x.id === id)
436
+ if (!i?.options[n]) return
437
+ if (toggle && picks.get(id) === n) picks.delete(id); else picks.set(id, n)
438
+ for (const b of $('inbox').querySelectorAll('[data-option]')) b.setAttribute('aria-pressed', String(picks.get(id) === Number(b.dataset.option)))
439
+ }
440
+ // What Send sends: the option picked, with the detail typed; or only what is typed.
441
+ function send(f) {
442
+ const id = Number(f.dataset.answer)
443
+ const i = state.inbox.find(x => x.id === id)
444
+ const typed = f.elements.answer.value.trim()
445
+ const choice = i?.options[picks.get(id)]
446
+ if (!choice && !typed) { f.elements.answer.focus(); return }
447
+ return answer(id, choice ? (typed ? `${choice}. ${typed}` : choice) : typed)
448
+ }
449
+
450
+ $('inbox').addEventListener('click', async e => {
451
+ // The open one, clicked again, closes.
452
+ const on = e.target.closest('.ibx-item.on')
453
+ if (on && !e.metaKey && !e.ctrlKey) { e.preventDefault(); closeTo(listHash()); return }
454
+ if (e.target.closest('.ibx-close') && !e.metaKey && !e.ctrlKey) { e.preventDefault(); closeTo(listHash()); return }
455
+ if (e.target.closest('[data-more]')) { done.failed = false; return void loadDone(done.loaded) }
456
+ // Everything to know, read: what is listed now, not what arrives meanwhile.
457
+ if (e.target.closest('[data-readall]')) {
458
+ const ids = entries()[1].list.map(x => x.i.id)
459
+ try { await postJson('/api/inbox/read-all', { ids }) } catch (err) { alertBox(err.message) }
460
+ return
461
+ }
462
+ if (e.target.closest('[data-addmachine]')) { location.hash = '#/hosts/new'; return }
463
+ if (e.target.closest('[data-newteam]')) { location.hash = '#/new'; return }
464
+ const opt = e.target.closest('[data-option]')
465
+ if (opt) return choose(Number(opt.dataset.option))
466
+ // A question put away: its coordinator is told not to wait, if it can be.
467
+ const dm = e.target.closest('[data-dismiss]')
468
+ if (dm) {
469
+ const id = Number(dm.dataset.dismiss)
470
+ const session = state.inbox.find(x => x.id === id)?.session ?? ''
471
+ try {
472
+ const r = await postJson('/api/inbox/dismiss', { id })
473
+ next(id)
474
+ if (r && r.told === false) alertBox(T.inboxDismissNotTold(session))
475
+ } catch (err) { alertBox(err.message) }
476
+ return
477
+ }
478
+ const b = e.target.closest('[data-resolve]')
479
+ if (b) {
480
+ try { await postJson('/api/inbox/resolve', { id: Number(b.dataset.resolve) }); next(Number(b.dataset.resolve)) } catch (err) { alertBox(err.message) }
481
+ }
482
+ })
483
+ // Searching what is done: as it is typed (a moment after), or a team picked.
484
+ let searchSoon = null
485
+ $('inbox').addEventListener('input', e => {
486
+ const f = e.target.closest('[data-answer]')
487
+ if (f) drafts.set(Number(f.dataset.answer), e.target.value)
488
+ if (e.target.id === 'ibxQ') {
489
+ done.q = e.target.value
490
+ clearTimeout(searchSoon)
491
+ searchSoon = setTimeout(() => { done.items = []; done.next = null; done.loaded = false; void loadDone() }, 250)
492
+ }
493
+ })
494
+ $('inbox').addEventListener('change', e => {
495
+ if (e.target.name !== 'team' || !e.target.closest('[data-donefilter]')) return
496
+ done.team = e.target.value
497
+ done.items = []; done.next = null; done.loaded = false
498
+ void loadDone()
499
+ })
500
+ $('inbox').addEventListener('submit', e => {
501
+ if (e.target.closest('[data-donefilter]')) { e.preventDefault(); return }
502
+ const f = e.target.closest('[data-answer]')
503
+ if (!f) return
504
+ e.preventDefault()
505
+ void send(f)
506
+ })
507
+ $('inbox').addEventListener('keydown', e => {
508
+ // Enter with Ctrl or ⌘ sends the answer: from the text, or from an option picked.
509
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
510
+ const f = e.target.name === 'answer' ? e.target.form : e.target.closest('[data-option]') ? $('inbox').querySelector('[data-answer]') : null
511
+ if (f) { e.preventDefault(); f.requestSubmit() }
512
+ }
513
+ // ↑ ↓ move along the list.
514
+ const item = e.target.closest('.ibx-item')
515
+ if (item && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
516
+ e.preventDefault()
517
+ const items = [...$('inbox').querySelectorAll('.ibx-item')].filter(x => x.offsetParent)
518
+ const to = items[items.indexOf(item) + (e.key === 'ArrowDown' ? 1 : -1)]
519
+ // With one open, the next opens too; with the list alone, it only moves.
520
+ if (to) { to.focus(); if (currentRoute().item) replaceHash(to.getAttribute('href')) }
521
+ }
522
+ })
523
+ // Esc closes the one open, back to the list and to its row.
524
+ document.addEventListener('keydown', e => {
525
+ if (e.key !== 'Escape' || $('inbox').hidden || !currentRoute().item) return
526
+ if (!$('palette').hidden || !$('settings').hidden || document.querySelector('.modal-bg')) return
527
+ if (e.target.closest?.('textarea, input') && e.target.value) return
528
+ closeTo(listHash())
529
+ })
530
+ // 1–9 picks an option (without sending it), from anywhere in the inbox but a text field.
531
+ document.addEventListener('keydown', e => {
532
+ if ($('inbox').hidden || !/^[1-9]$/.test(e.key) || e.ctrlKey || e.metaKey || e.altKey) return
533
+ if (e.target.closest?.('input, textarea, select, [contenteditable]') || !$('palette').hidden || !$('settings').hidden || document.querySelector('.modal-bg')) return
534
+ if (pickedAsk() != null) { e.preventDefault(); choose(Number(e.key) - 1, { toggle: false }) }
535
+ })