pisha-server 0.0.0-stage → 0.0.11

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 (125) 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 +1079 -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 +79 -0
  14. package/dashboard/dashboard.js +407 -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 +224 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +54 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3297 -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 +166 -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 +2093 -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 +40 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +103 -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 +141 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +653 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +179 -0
  89. package/ui/people.js +370 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +171 -0
  93. package/ui/routes.js +46 -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 +113 -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/session.js +42 -0
  105. package/ui/shell.css +122 -0
  106. package/ui/signin.js +120 -0
  107. package/ui/squads.js +370 -0
  108. package/ui/state.js +59 -0
  109. package/ui/stream.js +268 -0
  110. package/ui/styles.css +343 -0
  111. package/ui/team.js +115 -0
  112. package/ui/teams.js +58 -0
  113. package/ui/terminal.js +261 -0
  114. package/ui/theme.js +32 -0
  115. package/ui/timeline.js +163 -0
  116. package/ui/topbar.js +205 -0
  117. package/ui/voice-parse.js +98 -0
  118. package/ui/voice.js +320 -0
  119. package/vendor/InterVariable.woff2 +0 -0
  120. package/vendor/LICENSE-inter +92 -0
  121. package/vendor/LICENSE-xterm +21 -0
  122. package/vendor/README.md +8 -0
  123. package/vendor/addon-fit.js +2 -0
  124. package/vendor/xterm.css +218 -0
  125. package/vendor/xterm.js +2 -0
