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
package/ui/chat.js ADDED
@@ -0,0 +1,388 @@
1
+ import { T, LOCALE } from './i18n.js'
2
+ import { views, state, sessions } from './state.js'
3
+ import { esc, hhmm, num, dur, now } from './format.js'
4
+ import { api } from './api.js'
5
+ import {
6
+ MAX_VIEW_ITEMS, MAX_VIEW_HTML, MAX_VIEW_TAGS, tagsIn, clipEsc, MAX_RENDER_TEXT, mdCached, status,
7
+ } from './content.js'
8
+ import { msgTag } from './topbar.js'
9
+ import { showLogin } from './app.js'
10
+
11
+ // ChatView: one session's conversation. Used by mosaic panes and the full view.
12
+ export class ChatView {
13
+ constructor(name, { full = false } = {}) {
14
+ this.name = name
15
+ this.full = full
16
+ this.items = [] // sorted by ts
17
+ this.keys = new Set() // de-dup
18
+ this.nextBefore = null
19
+ this.hasMore = true
20
+ this.loading = false
21
+ this.unseen = 0
22
+ this.openGroups = new Map() // group key -> user choice
23
+ this.openDetails = new Set() // a tool's input or output the user opened
24
+ this.el = document.createElement('div')
25
+ this.el.className = 'chat'
26
+ this.el.innerHTML = `<div class="scroll"><div class="items"></div></div><button class="jump" hidden>${T.jump(0)}</button><div class="status"><span class="dot"></span><span class="txt"></span></div>`
27
+ this.scrollEl = this.el.querySelector('.scroll')
28
+ this.itemsEl = this.el.querySelector('.items')
29
+ this.jumpEl = this.el.querySelector('.jump')
30
+ this.scrollEl.addEventListener('scroll', () => this.onScroll())
31
+ this.jumpEl.addEventListener('click', () => this.toBottom())
32
+ this.itemsEl.addEventListener('toggle', e => {
33
+ const d = e.target
34
+ if (d.classList?.contains('tools')) this.openGroups.set(d.dataset.g, d.open)
35
+ else if (d.dataset?.d) { if (d.open) this.openDetails.add(d.dataset.d); else this.openDetails.delete(d.dataset.d) }
36
+ }, true)
37
+ // Text being selected isn't redrawn away: the view catches up when it ends
38
+ // (a moment later: the click that ended it lands on what it was aimed at),
39
+ // or after a while (left selected, it must not hide what arrives).
40
+ this.onSelection = () => { if (this.heldRender && !this.selecting()) setTimeout(() => { if (!this.selecting()) this.catchUp() }, 300) }
41
+ document.addEventListener('selectionchange', this.onSelection)
42
+ views.add(this)
43
+ this.renderStatus()
44
+ this.loadOlder(true)
45
+ }
46
+
47
+ destroy() {
48
+ views.delete(this)
49
+ document.removeEventListener('selectionchange', this.onSelection)
50
+ clearTimeout(this.heldTimer)
51
+ this.heldRender = false
52
+ }
53
+
54
+ catchUp() {
55
+ clearTimeout(this.heldTimer)
56
+ this.heldTimer = null
57
+ if (!this.heldRender) return
58
+ this.heldRender = false
59
+ this.render({ force: true })
60
+ if (this.heldStick) this.toBottom()
61
+ this.heldStick = false
62
+ }
63
+
64
+ selecting() {
65
+ const s = document.getSelection()
66
+ return !!s && !s.isCollapsed && !!s.anchorNode && this.itemsEl.contains(s.anchorNode)
67
+ }
68
+
69
+ // The chat was cleared on the server: start over.
70
+ reset() {
71
+ // A page still on its way belongs to the view before the reset: ignored.
72
+ this.gen = (this.gen ?? 0) + 1
73
+ this.loading = false
74
+ this.gapAfter = false
75
+ this.items = []
76
+ this.keys = new Set()
77
+ this.nextBefore = null
78
+ this.hasMore = true
79
+ this.unseen = 0
80
+ this.jumpEl.hidden = true
81
+ this.render()
82
+ this.loadOlder(true)
83
+ }
84
+
85
+ key(it) { return it.t === 'message' ? `m${it.id}` : `e${it.id}` }
86
+
87
+ // older: these items come from scrolling up (they are the oldest ones).
88
+ add(list, { live = false, older = false } = {}) {
89
+ let added = 0
90
+ // What arrives live goes at the end, whatever time the session put on
91
+ // it (an event dated in the past must not slip in above, unseen); the
92
+ // time shown is still its own. A reload orders everything by time.
93
+ let last = this.items.length ? this.items[this.items.length - 1] : null
94
+ for (const it of list) {
95
+ const k = this.key(it)
96
+ if (this.keys.has(k)) continue
97
+ this.keys.add(k)
98
+ if (live && last) it.order = Math.max(it.ts, last.order ?? last.ts)
99
+ this.items.push(it)
100
+ if (live) last = it
101
+ added++
102
+ }
103
+ if (!added) return 0
104
+ this.items.sort((a, b) => (a.order ?? a.ts) - (b.order ?? b.ts) || (a.id ?? 0) - (b.id ?? 0))
105
+ // Keep the view bounded. Scrolling up drops the newest items (the
106
+ // "jump" button loads the latest again); new items drop the oldest
107
+ // (scrolling up loads them again).
108
+ if (this.items.length > MAX_VIEW_ITEMS) {
109
+ // Reading back (scrolled up, or a page on its way): new items don't
110
+ // push the old ones out from under the reader; they wait behind the
111
+ // jump button.
112
+ if (older || (live && (this.loading || !this.atBottom()))) {
113
+ const drop = this.items.splice(MAX_VIEW_ITEMS)
114
+ for (const it of drop) this.keys.delete(this.key(it))
115
+ this.gapAfter = true
116
+ this.jumpEl.hidden = false
117
+ this.jumpEl.textContent = T.jump(this.unseen)
118
+ } else {
119
+ const drop = this.items.splice(0, this.items.length - MAX_VIEW_ITEMS)
120
+ for (const it of drop) this.keys.delete(this.key(it))
121
+ // Scrolling up continues from the newest item dropped (by its own
122
+ // time): nothing between it and what is shown is skipped, whatever
123
+ // times a session put on its events (repeats are de-duplicated).
124
+ // (In the server's order: time, then events before messages, then id.)
125
+ const rank = x => (x.t === 'event' ? 1 : 0)
126
+ const c = drop.reduce((a, b) => (b.ts > a.ts || (b.ts === a.ts && (rank(b) > rank(a) || (rank(b) === rank(a) && (b.id ?? 0) > (a.id ?? 0)))) ? b : a))
127
+ // (+1: the server returns what is strictly older, and c must come back too.)
128
+ this.nextBefore = `${c.ts}:${c.t === 'event' ? 1 : 0}:${c.id + 1}`
129
+ this.evictions = (this.evictions ?? 0) + 1
130
+ this.hasMore = true
131
+ }
132
+ }
133
+ if (live && !this.atBottom()) { this.unseen += added; this.jumpEl.hidden = false; this.jumpEl.textContent = T.jump(this.unseen) }
134
+ return added
135
+ }
136
+
137
+ accepts(it) {
138
+ if (it.t === 'event') return it.session === this.name
139
+ if (it.from === this.name || it.target === this.name) return true
140
+ return it.target?.startsWith('#') && state.groups.some(g => g.id === it.target && g.members.includes(this.name))
141
+ }
142
+
143
+ atBottom() { return this.scrollEl.scrollHeight - this.scrollEl.scrollTop - this.scrollEl.clientHeight < 60 }
144
+ toBottom() {
145
+ // Newer items were dropped while reading back: load the latest again.
146
+ if (this.gapAfter) return this.reset()
147
+ this.scrollEl.scrollTop = this.scrollEl.scrollHeight; this.unseen = 0; this.jumpEl.hidden = true
148
+ }
149
+
150
+ onScroll() {
151
+ if (this.atBottom() && !this.gapAfter) { this.unseen = 0; this.jumpEl.hidden = true }
152
+ if (this.scrollEl.scrollTop < 80) this.loadOlder()
153
+ }
154
+
155
+ async loadOlder(first = false) {
156
+ if (this.loading || !this.hasMore) return
157
+ this.loading = true
158
+ const gen = this.gen // a reset() meanwhile makes this answer stale
159
+ const evicted = this.evictions ?? 0 // and live items dropped meanwhile set their own cursor
160
+ try {
161
+ const q = `/api/timeline?session=${encodeURIComponent(this.name)}&limit=${this.full ? 200 : 120}${this.nextBefore != null ? `&before=${this.nextBefore}` : ''}`
162
+ const r = await api(q)
163
+ if (gen !== this.gen) return
164
+ // Live items were dropped while this page was on its way: the page
165
+ // would leave a hole above them. Dropped; the next scroll asks again
166
+ // from the right place.
167
+ if ((this.evictions ?? 0) !== evicted) { this.hasMore = true; this.loading = false; this.render(); return }
168
+ this.nextBefore = r.next_before
169
+ this.hasMore = r.has_more && r.items.length > 0
170
+ const fromBottom = this.scrollEl.scrollHeight - this.scrollEl.scrollTop
171
+ this.add(r.items, { older: !first })
172
+ this.loading = false
173
+ this.render()
174
+ if (first) this.toBottom()
175
+ else this.scrollEl.scrollTop = this.scrollEl.scrollHeight - fromBottom // keep the reader in place
176
+ } catch (e) {
177
+ if (e.status === 401) return showLogin(T.sessionEnded)
178
+ // The server refused the request: don't ask again on every scroll.
179
+ if (e.status >= 400 && e.status < 500) { this.hasMore = false; this.loading = false; this.render() }
180
+ } finally {
181
+ if (gen === this.gen) this.loading = false
182
+ }
183
+ }
184
+
185
+ live(it) {
186
+ if (!this.accepts(it)) return false
187
+ if (this.gapAfter) {
188
+ // Reading far back: count it; the jump button loads the latest.
189
+ if (this.keys.has(this.key(it))) return false
190
+ this.unseen++
191
+ this.jumpEl.textContent = T.jump(this.unseen)
192
+ return true
193
+ }
194
+ const stick = this.atBottom()
195
+ if (!this.add([it], { live: true })) return false
196
+ this.scheduleRender(stick)
197
+ return true
198
+ }
199
+
200
+ // A burst of changes re-renders once per frame, not once per change.
201
+ scheduleRender(stick = false) {
202
+ this.stick = this.stick || stick
203
+ if (!this.frame) {
204
+ this.frame = requestAnimationFrame(() => {
205
+ this.frame = null
206
+ if (this.render() === false) this.heldStick ||= this.stick
207
+ else if (this.stick) this.toBottom()
208
+ this.stick = false
209
+ })
210
+ }
211
+ }
212
+
213
+ // --- rendering ---------------------------------------------------------------
214
+ render({ force = false } = {}) {
215
+ if (!force && this.selecting()) {
216
+ this.heldRender = true
217
+ this.heldTimer ??= setTimeout(() => this.catchUp(), 20_000)
218
+ return false
219
+ }
220
+ const html = []
221
+ if (this.hasMore) html.push(`<div class="older">${this.loading ? T.loading : T.scrollMore}</div>`)
222
+ else {
223
+ const cleared = sessions.get(this.name)?.cleared_at
224
+ const when = cleared ? new Date(cleared).toLocaleString(LOCALE, { dateStyle: 'short', timeStyle: 'short' }) : ''
225
+ if (this.items.length === 0) html.push(`<div class="older">${cleared ? T.clearedEmpty(when) : T.noActivity}</div>`)
226
+ else html.push(`<div class="older">${cleared ? T.clearedTop(when) : T.historyStart}</div>`)
227
+ }
228
+
229
+ const a = sessions.get(this.name)?.activity
230
+ this.pairTools()
231
+ const parts = []
232
+ let group = null
233
+ const flush = () => { if (group) { parts.push({ group, n: group.list.length }); group = null } }
234
+ for (const it of this.items) {
235
+ if (it.t === 'event' && (it.kind === 'tool_start' || it.kind === 'tool_end' || it.kind === 'subagent_start' || it.kind === 'subagent_stop')) {
236
+ if (it.kind === 'tool_end' && this.started.has(it.ref)) continue // shown with its start
237
+ if (!group) group = { key: this.key(it), list: [] }
238
+ group.list.push(it)
239
+ continue
240
+ }
241
+ if (it.t === 'event' && (it.kind === 'usage' || (it.kind === 'prompt' && it.channel))) continue
242
+ flush()
243
+ parts.push({ it, n: 1 })
244
+ }
245
+ flush()
246
+ // At most MAX_VIEW_HTML of markup (and MAX_VIEW_TAGS tags) per redraw,
247
+ // newest first: a session can't make every redraw of its view parse
248
+ // megabytes (escaping can multiply a text's size). Older items are left
249
+ // out, and say so; a group of tools too big for what is left shows its
250
+ // newest tools.
251
+ const left = { chars: MAX_VIEW_HTML, tags: MAX_VIEW_TAGS }
252
+ const shown = []
253
+ let hidden = 0
254
+ for (let i = parts.length - 1; i >= 0; i--) {
255
+ const p = parts[i]
256
+ // (Nothing left for what a group of tools holds: no empty shells of them.)
257
+ if (p.group && left.chars <= 4000) { for (let j = 0; j <= i; j++) hidden += parts[j].n; break }
258
+ const h = p.group ? this.renderGroup(p.group, a, left) : this.renderItem(p.it)
259
+ const tags = tagsIn(h)
260
+ if (h.length > left.chars || tags > left.tags) { for (let j = 0; j <= i; j++) hidden += parts[j].n; break }
261
+ shown.push(h)
262
+ left.chars -= h.length
263
+ left.tags -= tags
264
+ }
265
+ if (hidden) html.push(`<div class="older">${T.olderHidden(hidden)}</div>`)
266
+ this.itemsEl.innerHTML = html.join('') + shown.reverse().join('')
267
+ }
268
+
269
+ // Each tool's end, wherever it fell: messages can come between a tool's start
270
+ // and its end (its own reply, the permission it waits for) and split their
271
+ // groups. And the tools that will never end (a denied permission gives no
272
+ // end): those of the main agent when its turn ends, all when the session does.
273
+ pairTools() {
274
+ this.started = new Set()
275
+ this.endOf = new Map()
276
+ this.stopped = new Set()
277
+ for (const it of this.items) {
278
+ if (it.t !== 'event' || !it.ref) continue
279
+ if (it.kind === 'tool_start') this.started.add(it.ref)
280
+ else if (it.kind === 'tool_end') this.endOf.set(it.ref, it)
281
+ }
282
+ let open = []
283
+ for (const it of this.items) {
284
+ if (it.t !== 'event') continue
285
+ if (it.kind === 'tool_start' && !this.endOf.has(it.ref)) open.push(it)
286
+ const over = it.kind === 'session_end' || (it.kind === 'session_start' && it.source !== 'compact')
287
+ if (over || (it.kind === 'stop' && !it.agent)) {
288
+ for (const t of open) if (over || !t.agent) this.stopped.add(t)
289
+ open = open.filter(t => !this.stopped.has(t))
290
+ }
291
+ }
292
+ }
293
+
294
+ renderItem(it) {
295
+ if (it.t === 'message') {
296
+ const file = it.file ? `${it.text ? '\n' : ''}${esc(it.file.name)}` : ''
297
+ if (it.system) return `<div class="sysline notice">${esc(it.text)}<div class="t">${hhmm(it.ts)} · ${T.serverNotice}</div></div>`
298
+ if (it.from === this.name) {
299
+ return `<div class="sent"><div class="h">→ <b>${esc(it.target)}</b>${msgTag(it)} · ${hhmm(it.ts)}${it.edited_at ? ` · ${T.editedMark}` : ''}</div><div class="x">${clipEsc(it, 'text', MAX_RENDER_TEXT)}${file}</div></div>`
300
+ }
301
+ return `<div class="row-user"><div class="bubble-head"><b>${esc(it.from)}</b>${it.target.startsWith('#') ? T.inGroup(esc(it.target)) : ''}${msgTag(it)} · ${hhmm(it.ts)}${it.edited_at ? ` · ${T.editedMark}` : ''}</div><div class="bubble in">${clipEsc(it, 'text', MAX_RENDER_TEXT)}${file}</div></div>`
302
+ }
303
+ switch (it.kind) {
304
+ case 'prompt': return `<div class="row-user"><div class="bubble-head"><b>${T.you}</b> · ${hhmm(it.ts)}</div><div class="bubble">${clipEsc(it, 'text', MAX_RENDER_TEXT)}</div></div>`
305
+ case 'text': return `<div class="assistant">${mdCached(it)}</div>`
306
+ case 'stop': return `<div class="divider">${T.turnEnded} · ${hhmm(it.ts)}${num(it.background_tasks) ? ` · ${T.background(num(it.background_tasks))}` : ''}</div>`
307
+ case 'notification': return `<div class="sysline warn">${it.text ? clipEsc(it, 'text', 500) : esc(it.type)} · ${hhmm(it.ts)}</div>`
308
+ case 'compact': return `<div class="sysline">${T.compactingLine} · ${hhmm(it.ts)}</div>`
309
+ case 'compacted': return `<div class="sysline">${T.compactedLine(it.trigger !== 'manual')} · ${hhmm(it.ts)}${it.summary ? `<details style="text-align:left"><summary>${T.compactSummary}</summary><pre style="white-space:pre-wrap;font:12px/1.4 var(--mono);background:var(--panel-2);padding:8px;border-radius:6px;max-height:300px;overflow:auto">${clipEsc(it, 'summary', MAX_RENDER_TEXT)}</pre></details>` : ''}</div>`
310
+ case 'session_start': if (it.source === 'clear') return `<div class="sysline">${T.contextCleared} · ${hhmm(it.ts)}</div>`
311
+ return `<div class="sysline">${T.sessionStarted(it.source === 'resume')}${it.cwd ? T.inDir(esc(it.cwd)) : ''} · ${hhmm(it.ts)}</div>`
312
+ case 'session_end': return `<div class="sysline">${T.sessionEnded}${it.reason ? ` (${esc(it.reason)})` : ''} · ${hhmm(it.ts)}</div>`
313
+ case 'observe_start': return `<div class="sysline">${T.observing(esc(it.level))} · ${hhmm(it.ts)}</div>`
314
+ default: return ''
315
+ }
316
+ }
317
+
318
+ renderGroup(group, activity, left = { chars: Infinity, tags: Infinity }) {
319
+ const tools = []
320
+ for (const ev of group.list) {
321
+ if (ev.kind === 'tool_start') tools.push({ start: ev, end: this.endOf.get(ev.ref) ?? null })
322
+ else if (ev.kind === 'tool_end') tools.push({ start: { ...ev, summary: '', detail: '' }, end: ev }) // its start isn't loaded
323
+ else tools.push({ sub: ev })
324
+ }
325
+ const real = tools.filter(t => !t.sub)
326
+ const running = real.filter(t => !t.end && !this.stopped.has(t.start))
327
+ const failed = real.filter(t => t.end && t.end.ok === false)
328
+ const noResult = real.some(t => !t.end && this.stopped.has(t.start))
329
+ const names = [...new Set(real.map(t => toolName(t.start.tool)))].slice(0, 12)
330
+ const waitingId = activity?.state === 'waiting' ? activity.tool?.id : null
331
+ const st = running.length
332
+ ? (running.some(t => t.start.ref === waitingId) ? `<span class="res err">${T.waitingPermission}</span>` : `<span class="res run"><span class="dot ok pulse" aria-hidden="true"></span> ${T.running(running.length)}</span>`)
333
+ : failed.length ? `<span class="res err">✗ ${T.withErrors(failed.length)}</span>` : noResult ? `<span class="res">${T.noResult}</span>` : '<span class="res ok">✓</span>'
334
+ const userChoice = this.openGroups.get(group.key)
335
+ const open = userChoice ?? (running.length > 0)
336
+ // Newest tools first, as many as fit in what the view has left.
337
+ const rows = []
338
+ let chars = left.chars - 4000 - esc(names.join(', ')).length, tags = left.tags - 40, k = tools.length
339
+ for (; k > 0; k--) {
340
+ const t = tools[k - 1]
341
+ const row = t.sub ? `<div class="tool"><div class="line"><span class="tn">${T.subagentShort}</span><span class="arg">${T.subagent(t.sub.kind === 'subagent_start')}</span></div>${t.sub.text ? `<details><summary>${T.result}</summary><pre>${clipEsc(t.sub, 'text')}</pre></details>` : ''}</div>` : this.renderTool(t, waitingId)
342
+ const n = tagsIn(row)
343
+ if (row.length > chars || n > tags) break
344
+ rows.push(row)
345
+ chars -= row.length
346
+ tags -= n
347
+ }
348
+ if (k) rows.push(`<div class="tool"><div class="line"><span class="arg">${T.olderHidden(k)}</span></div></div>`)
349
+ rows.reverse()
350
+ return `<details class="tools" data-g="${group.key}"${open ? ' open' : ''}>
351
+ <summary><span class="names">${T.tools(real.length)} · ${esc(names.join(', '))}</span><span class="st">${st}</span></summary>
352
+ <div class="list">${rows.join('')}</div></details>`
353
+ }
354
+
355
+ renderTool({ start, end }, waitingId) {
356
+ let res
357
+ if (!end && this.stopped.has(start)) res = `<span class="res">${T.noResult}</span>`
358
+ else if (!end && start.ref === waitingId) res = `<span class="res err">${T.permShort}</span>`
359
+ else if (!end) res = `<span class="res run" data-since="${start.ts}"><span class="dot ok pulse" aria-hidden="true"></span> ${dur(now() - start.ts)}</span>`
360
+ else if (end.ok === false) res = `<span class="res err">✗ ${end.interrupted ? T.interrupted : end.summary ? clipEsc(end, 'summary', 300) : T.error}${end.duration_ms ? ` · ${dur(end.duration_ms)}` : ''}</span>`
361
+ else res = `<span class="res ok">✓${end.summary ? ` ${clipEsc(end, 'summary', 300)}` : ''}${end.duration_ms ? ` · ${dur(end.duration_ms)}` : ''}</span>`
362
+ const det = []
363
+ const opened = key => (this.openDetails.has(key) ? ' open' : '')
364
+ const inKey = `i${start.id ?? ''}`, outKey = `o${end?.id ?? ''}`
365
+ if (start.detail) det.push(`<details data-d="${inKey}"${opened(inKey)}><summary>${T.input}</summary><pre>${clipEsc(start, 'detail')}</pre></details>`)
366
+ if (end?.detail) det.push(`<details data-d="${outKey}"${opened(outKey)}><summary>${end.ok === false ? T.error : T.output}</summary><pre>${clipEsc(end, 'detail')}</pre></details>`)
367
+ const sum = clipEsc(start, 'summary', 300)
368
+ const tip = esc(String(start.summary ?? '').slice(0, 300)) // an attribute: plain text only
369
+ return `<div class="tool"><div class="line"><span class="tn">${esc(toolName(start.tool))}</span>${start.agent ? `<span class="agent">${esc(start.agent)}</span>` : ''}<span class="arg" title="${tip}">${sum}</span>${res}</div>${det.join('')}</div>`
370
+ }
371
+
372
+ renderStatus() {
373
+ const s = sessions.get(this.name)
374
+ const st = status(s)
375
+ const bar = this.el.querySelector('.status')
376
+ bar.classList.toggle('waiting', !!st.waiting)
377
+ bar.querySelector('.dot').className = `dot ${st.dot}`
378
+ bar.querySelector('.txt').textContent = st.text
379
+ bar.querySelector('.txt').title = st.title ? `${st.text}\n${st.title}` : st.text
380
+ }
381
+
382
+ tick() {
383
+ for (const el of this.itemsEl.querySelectorAll('.res.run[data-since]')) el.innerHTML = `<span class="dot ok pulse" aria-hidden="true"></span> ${dur(now() - Number(el.dataset.since))}`
384
+ this.renderStatus()
385
+ }
386
+ }
387
+
388
+ export const toolName = t => String(t ?? '').startsWith('mcp__') ? String(t).split('__').slice(1).join(' › ') : (t ?? '')
package/ui/content.js ADDED
@@ -0,0 +1,157 @@
1
+ import { store } from './dom.js'
2
+ import { T, COLLATOR } from './i18n.js'
3
+ import { sessions, companyPref } from './state.js'
4
+ import { esc, dur, now } from './format.js'
5
+ import { nowPhrase } from './doing.js'
6
+
7
+ export const MAX_VIEW_ITEMS = 600 // per chat view
8
+ export const MAX_RENDER_TEXT = 8000 // characters of one text shown
9
+ const MAX_RENDER_TAGS = 600 // HTML tags one formatted text may become
10
+ export const MAX_VIEW_HTML = 1_500_000 // characters of markup one chat view draws
11
+ export const MAX_VIEW_TAGS = 60_000 // and HTML tags
12
+ export const tagsIn = h => { let n = 0; for (let i = h.indexOf('<'); i >= 0; i = h.indexOf('<', i + 1)) n++; return n }
13
+ const MAX_RENDER_DETAIL = 3000 // characters of a tool's input/output, a summary…
14
+
15
+ // Escaped and clipped text of an item's field, computed once: a session
16
+ // sending huge events can't make every re-render slow.
17
+ const clipCache = new WeakMap()
18
+ export function clipEsc(it, field, max = MAX_RENDER_DETAIL) {
19
+ if (!it || typeof it !== 'object') return ''
20
+ let m = clipCache.get(it)
21
+ if (!m) clipCache.set(it, m = new Map())
22
+ if (!m.has(field)) {
23
+ const t = String(it[field] ?? '')
24
+ m.set(field, esc(t.length > max ? t.slice(0, max) : t) + (t.length > max ? ` <span class="dim-note">${T.moreChars(t.length - max)}</span>` : ''))
25
+ }
26
+ return m.get(field)
27
+ }
28
+
29
+ // Markdown of an item, computed once.
30
+ const mdCache = new WeakMap()
31
+ export function mdCached(it) {
32
+ if (!mdCache.has(it)) {
33
+ const t = String(it.text ?? '')
34
+ const clipped = t.length > MAX_RENDER_TEXT ? `${t.slice(0, MAX_RENDER_TEXT)}…` : t
35
+ // At most MAX_RENDER_TAGS elements per text: thousands of lines, list
36
+ // items or `code` spans would make every redraw of the view slow, so
37
+ // such a text is shown as plain text (one element) instead.
38
+ const html = md(clipped)
39
+ let tags = 0
40
+ for (let i = html.indexOf('<'); i >= 0 && tags <= MAX_RENDER_TAGS; i = html.indexOf('<', i + 1)) tags++
41
+ mdCache.set(it, tags > MAX_RENDER_TAGS ? `<div style="white-space:pre-wrap">${esc(clipped)}</div>` : html)
42
+ }
43
+ return mdCache.get(it)
44
+ }
45
+
46
+ // Small, safe markdown: everything is escaped first, then a few constructs.
47
+ function md(src) {
48
+ const blocks = []
49
+ let text = esc(src).replace(/```([\w-]*)\n([\s\S]*?)```/g, (_, lang, code) => {
50
+ blocks.push(`<pre><code>${code.replace(/\n$/, '')}</code></pre>`)
51
+ return `\u0000${blocks.length - 1}\u0000`
52
+ })
53
+ const inline = s => s
54
+ .replace(/`([^`\n]+)`/g, '<code>$1</code>')
55
+ .replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>')
56
+ .replace(/(^|[^*\w])\*([^*\n]+)\*(?!\w)/g, '$1<em>$2</em>')
57
+ .replace(/\[([^\]\n]{1,200})\]\((https?:\/\/[^\s)<>]{1,2000})\)/g, (m, label, href) => {
58
+ // A link into this dashboard (e.g. straight to a terminal) is shown as text.
59
+ // Judged on the URL as the browser will read it (entities decoded);
60
+ // one with user:password@ in it is never made a link.
61
+ let own = true
62
+ let realHost = ''
63
+ const decode = x => x.replace(/&#39;/g, "'").replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
64
+ try {
65
+ const u = new URL(decode(href))
66
+ const bare = h => h.toLowerCase().replace(/\.+(?=:|$)/, '') // "host." is the same host
67
+ own = bare(u.host) === bare(location.host) || !!u.username || !!u.password || /@/.test(href) || u.hash.startsWith('#/')
68
+ // Whenever the text isn't the address itself, the real host goes
69
+ // next to it (a label can pass for another site in many ways).
70
+ const l = decode(label.replace(/<[^>]*>/g, '')).trim()
71
+ // So does a host written with characters that look like others
72
+ // (gіthub.com with a Cyrillic і, a division slash for "/", %2E for ".").
73
+ const written = decode(href).replace(/^https?:\/\//i, '').split(/[/?#\\]/)[0].replace(/^[^@]*@/, '')
74
+ if ((l !== decode(href) && l !== u.href) || /[^\x21-\x7e]|%/.test(written) || /(^|\.)xn--/i.test(u.hostname)) realHost = u.host
75
+ } catch {}
76
+ return own ? `${label} (${href})` : `<a href="${href}" target="_blank" rel="noopener noreferrer">${label}</a>${realHost ? ` <span class="dim-note">(${esc(realHost)})</span>` : ''}`
77
+ })
78
+ // Line by line: runs of "- " / "1. " lines become lists, headings stand
79
+ // alone, other lines join into paragraphs; blank lines end a paragraph.
80
+ const out = []
81
+ let para = [], list = null
82
+ const endPara = () => { if (para.length) out.push(`<p>${para.join('<br>')}</p>`); para = [] }
83
+ const endList = () => { if (list) out.push(`<${list.tag}>${list.items.map(i => `<li>${i}</li>`).join('')}</${list.tag}>`); list = null }
84
+ for (const line of text.split('\n')) {
85
+ const ul = /^\s*[-*+] (.*)$/.exec(line)
86
+ const ol = /^\s*\d+[.)] (.*)$/.exec(line)
87
+ if (ul || ol) {
88
+ endPara()
89
+ const tag = ul ? 'ul' : 'ol'
90
+ if (list && list.tag !== tag) endList()
91
+ if (!list) list = { tag, items: [] }
92
+ list.items.push(inline((ul ?? ol)[1]))
93
+ continue
94
+ }
95
+ endList()
96
+ if (!line.trim()) { endPara(); continue }
97
+ if (/^\u0000\d+\u0000$/.test(line.trim())) { endPara(); out.push(line.trim()); continue }
98
+ if (/^#{1,6} /.test(line)) { endPara(); out.push(`<span class="h">${inline(line.replace(/^#{1,6} /, ''))}</span>`); continue }
99
+ para.push(inline(line))
100
+ }
101
+ endList(); endPara()
102
+ return out.join('').replace(/\u0000(\d+)\u0000/g, (_, i) => blocks[Number(i)])
103
+ }
104
+
105
+ // The tool and its exact arguments, for a tooltip.
106
+ const toolLine = t => [t?.name, t?.summary].filter(Boolean).join(' · ')
107
+
108
+ // session status (sidebar, pane headers, status bars). title: the detail
109
+ // behind text, when there is more (the command it runs).
110
+ export function status(s) {
111
+ if (!s) return { dot: '', text: '' }
112
+ const a = s.activity ?? {}
113
+ if (!s.online) return { dot: '', text: T.offline(s.last_seen_at ? dur(now() - s.last_seen_at * 1000) : '—') }
114
+ switch (a.state) {
115
+ // (A phrase, not the command: the command itself is in the tooltip.)
116
+ case 'tool': return { dot: 'ok pulse', text: `${nowPhrase(a.tool)} · ${dur(now() - (a.tool?.since ?? now()))}`, title: toolLine(a.tool) }
117
+ case 'working': return { dot: 'ok pulse', text: T.working(dur(now() - (a.since ?? now()))) }
118
+ case 'waiting': return { dot: 'warn pulse', waiting: true, text: a.tool?.name ? T.waitingTool(nowPhrase(a.tool)) : T.waitingInput(a.waiting), ...(a.tool?.name ? { title: toolLine(a.tool) } : {}) }
119
+ case 'compacting': return { dot: 'info pulse', text: T.compacting }
120
+ case 'idle': return { dot: 'ok', text: T.idle(dur(now() - (a.since ?? now()))) }
121
+ case 'ended': return { dot: '', text: T.ended }
122
+ default: return { dot: 'ok', text: a.observe === 'off' ? T.connectedNoObs : T.connected }
123
+ }
124
+ }
125
+
126
+ export const byPresence = (a, b) => (b.online - a.online) || COLLATOR.compare(a.name, b.name)
127
+
128
+ // Squads: each coordinator with the workers that report to it. Workers whose
129
+ // coordinator isn't here (or sessions with no role) go in "orphans".
130
+ export function squadsOf(list) {
131
+ const coords = list.filter(s => s.role === 'coordinator').sort(byPresence)
132
+ const names = new Set(coords.map(c => c.name))
133
+ return {
134
+ squads: coords.map(c => ({ coord: c, workers: list.filter(s => s.role === 'worker' && s.coordinator === c.name).sort(byPresence) })),
135
+ orphans: list.filter(s => s.role !== 'coordinator' && s.role !== 'solo' && !(s.role === 'worker' && names.has(s.coordinator))).sort(byPresence),
136
+ // Standalone sessions: each on its own, outside every squad.
137
+ solos: list.filter(s => s.role === 'solo').sort(byPresence),
138
+ }
139
+ }
140
+
141
+ export function sortedSessions({ archived = false } = {}) {
142
+ const list = [...sessions.values()].filter(s => !s.deleted && !!s.archived_at === archived)
143
+ const { squads, orphans, solos } = squadsOf(list)
144
+ return [...squads.flatMap(q => [q.coord, ...q.workers]), ...orphans, ...solos]
145
+ }
146
+
147
+ // Which squads are unfolded in the sidebar (remembered per browser).
148
+ export const squadOpen = (() => { try { return JSON.parse(store.get(companyPref('pishaSquads')) || '{}') } catch { return {} } })()
149
+
150
+ // Which agent a session runs (Claude Code, Codex CLI or Grok CLI): a small mark
151
+ // beside its role, its name on hover. Our own marks, not the labs' logos.
152
+ const AGENT_MARK = { claude: 'A', codex: 'O', grok: 'X' }
153
+ export function agentMark(who) {
154
+ const s = typeof who === 'string' ? sessions.get(who) : who
155
+ const a = Object.hasOwn(AGENT_MARK, s?.agent) ? s.agent : 'claude'
156
+ return `<span class="agent ${a}" role="img" title="${esc(T.agentName[a])}" aria-label="${esc(T.agentName[a])}">${AGENT_MARK[a]}</span>`
157
+ }