pisha-server 0.0.11 → 0.0.13

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.
@@ -71,6 +71,7 @@
71
71
  .tl-bar i { display: block; height: 100%; border-radius: inherit; background: var(--info); }
72
72
  .tl-bar i.hot { background: var(--warn); }
73
73
  .tl-plan { display: flex; flex-direction: column; gap: 6px; margin-bottom: 12px; font-size: var(--fs-sm); color: var(--muted); }
74
+ .tl-why { margin: -6px 0 12px; padding: 8px 10px; border-radius: var(--r); background: var(--err-soft); color: var(--err); font-size: var(--fs-sm); overflow-wrap: anywhere; }
74
75
  .tl-task { margin: 0 0 12px; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r-md); background: var(--panel); }
75
76
  .tl-task .tq-label { display: block; margin: 0 0 3px; }
76
77
  .tl-facts { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 4px 14px; margin: 0; font-size: var(--fs-sm); }
@@ -0,0 +1,60 @@
1
+ /* Usage: what the agents spent, in tokens. The four kinds keep one colour
2
+ each everywhere on the screen (tiles, chart, bars). */
3
+
4
+ #usage { padding: 20px; }
5
+ .u-wrap { display: flex; flex-direction: column; gap: 16px; max-width: 1400px; margin: 0 auto; }
6
+ [data-k="input"] { --k: var(--info); }
7
+ [data-k="cache_write"] { --k: var(--warn); }
8
+ [data-k="cache_read"] { --k: color-mix(in srgb, var(--info) 38%, var(--panel)); }
9
+ [data-k="output"] { --k: var(--coord); }
10
+
11
+ .u-filters { display: flex; flex-wrap: wrap; gap: 8px; }
12
+ .u-filter select { height: 34px; padding: 0 30px 0 12px; border: 1px solid var(--line-2); border-radius: var(--r); background: var(--panel); color: var(--text); font: inherit; font-size: var(--fs-md); }
13
+
14
+ .u-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; }
15
+ .u-tile { display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border: 1px solid var(--line); border-radius: 14px; background: var(--panel); box-shadow: var(--shadow-card); }
16
+ .u-tl { display: inline-flex; align-items: center; gap: 7px; color: var(--muted); font-size: var(--fs-sm); }
17
+ .u-tl i { width: 9px; height: 9px; border-radius: 3px; background: var(--k); }
18
+ .u-tile b { font-size: 26px; font-weight: 650; letter-spacing: -.02em; font-variant-numeric: tabular-nums; }
19
+ .u-tn { color: var(--muted); font-size: var(--fs-xs); }
20
+
21
+ .u-card { padding: 14px 16px 16px; border-radius: 14px; }
22
+ .u-ch { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; }
23
+ .u-ch h2 { margin: 0; font-size: var(--fs-md); font-weight: 600; }
24
+ .u-legend { display: flex; flex-wrap: wrap; gap: 12px; color: var(--muted); font-size: var(--fs-sm); }
25
+ .u-legend span { display: inline-flex; align-items: center; gap: 6px; }
26
+ .u-legend i { width: 9px; height: 9px; border-radius: 3px; background: var(--k); }
27
+
28
+ .u-chart { position: relative; padding: 18px 0 22px; }
29
+ .u-chart svg { display: block; width: 100%; height: 220px; overflow: visible; }
30
+ .u-chart rect[data-k] { fill: var(--k); }
31
+ .u-chart .u-hit { fill: transparent; }
32
+ .u-chart .u-bar:hover rect[data-k] { opacity: .8; }
33
+ .u-max { position: absolute; top: 0; left: 0; color: var(--faint); font-size: var(--fs-xs); font-variant-numeric: tabular-nums; }
34
+ .u-axis { position: relative; height: 16px; margin-top: 6px; color: var(--muted); font-size: var(--fs-xs); }
35
+ .u-axis span { position: absolute; transform: translateX(-50%); white-space: nowrap; }
36
+
37
+ .u-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 420px), 1fr)); gap: 16px; align-items: start; }
38
+ .u-card.wide { grid-column: 1 / -1; }
39
+ .u-rows { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
40
+ .u-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 12px; align-items: center; }
41
+ .u-name { display: flex; align-items: center; gap: 8px; min-width: 0; }
42
+ .u-name .agent { width: 20px; height: 20px; border-radius: 6px; font-size: 10px; flex: none; }
43
+ .u-nt { display: flex; flex-direction: column; min-width: 0; }
44
+ .u-nt b { font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
45
+ .u-nt b a, .u-nt b .linkish { color: var(--text); text-decoration: none; font: inherit; }
46
+ .u-nt b .linkish { padding: 0; border: 0; background: none; cursor: pointer; text-align: left; }
47
+ .u-nt b a:hover, .u-nt b .linkish:hover { text-decoration: underline; text-decoration-color: var(--line-2); text-underline-offset: 3px; }
48
+ .u-nt span { color: var(--muted); font-size: var(--fs-xs); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
49
+ .u-val { font-variant-numeric: tabular-nums; font-weight: 600; white-space: nowrap; }
50
+ .u-val small { margin-left: 6px; color: var(--muted); font-weight: 400; font-size: var(--fs-xs); }
51
+ .u-stack { grid-column: 1 / -1; display: flex; height: 6px; border-radius: 4px; background: var(--tray); overflow: hidden; }
52
+ .u-stack i { display: block; height: 100%; background: var(--k); }
53
+ .u-empty { padding: 60px 20px; }
54
+
55
+ @media (max-width: 900px) {
56
+ #usage { padding: 14px; }
57
+ .u-tiles { grid-template-columns: repeat(2, 1fr); }
58
+ .u-tiles > :first-child { grid-column: 1 / -1; }
59
+ .u-chart svg { height: 160px; }
60
+ }
@@ -0,0 +1,111 @@
1
+ /* Webhooks: a team's list on its page, the log of what came in, and the
2
+ dialogs to make one and to read one delivery. */
3
+
4
+ /* On a team's page. */
5
+ .wh-h-acts { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 6px; }
6
+ .wh-list { list-style: none; margin: 0; padding: 4px 0; }
7
+ .wh-row { position: relative; display: flex; flex-direction: column; gap: 6px; padding: 10px 52px 10px 16px; }
8
+ .wh-row + .wh-row { border-top: 1px solid var(--line); }
9
+ .wh-main, .wh-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; min-width: 0; }
10
+ .wh-name { font-weight: 600; overflow-wrap: anywhere; }
11
+ .wh-state { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-sm); color: var(--muted); }
12
+ .wh-meta { font-size: var(--fs-sm); color: var(--muted); }
13
+ .wh-when { white-space: nowrap; }
14
+ .wh-events { white-space: nowrap; }
15
+ .wh-more { position: absolute; top: 8px; right: 10px; }
16
+
17
+ /* The log. */
18
+ #webhooks { flex: 1; min-height: 0; overflow-y: auto; padding: 20px; }
19
+ .wh-table-card { overflow: hidden; padding: 0; }
20
+ .wh-table { width: 100%; min-width: 640px; border-collapse: collapse; }
21
+ .wh-table th { padding: 9px 14px; border-bottom: 1px solid var(--line); text-align: left; font-size: var(--fs-xs); font-weight: 600; letter-spacing: .03em; text-transform: uppercase; color: var(--muted); }
22
+ .wh-table td { padding: 9px 14px; border-bottom: 1px solid var(--line); vertical-align: top; }
23
+ .wh-table tr:last-child td { border-bottom: 0; }
24
+ .wh-table tbody tr { cursor: pointer; }
25
+ .wh-table tbody tr:hover { background: var(--raised); }
26
+ .wh-table tbody tr:focus-visible { outline: 2px solid var(--focus); outline-offset: -2px; }
27
+ .wh-table td small { display: block; margin-top: 2px; font-size: var(--fs-xs); color: var(--muted); }
28
+ .wh-when-c { white-space: nowrap; font-variant-numeric: tabular-nums; }
29
+ .wh-ev { font-family: var(--mono); font-size: 12.5px; overflow-wrap: anywhere; }
30
+ .wh-res { color: var(--muted); font-size: var(--fs-sm); max-width: 360px; overflow-wrap: anywhere; }
31
+ .wh-more-row { display: flex; justify-content: center; }
32
+
33
+ /* The dialogs. */
34
+ /* (Long ones scroll; their buttons stay in sight.) */
35
+ .modal .wh-actions { position: sticky; bottom: calc(var(--pad) * -1); z-index: 1; }
36
+ .wh-form { display: flex; flex-direction: column; gap: 12px; }
37
+ .wh-form .field { margin: 0; }
38
+ .wh-form .field small { display: block; margin-top: 4px; }
39
+ .wh-form .field > .seg { margin-top: 4px; }
40
+ .wh-custom { display: flex; flex-direction: column; gap: 12px; }
41
+ .wh-custom[hidden] { display: none; }
42
+ .wh-label { margin: 12px 0 6px; font-size: var(--fs-sm); font-weight: 600; color: var(--ink-2); }
43
+ .wh-label:first-child { margin-top: 0; }
44
+ .wh-note { margin: 0 0 8px; font-size: var(--fs-sm); color: var(--warn); }
45
+ .wh-secret .cmdrow, .wh-detail .cmdrow { display: flex; align-items: flex-start; gap: 6px; margin-bottom: 8px; }
46
+ .wh-secret .cmdrow .cmd { flex: 1; min-width: 0; margin: 0; white-space: pre-wrap; word-break: break-all; }
47
+ .wh-steps { margin: 14px 0 10px; padding-left: 20px; color: var(--ink-2); line-height: 1.55; }
48
+ .wh-steps li + li { margin-top: 4px; }
49
+ .wh-d-h { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
50
+ .wh-facts { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 16px; margin: 0 0 12px; }
51
+ .wh-facts dt { color: var(--muted); font-size: var(--fs-sm); }
52
+ .wh-facts dd { margin: 0; overflow-wrap: anywhere; }
53
+ .wh-facts code, .wh-kv code { font-family: var(--mono); font-size: 12.5px; }
54
+ .wh-headers { margin: 0 0 12px; }
55
+ .wh-headers summary { cursor: pointer; color: var(--ink-2); font-size: var(--fs-sm); }
56
+ .wh-kv { margin-top: 8px; border-collapse: collapse; }
57
+ .wh-kv th { padding: 3px 14px 3px 0; text-align: left; font-weight: 500; color: var(--muted); font-size: var(--fs-sm); white-space: nowrap; vertical-align: top; }
58
+ .wh-kv td { padding: 3px 0; overflow-wrap: anywhere; }
59
+ .wh-body { max-height: 46vh; margin: 0; overflow: auto; white-space: pre; }
60
+ .wh-detail + .err { margin-top: 8px; }
61
+
62
+ /* What to do by event, and gathering bursts, in the dialog. */
63
+ .wh-form .seg { flex-wrap: wrap; }
64
+ .wh-by-event > small { display: block; margin: 2px 0 8px; }
65
+ .wh-pe-list { display: flex; flex-direction: column; gap: 8px; }
66
+ .wh-pe-row { display: grid; grid-template-columns: minmax(120px, 200px) minmax(0, 1fr) auto; gap: 8px; align-items: start; }
67
+ .wh-pe-row input, .wh-pe-row textarea { width: 100%; }
68
+ .wh-pe-row input { font-family: var(--mono); font-size: 12.5px; }
69
+ .wh-pe-add { align-self: flex-start; margin-top: 6px; padding-left: 0; }
70
+ .wh-batch input { max-width: 120px; }
71
+
72
+ /* What the coordinator did with it. */
73
+ .wh-turn { margin: 0 0 14px; padding: 12px 14px; border-radius: var(--r-md); background: var(--raised); }
74
+ .wh-turn .wh-label { margin-top: 0; }
75
+ .wh-report { margin: 0 0 6px; overflow-wrap: anywhere; }
76
+ .wh-report .tag { margin-right: 4px; vertical-align: 1px; }
77
+ .wh-report small { margin-left: 8px; color: var(--muted); font-size: var(--fs-xs); white-space: nowrap; }
78
+ .wh-turn .dim-note { margin: 0 0 6px; }
79
+ .wh-turn-meta { display: flex; flex-wrap: wrap; gap: 4px 14px; margin: 0 0 6px; color: var(--muted); font-size: var(--fs-sm); }
80
+ .wh-trace-part { margin-top: 6px; }
81
+ .wh-trace-part summary { cursor: pointer; color: var(--ink-2); font-size: var(--fs-sm); }
82
+ .wh-tools, .wh-msgs { margin: 6px 0 0; padding-left: 20px; font-size: var(--fs-sm); max-height: 240px; overflow: auto; }
83
+ .wh-tools li, .wh-msgs li { margin: 2px 0; overflow-wrap: anywhere; }
84
+ .wh-tools code { font-family: var(--mono); font-size: 12px; }
85
+ .wh-tools span { color: var(--muted); }
86
+ .wh-tools li.bad code { color: var(--err); }
87
+ .wh-said { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: var(--fs-sm); max-height: 240px; overflow: auto; }
88
+
89
+ .wh-wreport { margin: 3px 0 6px; overflow-wrap: anywhere; }
90
+ .wh-wreport .tag { margin-right: 4px; }
91
+
92
+ @media (max-width: 900px) {
93
+ #webhooks { padding: 12px; }
94
+ .wh-pe-row { grid-template-columns: minmax(0, 1fr) auto; }
95
+ .wh-pe-row textarea { grid-column: 1 / -1; grid-row: 2; }
96
+ /* The log as a list: each entry two lines, nothing cut off. */
97
+ .wh-table { min-width: 0; }
98
+ .wh-table thead { display: none; }
99
+ .wh-table tbody tr { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 12px; padding: 10px 14px; border-bottom: 1px solid var(--line); }
100
+ .wh-table tbody tr:last-child { border-bottom: 0; }
101
+ .wh-table td { display: block; padding: 0; border: 0; }
102
+ .wh-table td:nth-child(2) { grid-column: 1; grid-row: 1; }
103
+ .wh-table td:nth-child(4) { grid-column: 2; grid-row: 1; justify-self: end; }
104
+ .wh-table td.wh-when-c { grid-column: 1 / -1; color: var(--muted); font-size: var(--fs-sm); }
105
+ .wh-table td.wh-when-c small { display: inline; margin-left: 6px; }
106
+ .wh-table td.wh-ev, .wh-table td.wh-res { grid-column: 1 / -1; max-width: none; }
107
+ .wh-table td.wh-res:empty { display: none; }
108
+ .wh-facts { grid-template-columns: minmax(0, 1fr); gap: 2px; }
109
+ .wh-facts dd { margin-bottom: 8px; }
110
+ .wh-row { padding-right: 48px; min-height: 48px; }
111
+ }
package/ui/session.js CHANGED
@@ -2,7 +2,7 @@ import { $ } from './dom.js'
2
2
  import { T, LOCALE } from './i18n.js'
3
3
  import { state, sessions, hosts } from './state.js'
4
4
  import { esc, kfmt } from './format.js'
5
- import { sortedSessions, status, agentMark } from './content.js'
5
+ import { sortedSessions, status, agentMark, loginError } from './content.js'
6
6
  import { setHtml } from './nav.js'
7
7
  import { currentRoute } from './router.js'
8
8
  import { permissionsSection } from './permissions.js'
@@ -34,7 +34,10 @@ export function renderSessionAside() {
34
34
  [T.svPersona, s.persona?.name ? esc(s.persona.name) : ''],
35
35
  [T.svOpened, s.created_at ? esc(when(s.created_at * 1000)) : ''],
36
36
  ].filter(f => f[1])
37
- setHtml(box, `${members.length ? `<section><h2 class="tq-label">${esc(T.svTeam)}</h2><ul class="sv-members">${members.map(m => member(m, s.name)).join('')}</ul><a class="ibx-link sv-small" href="#/q/${encodeURIComponent(team)}">${esc(T.svSeeTeam)}</a></section>` : ''}
37
+ // Running on its machine, but its plugin refused to log in: why, first.
38
+ const why = !s.online ? loginError(s) : null
39
+ setHtml(box, `${why ? `<section><h2 class="tq-label">${esc(T.svNotJoined)}</h2><p class="tl-why" data-login-error>${esc(why)}</p></section>` : ''}
40
+ ${members.length ? `<section><h2 class="tq-label">${esc(T.svTeam)}</h2><ul class="sv-members">${members.map(m => member(m, s.name)).join('')}</ul><a class="ibx-link sv-small" href="#/q/${encodeURIComponent(team)}">${esc(T.svSeeTeam)}</a></section>` : ''}
38
41
  ${facts.length ? `<section><h2 class="tq-label">${esc(T.svDetails)}</h2><dl class="ibx-facts sv-facts">${facts.map(([k, v]) => `<dt>${esc(k)}</dt><dd>${v}</dd>`).join('')}</dl></section>` : ''}
39
42
  ${s.role !== 'solo' && s.opened_role !== 'solo' ? permissionsSection({ session: s.name }) : ''}
40
43
  ${a.observe === 'off' ? `<p class="sv-small sv-quiet">${esc(T.svNotObserved)}</p>` : ''}`)
package/ui/squads.js CHANGED
@@ -8,7 +8,7 @@ import { roleTag } from './topbar.js'
8
8
  import { alertBox } from './mosaic.js'
9
9
  import { dialog } from './dialogs.js'
10
10
  import { terminalOf, postJson, addFolderDialog, renderHosts } from './machines.js'
11
- import { renderOrg } from './org.js'
11
+ import { renderOrg, flashLink } from './org.js'
12
12
 
13
13
  // A worker for this coordinator's squad, by default on the coordinator's machine.
14
14
  // A session opened from here that ended (/quit, closed): open it again on
@@ -144,6 +144,7 @@ export function noteLinkMessage(m) {
144
144
  const l = state.links.find(x => (x.a === m.from && x.b === m.target) || (x.b === m.from && x.a === m.target))
145
145
  if (!l) return
146
146
  l.recent = [m.created_at, ...(l.recent ?? [])].slice(0, 100)
147
+ flashLink(m.from, m.target)
147
148
  if (currentRoute().view === 'org') soon(renderOrg)
148
149
  }
149
150
 
package/ui/stream.js CHANGED
@@ -20,6 +20,7 @@ import { renderInbox, refreshInbox } from './inbox.js'
20
20
  import { refreshTeams } from './teams.js'
21
21
  import { boardsArrived, taskArrived, boardDeleted } from './boards.js'
22
22
  import { refreshTeam, noteReport } from './team.js'
23
+ import { webhooksArrived, deliveryArrived } from './webhooks.js'
23
24
  import { refreshSessionAside } from './session.js'
24
25
  import { setVersion, showLogin } from './app.js'
25
26
 
@@ -103,6 +104,7 @@ function onStream(type, data) {
103
104
  if (type === 'plans') {
104
105
  state.plans = new Map((Array.isArray(data) ? data : []).map(p => [p.coordinator, p]))
105
106
  soon(refreshTeam); soon(refreshTeams); soon(refreshTimelines)
107
+ if (currentRoute().view === 'org') soon(renderOrg) // (what each agent is on comes from its coordinator's plan)
106
108
  }
107
109
  if (type === 'inbox') {
108
110
  state.inbox = Array.isArray(data) ? data : []
@@ -120,6 +122,8 @@ function onStream(type, data) {
120
122
  soon(renderNav); soon(refreshInbox); soon(refreshTeams); soon(refreshTeam); soon(refreshSessionAside)
121
123
  return
122
124
  }
125
+ if (type === 'webhooks') return webhooksArrived(data)
126
+ if (type === 'webhook-delivery') return deliveryArrived(data)
123
127
  if (type === 'squads') {
124
128
  state.squadMeta = new Map((Array.isArray(data) ? data : []).map(q => [q.coordinator, q]))
125
129
  if (currentRoute().view === 'org') soon(renderOrg)
package/ui/team.js CHANGED
@@ -7,6 +7,7 @@ import { sortedSessions, status, agentMark } from './content.js'
7
7
  import { setHtml } from './nav.js'
8
8
  import { currentRoute } from './router.js'
9
9
  import { permissionsSection } from './permissions.js'
10
+ import { webhooksSection } from './webhooks.js'
10
11
 
11
12
  // One team: what it is for, what its workers last reported, who is in it and
12
13
  // where each runs, the teams it is linked with, and saving it as a template.
@@ -91,6 +92,7 @@ export function renderTeam() {
91
92
  <header class="tq-h"><h2>${esc(T.tqReports)}</h2><span class="tq-sub">${esc(T.tqReportsHint)}</span></header>
92
93
  ${repHtml}
93
94
  </section>
95
+ ${webhooksSection(coord.name)}
94
96
  </div>
95
97
  <aside class="tq-aside" aria-label="${esc(T.tqTeam)}">
96
98
  <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>
package/ui/timeline.js CHANGED
@@ -128,6 +128,7 @@ export class Timeline {
128
128
  const pct = a.context_pct
129
129
  const now = `<section class="tl-now"><h2 class="tq-label">${esc(T.tlNow)}</h2>
130
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
+ ${st.why ? `<p class="tl-why" data-login-error>${esc(st.why)}</p>` : ''}
131
132
  ${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
133
  ${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
134
  ${task ? `<p class="tl-task"><span class="tq-label">${esc(T.tlTask)}</span>${esc(task.title)}</p>` : ''}
package/ui/topbar.js CHANGED
@@ -13,6 +13,8 @@ import { orgSquads, orgZoom, linksDialog } from './org.js'
13
13
  import { renderBack } from './back.js'
14
14
  import { voiceButton } from './voice.js'
15
15
  import { boardsHead, boardsTopClick } from './boards.js'
16
+ import { usageHead } from './usage.js'
17
+ import { webhooksHead } from './webhooks.js'
16
18
 
17
19
  // The terminal a session view shows (null: its chat).
18
20
  // (An observer has no terminals: its chat instead.)
@@ -63,6 +65,16 @@ function renderHead() {
63
65
  setHtml($('topRight'), voiceButton())
64
66
  return
65
67
  }
68
+ if (r.view === 'usage') {
69
+ const h = usageHead()
70
+ setHtml($('topTitle'), h.title); setHtml($('topTabs'), h.tabs); setHtml($('topRight'), h.right)
71
+ return
72
+ }
73
+ if (r.view === 'webhooks') {
74
+ // (Its subtitle, how many are shown, is the log's own: see renderWebhooks.)
75
+ setHtml($('topTitle'), webhooksHead().title); setHtml($('topRight'), '')
76
+ return
77
+ }
66
78
  if (r.view === 'boards' || r.view === 'board') {
67
79
  // (Its subtitle, how many boards or tasks, is the board's own: see renderBoards.)
68
80
  const h = boardsHead(r)
package/ui/usage.js ADDED
@@ -0,0 +1,175 @@
1
+ import { $, store } from './dom.js'
2
+ import { T, LOCALE, COLLATOR } from './i18n.js'
3
+ import { state, companyPref } from './state.js'
4
+ import { esc } from './format.js'
5
+ import { api } from './api.js'
6
+ import { setHtml, soon } from './nav.js'
7
+ import { currentRoute } from './router.js'
8
+ import { agentMark } from './content.js'
9
+
10
+ // What the agents spent, in tokens: a period, filters, the totals, the
11
+ // spending over time, and by team, what started it, task, session and model.
12
+ // Read from /api/usage (kept by the hour on the server); counts only.
13
+ const KINDS = ['input', 'cache_write', 'cache_read', 'output']
14
+ const RANGES = { today: 0, d7: 7, d30: 30, d90: 90 }
15
+ const HOUR = 3600_000, DAY = 24 * HOUR
16
+ const COMPACT = new Intl.NumberFormat(LOCALE, { notation: 'compact', maximumFractionDigits: 1 })
17
+ const FULL = new Intl.NumberFormat(LOCALE)
18
+ const DAY_FMT = new Intl.DateTimeFormat(LOCALE, { day: 'numeric', month: 'short' })
19
+ const HOUR_FMT = new Intl.DateTimeFormat(LOCALE, { hour: '2-digit', minute: '2-digit', hour12: false })
20
+
21
+ let view = { range: store.get(companyPref('pishaUsageRange')) ?? 'd7', team: '', agent: '', model: '' }
22
+ let data = null, loading = 0, timer = null
23
+
24
+ const total = r => r.input + r.cache_read + r.cache_write + r.output
25
+ const num = n => COMPACT.format(n)
26
+ const period = () => {
27
+ const now = Date.now()
28
+ if (view.range === 'today') { const d = new Date(); d.setHours(0, 0, 0, 0); return { from: d.getTime(), to: now, bucket: 'hour' } }
29
+ return { from: now - (RANGES[view.range] ?? 7) * DAY, to: now, bucket: 'day' }
30
+ }
31
+
32
+ async function load() {
33
+ const seq = ++loading
34
+ const p = period()
35
+ const q = new URLSearchParams({ from: p.from, to: p.to, bucket: p.bucket, tz: -new Date().getTimezoneOffset() })
36
+ for (const k of ['team', 'agent', 'model']) if (view[k]) q.set(k, view[k])
37
+ try {
38
+ const r = await api(`/api/usage?${q}`)
39
+ if (seq !== loading) return
40
+ data = r
41
+ } catch (err) { if (seq === loading) data = { error: err.message } }
42
+ if (currentRoute().view === 'usage') draw()
43
+ }
44
+
45
+ export function renderUsage() {
46
+ if (!data) setHtml($('usage'), `<div class="u-wrap"><p class="dim-note">${esc(T.usageLoading)}</p></div>`)
47
+ void load()
48
+ clearInterval(timer)
49
+ // (While it is open: what is being spent now shows up within a minute.)
50
+ timer = setInterval(() => { if (currentRoute().view === 'usage' && !$('usage').hidden) void load(); else clearInterval(timer) }, 60_000)
51
+ }
52
+
53
+ // The header: the period, and the export.
54
+ export function usageHead() {
55
+ const seg = Object.keys(RANGES).map(k => `<button type="button" data-urange="${k}" class="${view.range === k ? 'on' : ''}" aria-pressed="${view.range === k}">${esc(T.usageRanges[k])}</button>`).join('')
56
+ return { title: esc(T.usage), tabs: `<span class="seg" role="group" aria-label="${esc(T.usagePeriod)}">${seg}</span>`, right: `<button type="button" class="btn" data-uexport>${esc(T.usageExport)}</button>` }
57
+ }
58
+
59
+ const teamName = t => (t ? state.squadMeta.get(t)?.title || t : T.usageNoTeam)
60
+
61
+ function draw() {
62
+ const box = $('usage')
63
+ if (data?.error) { setHtml(box, `<div class="u-wrap"><p class="err">${esc(data.error)}</p></div>`); return }
64
+ const d = data
65
+ const opts = (k, list, label, name = x => x) => `<label class="u-filter"><span class="sr-only">${esc(label)}</span><select data-ufilter="${k}"><option value="">${esc(label)}</option>${list.map(v => `<option value="${esc(v)}"${view[k] === v ? ' selected' : ''}>${esc(name(v))}</option>`).join('')}</select></label>`
66
+ const teams = [...new Set([...(view.team ? [view.team] : []), ...d.by.team.map(r => r.team).filter(Boolean)])].sort((a, b) => COLLATOR.compare(teamName(a), teamName(b)))
67
+ const agents = [...new Set([...(view.agent ? [view.agent] : []), ...d.by.agent.map(r => r.agent)])]
68
+ const models = [...new Set([...(view.model ? [view.model] : []), ...d.by.model.map(r => r.model).filter(Boolean)])]
69
+ const filters = `<div class="u-filters">${opts('team', teams, T.usageAllTeams, teamName)}${opts('agent', agents, T.usageAllAgents, a => T.agentName[a] ?? a)}${opts('model', models, T.usageAllModels)}</div>`
70
+ const t = d.totals, all = total(t)
71
+ if (!all) {
72
+ setHtml(box, `<div class="u-wrap">${filters}<div class="empty u-empty"><b>${esc(T.usageEmpty)}</b><span>${esc(T.usageEmptyHint)}</span></div></div>`)
73
+ return
74
+ }
75
+ const inAll = t.input + t.cache_read + t.cache_write
76
+ const cached = inAll ? Math.round(t.cache_read / inAll * 100) : 0
77
+ const tile = (k, label, value, note = '') => `<div class="u-tile"${k ? ` data-k="${k}"` : ''}><span class="u-tl">${k ? '<i aria-hidden="true"></i>' : ''}${esc(label)}</span><b title="${esc(FULL.format(value))}">${esc(num(value))}</b>${note ? `<span class="u-tn">${esc(note)}</span>` : ''}</div>`
78
+ const tiles = `<div class="u-tiles">
79
+ ${tile('', T.usageTotal, all, T.usageCalls(t.calls))}
80
+ ${tile('input', T.usageKinds.input, t.input)}
81
+ ${tile('output', T.usageKinds.output, t.output)}
82
+ ${tile('cache_read', T.usageKinds.cache_read, t.cache_read, T.usageCached(cached))}
83
+ ${tile('cache_write', T.usageKinds.cache_write, t.cache_write)}
84
+ </div>`
85
+ setHtml(box, `<div class="u-wrap">${filters}${tiles}
86
+ <section class="card u-card"><header class="u-ch"><h2>${esc(T.usageOverTime)}</h2>${legend()}</header>${chart(d)}</section>
87
+ <div class="u-grid">
88
+ ${breakdown(T.usageByTeam, d.by.team.map(r => ({ ...r, label: teamName(r.team), key: r.team })), 'team')}
89
+ ${breakdown(T.usageByCause, d.by.cause.map(r => ({ ...r, label: T.usageCauses[r.cause] ?? r.cause, hint: T.usageCauseHints[r.cause] ?? '' })))}
90
+ ${breakdown(T.usageByTask, d.by.task.filter(r => r.task).map(r => ({ ...r, label: r.task, href: taskHref(r.task) })), '', T.usageNoTasks)}
91
+ ${breakdown(T.usageByModel, d.by.model.map(r => ({ ...r, label: r.model || '?' })))}
92
+ ${breakdown(T.usageBySession, d.by.session.map(r => ({ ...r, label: r.session, sub: [teamName(r.team), T.roleName[r.role] ?? r.role].filter(Boolean).join(' · '), lead: agentMark({ agent: r.agent }), href: `#/s/${encodeURIComponent(r.session)}` })), '', '', true)}
93
+ </div>
94
+ </div>`)
95
+ }
96
+
97
+ const legend = () => `<span class="u-legend">${KINDS.map(k => `<span data-k="${k}"><i aria-hidden="true"></i>${esc(T.usageKinds[k])}</span>`).join('')}</span>`
98
+
99
+ // Stacked bars, one per hour or day of the period (empty ones too).
100
+ function chart(d) {
101
+ const p = period(), step = d.bucket === 'hour' ? HOUR : DAY
102
+ const start = d.bucket === 'hour' ? Math.floor(p.from / HOUR) * HOUR : (() => { const x = new Date(p.from); x.setHours(0, 0, 0, 0); return x.getTime() })()
103
+ const byT = new Map(d.series.map(s => [s.t, s]))
104
+ const buckets = []
105
+ for (let x = start; x <= p.to; x += step) {
106
+ // (Days by the calendar: a day with a clock change isn't 24 h.)
107
+ const key = d.bucket === 'hour' ? x : [...byT.keys()].find(k => Math.abs(k - x) < 3 * HOUR) ?? x
108
+ buckets.push({ t: x, ...(byT.get(key) ?? { input: 0, cache_read: 0, cache_write: 0, output: 0, calls: 0 }) })
109
+ if (d.bucket === 'day') { const n = new Date(x); n.setDate(n.getDate() + 1); x = n.getTime() - step }
110
+ }
111
+ const max = Math.max(1, ...buckets.map(total))
112
+ const W = 1000, H = 220, gap = buckets.length > 40 ? 1 : 3, bw = (W - gap * (buckets.length - 1)) / buckets.length
113
+ const fmt = d.bucket === 'hour' ? HOUR_FMT : DAY_FMT
114
+ const bars = buckets.map((b, i) => {
115
+ let y = H
116
+ const x = i * (bw + gap)
117
+ const parts = KINDS.map(k => { const h = b[k] / max * H; y -= h; return h > 0 ? `<rect data-k="${k}" x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${bw.toFixed(1)}" height="${h.toFixed(1)}"/>` : '' }).join('')
118
+ const tip = `${fmt.format(b.t)}: ${FULL.format(total(b))} · ${KINDS.map(k => `${T.usageKinds[k]} ${num(b[k])}`).join(' · ')}`
119
+ return `<g class="u-bar"><title>${esc(tip)}</title><rect class="u-hit" x="${x.toFixed(1)}" y="0" width="${bw.toFixed(1)}" height="${H}"/>${parts}</g>`
120
+ }).join('')
121
+ const every = Math.ceil(buckets.length / 8)
122
+ const labels = buckets.map((b, i) => (i % every ? '' : `<span style="left:${((i * (bw + gap) + bw / 2) / W * 100).toFixed(2)}%">${esc(fmt.format(b.t))}</span>`)).join('')
123
+ return `<div class="u-chart"><span class="u-max">${esc(num(max))}</span><svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="${esc(T.usageOverTime)}">${bars}</svg><div class="u-axis">${labels}</div></div>`
124
+ }
125
+
126
+ // One breakdown: a row per item with its share of the period and its kinds.
127
+ function breakdown(title, rows, filterKey = '', empty = '', wide = false) {
128
+ const max = Math.max(1, ...rows.map(total))
129
+ const sumAll = rows.reduce((n, r) => n + total(r), 0) || 1
130
+ const row = r => {
131
+ const name = r.href ? `<a href="${esc(r.href)}">${esc(r.label)}</a>` : filterKey && r.key ? `<button type="button" class="linkish" data-ufilter-set="${filterKey}" data-v="${esc(r.key)}">${esc(r.label)}</button>` : esc(r.label)
132
+ const bar = KINDS.map(k => (r[k] ? `<i data-k="${k}" style="width:${(r[k] / max * 100).toFixed(2)}%"></i>` : '')).join('')
133
+ return `<li class="u-row"${r.hint ? ` title="${esc(r.hint)}"` : ''}>
134
+ <span class="u-name">${r.lead ?? ''}<span class="u-nt"><b>${name}</b>${r.sub ? `<span>${esc(r.sub)}</span>` : ''}</span></span>
135
+ <span class="u-val" title="${esc(FULL.format(total(r)))} · ${esc(T.usageCalls(r.calls))}">${esc(num(total(r)))}<small>${Math.round(total(r) / sumAll * 100)}%</small></span>
136
+ <span class="u-stack">${bar}</span>
137
+ </li>`
138
+ }
139
+ return `<section class="card u-card${wide ? ' wide' : ''}"><header class="u-ch"><h2>${esc(title)}</h2></header>${rows.length ? `<ul class="u-rows">${rows.slice(0, 50).map(row).join('')}</ul>` : `<p class="dim-note">${esc(empty)}</p>`}</section>`
140
+ }
141
+
142
+ // A task's link: on the board it is on (the dashboard's first open one).
143
+ const taskHref = id => {
144
+ const b = state.boards.find(x => !x.archived_at) ?? state.boards[0]
145
+ return b ? `#/b/${b.id}/${encodeURIComponent(id)}` : ''
146
+ }
147
+
148
+ // The period's spending as CSV: by session, day or hour, with every column.
149
+ function exportCsv() {
150
+ if (!data?.by) return
151
+ const cell = v => (/[",\n]/.test(String(v)) ? `"${String(v).replace(/"/g, '""')}"` : String(v))
152
+ const head = ['session', 'team', 'role', 'agent', ...KINDS, 'total', 'calls']
153
+ const lines = [head.join(','), ...data.by.session.map(r => [r.session, r.team, r.role, r.agent, ...KINDS.map(k => r[k]), total(r), r.calls].map(cell).join(','))]
154
+ const a = document.createElement('a')
155
+ a.href = URL.createObjectURL(new Blob([lines.join('\n') + '\n'], { type: 'text/csv' }))
156
+ a.download = `pisha-usage-${new Date(data.from).toISOString().slice(0, 10)}-${new Date(data.to).toISOString().slice(0, 10)}.csv`
157
+ a.click()
158
+ setTimeout(() => URL.revokeObjectURL(a.href), 1000)
159
+ }
160
+
161
+ // Clicks and choices on the screen and in its header.
162
+ document.addEventListener('click', e => {
163
+ if (currentRoute().view !== 'usage') return
164
+ const r = e.target.closest('[data-urange]')
165
+ if (r) { view.range = r.dataset.urange; store.set(companyPref('pishaUsageRange'), view.range); soon(async () => (await import('./topbar.js')).renderTop()); void load(); return }
166
+ if (e.target.closest('[data-uexport]')) return exportCsv()
167
+ const f = e.target.closest('[data-ufilter-set]')
168
+ if (f) { view[f.dataset.ufilterSet] = f.dataset.v; void load() }
169
+ })
170
+ document.addEventListener('change', e => {
171
+ const f = e.target.closest?.('[data-ufilter]')
172
+ if (!f || currentRoute().view !== 'usage') return
173
+ view[f.dataset.ufilter] = f.value
174
+ void load()
175
+ })