package/ui/team.js ADDED
@@ -0,0 +1,115 @@
1
+ import { $ } from './dom.js'
2
+ import { T, LOCALE } from './i18n.js'
3
+ import { state, sessions, hosts, can, linksOf } from './state.js'
4
+ import { api } from './api.js'
5
+ import { esc, now, ago } from './format.js'
6
+ import { sortedSessions, status, agentMark } from './content.js'
7
+ import { setHtml } from './nav.js'
8
+ import { currentRoute } from './router.js'
9
+ import { permissionsSection } from './permissions.js'
10
+
11
+ // One team: what it is for, what its workers last reported, who is in it and
12
+ // where each runs, the teams it is linked with, and saving it as a template.
13
+
14
+ const titleOf = c => state.squadMeta.get(c)?.title || c
15
+ const REPORT_TAG = { done: 'ok', blocked: 'err', failed: 'err', question: 'warn' }
16
+
17
+ // Its workers' final reports, newest first (asked once per team shown, and
18
+ // again when a new one may have come).
19
+ const reports = new Map() // coordinator -> { at, list }
20
+ async function loadReports(coord) {
21
+ const have = reports.get(coord)
22
+ if (have && now() - have.at < 15_000) return
23
+ reports.set(coord, { at: now(), list: have?.list ?? null })
24
+ try {
25
+ const list = await api(`/api/messages?session=${encodeURIComponent(coord)}&limit=300`)
26
+ reports.set(coord, { at: now(), list: list.filter(m => m.report && m.target === coord).reverse().slice(0, 12) })
27
+ } catch { reports.set(coord, { at: now(), list: [] }) }
28
+ if (currentRoute().view === 'team' && currentRoute().squad === coord) renderTeam()
29
+ }
30
+
31
+ function who(s, extra = '') {
32
+ const st = status(s)
33
+ const role = s.role === 'coordinator' ? 'coord' : 'worker'
34
+ const h = hosts.get(s.host_id)
35
+ return `<li><a href="#/s/${encodeURIComponent(s.name)}" class="tq-member${s.online ? '' : ' offline'}"><span class="role ${role}" aria-hidden="true"></span>${agentMark(s)}<span class="sr-only">${esc(T.roleName[s.role] ?? '')}</span>`
36
+ + `<span class="tq-name">${esc(s.name)}</span><span class="dot ${st.dot || 'off'}" aria-hidden="true"></span><span class="tq-where">${esc(h?.name ?? T.tqNoMachine)}</span>${extra}</a></li>`
37
+ }
38
+
39
+ // The plan its coordinator keeps (update_plan): how far it is, and each task.
40
+ const TASK_DOT = { todo: 'off', doing: 'info', done: 'ok', blocked: 'err', waiting: 'warn' }
41
+ const refLink = ref => {
42
+ let url = null
43
+ try { url = new URL(ref) } catch {}
44
+ return url && (url.protocol === 'https:' || url.protocol === 'http:') ? `<a class="ibx-link" href="${esc(url.href)}" target="_blank" rel="noopener noreferrer">${esc(ref)}</a>` : `<span class="sv-mono">${esc(ref)}</span>`
45
+ }
46
+ export function planMeter(plan, big = false) {
47
+ const n = plan.tasks.length
48
+ const count = s => plan.tasks.filter(t => t.state === s).length
49
+ const parts = ['done', 'doing', 'blocked', 'waiting'].map(s => [s, count(s)]).filter(([, c]) => c)
50
+ const say = T.planSays(count('done'), n, count('doing'), count('blocked'), count('waiting'))
51
+ return `<div class="pl-meter${big ? ' big' : ''}" role="img" aria-label="${esc(say)}">${parts.map(([s, c]) => `<i class="pl-${s}" style="width: ${(c / n * 100).toFixed(2)}%"></i>`).join('')}</div>`
52
+ }
53
+ function planCard(coord) {
54
+ const plan = state.plans.get(coord)
55
+ if (!plan?.tasks.length) return ''
56
+ const count = s => plan.tasks.filter(t => t.state === s).length
57
+ const n = plan.tasks.length
58
+ return `<section class="card tq-card">
59
+ <header class="tq-h"><h2>${esc(plan.title || T.planTitle)}</h2><span class="tq-sub">${esc(T.planBy(coord, ago(plan.updated_at)))}</span></header>
60
+ <div class="tq-body pl-sum">${planMeter(plan, true)}<div class="pl-legend">${[['done', T.planDone(count('done'), n)], ['doing', T.planDoing(count('doing'))], ['blocked', T.planBlocked(count('blocked'))], ['waiting', T.planWaiting(count('waiting'))]].filter(([s]) => count(s)).map(([s, l]) => `<span><i class="pl-key pl-${s}" aria-hidden="true"></i>${esc(l)}</span>`).join('')}</div></div>
61
+ <div class="mc-scroll"><table class="pl-table"><thead><tr><th scope="col">${esc(T.planTask)}</th><th scope="col">${esc(T.planWho)}</th><th scope="col">${esc(T.mcState)}</th><th scope="col">${esc(T.ibxRef)}</th></tr></thead><tbody>
62
+ ${plan.tasks.map(t => `<tr class="pl-row-${t.state}"><td><span class="pl-t">${esc(t.title)}</span>${t.note ? `<span class="pl-note">${esc(t.note)}</span>` : ''}</td>
63
+ <td>${t.who ? `<a class="pl-who" href="#/s/${encodeURIComponent(t.who)}"><span class="role ${sessions.get(t.who)?.role === 'coordinator' ? 'coord' : 'worker'}" aria-hidden="true"></span>${agentMark(t.who)}${esc(t.who)}</a>` : `<span class="tq-quiet0">${esc(T.planNobody)}</span>`}</td>
64
+ <td><span class="mc-state"><span class="dot ${TASK_DOT[t.state]}${t.state === 'doing' ? ' pulse' : ''}" aria-hidden="true"></span>${esc(T.planState[t.state])}</span></td>
65
+ <td>${t.ref ? refLink(t.ref) : ''}</td></tr>`).join('')}
66
+ </tbody></table></div>
67
+ <footer class="pl-foot">${esc(T.planWhose)}</footer>
68
+ </section>`
69
+ }
70
+
71
+ export function renderTeam() {
72
+ const r = currentRoute()
73
+ const coord = sessions.get(r.squad)
74
+ if (!coord) { setHtml($('team'), `<div class="empty"><b>${esc(T.tqGone(r.squad))}</b><a class="btn" href="#/teams">${esc(T.teams)}</a></div>`); return }
75
+ const meta = state.squadMeta.get(coord.name) ?? {}
76
+ const workers = sortedSessions().filter(s => s.role !== 'coordinator' && s.coordinator === coord.name)
77
+ const linked = linksOf(coord.name)
78
+ void loadReports(coord.name)
79
+ const rep = reports.get(coord.name)?.list
80
+ const repHtml = rep == null ? `<p class="tq-quiet">${esc(T.loading)}</p>`
81
+ : rep.length ? `<ul class="tq-reports">${rep.map(m => `<li><a href="#/s/${encodeURIComponent(m.from)}" class="tq-report"><span class="tag ${REPORT_TAG[m.report] ?? ''}">${esc(T.reportWord[m.report] ?? m.report)}</span><span class="role worker" aria-hidden="true"></span><span class="tq-name">${esc(m.from)}</span><span class="tq-text">${esc((m.text ?? '').replace(/\s+/g, ' '))}</span><span class="tq-when">${esc(ago(m.created_at))}</span></a></li>`).join('')}</ul>`
82
+ : `<p class="tq-quiet">${esc(T.tqNoReports)}</p>`
83
+ setHtml($('team'), `<div class="tq">
84
+ <div class="tq-main">
85
+ ${planCard(coord.name)}
86
+ <section class="card tq-card">
87
+ <header class="tq-h"><h2>${esc(T.tqGoal)}</h2>${can('manager') ? `<button type="button" class="btn quiet" data-describe>${esc(T.tqEdit)}</button>` : ''}</header>
88
+ <div class="tq-body">${meta.goal ? `<p class="tq-goal">${esc(meta.goal)}</p>` : `<p class="tq-quiet">${esc(T.tmNoGoal)}</p>`}</div>
89
+ </section>
90
+ <section class="card tq-card">
91
+ <header class="tq-h"><h2>${esc(T.tqReports)}</h2><span class="tq-sub">${esc(T.tqReportsHint)}</span></header>
92
+ ${repHtml}
93
+ </section>
94
+ </div>
95
+ <aside class="tq-aside" aria-label="${esc(T.tqTeam)}">
96
+ <section><h3 class="tq-label">${esc(T.tqWho)}</h3><ul class="tq-members">${who(coord)}${workers.map(w => who(w)).join('')}</ul>${workers.length ? '' : `<p class="tq-quiet">${esc(T.noWorkers)}</p>`}</section>
97
+ <section><h3 class="tq-label">${esc(T.tqLinks)}</h3><p class="tq-small">${linked.length ? esc(T.tqLinkedTo(linked.map(titleOf).join(', '))) : esc(T.tqNoLinks)}</p>${can('manager') ? `<button type="button" class="btn quiet tq-act" data-links="${esc(coord.name)}">${esc(T.tqManageLinks)}</button>` : ''}</section>
98
+ ${permissionsSection({ coordinator: coord.name })}
99
+ ${can('manager') ? `<section><h3 class="tq-label">${esc(T.tqTemplate)}</h3><p class="tq-small">${esc(T.tqTemplateHint)}</p><button type="button" class="btn tq-act" data-savetpl="${esc(coord.name)}">${esc(T.tqSaveTemplate)}</button></section>` : ''}
100
+ </aside>
101
+ </div>`)
102
+ $('topSub').textContent = workers.length ? T.squadCount(workers.filter(w => w.online).length, workers.length) : T.noWorkers
103
+ }
104
+ export const refreshTeam = () => { if (currentRoute().view === 'team' && !$('team').hidden) renderTeam() }
105
+ // A new report from a worker: the list is asked for again.
106
+ export function noteReport(m) { if (m?.report && m.target) reports.delete(m.target) }
107
+
108
+ $('team').addEventListener('click', async e => {
109
+ const name = currentRoute().squad
110
+ if (e.target.closest('[data-describe]')) return (await import('./org.js')).squadDialog(name)
111
+ const l = e.target.closest('[data-links]')
112
+ if (l) return (await import('./org.js')).linksDialog(l.dataset.links)
113
+ const t = e.target.closest('[data-savetpl]')
114
+ if (t) return (await import('./squads.js')).saveTemplateDialog(t.dataset.savetpl)
115
+ })
package/ui/teams.js ADDED
@@ -0,0 +1,58 @@
1
+ import { $ } from './dom.js'
2
+ import { T } from './i18n.js'
3
+ import { state, can, linksOf, unread } from './state.js'
4
+ import { esc } from './format.js'
5
+ import { sortedSessions, status, squadsOf, agentMark } from './content.js'
6
+ import { setHtml } from './nav.js'
7
+ import { currentRoute } from './router.js'
8
+ import { personaTag } from './topbar.js'
9
+ import { planMeter } from './team.js'
10
+
11
+ // Teams: one card per team, its coordinator and its workers, what each is
12
+ // doing, and what the team is for. Sessions outside every team after them.
13
+
14
+ const titleOf = c => state.squadMeta.get(c)?.title || c
15
+
16
+ function person(s, sub) {
17
+ const st = status(s)
18
+ const role = s.role === 'coordinator' ? 'coord' : s.role === 'solo' ? 'solo' : 'worker'
19
+ const n = unread.get(s.name) ?? 0
20
+ const attention = st.waiting ? `<span class="badge attn" aria-hidden="true">!</span><span class="sr-only">${esc(T.waitingOnYou)}</span>` : n ? `<span class="badge" aria-hidden="true">${n > 99 ? '99+' : n}</span><span class="sr-only">${esc(T.unreadN(n))}</span>` : ''
21
+ return `<li><a href="#/s/${encodeURIComponent(s.name)}" class="tm-person${sub ? ' sub' : ''}${s.online ? '' : ' offline'}">
22
+ <span class="role ${role}" aria-hidden="true"></span>${agentMark(s)}<span class="sr-only">${esc(T.roleName[s.role] ?? T.roleName.worker)}</span>
23
+ <span class="tm-who">${esc(s.name)}</span><span class="dot ${st.dot || 'off'}" aria-hidden="true"></span>${personaTag(s.persona)}
24
+ <span class="tm-what">${esc(st.text)}</span>${attention}</a></li>`
25
+ }
26
+
27
+ function card({ coord, workers }) {
28
+ const meta = state.squadMeta.get(coord.name)
29
+ const plan = state.plans.get(coord.name)
30
+ const linked = linksOf(coord.name).map(titleOf)
31
+ const on = workers.filter(w => w.online).length
32
+ return `<section class="card tm-card" aria-labelledby="tm-${esc(coord.name)}">
33
+ <header class="tm-h"><h2 id="tm-${esc(coord.name)}"><a href="#/q/${encodeURIComponent(coord.name)}">${esc(titleOf(coord.name))}</a></h2>
34
+ <span class="tm-sub">${esc([workers.length ? T.squadCount(on, workers.length) : T.noWorkers, linked.length ? T.linkedWith(linked.join(', ')) : ''].filter(Boolean).join(' · '))}</span></header>
35
+ <ul class="tm-people">${person(coord, false)}${workers.map(w => person(w, true)).join('')}</ul>
36
+ <footer class="tm-foot">${plan?.tasks.length ? `<div class="tm-plan"><span class="tm-goal">${esc(plan.title || meta?.goal || T.planTitle)}</span><span class="tm-none">${esc(T.ofTotal(plan.tasks.filter(t => t.state === 'done').length, plan.tasks.length))}</span></div>${planMeter(plan)}` : meta?.goal ? `<span class="tm-goal">${esc(meta.goal)}</span>` : `<span class="tm-none">${esc(T.tmNoGoal)}</span>`}</footer>
37
+ </section>`
38
+ }
39
+
40
+ function loose(title, list) {
41
+ return `<section class="card tm-card"><header class="tm-h"><h2>${esc(title)}</h2><span class="tm-sub">${esc(T.tmSessions(list.length))}</span></header>
42
+ <ul class="tm-people">${list.map(s => person(s, false)).join('')}</ul></section>`
43
+ }
44
+
45
+ export function renderTeams() {
46
+ const list = sortedSessions()
47
+ const { squads, orphans, solos } = squadsOf(list)
48
+ const cards = [...squads.map(card), ...(orphans.length ? [loose(squads.length ? T.noCoordinator : T.workers, orphans)] : []), ...(solos.length ? [loose(T.standalone, solos)] : [])]
49
+ setHtml($('teams'), cards.length
50
+ ? `<div class="tm-grid">${cards.join('')}</div>`
51
+ : `<div class="empty"><b>${esc(T.noTeams)}</b><span>${esc(T.tmEmptyHint)}</span>${can('operator') ? '<button type="button" class="btn primary" data-newteam>' + esc(T.newTeam) + '</button>' : ''}</div>`)
52
+ $('topSub').textContent = T.tmCount(squads.length, list.length)
53
+ }
54
+ export const refreshTeams = () => { if (currentRoute().view === 'teams' && !$('teams').hidden) renderTeams() }
55
+
56
+ $('teams').addEventListener('click', async e => {
57
+ if (e.target.closest('[data-newteam]')) location.hash = '#/new'
58
+ })
package/ui/terminal.js ADDED
@@ -0,0 +1,261 @@
1
+ import { T } from './i18n.js'
2
+ import { state, hosts, hostListeners } from './state.js'
3
+ import { esc } from './format.js'
4
+ import { navigatedInApp, mosaicPanes } from './router.js'
5
+ import { postJson } from './machines.js'
6
+
7
+ // web terminal: xterm.js (loaded on first use) over one WebSocket per tab
8
+ let xtermReady = null
9
+ function loadXterm() {
10
+ if (xtermReady) return xtermReady
11
+ // Served by pisha-server itself (vendor/): no third-party scripts.
12
+ const css = document.createElement('link')
13
+ css.rel = 'stylesheet'
14
+ css.href = '/vendor/xterm.css'
15
+ document.head.appendChild(css)
16
+ const script = src => new Promise((res, rej) => { const s = document.createElement('script'); s.src = src; s.onload = res; s.onerror = rej; document.head.appendChild(s) })
17
+ xtermReady = script('/vendor/xterm.js').then(() => script('/vendor/addon-fit.js'))
18
+ xtermReady.catch(() => { xtermReady = null })
19
+ return xtermReady
20
+ }
21
+
22
+ const b64bytes = b => Uint8Array.from(atob(b), c => c.charCodeAt(0))
23
+
24
+ export const termLink = {
25
+ ws: null, ready: false, views: new Set(), backoff: 1000, timer: null,
26
+ retry() {
27
+ for (const v of this.views) v.overlay(T.termLinkDown)
28
+ if (this.views.size) { clearTimeout(this.timer); this.timer = setTimeout(() => this.ensure(), this.backoff); this.backoff = Math.min(this.backoff * 2, 15000) }
29
+ },
30
+ ensure() {
31
+ if (this.ws || this.connecting || !state.me || state.role === 'observer') return
32
+ // A one-time ticket, in this user's name:
33
+ // the server only accepts the socket with it.
34
+ this.connecting = true
35
+ postJson('/api/terminal/ticket', {}).then(({ ticket }) => {
36
+ this.connecting = false
37
+ if (!this.ws && this.views.size) this.open(ticket)
38
+ }, () => { this.connecting = false; if (state.me) this.retry() })
39
+ },
40
+ open(ticket) {
41
+ const ws = this.ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/api/terminal`, ['pisha', `auth.${ticket}`])
42
+ ws.onmessage = ev => {
43
+ let m
44
+ try { m = JSON.parse(ev.data) } catch { return }
45
+ if (m.t === 'ready') { this.ready = true; this.backoff = 1000; for (const v of this.views) v.attach(); return }
46
+ for (const v of this.views) if (v.host === m.host && v.term === m.term) v.onMessage(m)
47
+ }
48
+ ws.onclose = ev => {
49
+ if (this.ws !== ws) return
50
+ this.ws = null
51
+ this.ready = false
52
+ this.retry()
53
+ }
54
+ },
55
+ send(m) { if (this.ready && this.ws?.readyState === 1) this.ws.send(JSON.stringify(m)) },
56
+ add(v) { this.views.add(v); this.ensure(); if (this.ready) v.attach() },
57
+ remove(v) { this.send({ t: 'detach', host: v.host, term: v.term }); this.views.delete(v) },
58
+ close() { clearTimeout(this.timer); const ws = this.ws; this.ws = null; this.ready = false; this.views.clear(); ws?.close() },
59
+ }
60
+ export class TermView {
61
+ // compact: a pane of a mosaic (no long hint underneath, never focused by
62
+ // itself); root gets "term-focused" while typing goes to this terminal.
63
+ constructor(host, term, root, { compact = false } = {}) {
64
+ this.host = host
65
+ this.term = term
66
+ this.dead = false
67
+ this.compact = compact
68
+ this.root = root
69
+ root.innerHTML = `<div class="term-box"><div class="term-over">${T.termLoading}</div></div><div class="term-foot"></div>`
70
+ this.box = root.querySelector('.term-box')
71
+ this.over = root.querySelector('.term-over')
72
+ this.foot = root.querySelector('.term-foot')
73
+ this.renderFoot()
74
+ loadXterm().then(() => { if (!this.dead) this.start() }, () => this.overlay(T.termLoadFailed))
75
+ }
76
+
77
+ renderFoot() {
78
+ const h = hosts.get(this.host)
79
+ const ro = h?.info?.allow_input === false
80
+ // (Codex CLI and Grok CLI: no channels prompt, no image paste.)
81
+ const agent = (h?.info?.terminals ?? []).find(x => x?.id === this.term)?.agent
82
+ this.foot.innerHTML = (ro ? `<span class="ro">${T.readOnly}</span><span>${esc(T.typingOff)}</span>` : this.compact ? '' : `<span>${esc(agent && agent !== 'claude' ? T.termHintTyped(h?.name ?? this.host, T.agentName[agent] ?? agent) : T.termHint(h?.name ?? this.host))}</span>`) +
83
+ (this.notice ? `<span class="ro">${T.machineSays}: ${esc(this.notice)}</span>` : '')
84
+ }
85
+
86
+ // A pasted image, at most the size Claude uses (1568 px on its long side)
87
+ // and small enough to send: PNG, or WebP/JPEG, smaller if needed.
88
+ async pasteImage(file) {
89
+ if (hosts.get(this.host)?.info?.allow_input === false) return this.toast(T.typingOff)
90
+ try {
91
+ const bmp = await createImageBitmap(file)
92
+ let scale = Math.min(1, 1568 / Math.max(bmp.width, bmp.height))
93
+ let data = null, type = null
94
+ for (let i = 0; i < 6 && !data; i++, scale *= 0.75) {
95
+ const c = document.createElement('canvas')
96
+ c.width = Math.max(1, Math.round(bmp.width * scale)); c.height = Math.max(1, Math.round(bmp.height * scale))
97
+ c.getContext('2d').drawImage(bmp, 0, 0, c.width, c.height)
98
+ for (const [t, q] of [['image/png'], ['image/webp', 0.9], ['image/jpeg', 0.85]]) {
99
+ const blob = await new Promise(r => c.toBlob(r, t, q))
100
+ if (!blob || blob.type !== t || blob.size > 580_000) continue
101
+ const url = await new Promise((res, rej) => { const fr = new FileReader(); fr.onload = () => res(String(fr.result)); fr.onerror = rej; fr.readAsDataURL(blob) })
102
+ data = url.slice(url.indexOf(',') + 1); type = t
103
+ break
104
+ }
105
+ }
106
+ bmp.close?.()
107
+ if (!data) throw new Error('too large')
108
+ termLink.send({ t: 'image', host: this.host, term: this.term, type, data })
109
+ this.toast(T.imageSent)
110
+ this.x.focus()
111
+ } catch { this.toast(T.imageFailed) }
112
+ }
113
+
114
+ // A short note over the terminal ("Copied").
115
+ toast(text) {
116
+ this.box.querySelector('.term-toast')?.remove()
117
+ const t = document.createElement('div')
118
+ t.className = 'term-toast'
119
+ t.textContent = text
120
+ this.box.appendChild(t)
121
+ setTimeout(() => t.remove(), 1200)
122
+ }
123
+
124
+ start() {
125
+ const dark = { background: '#161513', foreground: '#ecebe7', cursor: '#e0855f', selectionBackground: '#4a4740' }
126
+ this.x = new window.Terminal({
127
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', fontSize: 13.5, cursorBlink: true, scrollback: 5000, theme: dark, allowProposedApi: false,
128
+ // (On macOS, Option+drag selects even when the program uses the mouse;
129
+ // Shift+drag does everywhere.)
130
+ macOptionClickForcesSelection: true,
131
+ // Links printed by the program (OSC 8): only http(s), after a confirmation, in a new tab.
132
+ // Only plain http(s) links, shown as they are (no user:password@, no
133
+ // control or direction characters that could make it read otherwise).
134
+ linkHandler: { activate: (e, uri) => {
135
+ let u
136
+ try { u = new URL(uri) } catch { return }
137
+ if (!/^https?:$/.test(u.protocol) || u.username || u.password || /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/.test(uri)) return
138
+ if (confirm(`${T.openLink}\n${u.href}`)) window.open(u.href, '_blank', 'noopener,noreferrer')
139
+ } },
140
+ })
141
+ this.fit = new window.FitAddon.FitAddon()
142
+ this.x.loadAddon(this.fit)
143
+ this.x.open(this.box)
144
+ this.fitNow()
145
+ // Copying, as in usual terminals: what is selected is copied by itself;
146
+ // Ctrl+Shift+C (Cmd+C on macOS) copies too, and so does Ctrl+C while
147
+ // something is selected (without a selection it still goes to Claude).
148
+ const copy = async () => {
149
+ const text = this.x.getSelection()
150
+ if (!text) return false
151
+ try { await navigator.clipboard.writeText(text) } catch {
152
+ const ta = document.createElement('textarea')
153
+ ta.value = text
154
+ ta.style.cssText = 'position:fixed;opacity:0;top:0;left:0'
155
+ document.body.appendChild(ta)
156
+ ta.select()
157
+ try { document.execCommand('copy') } catch {}
158
+ ta.remove()
159
+ this.x.focus()
160
+ }
161
+ this.toast(T.copied)
162
+ return true
163
+ }
164
+ let selTimer = null
165
+ this.x.onSelectionChange(() => {
166
+ clearTimeout(selTimer)
167
+ if (this.x.hasSelection()) selTimer = setTimeout(() => { void copy() }, 250)
168
+ })
169
+ this.x.attachCustomKeyEventHandler(e => {
170
+ // Ctrl+V pastes (text or an image) instead of sending ^V to Claude,
171
+ // whose own image paste reads the machine's clipboard, not this one.
172
+ if (e.type === 'keydown' && e.code === 'KeyV' && e.ctrlKey && !e.altKey && !e.metaKey) return false
173
+ if (e.type !== 'keydown' || e.code !== 'KeyC' || !this.x.hasSelection()) return true
174
+ if ((e.ctrlKey && !e.altKey) || (e.metaKey && !e.ctrlKey)) {
175
+ e.preventDefault()
176
+ void copy().then(() => this.x.clearSelection())
177
+ return false
178
+ }
179
+ return true
180
+ })
181
+ // What xterm.js answers by itself to a program's queries (device
182
+ // attributes, cursor position, modes, focus) isn't sent: tmux already
183
+ // answers them, and every dashboard watching would type them in again.
184
+ // (Unless a key was just pressed: Shift+F3 also looks like a report.)
185
+ let keyAt = 0
186
+ this.box.addEventListener('keydown', () => { keyAt = performance.now() }, true)
187
+ const REPORT = /^(?:\x1b\[[?>=]?[\d;]*c|\x1b\[\??\d+;\d+R|\x1b\[\??[\d;]*\$y|\x1bP[01]\$r[^\x1b]*\x1b\\|\x1b\[[IO]|\x1b\[[\d;]*t|\x1b\][\d;]*rgb:[^\x07\x1b]*(?:\x07|\x1b\\))+$/
188
+ this.x.onData(data => {
189
+ if (hosts.get(this.host)?.info?.allow_input === false) return
190
+ if (REPORT.test(data) && performance.now() - keyAt > 100) return
191
+ termLink.send({ t: 'in', host: this.host, term: this.term, data })
192
+ })
193
+ // Pasted text can't carry escape sequences (they could end bracketed
194
+ // paste and run what follows): control and bidi characters are dropped.
195
+ this.box.addEventListener('paste', e => {
196
+ // An image (a screenshot): sent to the machine, which hands it to
197
+ // Claude Code. (Claude Code can't read this browser's clipboard.)
198
+ const text = e.clipboardData?.getData('text') ?? ''
199
+ const image = text ? null : [...(e.clipboardData?.items ?? [])].find(i => i.kind === 'file' && /^image\//.test(i.type))?.getAsFile()
200
+ if (image) { e.preventDefault(); e.stopPropagation(); void this.pasteImage(image); return }
201
+ const clean = text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u00ad\u034f\u061c\u180e\u200b-\u200f\u2028\u2029\u202a-\u202e\u2060-\u2064\u2066-\u2069\u115f\u1160\u17b4\u17b5\u2065\u2800\u3164\uffa0\ufeff\ufff9-\ufffb\u{1d173}-\u{1d17a}\u{e0000}-\u{e007f}\u180b-\u180f\ufe00-\ufe0f\u{e0100}-\u{e01ef}\p{Cf}]/gu, '')
202
+ if (clean !== text) { e.preventDefault(); e.stopPropagation(); this.x.paste(clean) }
203
+ }, true)
204
+ let resizeTimer = null
205
+ this.x.onResize(({ cols, rows }) => {
206
+ clearTimeout(resizeTimer)
207
+ resizeTimer = setTimeout(() => termLink.send({ t: 'resize', host: this.host, term: this.term, cols, rows }), 150)
208
+ })
209
+ this.ro = new ResizeObserver(() => this.fitNow())
210
+ this.ro.observe(this.box)
211
+ // Not when the page was opened straight on this terminal (e.g. from a
212
+ // link): typing goes to a machine only after the user chose it here.
213
+ // (Nor a mosaic's pane: there it is clicked first.)
214
+ if (navigatedInApp && !this.compact) this.x.focus()
215
+ this.x.textarea?.addEventListener('focus', () => this.root.classList.add('term-focused'))
216
+ this.x.textarea?.addEventListener('blur', () => this.root.classList.remove('term-focused'))
217
+ termLink.add(this)
218
+ }
219
+
220
+ fitNow() { try { this.fit?.fit() } catch {} }
221
+
222
+ attach() {
223
+ if (!this.x) return
224
+ this.overlay(null)
225
+ termLink.send({ t: 'attach', host: this.host, term: this.term, cols: this.x.cols, rows: this.x.rows })
226
+ }
227
+
228
+ refresh() { termLink.send({ t: 'refresh', host: this.host, term: this.term }) }
229
+
230
+ overlay(text) {
231
+ this.over.hidden = !text
232
+ if (text) this.over.textContent = text
233
+ }
234
+
235
+ onMessage(m) {
236
+ if (m.t === 'screen') { this.x.reset(); this.x.write(b64bytes(m.data)); this.overlay(null); return }
237
+ if (m.t === 'out') { this.x.write(b64bytes(m.data)); return }
238
+ if (m.t === 'exit') return this.overlay(T.termEnded)
239
+ if (m.t === 'host_down') return this.overlay(T.termHostDown)
240
+ // What the machine says goes next to the footer, never in place of it:
241
+ // the read-only state shown always comes from the machine's settings.
242
+ if (m.t === 'notice') { this.notice = String(m.text ?? '').slice(0, 300); this.renderFoot() }
243
+ }
244
+
245
+ destroy() {
246
+ this.dead = true
247
+ this.ro?.disconnect()
248
+ if (this.x) termLink.remove(this)
249
+ this.x?.dispose()
250
+ }
251
+ }
252
+
253
+ // A machine that comes back: re-attach the terminal on screen.
254
+ hostListeners.add(h => {
255
+ const terms = [state.termView, ...[...mosaicPanes.values()].filter(p => p.kind === 'term').map(p => p.view)]
256
+ for (const v of terms) {
257
+ if (!v || v.host !== h.id) continue
258
+ v.renderFoot()
259
+ if (h.online && !v.over.hidden && v.over.textContent === T.termHostDown) v.attach()
260
+ }
261
+ })
package/ui/theme.js ADDED
@@ -0,0 +1,32 @@
1
+ import { store } from './dom.js'
2
+
3
+ // Light or dark: the system's, unless chosen here (remembered per browser).
4
+ // The page sets it first thing, so it doesn't flash.
5
+ const darkQuery = window.matchMedia?.('(prefers-color-scheme: dark)') ?? { matches: false, addEventListener() {} }
6
+ const listeners = new Set()
7
+
8
+ // What was chosen: 'system', 'light' or 'dark'.
9
+ export const themeChoice = () => document.documentElement.dataset.theme || 'system'
10
+ // What is on screen now.
11
+ export const themeNow = () => document.documentElement.dataset.theme || (darkQuery.matches ? 'dark' : 'light')
12
+
13
+ export function setTheme(choice) {
14
+ if (choice === 'light' || choice === 'dark') { document.documentElement.dataset.theme = choice; store.set('pishaTheme', choice) }
15
+ else { delete document.documentElement.dataset.theme; store.del('pishaTheme') }
16
+ for (const f of listeners) f()
17
+ }
18
+ export const toggleTheme = () => setTheme(themeNow() === 'dark' ? 'light' : 'dark')
19
+ export const onTheme = f => { listeners.add(f); return () => listeners.delete(f) }
20
+ darkQuery.addEventListener('change', () => { for (const f of listeners) f() })
21
+
22
+ // The colour of the phone's bar, installed as an app: the theme on screen,
23
+ // also when it was chosen here rather than by the system.
24
+ function themeBar() {
25
+ const now = themeNow()
26
+ for (const m of document.querySelectorAll('meta[name="theme-color"]')) {
27
+ if (document.documentElement.dataset.theme) m.setAttribute('media', /dark/.test(m.dataset.was ??= m.getAttribute('media') ?? '') === (now === 'dark') ? 'all' : 'not all')
28
+ else if (m.dataset.was != null) m.setAttribute('media', m.dataset.was)
29
+ }
30
+ }
31
+ onTheme(themeBar)
32
+ themeBar()
package/ui/timeline.js ADDED
@@ -0,0 +1,163 @@
1
+ import { T, LOCALE } from './i18n.js'
2
+ import { state, sessions, hosts, companyPref } from './state.js'
3
+ import { store } from './dom.js'
4
+ import { esc, hhmm } from './format.js'
5
+ import { api } from './api.js'
6
+ import { status } from './content.js'
7
+ import { planMeter } from './team.js'
8
+ import { TEST_RE, COMMIT_RE, PUSH_RE } from './doing.js'
9
+
10
+ // Beside a session's terminal: what it is doing now, and what mattered so far.
11
+ // Nothing is asked of the model: it is read from what the session already
12
+ // reports (its events and messages), and from the inbox and the plan. What
13
+ // isn't recognised isn't shown, and nothing is made up.
14
+
15
+ export const timelines = new Set()
16
+
17
+ // Commands that say what they did: tests, a commit, a push (doing.js).
18
+ const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
19
+ const firstLine = (s, n = 140) => { const l = String(s ?? '').trim().split('\n')[0]; return l.length > n ? `${l.slice(0, n - 1)}…` : l }
20
+ const commitMsg = cmd => /-m\s+(["'])(.+?)\1/.exec(cmd)?.[2] ?? /-m\s+(\S+)/.exec(cmd)?.[1] ?? ''
21
+ const passed = text => /(\d+)\s+(?:tests?\s+)?(?:passed|passing)\b/i.exec(text ?? '')?.[1]
22
+ const fileOf = summary => String(summary ?? '').replace(/\s+\([^)]*\)$/, '').replace(/\s+\+\d+\s+[−-]\d+$/, '')
23
+
24
+ // What mattered, oldest first, from the session's history.
25
+ function milestones(name, items) {
26
+ const s = sessions.get(name)
27
+ const out = []
28
+ const add = (ts, kind, tone, title, detail = '', full = '') => out.push({ ts, kind, tone, title, detail, full: full || detail })
29
+ const starts = new Map() // tool use id -> its start
30
+ let edits = null // the files edited in this turn, and when the last one was
31
+ let editedAt = 0
32
+ const flush = () => { if (edits?.size) add(editedAt, 'edits', 'muted', T.tlEdits(edits.size), [...edits].slice(0, 3).join(', ') + (edits.size > 3 ? '…' : ''), [...edits].join('\n')); edits = null }
33
+ for (const it of items) {
34
+ if (it.t === 'event') {
35
+ if (it.agent) continue // a subagent's own steps: its Task is the main session's
36
+ switch (it.kind) {
37
+ case 'session_start': if (it.source === 'clear') add(it.ts, 'start', 'muted', T.tlCleared); else if (it.source !== 'compact') add(it.ts, 'start', 'muted', T.tlStart); break
38
+ case 'prompt':
39
+ flush()
40
+ if (it.channel || !it.text) break // a channel message: shown as the message itself
41
+ if (/^\s*Inbox #\d+/.test(it.text)) add(it.ts, 'answer', 'ok', T.tlInboxAnswer, firstLine(it.text.replace(/^\s*Inbox #\d+\s*(\("[^"]*"\))?,?\s*/, '').replace(/\s*\[They are not following[\s\S]*$/, '')))
42
+ else add(it.ts, 'order', 'info', T.tlTyped, firstLine(it.text))
43
+ break
44
+ case 'tool_start':
45
+ starts.set(it.ref, it)
46
+ if (EDIT_TOOLS.has(it.tool) && it.summary) { (edits ??= new Set()).add(fileOf(it.summary)); editedAt = it.ts }
47
+ break
48
+ case 'tool_end': {
49
+ const start = starts.get(it.ref)
50
+ const cmd = it.tool === 'Bash' ? start?.summary ?? '' : ''
51
+ if (cmd && TEST_RE.test(cmd)) {
52
+ const n = passed(it.detail)
53
+ add(it.ts, 'tests', it.ok === false ? 'err' : 'ok', it.ok === false ? T.tlTestsFailed : T.tlTestsPassed, n && it.ok !== false ? T.tlPassedN(n) : firstLine(cmd, 80), cmd)
54
+ } else if (cmd && COMMIT_RE.test(cmd) && it.ok !== false) add(it.ts, 'commit', 'ok', T.tlCommit, commitMsg(cmd), cmd)
55
+ else if (cmd && PUSH_RE.test(cmd) && it.ok !== false) add(it.ts, 'push', 'ok', T.tlPush, firstLine(cmd, 80))
56
+ else if (/update_plan$/.test(it.tool ?? '') && it.ok !== false) add(it.ts, 'plan', 'info', T.tlPlan)
57
+ break
58
+ }
59
+ case 'notification': if (it.type === 'permission_prompt') add(it.ts, 'perm', 'warn', T.tlPerm, firstLine(it.text)); break
60
+ case 'stop': flush(); break
61
+ case 'compacted': add(it.ts, 'compact', 'muted', T.tlCompact); break
62
+ case 'session_end': flush(); add(it.ts, 'end', 'muted', T.tlEnd); break
63
+ }
64
+ } else if (it.t === 'message' && !it.system) {
65
+ // Its coordinator's orders, its own reports, and (a coordinator) its workers'.
66
+ const tone = it.report === 'done' ? 'ok' : it.report === 'question' ? 'warn' : 'err'
67
+ if (it.target === name && s?.coordinator && it.from === s.coordinator && !it.fyi) add(it.ts, 'order', 'info', T.tlOrder(it.from), firstLine(it.text))
68
+ else if (it.from === name && it.report) add(it.ts, 'report', tone, T.tlReport[it.report] ?? it.report, firstLine(it.text))
69
+ else if (it.target === name && it.report && sessions.get(it.from)?.coordinator === name) add(it.ts, 'report', tone, T.tlReportFrom(it.from, it.report), firstLine(it.text))
70
+ }
71
+ }
72
+ flush()
73
+ // What it left in the inbox, and what became of it.
74
+ for (const i of state.inbox.filter(x => x.session === name)) {
75
+ add(i.created_at, 'inbox', i.kind === 'ask' ? 'warn' : 'info', i.kind === 'ask' ? T.tlAsked : T.tlTold, firstLine(i.text))
76
+ if (i.resolved_at && i.answer != null) add(i.resolved_at, 'answer', 'ok', T.tlAnswered, firstLine(i.answer))
77
+ else if (i.resolved_at && i.dismissed_by) add(i.resolved_at, 'dismiss', 'err', T.tlDismissed, firstLine(i.text))
78
+ }
79
+ return out.sort((a, b) => b.ts - a.ts)
80
+ }
81
+
82
+ const day = ts => new Date(ts).toLocaleDateString(LOCALE, { weekday: 'long', day: 'numeric', month: 'long' })
83
+
84
+ export class Timeline {
85
+ // now: false leaves out what it is doing now (beside its conversation,
86
+ // the team and the details already say it).
87
+ constructor(name, box, { now = true } = {}) {
88
+ this.name = name
89
+ this.box = box
90
+ this.showNow = now
91
+ this.items = []
92
+ this.loaded = false
93
+ this.timer = null
94
+ timelines.add(this)
95
+ this.render()
96
+ this.load()
97
+ }
98
+ async load() {
99
+ try {
100
+ const r = await api(`/api/timeline?session=${encodeURIComponent(this.name)}&limit=500`)
101
+ if (!timelines.has(this)) return
102
+ this.items = r.items
103
+ } catch { /* shown as nothing yet */ }
104
+ this.loaded = true
105
+ this.render()
106
+ }
107
+ // Something new from the server: kept if it is this session's.
108
+ live(it) {
109
+ if (!this.loaded) return
110
+ const mine = it.t === 'event' ? it.session === this.name : it.from === this.name || it.target === this.name
111
+ if (!mine || (it.t === 'event' && it.kind === 'usage')) return
112
+ this.items.push(it)
113
+ if (this.items.length > 2000) this.items.splice(0, this.items.length - 2000)
114
+ this.soon()
115
+ }
116
+ soon() { clearTimeout(this.timer); this.timer = setTimeout(() => this.render(), 250) }
117
+ destroy() { clearTimeout(this.timer); timelines.delete(this) }
118
+
119
+ render() {
120
+ const s = sessions.get(this.name)
121
+ if (!s) { this.box.innerHTML = ''; return }
122
+ const st = status(s)
123
+ const a = s.activity ?? {}
124
+ const team = s.role === 'coordinator' ? s.name : s.coordinator
125
+ const plan = team ? state.plans.get(team) : null
126
+ const task = plan?.tasks.find(t => t.who === this.name && t.state === 'doing') ?? plan?.tasks.find(t => t.who === this.name && (t.state === 'blocked' || t.state === 'waiting'))
127
+ const h = hosts.get(s.host_id)
128
+ const pct = a.context_pct
129
+ const now = `<section class="tl-now"><h2 class="tq-label">${esc(T.tlNow)}</h2>
130
+ <p class="tl-state"><span class="dot ${st.dot || 'off'}" aria-hidden="true"></span><span${st.title ? ` title="${esc(st.title)}"` : ''}>${esc(st.text)}</span></p>
131
+ ${pct != null ? `<div class="tl-ctx" title="${esc(T.contextPct(pct))}"><span>${esc(T.svContext)}</span><span class="tl-bar"><i style="width:${pct}%"${pct >= 80 ? ' class="hot"' : ''}></i></span><span>${pct} %</span></div>` : ''}
132
+ ${s.role === 'coordinator' && plan?.tasks.length ? `<div class="tl-plan">${planMeter(plan)}<span>${esc(T.planDone(plan.tasks.filter(t => t.state === 'done').length, plan.tasks.length))}</span></div>` : ''}
133
+ ${task ? `<p class="tl-task"><span class="tq-label">${esc(T.tlTask)}</span>${esc(task.title)}</p>` : ''}
134
+ <dl class="tl-facts">${h ? `<dt>${esc(T.svMachine)}</dt><dd>${esc(h.name)}</dd>` : ''}${a.cwd ? `<dt>${esc(T.svFolder)}</dt><dd class="sv-mono" title="${esc(a.cwd)}">${esc(a.cwd)}</dd>` : ''}</dl>
135
+ </section>`
136
+ const list = this.loaded ? milestones(this.name, this.items) : []
137
+ let lastDay = new Date().toDateString()
138
+ const rows = list.map(m => {
139
+ const d = new Date(m.ts).toDateString()
140
+ const head = d !== lastDay ? `<li class="tl-day">${esc(day(m.ts))}</li>` : ''
141
+ lastDay = d
142
+ return `${head}<li class="tl-item ${m.tone}" data-kind="${m.kind}"><time datetime="${new Date(m.ts).toISOString()}">${esc(hhmm(m.ts))}</time><span class="tl-mark" aria-hidden="true"></span><div><b>${esc(m.title)}</b>${m.detail ? `<span title="${esc(m.full)}">${esc(m.detail)}</span>` : ''}</div></li>`
143
+ }).join('')
144
+ this.box.innerHTML = `${this.showNow ? now : ''}<section class="tl-past"><h2 class="tq-label">${esc(T.tlImportant)}</h2>
145
+ ${!this.loaded ? `<p class="sv-small sv-quiet">${esc(T.termLoading)}</p>` : rows ? `<ol class="tl-list">${rows}</ol>` : `<p class="sv-small sv-quiet">${esc(T.tlEmpty)}</p>`}
146
+ ${a.observe === 'off' ? `<p class="sv-small sv-quiet">${esc(T.svNotObserved)}</p>` : `<p class="tl-kept">${esc(T.tlKept)}</p>`}</section>`
147
+ }
148
+ }
149
+
150
+ export const refreshTimelines = () => { for (const t of timelines) t.soon() }
151
+
152
+ // The panel folds to a thin edge (and back); the choice is kept per company.
153
+ document.addEventListener('click', e => {
154
+ const b = e.target.closest?.('[data-tvfold]')
155
+ const tv = b?.closest('.tv')
156
+ if (!tv) return
157
+ const folded = tv.classList.toggle('folded')
158
+ store.set(companyPref('pishaTlFolded'), folded ? '1' : '0')
159
+ b.setAttribute('aria-expanded', String(!folded))
160
+ b.setAttribute('aria-label', folded ? T.tlShow : T.tlHide)
161
+ b.title = folded ? T.tlShow : T.tlHide
162
+ b.querySelector('.ic')?.classList.toggle('flip', folded)
163
+ })