shapewall 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +252 -0
  2. package/README.md +39 -2
  3. package/THIRD_PARTY.md +15 -0
  4. package/dist/agent/package-lock.json +594 -2
  5. package/dist/client/assets/{BoardChat-DdwBcb2N.js → BoardChat-WS8mAIW6.js} +1 -1
  6. package/dist/client/assets/{BuzzDialog-DpUcnU6S.js → BuzzDialog-B-Mlr6wF.js} +1 -1
  7. package/dist/client/assets/{ChecksPanel-CngYV4yz.js → ChecksPanel-Dx1ZLBR6.js} +1 -1
  8. package/dist/client/assets/{History-CD0saQA5.js → History-sXhmpcvs.js} +1 -1
  9. package/dist/client/assets/{LocalSettings-MZy2baig.js → LocalSettings-CtGzz9F3.js} +1 -1
  10. package/dist/client/assets/{Management-CSvZ-SHO.js → Management-CGHe8Wt9.js} +1 -1
  11. package/dist/client/assets/{QuickConnect-foLh2QUm.js → QuickConnect-DEk84E4A.js} +1 -1
  12. package/dist/client/assets/{ShareDialog-DPWDftoL.js → ShareDialog-CGGx-AYK.js} +1 -1
  13. package/dist/client/assets/{app-update-dialog-CtiXpTRD.js → app-update-dialog-_bVp8hnC.js} +1 -1
  14. package/dist/client/assets/{circle-x-CteRBtXC.js → circle-x-BWoHA1QY.js} +1 -1
  15. package/dist/client/assets/index-Bm-Xd3YN.js +37 -0
  16. package/dist/client/assets/index-C7Ostk3K.css +2 -0
  17. package/dist/client/assets/{play-BjRNIGSf.js → play-BzQ3tRTv.js} +1 -1
  18. package/dist/client/assets/{refresh-cw-r_tZiFfB.js → refresh-cw-BYBMyDKT.js} +1 -1
  19. package/dist/client/assets/{ui-zQpn-PdL.js → ui-CAY6myRA.js} +1 -1
  20. package/dist/client/build-info.json +1 -1
  21. package/dist/client/index.html +3 -3
  22. package/dist/client/sw.js +2 -2
  23. package/dist/console/assets/LocalAccountsApp-CWRguRRL.js +1 -0
  24. package/dist/console/assets/LocalConsole--I2SaIpr.js +2 -0
  25. package/dist/console/assets/LocalUsage-BmpCZ36k.js +1 -0
  26. package/dist/console/assets/app-update-dialog-B8M9plaT.js +1 -0
  27. package/dist/console/assets/app-version-muKrQqbL.js +1 -0
  28. package/dist/console/assets/console-CrhTsPbz.css +2 -0
  29. package/dist/console/assets/console-DxapQ9oS.js +11 -0
  30. package/dist/console/assets/local-agents-CoqD4dSN.js +6 -0
  31. package/dist/console/assets/minus-DDQ0ydcM.js +1 -0
  32. package/dist/console/assets/tailnet-C5Flwl_d.js +2 -0
  33. package/dist/console/assets/theme-DCd0qh4l.js +1 -0
  34. package/dist/console/assets/ui-Bry1mnCY.js +41 -0
  35. package/dist/console/assets/usage-CIPWnHaS.css +1 -0
  36. package/dist/console/assets/usage-CqVjMb7m.js +5 -0
  37. package/dist/console/assets/usage-D1G0GgE3.js +56 -0
  38. package/dist/console/build-info.json +1 -1
  39. package/dist/console/console.html +8 -2
  40. package/docs/agent-hardening.md +31 -17
  41. package/docs/agents.md +35 -0
  42. package/docs/architecture.md +10 -4
  43. package/docs/deployment.md +39 -17
  44. package/docs/design-system.md +56 -7
  45. package/docs/hosted.md +1004 -43
  46. package/docs/images/board-overview.png +0 -0
  47. package/docs/images/journeys.png +0 -0
  48. package/docs/images/live-comment.png +0 -0
  49. package/docs/images/phone-comment.png +0 -0
  50. package/docs/images/phone-overview.png +0 -0
  51. package/docs/images/variant.png +0 -0
  52. package/docs/where-to-run.md +82 -1
  53. package/package.json +6 -1
  54. package/src/agent/backends/acp.js +224 -26
  55. package/src/agent/routes.js +21 -0
  56. package/src/agent/usage-log.js +251 -0
  57. package/src/cli/args.js +24 -0
  58. package/src/cli/help.js +37 -2
  59. package/src/cli/init.js +2 -1
  60. package/src/cli/serve.js +20 -5
  61. package/src/cli.js +8 -0
  62. package/src/hosted/access-cli.js +99 -1
  63. package/src/hosted/activity-core.js +232 -0
  64. package/src/hosted/activity.js +375 -0
  65. package/src/hosted/admin.js +80 -13
  66. package/src/hosted/agent-approvals.js +2 -2
  67. package/src/hosted/agent-routes.js +3 -3
  68. package/src/hosted/agents.js +11 -4
  69. package/src/hosted/app.js +89 -7
  70. package/src/hosted/auth-routes.js +156 -15
  71. package/src/hosted/auth.js +123 -20
  72. package/src/hosted/board-routes.js +3 -3
  73. package/src/hosted/chat-frames.js +5 -15
  74. package/src/hosted/chat-permissions.js +12 -0
  75. package/src/hosted/chat-routes.js +8 -8
  76. package/src/hosted/chat-store.js +20 -3
  77. package/src/hosted/comment-files.js +5 -2
  78. package/src/hosted/console-routes.js +111 -34
  79. package/src/hosted/db.js +130 -0
  80. package/src/hosted/device-routes.js +25 -3
  81. package/src/hosted/device.js +23 -4
  82. package/src/hosted/guards.js +337 -27
  83. package/src/hosted/http.js +6 -3
  84. package/src/hosted/membership.js +13 -2
  85. package/src/hosted/operator-access.js +418 -0
  86. package/src/hosted/operator.js +106 -2
  87. package/src/hosted/ops-cli.js +238 -3
  88. package/src/hosted/pages.js +2 -0
  89. package/src/hosted/passkey-policy.js +75 -0
  90. package/src/hosted/permissions.js +14 -6
  91. package/src/hosted/presence.js +14 -2
  92. package/src/hosted/projects.js +2 -1
  93. package/src/hosted/public.js +4 -4
  94. package/src/hosted/ratelimit.js +6 -0
  95. package/src/hosted/retention.js +18 -2
  96. package/src/hosted/server.js +123 -11
  97. package/src/hosted/shares.js +2 -2
  98. package/src/hosted/step-up-settings.js +68 -0
  99. package/src/hosted/step-up.js +135 -0
  100. package/src/hosted/tailnet-identity.js +24 -0
  101. package/src/hosted/tailnet-routes.js +342 -0
  102. package/src/hosted/tailnet.js +220 -0
  103. package/src/hosted/tailscale.js +75 -9
  104. package/src/hosted/tenancy.js +48 -1
  105. package/src/hosted/token-api.js +2 -2
  106. package/src/hosted/tokens.js +9 -2
  107. package/src/hosted/usage-core.js +624 -0
  108. package/src/hosted/usage-layout.js +724 -0
  109. package/src/hosted/usage-routes.js +375 -0
  110. package/src/hosted/usage-shape.js +256 -0
  111. package/src/hosted/usage.js +641 -0
  112. package/src/remote/agent-connect.js +37 -1
  113. package/src/remote/agent-link.js +2 -0
  114. package/src/remote/login.js +33 -8
  115. package/src/remote/share.js +1 -1
  116. package/src/remote/tailnet-cli.js +547 -0
  117. package/src/server/app.js +15 -0
  118. package/src/server/pairing-routes.js +34 -5
  119. package/src/server/tailscale.js +97 -4
  120. package/src/tailnet-proof.js +766 -0
  121. package/dist/client/assets/index-Cxz1UVcV.css +0 -2
  122. package/dist/client/assets/index-uUZVBYUS.js +0 -37
  123. package/dist/console/assets/LocalAccountsApp-DIdy1KnN.js +0 -1
  124. package/dist/console/assets/LocalConsole-DfcQztF-.js +0 -1
  125. package/dist/console/assets/app-update-dialog-ttl9lF5A.js +0 -1
  126. package/dist/console/assets/console-OqAjD0kV.js +0 -55
  127. package/dist/console/assets/console-kvjrAArQ.css +0 -2
@@ -0,0 +1,724 @@
1
+ // The layout of the Usage dashboard, as plain values with no imports beyond
2
+ // the usage shape: the widgets there are, what each may be sized to and
3
+ // which options it takes, and every change a person can make to a layout
4
+ // (move, resize, hide, add, duplicate, reorder, reset). The server
5
+ // (usage.js), the console and the public demo all go through this file, so
6
+ // a stored layout is checked the same way wherever it is read or written.
7
+ //
8
+ // A layout is { v, items }: one item per widget on a grid of 12 columns,
9
+ // { id, type, x, y, w, h, options }. Rows are a fixed height; a widget is
10
+ // `h` rows tall. The widgets' order and sizes are the layout: their places
11
+ // follow by flowing them into the grid (flow), so nothing overlaps, nothing
12
+ // floats, and a change never leaves a hole the widgets after it fit.
13
+ // Narrower screens show the same layout reflowed to fewer columns (reflow),
14
+ // never a second stored layout.
15
+ //
16
+ // A list, a breakdown and the budgets are as tall as what they hold (so many
17
+ // rows, so many projects) until someone sizes them by hand: such an item
18
+ // carries `auto: true`, and fitLayout gives it its height.
19
+ //
20
+ // Nothing here trusts what it is given. cleanLayout drops any item whose
21
+ // type is unknown or whose size or place is out of range, and any option
22
+ // that is not one of the listed values; what is left is safe to draw.
23
+
24
+ import { USAGE_BUCKETS, USAGE_DIMENSIONS, USAGE_METRICS } from './usage-shape.js'
25
+
26
+ export const LAYOUT_VERSION = 1
27
+ export const LAYOUT_COLS = 12
28
+ export const LAYOUT_LIMITS = {
29
+ // The stored JSON, in characters.
30
+ bytes: 16_000,
31
+ // Widgets on one dashboard.
32
+ items: 40,
33
+ // Copies of one chart.
34
+ copies: 4,
35
+ // The lowest row a widget may start on.
36
+ rows: 400,
37
+ }
38
+ // The grid in pixels: a row's height and the gap between widgets.
39
+ export const LAYOUT_ROW = 56
40
+ export const LAYOUT_GAP = 16
41
+ // Columns by the width of the dashboard itself: 12 on a desktop or a
42
+ // tablet held sideways, 6 on a narrow window, 2 on a phone (tiles side by
43
+ // side, everything else one under the other).
44
+ export const LAYOUT_MODES = [
45
+ { cols: 12, min: 840 },
46
+ { cols: 6, min: 560 },
47
+ { cols: 2, min: 0 },
48
+ ]
49
+ export const colsFor = (width) => LAYOUT_MODES.find((mode) => width >= mode.min).cols
50
+
51
+ const clamp = (value, low, high) => Math.min(Math.max(value, low), high)
52
+ const bool = (fallback) => ({ kind: 'bool', fallback })
53
+ const pick = (values, fallback) => ({ kind: 'enum', values, fallback })
54
+ const some = (values, fallback) => ({ kind: 'set', values, fallback })
55
+
56
+ // (`oldMinW`: the least a stored layout may still hold from before the least
57
+ // was raised; it reads as the least there is now.)
58
+ const TILE = { w: 4, h: 2, minW: 3, oldMinW: 2, maxW: 4, minH: 2, maxH: 2 }
59
+ const CHART = { w: 6, h: 5, minW: 4, maxW: 12, minH: 4, maxH: 8 }
60
+ const LIST = { w: 3, h: 4, minW: 3, maxW: 6, minH: 3, maxH: 9 }
61
+ const VIEW = pick(['chart', 'table'], 'chart')
62
+ const tile = (title, spark) => ({
63
+ title,
64
+ group: 'tile',
65
+ size: TILE,
66
+ options: { ...(spark === null ? {} : { spark: bool(spark) }), compare: bool(true) },
67
+ })
68
+ // `auto(options, facts)`: the rows a widget needs for what it holds.
69
+ const list = (title) => ({
70
+ title,
71
+ group: 'list',
72
+ size: LIST,
73
+ options: { rows: pick([3, 5, 10], 5) },
74
+ auto: (options) => ({ 3: 3, 5: 4, 10: 7 })[options.rows],
75
+ })
76
+
77
+ export const TIME_STYLES = ['stacked', 'grouped', 'lines']
78
+ export const PERCENTILES = ['p50', 'p90', 'p95', 'p99']
79
+ // Every widget type. `many`: a chart that may be on the dashboard more than
80
+ // once, each copy with its own options. `admin`: drawn for admins and
81
+ // owners only.
82
+ export const WIDGETS = {
83
+ tile_calls: tile('Turns', true),
84
+ tile_tokens: tile('Tokens', false),
85
+ tile_duration: tile('Agent time', false),
86
+ tile_cost: tile('Reported cost', false),
87
+ tile_fixes: tile('Fixes ready', null),
88
+ tile_failed: tile('Failed or stopped', false),
89
+ time: {
90
+ title: 'Usage over time',
91
+ group: 'chart',
92
+ many: true,
93
+ size: { w: 12, h: 6, minW: 4, maxW: 12, minH: 4, maxH: 10 },
94
+ options: {
95
+ metric: pick(USAGE_METRICS, 'calls'),
96
+ by: pick([...USAGE_DIMENSIONS, 'none'], 'agent'),
97
+ // "auto": the bucket that suits the period.
98
+ bucket: pick(['auto', ...USAGE_BUCKETS], 'auto'),
99
+ style: pick(TIME_STYLES, 'stacked'),
100
+ legend: bool(true),
101
+ brush: bool(true),
102
+ view: VIEW,
103
+ },
104
+ },
105
+ breakdown: {
106
+ title: 'Breakdown',
107
+ group: 'chart',
108
+ many: true,
109
+ size: { w: 6, h: 5, minW: 3, maxW: 12, minH: 3, maxH: 10 },
110
+ options: {
111
+ by: pick(USAGE_DIMENSIONS, 'project'),
112
+ // "chart": the measure of the first "over time" chart.
113
+ metric: pick(['chart', ...USAGE_METRICS], 'chart'),
114
+ rows: pick([5, 8, 12, 20], 8),
115
+ share: bool(true),
116
+ view: VIEW,
117
+ },
118
+ auto: (options) => ({ 5: 4, 8: 5, 12: 7, 20: 10 })[options.rows],
119
+ },
120
+ outcomes: {
121
+ title: 'How turns ended',
122
+ group: 'chart',
123
+ many: true,
124
+ size: CHART,
125
+ options: { mode: pick(['share', 'counts'], 'share'), view: VIEW },
126
+ },
127
+ approvals: {
128
+ title: 'Approvals',
129
+ group: 'chart',
130
+ many: true,
131
+ size: CHART,
132
+ options: { mode: pick(['stacked', 'separate'], 'stacked'), view: VIEW },
133
+ },
134
+ latency: {
135
+ title: 'Turn duration',
136
+ group: 'chart',
137
+ many: true,
138
+ size: CHART,
139
+ options: { percentiles: some(PERCENTILES, ['p50', 'p95']), log: bool(false), view: VIEW },
140
+ },
141
+ top_agents: list('Busiest agents'),
142
+ top_threads: list('Threads that used the most tokens'),
143
+ top_slowest: list('Slowest turns'),
144
+ top_denied: list('Most denied approvals'),
145
+ budgets: {
146
+ title: 'Budgets today',
147
+ group: 'budgets',
148
+ admin: true,
149
+ size: { w: 12, h: 4, minW: 4, maxW: 12, minH: 3, maxH: 10 },
150
+ options: {},
151
+ // A row per project under the heading; from six projects on the list scrolls.
152
+ auto: (_options, facts) =>
153
+ Number.isInteger(facts?.budgets) ? clamp(Math.ceil((89 + Math.max(facts.budgets, 1) * 65) / 72), 3, 6) : null,
154
+ },
155
+ }
156
+ export const WIDGET_TYPES = Object.keys(WIDGETS)
157
+ const known = (type) => typeof type === 'string' && Object.hasOwn(WIDGETS, type)
158
+ const ID = /^[a-z][a-z0-9_]{0,23}(?:-[1-9][0-9]?)?$/
159
+
160
+ export class LayoutError extends Error {
161
+ constructor(code, message) {
162
+ super(message)
163
+ this.code = code
164
+ }
165
+ }
166
+
167
+ // ---- Options ----
168
+
169
+ // A widget's options with every key present: what was stored where it is
170
+ // one of the listed values, the default where it is not. Unknown keys go.
171
+ export function cleanOptions(type, given) {
172
+ const out = {}
173
+ if (!known(type)) return out
174
+ const source = given && typeof given === 'object' && !Array.isArray(given) ? given : {}
175
+ for (const [key, spec] of Object.entries(WIDGETS[type].options)) {
176
+ const value = Object.hasOwn(source, key) ? source[key] : undefined
177
+ if (spec.kind === 'bool') out[key] = typeof value === 'boolean' ? value : spec.fallback
178
+ else if (spec.kind === 'enum') out[key] = spec.values.includes(value) ? value : spec.fallback
179
+ else {
180
+ // A set: listed values only, in the listed order, never empty.
181
+ const chosen = Array.isArray(value) ? spec.values.filter((item) => value.includes(item)) : []
182
+ out[key] = chosen.length ? chosen : [...spec.fallback]
183
+ }
184
+ }
185
+ return out
186
+ }
187
+
188
+ // ---- Geometry ----
189
+
190
+ const whole = (value) => Number.isInteger(value)
191
+ export const collides = (a, b) => a.id !== b.id && a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
192
+ const byPlace = (a, b) => a.y - b.y || a.x - b.x || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
193
+ const firstHit = (placed, item) => placed.find((other) => collides(other, item))
194
+ // The widgets from the top left, row by row: the order a narrow screen, a
195
+ // printed page and a screen reader take them in.
196
+ export const readingOrder = (items) => [...items].sort(byPlace)
197
+
198
+ // The widgets flowed into the grid in the order given, like words on a
199
+ // page: each goes to the first place after the one before it (row by row
200
+ // from the top, left to right) where it fits. So nothing overlaps, nothing
201
+ // floats, and a widget that is hidden, moved or resized never leaves a hole
202
+ // that the widgets after it fit: they close up. The order is the layout;
203
+ // the places follow from it, so flowing a flowed layout changes nothing.
204
+ export function flow(items, cols = LAYOUT_COLS) {
205
+ const placed = []
206
+ let from = { x: 0, y: 0 }
207
+ for (const given of items) {
208
+ const w = Math.min(given.w, cols)
209
+ let spot = null
210
+ for (let y = from.y; !spot; y += 1)
211
+ for (let x = y === from.y ? from.x : 0; x + w <= cols && !spot; x += 1) {
212
+ const at = { ...given, w, x, y }
213
+ if (!firstHit(placed, at)) spot = at
214
+ }
215
+ placed.push(spot)
216
+ // The next one starts after this one (on its row, to its right).
217
+ from = { x: spot.x + 1, y: spot.y }
218
+ }
219
+ return placed
220
+ }
221
+ // A layout's items tidied: flowed in their reading order. (A tidy layout
222
+ // comes out as it went in, so what is stored reads back the same.)
223
+ export const compact = (items, cols = LAYOUT_COLS) => flow(readingOrder(items), cols)
224
+
225
+ // Where a widget dragged to a point of the grid (in columns and rows, the
226
+ // pointer's place) goes in the order: in front of the widget under the
227
+ // point when it is dragged back, after it when it is dragged on; over empty
228
+ // space, after every widget that starts before that place. Returns the id
229
+ // of the widget it goes in front of (null: last). `items`: the widgets
230
+ // where they are drawn.
231
+ export function dropBefore(items, id, px, py) {
232
+ const order = readingOrder(items)
233
+ const self = order.find((item) => item.id === id)
234
+ if (!self) return null
235
+ const others = order.filter((item) => item.id !== id)
236
+ const under = others.find((item) => px >= item.x && px < item.x + item.w && py >= item.y && py < item.y + item.h)
237
+ if (under) {
238
+ const on = order.indexOf(under) > order.indexOf(self)
239
+ return on ? (others[others.indexOf(under) + 1]?.id ?? null) : under.id
240
+ }
241
+ const x = Math.floor(px)
242
+ const y = Math.floor(py)
243
+ return others.find((item) => item.y > y || (item.y === y && item.x > x))?.id ?? null
244
+ }
245
+
246
+ const sizeOf = (type) => WIDGETS[type].size
247
+ // A size inside what the widget's type allows, and inside the grid.
248
+ export function fitSize(type, w, h, x = 0) {
249
+ const size = sizeOf(type)
250
+ return { w: clamp(w, size.minW, Math.min(size.maxW, LAYOUT_COLS - x)), h: clamp(h, size.minH, size.maxH) }
251
+ }
252
+
253
+ // ---- Reading a stored layout ----
254
+
255
+ // Older shapes of a stored layout, brought to the current one. Before a
256
+ // layout carried a version it was a bare list of grid items keyed `i`.
257
+ // A version this build does not know reads as no layout at all.
258
+ export function migrateLayout(stored) {
259
+ if (Array.isArray(stored))
260
+ return {
261
+ v: LAYOUT_VERSION,
262
+ items: stored.map((item) =>
263
+ item && typeof item === 'object'
264
+ ? {
265
+ id: item.i,
266
+ type: typeof item.i === 'string' ? item.i.replace(/-[0-9]+$/, '') : undefined,
267
+ x: item.x,
268
+ y: item.y,
269
+ w: item.w,
270
+ h: item.h,
271
+ options: item.options,
272
+ }
273
+ : item,
274
+ ),
275
+ }
276
+ if (!stored || typeof stored !== 'object') return null
277
+ if (stored.v !== LAYOUT_VERSION) return null
278
+ return stored
279
+ }
280
+
281
+ function cleanItem(given, seen, counts) {
282
+ if (!given || typeof given !== 'object' || Array.isArray(given)) return null
283
+ const { id, type, x, y, w, h } = given
284
+ if (!known(type) || typeof id !== 'string' || !ID.test(id) || seen.has(id)) return null
285
+ const size = sizeOf(type)
286
+ if (![x, y, w, h].every(whole)) return null
287
+ if (w < (size.oldMinW ?? size.minW) || w > size.maxW || h < size.minH || h > size.maxH) return null
288
+ if (x < 0 || x + w > LAYOUT_COLS || y < 0 || y > LAYOUT_LIMITS.rows) return null
289
+ const count = counts.get(type) || 0
290
+ if (count >= (WIDGETS[type].many ? LAYOUT_LIMITS.copies : 1)) return null
291
+ counts.set(type, count + 1)
292
+ seen.add(id)
293
+ const item = { id, type, x, y, w: Math.max(w, size.minW), h, options: cleanOptions(type, given.options) }
294
+ // Whether its height still follows what it holds. A layout stored before this was kept: it does while it has the default height.
295
+ if (WIDGETS[type].auto) item.auto = typeof given.auto === 'boolean' ? given.auto : h === size.h
296
+ return item
297
+ }
298
+
299
+ // A layout as it may be stored and drawn, from anything at all. Throws a
300
+ // LayoutError for something that is not a layout (or is too large to be
301
+ // one); drops the items and options it does not know.
302
+ export function cleanLayout(given) {
303
+ let size
304
+ try {
305
+ size = JSON.stringify(given)?.length ?? 0
306
+ } catch {
307
+ throw new LayoutError('invalid_layout', 'layout: an object with its widgets.')
308
+ }
309
+ if (size > LAYOUT_LIMITS.bytes) throw new LayoutError('layout_too_large', `A layout holds at most ${LAYOUT_LIMITS.bytes} characters.`)
310
+ const layout = migrateLayout(given)
311
+ if (!layout || !Array.isArray(layout.items)) throw new LayoutError('invalid_layout', 'layout: { v, items } as the page saves it.')
312
+ const seen = new Set()
313
+ const counts = new Map()
314
+ const items = []
315
+ for (const item of layout.items) {
316
+ if (items.length >= LAYOUT_LIMITS.items) break
317
+ const clean = cleanItem(item, seen, counts)
318
+ if (clean) items.push(clean)
319
+ }
320
+ return { v: LAYOUT_VERSION, items: compact(items) }
321
+ }
322
+ // The same, for a reader: anything that is not a layout reads as none.
323
+ export function readLayout(given) {
324
+ try {
325
+ return given === null || given === undefined ? null : cleanLayout(given)
326
+ } catch {
327
+ return null
328
+ }
329
+ }
330
+
331
+ // ---- The default ----
332
+
333
+ const at = (type, x, y, extra = {}) => ({
334
+ id: type,
335
+ type,
336
+ x,
337
+ y,
338
+ w: sizeOf(type).w,
339
+ h: sizeOf(type).h,
340
+ options: cleanOptions(type, {}),
341
+ ...(WIDGETS[type].auto ? { auto: true } : {}),
342
+ ...extra,
343
+ })
344
+ // The dashboard as it is before anyone changes it: six tiles, usage over
345
+ // time, four charts in pairs, the top lists, the budgets.
346
+ export function defaultLayout() {
347
+ return {
348
+ v: LAYOUT_VERSION,
349
+ items: [
350
+ at('tile_calls', 0, 0),
351
+ at('tile_tokens', 4, 0),
352
+ at('tile_duration', 8, 0),
353
+ at('tile_cost', 0, 2),
354
+ at('tile_fixes', 4, 2),
355
+ at('tile_failed', 8, 2),
356
+ at('time', 0, 4),
357
+ at('breakdown', 0, 10),
358
+ at('outcomes', 6, 10),
359
+ at('approvals', 0, 15),
360
+ at('latency', 6, 15),
361
+ at('top_agents', 0, 20),
362
+ at('top_threads', 3, 20),
363
+ at('top_slowest', 6, 20),
364
+ at('top_denied', 9, 20),
365
+ at('budgets', 0, 24),
366
+ ],
367
+ }
368
+ }
369
+ export const sameLayout = (a, b) => JSON.stringify(a) === JSON.stringify(b)
370
+
371
+ // What a reader may see of a layout: the admin-only widgets leave (and the
372
+ // rest close up) for everyone else.
373
+ export function visibleItems(layout, { admin = false } = {}) {
374
+ const items = layout.items.filter((item) => admin || !WIDGETS[item.type].admin)
375
+ return items.length === layout.items.length ? layout.items : compact(items)
376
+ }
377
+
378
+ // The layout with every widget whose height follows its content at the
379
+ // height that content needs now. `facts`: what only the page knows
380
+ // ({ budgets: how many projects have budgets }); a height that cannot be
381
+ // worked out yet stays as stored. The same layout when nothing changes.
382
+ export function fitLayout(layout, facts = {}) {
383
+ let changed = false
384
+ const items = layout.items.map((item) => {
385
+ if (!item.auto) return item
386
+ const wanted = WIDGETS[item.type].auto(item.options, facts)
387
+ const size = sizeOf(item.type)
388
+ const h = Number.isInteger(wanted) ? clamp(wanted, size.minH, size.maxH) : item.h
389
+ if (h === item.h) return item
390
+ changed = true
391
+ return { ...item, h }
392
+ })
393
+ return changed ? { v: LAYOUT_VERSION, items: compact(items) } : layout
394
+ }
395
+
396
+ // ---- Changes ----
397
+
398
+ const withItems = (layout, items) => ({ v: LAYOUT_VERSION, items })
399
+ const find = (layout, id) => layout.items.find((item) => item.id === id)
400
+
401
+ // Puts a widget in front of another in the order (null: last); everything
402
+ // flows again from there.
403
+ export function placeBefore(layout, id, before) {
404
+ const order = readingOrder(layout.items)
405
+ const item = order.find((other) => other.id === id)
406
+ if (!item || before === id) return layout
407
+ const rest = order.filter((other) => other.id !== id)
408
+ const at = before === null ? rest.length : rest.findIndex((other) => other.id === before)
409
+ if (at < 0) return layout
410
+ rest.splice(at, 0, item)
411
+ const items = flow(rest)
412
+ return sameLayout(items, layout.items) ? layout : withItems(layout, items)
413
+ }
414
+ // A widget dragged by its top left corner to a column and a row: it goes
415
+ // where dropBefore says for that corner.
416
+ export function moveItem(layout, id, x, y) {
417
+ return find(layout, id) ? placeBefore(layout, id, dropBefore(layout.items, id, x + 0.5, y + 0.5)) : layout
418
+ }
419
+ // Sizes a widget, inside what its type allows; the ones after it flow again.
420
+ export function resizeItem(layout, id, w, h) {
421
+ const item = find(layout, id)
422
+ if (!item) return layout
423
+ // (Never past the right edge from where it is: a corner dragged there stops there.)
424
+ const next = { ...item, ...fitSize(item.type, Math.round(w), Math.round(h), item.x) }
425
+ if (next.w === item.w && next.h === item.h) return layout
426
+ // A height set by hand stays as it was set.
427
+ if (item.auto && next.h !== item.h) next.auto = false
428
+ const changed = new Map([[id, next]])
429
+ // A row stays whole: the widget just to its right gives or takes the width
430
+ // (when its own sizes allow), and the widgets beside it that were as tall
431
+ // take the new height, so a resize never opens a hole beside or under it.
432
+ const row = layout.items.filter((other) => other.id !== id && other.y === item.y)
433
+ const dw = next.w - item.w
434
+ // The tiles are one row of numbers: they share one width (three or four to a row).
435
+ const tile = WIDGETS[item.type]?.group === 'tile'
436
+ if (dw && tile)
437
+ for (const other of layout.items)
438
+ if (other.id !== id && WIDGETS[other.type]?.group === 'tile') changed.set(other.id, { ...other, w: next.w })
439
+ const right = dw && !tile ? row.find((other) => other.x === item.x + item.w) : null
440
+ // The last of a full row made narrower: the one to its left takes the width (else the row would be drawn across again
441
+ // and the widget would look stuck at its width).
442
+ const left = dw < 0 && !tile && !right && item.x + item.w === LAYOUT_COLS ? row.find((other) => other.x + other.w === item.x) : null
443
+ for (const other of [right, left]) {
444
+ if (!other) continue
445
+ const size = sizeOf(other.type)
446
+ const w2 = other.w - dw
447
+ if (w2 >= size.minW && w2 <= size.maxW) changed.set(other.id, { ...other, w: w2 })
448
+ }
449
+ let items = flow(readingOrder(layout.items).map((other) => changed.get(other.id) ?? other))
450
+ if (next.h !== item.h) {
451
+ // (Beside it once it has its new width: a neighbour that went on to the next row keeps its height.)
452
+ const placed = items.find((other) => other.id === id)
453
+ const beside = (other) => {
454
+ const size = sizeOf(other.type)
455
+ // (A widget as tall as what it holds keeps its own height: only the ones sized like it follow.)
456
+ return other.id !== id && !other.auto && other.y === placed.y && other.h === item.h && next.h >= size.minH && next.h <= size.maxH
457
+ }
458
+ if (items.some(beside))
459
+ items = flow(items.map((other) => (beside(other) ? { ...other, h: next.h, ...(other.auto ? { auto: false } : {}) } : other)))
460
+ }
461
+ return withItems(layout, items)
462
+ }
463
+ const overlapsColumns = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w
464
+ // One step with an arrow key. Left and right: one place back or on in the
465
+ // order (beside it, they change places). Up and down: in front of the
466
+ // widget above it, or after the widget below it.
467
+ export function stepMove(layout, id, direction) {
468
+ const order = readingOrder(layout.items)
469
+ const at = order.findIndex((other) => other.id === id)
470
+ if (at < 0) return layout
471
+ const item = order[at]
472
+ if (direction === 'left') return at > 0 ? placeBefore(layout, id, order[at - 1].id) : layout
473
+ if (direction === 'right') return at < order.length - 1 ? placeBefore(layout, id, order[at + 2]?.id ?? null) : layout
474
+ const others = order.filter((other) => other.id !== id && overlapsColumns(other, item))
475
+ const other =
476
+ direction === 'up'
477
+ ? others.filter((one) => one.y + one.h <= item.y).sort((a, b) => b.y + b.h - (a.y + a.h) || a.x - b.x)[0]
478
+ : others.filter((one) => one.y >= item.y + item.h).sort((a, b) => a.y - b.y || a.x - b.x)[0]
479
+ if (!other) return layout
480
+ // The two change places in the order.
481
+ const swapped = [...order]
482
+ swapped[at] = other
483
+ swapped[order.indexOf(other)] = item
484
+ return withItems(layout, flow(swapped))
485
+ }
486
+ // One step with Shift and an arrow key: a column wider or narrower, a row
487
+ // taller or shorter.
488
+ export function stepResize(layout, id, direction) {
489
+ const item = find(layout, id)
490
+ if (!item) return layout
491
+ const dw = direction === 'right' ? 1 : direction === 'left' ? -1 : 0
492
+ const dh = direction === 'down' ? 1 : direction === 'up' ? -1 : 0
493
+ return resizeItem(layout, id, item.w + dw, item.h + dh)
494
+ }
495
+
496
+ export function setOptions(layout, id, changes) {
497
+ return withItems(
498
+ layout,
499
+ layout.items.map((item) => (item.id === id ? { ...item, options: cleanOptions(item.type, { ...item.options, ...changes }) } : item)),
500
+ )
501
+ }
502
+ export const removeItem = (layout, id) => withItems(layout, compact(layout.items.filter((item) => item.id !== id)))
503
+ const bottomOf = (items) => items.reduce((low, item) => Math.max(low, item.y + item.h), 0)
504
+ function freeId(layout, type) {
505
+ if (!find(layout, type)) return type
506
+ for (let n = 2; n < 100; n += 1) if (!find(layout, `${type}-${n}`)) return `${type}-${n}`
507
+ return null
508
+ }
509
+ // How many more of a type the dashboard takes.
510
+ export function roomFor(layout, type) {
511
+ if (!known(type) || layout.items.length >= LAYOUT_LIMITS.items) return 0
512
+ const have = layout.items.filter((item) => item.type === type).length
513
+ return Math.max(0, (WIDGETS[type].many ? LAYOUT_LIMITS.copies : 1) - have)
514
+ }
515
+ // The types not on the dashboard: what "Add widget" lists.
516
+ export const hiddenTypes = (layout, { admin = false } = {}) =>
517
+ WIDGET_TYPES.filter((type) => (admin || !WIDGETS[type].admin) && !layout.items.some((item) => item.type === type))
518
+
519
+ // Adds a widget at its default size, after the last one (`before`: in
520
+ // front of that widget instead). Returns { layout, id } (the same layout
521
+ // and no id when there is no room for one).
522
+ export function addItem(layout, type, options = {}, { before = null } = {}) {
523
+ const id = roomFor(layout, type) ? freeId(layout, type) : null
524
+ if (!id) return { layout, id: null }
525
+ const item = { ...at(type, 0, bottomOf(layout.items)), id, options: cleanOptions(type, options) }
526
+ const order = readingOrder(layout.items)
527
+ const index = before === null ? -1 : order.findIndex((other) => other.id === before)
528
+ order.splice(index < 0 ? order.length : index, 0, item)
529
+ return { layout: withItems(layout, flow(order)), id }
530
+ }
531
+ // A second copy of a chart, with the same options, right after the first:
532
+ // beside it where there is room, under it where there is not.
533
+ export function duplicateItem(layout, id) {
534
+ const item = find(layout, id)
535
+ if (!item || !WIDGETS[item.type].many || !roomFor(layout, item.type)) return { layout, id: null }
536
+ const copy = { ...item, id: freeId(layout, item.type), options: cleanOptions(item.type, item.options) }
537
+ const order = readingOrder(layout.items)
538
+ order.splice(order.indexOf(item) + 1, 0, copy)
539
+ return { layout: withItems(layout, flow(order)), id: copy.id }
540
+ }
541
+
542
+ // ---- Narrower screens ----
543
+
544
+ // How wide a widget is on a grid of fewer columns.
545
+ function narrowWidth(item, cols) {
546
+ if (cols >= LAYOUT_COLS) return item.w
547
+ const group = WIDGETS[item.type].group
548
+ if (cols === 2) return group === 'tile' ? 1 : 2
549
+ const least = group === 'tile' ? 2 : group === 'list' ? 3 : cols
550
+ return clamp(Math.round((item.w * cols) / LAYOUT_COLS), least, cols)
551
+ }
552
+ // The layout on a grid of `cols` columns: the same widgets in reading
553
+ // order, at the widths that grid allows. 12 columns: the layout itself.
554
+ export function reflow(items, cols = LAYOUT_COLS) {
555
+ if (cols >= LAYOUT_COLS) return items
556
+ return flow(
557
+ readingOrder(items).map((item) => ({ ...item, w: narrowWidth(item, cols) })),
558
+ cols,
559
+ )
560
+ }
561
+
562
+ // The layout as it is drawn: a row that stops short of the right edge, with
563
+ // nothing that could fill the rest, shares the rest among its widgets (the
564
+ // ones that end the row and are as tall as its last). Only the drawing:
565
+ // what is stored keeps its own widths, so a widget added back or moved finds
566
+ // the room it had.
567
+ export function fill(items, cols = LAYOUT_COLS) {
568
+ const out = items.map((item) => ({ ...item }))
569
+ const taken = (c, top, bottom, skip) =>
570
+ out.some((other) => !skip.has(other) && other.x <= c && c < other.x + other.w && other.y < bottom && top < other.y + other.h)
571
+ for (const y of [...new Set(out.map((item) => item.y))].sort((a, b) => a - b)) {
572
+ const row = out.filter((item) => item.y === y).sort((a, b) => a.x - b.x)
573
+ const last = row[row.length - 1]
574
+ // The run of widgets side by side that ends the row, all as tall as the last.
575
+ const run = [last]
576
+ for (let at = row.length - 2; at >= 0; at--) {
577
+ const one = row[at]
578
+ if (one.x + one.w !== run[0].x || one.h !== last.h) break
579
+ run.unshift(one)
580
+ }
581
+ const skip = new Set(run)
582
+ let spare = 0
583
+ while (last.x + last.w + spare < cols && !taken(last.x + last.w + spare, y, y + last.h, skip)) spare++
584
+ if (!spare) continue
585
+ let x = run[0].x
586
+ run.forEach((item, index) => {
587
+ item.w += Math.floor(spare / run.length) + (index < spare % run.length ? 1 : 0)
588
+ item.x = x
589
+ x += item.w
590
+ })
591
+ }
592
+ return out
593
+ }
594
+
595
+ // ---- Drawn heights ----
596
+ //
597
+ // A widget as tall as what it holds (a list, a breakdown, the budgets, while
598
+ // nobody sized it by hand) is drawn at the height of its content, measured
599
+ // on the page, not at the rows it is stored with: a breakdown of two
600
+ // projects is no taller than two rows of bars. So the grid is drawn on finer
601
+ // rows, LAYOUT_SUB to a row: a stored height of h is drawn h * LAYOUT_SUB
602
+ // fine rows tall, the same pixels as ever.
603
+ export const LAYOUT_SUB = 4
604
+ // A fine row's pitch in pixels (one fine row and the gap after it), and the
605
+ // height a fine row is given to the grid so that h fine rows and the gaps
606
+ // between them come to the same pixels as a stored row.
607
+ export const LAYOUT_SUB_PITCH = (LAYOUT_ROW + LAYOUT_GAP) / LAYOUT_SUB
608
+ export const LAYOUT_SUB_ROW = LAYOUT_SUB_PITCH - LAYOUT_GAP
609
+ // The fine rows a widget whose card is `px` tall takes (never fewer than a heading needs).
610
+ export const subRowsFor = (px) => Math.max(6, Math.ceil((px + LAYOUT_GAP) / LAYOUT_SUB_PITCH))
611
+ // Whether a widget is drawn at the height of its content.
612
+ export const fitsContent = (item) => Boolean(item.auto && WIDGETS[item.type]?.auto)
613
+
614
+ // The widgets as drawn, in fine rows: each at its own height (`fitted`:
615
+ // { id: fine rows } for the widgets that are as tall as their content; the
616
+ // rest at their stored height). The stored layout is taken a band at a time
617
+ // (rows no widget reaches across, grouped as below: the tiles, the charts in
618
+ // pairs, the top lists, the budgets): in a band the widgets flow in
619
+ // reading order as the stored layout does, so a widget under a shorter one
620
+ // moves up into the room it leaves, and a chart that ends a column short of
621
+ // the band's bottom reaches down to it. A widget as tall as its content that
622
+ // still ends short of the band, with nothing that fits under it, reaches down
623
+ // last, so a band never leaves a hole and always ends on one line (a Top 5
624
+ // beside a Top 10 is as tall as it, its rows at its top). Bands stay in line
625
+ // with each other, so a row of lists keeps one top edge, and the lists side
626
+ // by side in a row, set to the same number of rows, are as tall as the
627
+ // tallest of them.
628
+ export function settle(items, cols = LAYOUT_COLS, fitted = {}) {
629
+ const order = readingOrder(items)
630
+ // (Never taller than the rows it is given for what it holds: past those it scrolls, as it always has.)
631
+ const own = (item) => (fitsContent(item) && Number.isInteger(fitted[item.id]) ? Math.min(fitted[item.id], item.h * LAYOUT_SUB) : null)
632
+ const heights = new Map(order.map((item) => [item.id, own(item) ?? item.h * LAYOUT_SUB]))
633
+ for (const item of order) {
634
+ if (WIDGETS[item.type].group !== 'list' || own(item) === null) continue
635
+ const run = order.filter(
636
+ (other) => other.y === item.y && other.h === item.h && WIDGETS[other.type].group === 'list' && own(other) !== null,
637
+ )
638
+ heights.set(item.id, Math.max(...run.map((other) => own(other))))
639
+ }
640
+ // Rows: the runs no widget reaches across. A row joins the band above it when it is split into the same columns
641
+ // (charts in pairs, row after row, are two columns), or when it holds charts only: they can take up what the
642
+ // band above leaves uneven.
643
+ const rows = []
644
+ let bottom = -1
645
+ for (const item of order) {
646
+ if (item.y >= bottom) rows.push([])
647
+ rows[rows.length - 1].push(item)
648
+ bottom = Math.max(bottom, item.y + item.h)
649
+ }
650
+ const stretches = (item) => WIDGETS[item.type].group === 'chart' && !WIDGETS[item.type].auto
651
+ const columnsOf = (row) => row.map((item) => `${item.x}:${item.w}`).join(' ')
652
+ const bands = []
653
+ rows.forEach((row, index) => {
654
+ if (index && (columnsOf(row) === columnsOf(rows[index - 1]) || row.every(stretches))) bands[bands.length - 1].push(...row)
655
+ else bands.push([...row])
656
+ })
657
+ const out = []
658
+ let top = 0
659
+ for (const band of bands) {
660
+ // The band drawn with its widgets as tall as their content, then (should that leave a hole no widget can
661
+ // reach into, as when the charts under a short widget are split into other columns than the row above)
662
+ // with one of them, or none, kept at its stored height: the first with the fewest empty cells wins.
663
+ const fits = band.filter((item) => heights.get(item.id) !== item.h * LAYOUT_SUB)
664
+ let best = null
665
+ for (const tall of [null, ...fits.map((item) => item.id), ...(fits.length > 1 ? ['*'] : [])]) {
666
+ const height = (item) => (tall === '*' || tall === item.id ? item.h * LAYOUT_SUB : heights.get(item.id))
667
+ const fitted = new Set(band.filter((item) => height(item) !== item.h * LAYOUT_SUB).map((item) => item.id))
668
+ const tried = settleBand(
669
+ band.map((item) => ({ ...item, h: height(item) })),
670
+ cols,
671
+ stretches,
672
+ fitted,
673
+ )
674
+ if (!best || tried.holes < best.holes) best = tried
675
+ if (!best.holes) break
676
+ }
677
+ for (const item of best.placed) out.push({ ...item, y: item.y + top })
678
+ top += best.end
679
+ }
680
+ return out
681
+ }
682
+
683
+ // One band of settle(): flowed, then every column reaches down to the band's end where nothing is under it.
684
+ // Returns the places, the band's end and how many cells of it are left empty. `fitted`: the ids drawn shorter
685
+ // than stored, at their content's height (a widget sized by hand keeps the height it was given).
686
+ function settleBand(items, cols, stretches, fitted) {
687
+ const placed = flow(items, cols)
688
+ const end = placed.reduce((low, item) => Math.max(low, item.y + item.h), 0)
689
+ const taken = (c, row, self) =>
690
+ placed.some((other) => other !== self && other.x <= c && c < other.x + other.w && other.y <= row && row < other.y + other.h)
691
+ const reach = (item) => {
692
+ const under = (other) => other !== item && other.y >= item.y + item.h && other.x < item.x + item.w && item.x < other.x + other.w
693
+ const below = Math.min(end, ...placed.filter(under).map((other) => other.y))
694
+ const free = (row) => !Array.from({ length: item.w }, (_, at) => item.x + at).some((c) => taken(c, row, item))
695
+ while (item.y + item.h < below && free(item.y + item.h)) item.h += 1
696
+ }
697
+ // The charts first (a plot can take the room). Then whatever still ends short of the band (a short list
698
+ // beside a longer one, a breakdown with nothing that fits under it) reaches down too, so no hole is left
699
+ // and the band ends on one line: its card ends there, what it holds stays at its top.
700
+ for (const item of placed) if (stretches(item)) reach(item)
701
+ for (const item of placed) if (!stretches(item) && fitted.has(item.id)) reach(item)
702
+ const used = new Set(placed.map((item) => item.x + item.w))
703
+ const right = Math.max(...used)
704
+ let holes = 0
705
+ for (let c = 0; c < right; c += 1) for (let row = 0; row < end; row += 1) if (!taken(c, row, null)) holes += 1
706
+ return { placed, end, holes }
707
+ }
708
+
709
+ // Moves a widget to a place in the reading order (what the up and down
710
+ // buttons of a narrow screen do, and a drag on fewer columns).
711
+ export function reorder(layout, id, index) {
712
+ const order = readingOrder(layout.items)
713
+ const from = order.findIndex((item) => item.id === id)
714
+ if (from < 0) return layout
715
+ const to = clamp(index, 0, order.length - 1)
716
+ if (to === from) return layout
717
+ const rest = order.filter((item) => item.id !== id)
718
+ return placeBefore(layout, id, rest[to]?.id ?? null)
719
+ }
720
+
721
+ // What a screen reader hears after a move or a resize.
722
+ export function describeItem(item) {
723
+ return `row ${item.y + 1}, column ${item.x + 1}; ${item.w} wide, ${item.h} tall`
724
+ }