dsh-project-mcp 0.2.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.
@@ -0,0 +1,4120 @@
1
+ /**
2
+ * Browser half of the panel: the tab shows one surface for the project of the
3
+ * session it is open in — the session's declared servers, the sessions that read
4
+ * differently from the project, what the model sees, and the problems and the
5
+ * event ring under their own disclosures — while the side card settings popup
6
+ * keeps the whole picture across every project with a live session. The native
7
+ * Settings page
8
+ * (`settings.section`, see `./settings.ts`) is the third surface and shares
9
+ * this module's fetch/poll path, status colours and storage helpers.
10
+ *
11
+ * Data comes from the host over `/project-mcp/*` (see `src/ui.ts`):
12
+ * `ctx.betterSidebar` exists only in the browser half, so there is nothing to
13
+ * call in process. The host half's types are imported type-only, which the
14
+ * bundler erases — the client bundle stays free of host code.
15
+ *
16
+ * @module dsh-project-mcp/client/view
17
+ */
18
+
19
+ import { createElement as h, useCallback, useEffect, useState } from 'react'
20
+ import type { CSSProperties, ReactNode } from 'react'
21
+ import { ROUTE_ACTIONS, ROUTE_PREFIX, TAB_ID } from '../shared.ts'
22
+ import type { LogEvent, McpSnapshot, ProjectSnapshot, ServerRow, ServerStatus, SessionTools, SnapshotChange, ToolMode, ToolPolicy } from '../types.ts'
23
+ import { hostTranslate, resolveHost } from './locales/host.ts'
24
+ import { operatorBody, pinBody, policyOf } from './policy.ts'
25
+ import { MCP_TOOL_PREFIX, idleOf, serverOfToolName, toolCalls } from './usage-view.ts'
26
+ import type { ProjectUsage, ToolCalls } from './usage-view.ts'
27
+
28
+ // The registry-name vocabulary is defined in `./usage-view.ts` — the counter
29
+ // reader, which must not import this module back — and re-exported here: the
30
+ // panel and every caller outside it (`settings-tools.ts`, the tests) have always
31
+ // read `MCP_TOOL_PREFIX` and `serverOfToolName` from this module.
32
+ export { MCP_TOOL_PREFIX, serverOfToolName, toolCalls }
33
+ export type { ToolCalls }
34
+
35
+ /**
36
+ * The panel's own English copy.
37
+ *
38
+ * The tab is created through the sidebar service rather than through a slot, so
39
+ * it carries its English table here and reaches the render functions through
40
+ * {@link Translate}; `./tab-locale.ts` binds that table to the shell's locale
41
+ * service and repaints the tab when the language changes. The settings page
42
+ * registers the same table with `ctx.locale.register` (see
43
+ * `./settings.ts`), which is why both halves share one namespace: one plugin,
44
+ * one dictionary.
45
+ */
46
+ export const en = {
47
+ // The tab itself: its label in the sidebar and the line under it.
48
+ tab: 'Project MCP',
49
+ tabDescription:
50
+ 'MCP servers each project declares, and what is mounted for its sessions',
51
+ sync: 'Sync',
52
+ retryFailed: 'Retry failed',
53
+ // Tool presentation: the tab's tools block and the settings page's Tools rows.
54
+ toolsSeeModel: 'what the model sees',
55
+ toolsPinned: 'pinned',
56
+ toolsByCounters: 'by the counters',
57
+ toolsDisclosed: 'disclosed',
58
+ toolsHidden: 'hidden',
59
+ toolsNotMounted: 'Nothing to hide yet',
60
+ toolsNotMountedHint:
61
+ 'lazy mounting: the project’s servers come up on the session’s first step, so the catalog is empty until then',
62
+ toolsNotMountedCode: 'tools[] = built-ins only · mcp__* not registered yet',
63
+ // The declared servers of this session, on the tools block: the reason an
64
+ // apparently empty catalog is empty.
65
+ toolsServers: 'Servers',
66
+ toolsServersUp: '{up}/{total} up',
67
+ toolsGroupPinned: 'pinned · always in the request',
68
+ toolsGroupCounters: 'offered by the counters',
69
+ toolsGroupDisclosed: 'disclosed by the model · until the session ends',
70
+ toolsGroupHidden: 'hidden',
71
+ toolsPin: 'Pin',
72
+ toolsPinHint: 'Keep this tool in every request of this project',
73
+ toolsUnpin: 'Unpin',
74
+ toolsUnpinHint: 'Stop pinning this tool in every request of this project',
75
+ toolsHide: 'Hide',
76
+ toolsHideHint: 'Drop this disclosure and stop offering the tool',
77
+ toolsHiddenVia: 'available to the model through mcp_search_tools only',
78
+ // The tools block's own filter (F-43): the counter chips above the list stop
79
+ // being a reading and become the tier switch, and a query narrows by name.
80
+ toolsFilterPlaceholder: 'filter by name…',
81
+ toolsFilterLabel: 'filter this session’s tools by registry name',
82
+ toolsFilterTier: 'Show this tier alone; press again for every tier',
83
+ toolsFilterClear: 'Clear',
84
+ toolsFilterClearHint: 'Show every tier and drop the query',
85
+ toolsFilterShown: 'showing {shown} of {total}',
86
+ toolsFilterNone: 'No tool of this session matches the filter.',
87
+ // The server-level pin (F-44): one press for a whole server's names, since a
88
+ // server is how the hidden tier and the settings page both group them.
89
+ toolsPinAll: 'Pin all',
90
+ toolsPinAllHint: 'Pin every hidden tool of this server in every request',
91
+ // The other direction of the same press, said by both surfaces when the set is
92
+ // already wholly pinned. A tier's names are usually unpinned, but the snapshot
93
+ // can hold a pin that is still listed as deferred — a pin written between two
94
+ // assemblies, or one the host itself defers — and a button that read `Pin all`
95
+ // while it released it would be a lie.
96
+ toolsUnpinAll: 'Unpin all',
97
+ toolsUnpinAllHint: 'Stop pinning every hidden tool of this server',
98
+ // The same press on the pinned tier, where the names it releases are the ones
99
+ // the user pinned rather than the ones the host hid.
100
+ toolsUnpinServerHint: 'Stop pinning every tool of this server',
101
+ toolsBudget: '{used} chars of {total} · ≈ {tokens} tokens',
102
+ toolsBudgetExhausted: 'the budget is spent: further disclosures are rejected with a reason',
103
+ toolsBudgetFree: 'free room in the budget or pin the tool in the project settings',
104
+ toolsBudgetGateOff: 'the disclosure gate is off: every mounted tool goes into the request',
105
+ toolsBudgetBreakdown: '{used} of {total} ({percent}%)',
106
+ toolsModeOff: 'this project’s MCP tools are switched off',
107
+ toolsModeOffCounters: '{mounted} mounted · none offered',
108
+ toolsModeOffHint:
109
+ 'Nothing from this project is offered to the model. Set the mode to “Disclosure” on the Tools page to offer them again.',
110
+ toolsModeDirect: 'nothing is deferred: every mounted tool goes into the request',
111
+ toolsPresentationOwner: 'Another plugin is shaping the request',
112
+ toolsOtherOwner: 'Another presentation owner',
113
+ toolsDemo: 'demo',
114
+ toolsStep: 'step {step}',
115
+ // The host's own usage counters (`ProjectSnapshot.usage`), read as two quiet
116
+ // labels: how often one tool was called, and how long one server has gone
117
+ // unused. Both are drawn only where the host published a record — no data, no
118
+ // label — so `never called` means "the server is in the counters and this tool
119
+ // is not", never "the host said nothing".
120
+ callsOne: '1 call',
121
+ callsMany: '{count} calls',
122
+ callsNone: 'never called',
123
+ callsProject: '{count} in the project',
124
+ idleDay: 'idle {count}d',
125
+ idleHour: 'idle {count}h',
126
+ idleMinute: 'idle {count}m',
127
+ // One tool row's detail block: the registry name it carries, the server the
128
+ // name was registered under, and the tier that offered it. The host publishes
129
+ // no size for a single tool, so the budget estimate stays in the group line
130
+ // above — nothing here is derived from it.
131
+ toolServer: 'server {server}',
132
+ toolTierPinned: 'pinned',
133
+ toolTierSession: 'via: session',
134
+ toolTierContext: 'via: context',
135
+ showTool: 'show this tool’s registry name and how it was offered',
136
+ hideTool: 'hide this tool’s registry name',
137
+ // The errors and logs blocks, under their own disclosures: the event ring is
138
+ // the plugin's own, one project at a time.
139
+ errorsSection: 'Problems',
140
+ showErrors: 'show the servers that need a look',
141
+ hideErrors: 'hide the servers that need a look',
142
+ logsSection: 'Logs',
143
+ showLogs: 'show this project’s events',
144
+ hideLogs: 'hide this project’s events',
145
+ logsThisSession: 'this session',
146
+ logsAllSessions: 'all sessions',
147
+ logsAllLevels: 'all levels',
148
+ logsErrorsOnly: 'errors',
149
+ logsLevelInfo: 'info',
150
+ logsLevelUp: 'up',
151
+ logsLevelWarn: 'warn',
152
+ logsLevelError: 'error',
153
+ logsClear: 'Clear',
154
+ logsClearHint: 'Hide every event recorded so far; new ones still appear',
155
+ logsEmptyTitle: 'No events yet',
156
+ logsEmptyHint:
157
+ 'This project’s servers come up on the session’s first step or when you press Sync; mounting, start and stop will show up here.',
158
+ logsNoErrorsTitle: 'No errors',
159
+ logsNoErrorsHint:
160
+ 'This project’s ring holds other events; switch the level filter to “all levels” to read them.',
161
+ logsMore: 'Show older',
162
+ logsMoreHint: 'Load the events older than the ones on screen',
163
+ logsShown: 'showing {shown} of {total}',
164
+ logsProjectCount: '{count} in this project',
165
+ logsLoading: 'loading older events…',
166
+ logsLoadFailed: 'older events could not be read',
167
+ // The tab's own states, in the same table for the same reason.
168
+ noSession: 'No session is attached to this tab.',
169
+ noSessionHint: 'The panel reads the project of the session it is open in.',
170
+ noProject: 'This session’s folder is not inside a project yet.',
171
+ noProjectHint:
172
+ 'The host walks up from the session cwd looking for .git · .dsh · .kimi-code · package.json · *.sln.',
173
+ nothingNeedsAttention: 'Nothing needs attention.',
174
+ noServersDeclared: 'This project declares no MCP servers.',
175
+ noServersDeclaredHint: 'Add {documents}.',
176
+ noServersDeclaredUnknown: 'Add an MCP document to the project.',
177
+ noServersDeclaredNowhere:
178
+ 'This deployment reads no project document, so there is nowhere to declare one — list one in the plugin config (`localFiles`).',
179
+ // Surface A's own header and the vocabulary its rows are built from. The
180
+ // segment bar is gone (F-26): the toolbar names the project and carries one
181
+ // phrase on its right edge, and every count a mode segment used to badge lives
182
+ // on the block it describes.
183
+ thisSession: 'this session',
184
+ noProjectLabel: 'no project',
185
+ retry: 'Retry',
186
+ retryHint: 'Retry this project’s failed mounts now',
187
+ sessionsSection: 'sessions',
188
+ // The `sessions` section is the project's *disagreement* view: its chip counts
189
+ // the sessions whose own reading differs from the merged rows, not the
190
+ // sessions that exist. The count of existing sessions lives on the toolbar's
191
+ // right edge, which keeps `sessionsOne` / `sessionsMany` for itself.
192
+ differsOne: '1 differs',
193
+ differsMany: '{count} differ',
194
+ sessionsOne: '1 session',
195
+ sessionsMany: '{count} sessions',
196
+ serversOne: '1 server',
197
+ serversMany: '{count} servers',
198
+ mergedAcrossSessions: 'merged across sessions',
199
+ release: 'Release',
200
+ nothingDeclared: 'nothing declared',
201
+ showSessions: 'show the sessions of this project',
202
+ hideSessions: 'hide the sessions of this project',
203
+ showSession: 'show this session’s servers',
204
+ hideSession: 'hide this session’s servers',
205
+ mountedPerProject: 'Mounted per project',
206
+ projectsCount: '{count} project(s)',
207
+ nothingMounted: 'Nothing is mounted yet.',
208
+ // The status vocabulary (F-47): the word a row wears and the one-line
209
+ // explanation its tooltip carries. Both are read through `STATUS_KEYS` /
210
+ // `STATUS_HINT` — `Record<ServerStatus, LocaleKey>` tables — so a new enum
211
+ // member without a key is a compile error, never a raw token on screen.
212
+ statusActive: 'active',
213
+ statusConnecting: 'connecting',
214
+ statusConflict: 'conflict',
215
+ statusError: 'error',
216
+ statusIdle: 'idle',
217
+ statusDisabled: 'disabled',
218
+ statusHintActive: 'mounted, its tools are visible in this session',
219
+ statusHintConnecting: 'mounted, no tool published yet',
220
+ statusHintIdle: 'declared but not mounted — mounts on the next turn',
221
+ statusHintDisabled: 'declared with enabled: false',
222
+ statusHintConflict: 'the same serverName is reserved by a profile-level instance',
223
+ statusHintError: 'see the detail',
224
+ // One project's or session's status line (`2 active, 1 idle`): one template
225
+ // per status, so the count is a `{count}` placeholder in every language and
226
+ // never a concatenation. `summarize` names no `disabled` count today; the
227
+ // template is here so the day it does, the word is too.
228
+ summaryActive: '{count} active',
229
+ summaryConnecting: '{count} connecting',
230
+ summaryIdle: '{count} idle',
231
+ summaryDisabled: '{count} disabled',
232
+ summaryError: '{count} error',
233
+ summaryConflict: '{count} conflict',
234
+ summaryNone: 'nothing declared',
235
+ close: 'Close',
236
+ // The frame-wide toasts (F-47): drafts carry these keys, and the stack
237
+ // resolves them at render, so a language switch repaints the banners on
238
+ // screen. The quieter line weaves the project around the fact behind the
239
+ // moment — the host's own detail sentence, or a status hint.
240
+ toastUp: '{server} is up',
241
+ toastFailed: '{server} failed',
242
+ toastReleased: '{server} released',
243
+ toastDetail: '{project} · {detail}',
244
+ // The sidebar plugin toggle: the poll interval's row in the tab's settings,
245
+ // read live through the seat on every render.
246
+ refreshTitle: 'Refresh interval',
247
+ refreshDesc: 'How often the panel re-reads the host snapshot',
248
+ // The design stand's own tab title and description (design.ts).
249
+ designTitle: 'Project MCP · design ({variant})',
250
+ designDesc: 'design mode: the {variant} fixture, no host behind it',
251
+ }
252
+
253
+ /** A dictionary key of this namespace. */
254
+ export type LocaleKey = keyof typeof en
255
+
256
+ /** Translate one key, with optional `{name}` template params (the DSH seat). */
257
+ export type Translate = (key: string, params?: Record<string, unknown>) => string
258
+
259
+ /**
260
+ * Bind the translate seat a surface was given, falling back to this module's own
261
+ * English dictionary when it renders outside a DSH shell (tests, or a browser
262
+ * half newer than the host).
263
+ * @param t - the injected `t` seat, when there is one.
264
+ * @returns a translate function that always answers.
265
+ */
266
+ export function translateOf(t?: Translate): Translate {
267
+ return t ?? fallbackTranslate
268
+ }
269
+
270
+ /** The panel's own English copy, same shape as the settings page's fallback. */
271
+ export function fallbackTranslate(key: string, params?: Record<string, unknown>): string {
272
+ const template = (en as Record<string, string>)[key] ?? key
273
+ if (params === undefined) return template
274
+ return template.replace(/\{(\w+)\}/g, (match, name: string) =>
275
+ name in params ? String(params[name]) : match,
276
+ )
277
+ }
278
+
279
+ /** Setting key of the poll interval, persisted in `prefs.pluginSettings[TAB_ID]`. */
280
+ export const REFRESH_KEY = 'refreshMs'
281
+
282
+ /** Poll interval used until the setting is read. */
283
+ export const DEFAULT_REFRESH_MS = 5_000
284
+
285
+ /**
286
+ * Status colours, taken from the design system's alias layer
287
+ * (`packages/client/ui-theme/src/styles/design-platform.css` in the DSH
288
+ * checkout): `state-*` for the lifecycle, `label-tertiary` for the two quiet
289
+ * states. The fallbacks only ever fire outside the DSH web client, where that
290
+ * alias layer is not loaded.
291
+ */
292
+ export const STATUS_COLOR: Record<ServerStatus, string> = {
293
+ active: 'var(--dsw-alias-state-success-primary, #22c55e)',
294
+ connecting: 'var(--dsw-alias-state-warn-primary, #f59e0b)',
295
+ conflict: 'var(--dsw-alias-state-warn-primary, #f59e0b)',
296
+ error: 'var(--dsw-alias-state-error-primary, #ec1313)',
297
+ idle: 'var(--dsw-alias-label-tertiary, #81858c)',
298
+ disabled: 'var(--dsw-alias-label-tertiary, #81858c)',
299
+ }
300
+
301
+ /**
302
+ * The dictionary key of the word each status wears on its row, so the panel
303
+ * never prints the enum token itself: a `ServerStatus` member without a key
304
+ * here is a compile error, not a silent English leak in another language.
305
+ */
306
+ export const STATUS_KEYS: Record<ServerStatus, LocaleKey> = {
307
+ active: 'statusActive',
308
+ connecting: 'statusConnecting',
309
+ conflict: 'statusConflict',
310
+ error: 'statusError',
311
+ idle: 'statusIdle',
312
+ disabled: 'statusDisabled',
313
+ }
314
+
315
+ /**
316
+ * The dictionary key of each status's one-line explanation, so the panel needs
317
+ * no legend. Readers translate through their own seat —
318
+ * `t(STATUS_HINT[row.status])` — which keeps the sentence the tooltip or the
319
+ * toast shows in the reader's language.
320
+ */
321
+ export const STATUS_HINT: Record<ServerStatus, LocaleKey> = {
322
+ active: 'statusHintActive',
323
+ connecting: 'statusHintConnecting',
324
+ idle: 'statusHintIdle',
325
+ disabled: 'statusHintDisabled',
326
+ conflict: 'statusHintConflict',
327
+ error: 'statusHintError',
328
+ }
329
+
330
+ const BORDER = '1px solid var(--dsw-alias-border-l1, rgba(127, 127, 127, 0.25))'
331
+
332
+ /**
333
+ * The alias layer's own tones, named once.
334
+ *
335
+ * The mockup's vocabulary has two levels of quiet text — `.muted` (secondary)
336
+ * and `.dim` (tertiary) — and this surface used to paint both by dropping the
337
+ * opacity of the primary colour, which is close to the token but not the same
338
+ * value. Reading the token keeps the two tones distinguishable in both themes.
339
+ */
340
+ const TONE = {
341
+ /** `.muted`: the secondary label tone, for text the user reads next. */
342
+ secondary: 'var(--dsw-alias-label-secondary, inherit)',
343
+ /** `.dim`: the tertiary label tone, for captions and quiet states. */
344
+ tertiary: 'var(--dsw-alias-label-tertiary, #81858c)',
345
+ } as const
346
+
347
+ /** The alias layer's layer-3 fill — the mockup's chip and the ring's filters. */
348
+ const LAYER_3 = 'var(--dsw-alias-bg-layer-3, rgba(127, 127, 127, 0.12))'
349
+
350
+ /**
351
+ * The counter chip's plate, named once because it has two readers now: the
352
+ * reading chip of {@link STYLE.tag} and the pressable tier chip of the tools
353
+ * block's filter (F-43). The two differ only in the three resets a `<button>`
354
+ * needs and in the fill the pressed one takes, so the words and the count read
355
+ * the same whether the tier is a label or a switch.
356
+ */
357
+ const LAYER_3_CHIP = {
358
+ background: LAYER_3,
359
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
360
+ fontSize: '0.85em',
361
+ borderRadius: 4,
362
+ padding: '0 5px',
363
+ color: TONE.secondary,
364
+ } satisfies CSSProperties
365
+
366
+ /**
367
+ * One step of the Servers surface's indentation ladder, in pixels.
368
+ *
369
+ * Surface A nests four levels and every one sits exactly one step right of the
370
+ * one above it — `project 0 → sessions 12 → session 24 → that session's servers
371
+ * 36`. The `sessions` rung is conditional: it exists only while at least one
372
+ * session disagrees with the project's merged rows, so a project whose sessions
373
+ * all agree stops at rung `0`. The scale lives here, once, and each level asks
374
+ * for its rung through {@link STYLE.indent}; the hand-picked `paddingLeft`
375
+ * values this replaced had drifted out of step with one another.
376
+ */
377
+ export const INDENT = 12
378
+
379
+ /**
380
+ * The panel's own inline styles.
381
+ *
382
+ * Exported for the design-only render mode (`./design.ts`), which composes the
383
+ * same `PanelHeader` / `tabBody` from a fixture and must therefore frame them
384
+ * with the very same root and body — a second copy of these two objects is
385
+ * exactly how a mockup drifts from the product.
386
+ */
387
+ export const STYLE = {
388
+ root: {
389
+ display: 'flex',
390
+ flexDirection: 'column',
391
+ height: '100%',
392
+ minHeight: 0,
393
+ color: 'inherit',
394
+ } satisfies CSSProperties,
395
+ bar: {
396
+ display: 'flex',
397
+ alignItems: 'center',
398
+ gap: 6,
399
+ // The mock's `.panel-bar` (`docs/design/mockups/harness.html`) — the panel's own inset, so the
400
+ // chips and the project name start on the picture's margin.
401
+ padding: '7px 9px',
402
+ borderBottom: BORDER,
403
+ flexWrap: 'wrap',
404
+ } satisfies CSSProperties,
405
+ body: {
406
+ flex: 1,
407
+ minHeight: 0,
408
+ overflow: 'auto',
409
+ // The one surface's blocks are direct children of this container (F-26), so
410
+ // the inset the old per-mode wrapper used to supply is here now — the
411
+ // mock's `.body { padding: 9px 10px }` (`docs/design/mockups/harness.html`).
412
+ padding: '9px 10px',
413
+ } satisfies CSSProperties,
414
+ /** The rows' own inset: the mock's `.body` (`docs/design/mockups/harness.html`). */
415
+ project: { padding: '9px 10px', borderBottom: BORDER } satisfies CSSProperties,
416
+ projectHead: {
417
+ display: 'flex',
418
+ alignItems: 'baseline',
419
+ gap: 6,
420
+ justifyContent: 'space-between',
421
+ } satisfies CSSProperties,
422
+ /**
423
+ * `.muted`: the secondary tone, at the text's own size.
424
+ *
425
+ * The mock's `.muted` states a colour and nothing else (`docs/design/mockups/harness.html`),
426
+ * and the dictionary's obligation is "a muted colour, not a blindly reduced
427
+ * size" — so the tone is here and the size is the neighbouring text's.
428
+ */
429
+ muted: { color: TONE.secondary } satisfies CSSProperties,
430
+ /** `.dim`: the tertiary tone, one step quieter than `.muted`. */
431
+ dim: { color: TONE.tertiary, fontSize: '0.9em' } satisfies CSSProperties,
432
+ row: {
433
+ display: 'flex',
434
+ alignItems: 'baseline',
435
+ gap: 6,
436
+ padding: '2px 0',
437
+ } satisfies CSSProperties,
438
+ sessions: {
439
+ marginTop: 4,
440
+ paddingTop: 4,
441
+ borderTop: BORDER,
442
+ } satisfies CSSProperties,
443
+ session: { padding: '2px 0' } satisfies CSSProperties,
444
+ sessionHead: {
445
+ display: 'flex',
446
+ alignItems: 'baseline',
447
+ gap: 6,
448
+ flexWrap: 'wrap',
449
+ } satisfies CSSProperties,
450
+ sessionToggle: {
451
+ padding: 0,
452
+ border: 'none',
453
+ background: 'transparent',
454
+ color: 'inherit',
455
+ cursor: 'pointer',
456
+ font: 'inherit',
457
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
458
+ textAlign: 'left',
459
+ } satisfies CSSProperties,
460
+ /**
461
+ * `tag`: the mockup's chip is a short plate on a layer fill in mono type — not
462
+ * a word in the row, and not a bordered box either (`docs/design/mockups/harness.html`,
463
+ * dictionary line 13).
464
+ */
465
+ tag: { ...LAYER_3_CHIP } satisfies CSSProperties,
466
+ /** The `idle` / `disabled` chip: the mockup's `.dim` tone, one step quieter. */
467
+ tagQuiet: {
468
+ color: TONE.tertiary,
469
+ } satisfies CSSProperties,
470
+ /** The `up/total` chip once a declared server is failing: red, not quiet. */
471
+ tagWarn: {
472
+ color: 'var(--dsw-alias-state-error-primary, #ec1313)',
473
+ } satisfies CSSProperties,
474
+ /**
475
+ * One counter chip of the tools block, as the filter's tier switch (F-43).
476
+ *
477
+ * The same plate {@link STYLE.tag} draws — the words and the count do not
478
+ * change with the tier — with the resets a `<button>` needs to sit in a row of
479
+ * spans without becoming a form control the shell styles. The chip is a leaf
480
+ * holding its text directly, which is also what lets the parity gate read
481
+ * `{count} pinned` off it.
482
+ *
483
+ * `font: inherit` comes **before** the plate, and the order is the whole
484
+ * point: `font` is a shorthand that resets `font-family` and `font-size` too,
485
+ * and React writes the inline style in this object's own order — behind the
486
+ * plate it silently turned the chips into the shell's sans face, which is the
487
+ * one thing a chip of this vocabulary is not (see the neighbouring
488
+ * `STYLE.logFilter`, where the shorthand is the last word on purpose because
489
+ * that chip is the shell's own type).
490
+ */
491
+ filterChip: {
492
+ font: 'inherit',
493
+ cursor: 'pointer',
494
+ border: 'none',
495
+ ...LAYER_3_CHIP,
496
+ } satisfies CSSProperties,
497
+ /** The pressed tier chip: the applied filter is the one that reads as active. */
498
+ filterChipOn: {
499
+ background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',
500
+ color: 'var(--dsw-alias-label-primary, inherit)',
501
+ } satisfies CSSProperties,
502
+ /**
503
+ * The filter's query field: the shell's own input plate, one size down and
504
+ * full width, so the field reads as the panel's own row rather than a form
505
+ * control borrowed from the settings page.
506
+ */
507
+ filterInput: {
508
+ flex: 1,
509
+ minWidth: 0,
510
+ border: BORDER,
511
+ borderRadius: 4,
512
+ padding: '2px 6px',
513
+ background: 'var(--dsw-alias-bg-layer-1, transparent)',
514
+ color: 'inherit',
515
+ font: 'inherit',
516
+ fontSize: '0.85em',
517
+ } satisfies CSSProperties,
518
+ /**
519
+ * A group label that shares its line with a chip. {@link STYLE.group} owns a
520
+ * whole line at the tertiary tone, which would bleach the chip with it.
521
+ */
522
+ groupInline: {
523
+ color: TONE.tertiary,
524
+ fontSize: '0.8em',
525
+ letterSpacing: '0.08em',
526
+ textTransform: 'uppercase',
527
+ } satisfies CSSProperties,
528
+ /** The session's declared-servers block, the single surface's first block. */
529
+ serversBlock: {
530
+ margin: '0 0 6px',
531
+ paddingBottom: 4,
532
+ borderBottom: BORDER,
533
+ } satisfies CSSProperties,
534
+ /**
535
+ * One rung of the Servers surface's indentation ladder: `level` steps right of
536
+ * the project's own rows, so `0` is the project, `1` the `sessions` section,
537
+ * `2` one session of it, `3` that session's own servers. The only left padding
538
+ * the surface has; nothing else may hand-pick one.
539
+ */
540
+ indent: (level: number): CSSProperties => ({ paddingLeft: level * INDENT }),
541
+ // An identifier is one unbreakable token (`mcp__tglider__workspace`), and the
542
+ // panel is 330px wide at its narrowest: without a break opportunity the name
543
+ // overflows its own row button instead of wrapping inside it. `anywhere` rather
544
+ // than `break-word` because only `anywhere` shrinks the item's own min-content
545
+ // width, which is what the flex row measures.
546
+ name: {
547
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
548
+ overflowWrap: 'anywhere',
549
+ } satisfies CSSProperties,
550
+ detail: { opacity: 0.7, overflowWrap: 'anywhere', whiteSpace: 'pre-wrap' } satisfies CSSProperties,
551
+ button: {
552
+ padding: '2px 8px',
553
+ borderRadius: 4,
554
+ border: BORDER,
555
+ background: 'transparent',
556
+ color: 'inherit',
557
+ cursor: 'pointer',
558
+ } satisfies CSSProperties,
559
+ error: { padding: 8, color: STATUS_COLOR.error } satisfies CSSProperties,
560
+ /**
561
+ * One disclosure of the single surface (F-26): a block of the scrolling body
562
+ * whose head is a button and whose body exists only while it is open. The
563
+ * parity gate finds it as a `div` with a `button[aria-expanded]` child, so the
564
+ * head is the block's first child and the body its second — the shape the
565
+ * mockup's `.disclosure` declares.
566
+ */
567
+ disclosure: { marginTop: 5 } satisfies CSSProperties,
568
+ disclosureHead: {
569
+ display: 'flex',
570
+ alignItems: 'baseline',
571
+ gap: 6,
572
+ width: '100%',
573
+ padding: '2px 0',
574
+ border: 'none',
575
+ background: 'transparent',
576
+ font: 'inherit',
577
+ textAlign: 'left',
578
+ cursor: 'pointer',
579
+ // `.disclosure-head`: the label is the control's word, read in the quiet
580
+ // tone (`docs/design/mockups/harness.html`, F-26 block).
581
+ color: TONE.tertiary,
582
+ } satisfies CSSProperties,
583
+ disclosureBody: { paddingLeft: 12 } satisfies CSSProperties,
584
+ /**
585
+ * One tool row: the line the user reads with its one action beside it, and the
586
+ * detail block on its own line while it is open. The line is the disclosure's
587
+ * `button[aria-expanded]` and a direct child of this wrapper, so a parity probe
588
+ * that looks for `div > button[aria-expanded]` finds the row, and the action
589
+ * stays a sibling — a button inside a button is not a thing HTML has.
590
+ */
591
+ tool: {
592
+ display: 'flex',
593
+ flexWrap: 'wrap',
594
+ alignItems: 'baseline',
595
+ gap: 6,
596
+ } satisfies CSSProperties,
597
+ /** The tool row's own line: the tier dot, the name, and the time and step. */
598
+ toolLine: {
599
+ display: 'flex',
600
+ alignItems: 'baseline',
601
+ gap: 6,
602
+ flex: 1,
603
+ minWidth: 0,
604
+ padding: '2px 0',
605
+ border: 'none',
606
+ background: 'transparent',
607
+ color: 'inherit',
608
+ cursor: 'pointer',
609
+ font: 'inherit',
610
+ textAlign: 'left',
611
+ } satisfies CSSProperties,
612
+ /**
613
+ * The open detail of one tool: its full public name in mono, then the server,
614
+ * the tier, and the step and time only while the host published them. One rung
615
+ * in from the row, like every other body of a disclosure.
616
+ */
617
+ toolDetail: {
618
+ flexBasis: '100%',
619
+ padding: '2px 0 4px 12px',
620
+ } satisfies CSSProperties,
621
+ group: {
622
+ opacity: 0.6,
623
+ fontSize: '0.8em',
624
+ letterSpacing: '0.08em',
625
+ textTransform: 'uppercase',
626
+ margin: '7px 0 1px',
627
+ } satisfies CSSProperties,
628
+ empty: {
629
+ display: 'flex',
630
+ flexDirection: 'column',
631
+ alignItems: 'center',
632
+ gap: 6,
633
+ padding: '14px 10px',
634
+ textAlign: 'center',
635
+ } satisfies CSSProperties,
636
+ emptyTitle: { opacity: 0.9 } satisfies CSSProperties,
637
+ hint: { opacity: 0.6, fontSize: '0.85em', overflowWrap: 'anywhere' } satisfies CSSProperties,
638
+ dot: {
639
+ width: 8,
640
+ height: 8,
641
+ borderRadius: '50%',
642
+ display: 'inline-block',
643
+ flex: 'none',
644
+ alignSelf: 'center',
645
+ } satisfies CSSProperties,
646
+ codeLine: {
647
+ margin: 8,
648
+ padding: '5px 8px',
649
+ border: BORDER,
650
+ borderRadius: 5,
651
+ background: 'var(--dsw-alias-markdown-code-block, transparent)',
652
+ color: 'var(--dsw-alias-link, inherit)',
653
+ fontSize: '0.8em',
654
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
655
+ overflowWrap: 'anywhere',
656
+ } satisfies CSSProperties,
657
+ budget: {
658
+ height: 4,
659
+ margin: '4px 0 2px',
660
+ borderRadius: 2,
661
+ background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',
662
+ overflow: 'hidden',
663
+ } satisfies CSSProperties,
664
+ budgetUsed: {
665
+ display: 'block',
666
+ height: '100%',
667
+ background: 'var(--dsw-alias-state-business-primary, currentColor)',
668
+ } satisfies CSSProperties,
669
+ warnNote: {
670
+ margin: '8px 0',
671
+ padding: '5px 7px',
672
+ borderLeft: '2px solid var(--dsw-alias-state-warn-primary, #f59e0b)',
673
+ background: 'var(--dsw-alias-state-warn-tertiary, transparent)',
674
+ fontSize: '0.85em',
675
+ overflowWrap: 'anywhere',
676
+ } satisfies CSSProperties,
677
+ /** A quiet row — `idle` or `disabled` — reads at the same size, dimmed. */
678
+ rowQuiet: { opacity: 0.6 } satisfies CSSProperties,
679
+ /** A row of chips: the hidden-by-server tags the tools block draws. */
680
+ chips: {
681
+ display: 'inline-flex',
682
+ alignItems: 'center',
683
+ gap: 4,
684
+ flexWrap: 'wrap',
685
+ } satisfies CSSProperties,
686
+ /** The header row of the collapsed sessions section. */
687
+ sessionsHead: {
688
+ display: 'flex',
689
+ alignItems: 'baseline',
690
+ gap: 6,
691
+ flexWrap: 'wrap',
692
+ } satisfies CSSProperties,
693
+ /** A failure banner: the coloured left rule carries the severity, not a word. */
694
+ banner: {
695
+ margin: '2px 0 4px',
696
+ padding: '4px 7px',
697
+ borderRadius: '0 5px 5px 0',
698
+ borderLeft: '2px solid var(--dsw-alias-state-error-primary, #ec1313)',
699
+ background: 'var(--dsw-alias-interactive-bg-hover-danger, transparent)',
700
+ color: 'var(--dsw-alias-label-primary, inherit)',
701
+ fontSize: '0.85em',
702
+ overflowWrap: 'anywhere',
703
+ // A mount detail is a multi-line diagnostic (error, endpoint, declaration,
704
+ // next step); collapsing its line breaks is what made it unreadable.
705
+ whiteSpace: 'pre-wrap',
706
+ } satisfies CSSProperties,
707
+ /** Laid over {@link STYLE.banner} for a restriction rather than a failure. */
708
+ bannerWarn: {
709
+ borderLeftColor: 'var(--dsw-alias-state-warn-primary, #f59e0b)',
710
+ background: 'var(--dsw-alias-state-warn-tertiary, transparent)',
711
+ } satisfies CSSProperties,
712
+ /**
713
+ * One log event's first line: time, level, server, message.
714
+ *
715
+ * `flexWrap` is the point of this row. A sidebar is narrow, and a message kept
716
+ * in a trailing column turns into a staircase of two-word fragments; wrapping
717
+ * the row lets the message take the rest of the line and the whole of the next
718
+ * one, which is how the mockup reads.
719
+ */
720
+ logRow: {
721
+ display: 'flex',
722
+ alignItems: 'baseline',
723
+ gap: 6,
724
+ padding: '2px 0',
725
+ flexWrap: 'wrap',
726
+ } satisfies CSSProperties,
727
+ /** The event's clock: mono, tertiary, fixed width so the column aligns. */
728
+ logTime: {
729
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
730
+ color: TONE.tertiary,
731
+ fontSize: '0.85em',
732
+ flex: 'none',
733
+ } satisfies CSSProperties,
734
+ /**
735
+ * The level chip. It reuses {@link STYLE.tag}'s plate and is only coloured on
736
+ * top of it, so `info` reads as the quiet chip it is and `error` as the alarm.
737
+ */
738
+ logLevel: { flex: 'none', textTransform: 'none', fontWeight: 500 } satisfies CSSProperties,
739
+ /**
740
+ * A filter chip of the Logs toolbar: a button that reads like {@link STYLE.tag}
741
+ * but keeps the interface font, since it is a control rather than a value.
742
+ */
743
+ logFilter: {
744
+ padding: '1px 6px',
745
+ border: 'none',
746
+ borderRadius: 4,
747
+ background: LAYER_3,
748
+ color: TONE.secondary,
749
+ cursor: 'pointer',
750
+ font: 'inherit',
751
+ fontSize: '0.85em',
752
+ } satisfies CSSProperties,
753
+ /** The filter currently applied: one pressed chip per pair. */
754
+ logFilterOn: {
755
+ background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',
756
+ color: 'var(--dsw-alias-label-primary, inherit)',
757
+ } satisfies CSSProperties,
758
+ /** Server name of the event, in the same mono face as every other name. */
759
+ logName: {
760
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
761
+ color: TONE.secondary,
762
+ flex: 'none',
763
+ } satisfies CSSProperties,
764
+ /** The message: its own width, so it never becomes a two-word column. */
765
+ logMessage: {
766
+ flex: '1 1 100%',
767
+ marginTop: 1,
768
+ overflowWrap: 'anywhere',
769
+ color: 'var(--dsw-alias-label-primary, inherit)',
770
+ } satisfies CSSProperties,
771
+ /** One fact line under a failing event; `marginLeft` sits it under the text. */
772
+ logDetail: {
773
+ margin: '0 0 3px',
774
+ paddingLeft: 7,
775
+ borderLeft: '2px solid var(--dsw-alias-state-error-primary, #ec1313)',
776
+ color: 'var(--dsw-alias-label-primary, inherit)',
777
+ fontSize: '0.85em',
778
+ overflowWrap: 'anywhere',
779
+ } satisfies CSSProperties,
780
+ /** `error` chip: the alarm tone of {@link STATUS_COLOR}. */
781
+ logError: { color: STATUS_COLOR.error } satisfies CSSProperties,
782
+ /** `warn` chip: the same tone a stalled server row uses. */
783
+ logWarn: { color: STATUS_COLOR.connecting } satisfies CSSProperties,
784
+ /** `up` chip: a successful mount reads like an active server. */
785
+ logUp: { color: STATUS_COLOR.active } satisfies CSSProperties,
786
+ }
787
+
788
+ interface Envelope<T> {
789
+ ok: boolean
790
+ value?: T
791
+ error?: { code?: string; message?: string }
792
+ }
793
+
794
+ /**
795
+ * Call one host route, unwrapping the `{ ok, value }` envelope.
796
+ *
797
+ * Exported so a surface that needs the snapshot outside the tab's own polling
798
+ * hook reads the same route the same way.
799
+ * @param path - route action under `ROUTE_PREFIX`.
800
+ * @param body - JSON body for a `POST` action; omitted for a `GET`.
801
+ * @returns the unwrapped snapshot.
802
+ */
803
+ export async function request(path: string, body?: unknown): Promise<McpSnapshot> {
804
+ const response = await fetch(`${ROUTE_PREFIX}/${path}`, routeInit(path, body))
805
+ const payload = (await response.json()) as Envelope<McpSnapshot>
806
+ if (payload.ok !== true || payload.value === undefined) {
807
+ throw new Error(payload.error?.message ?? `request failed (${response.status})`)
808
+ }
809
+ return payload.value
810
+ }
811
+
812
+ /**
813
+ * The `fetch` init for one route call.
814
+ *
815
+ * The method follows the **action**, never whether a payload happened to be
816
+ * passed: the reads — the snapshot, the status channel and a page of logs — are
817
+ * `GET`, and every other action is a `POST` the host refuses for `GET`. Deciding
818
+ * this from the body was a real defect — `Sync` and `Retry` pass no payload, so
819
+ * they were sent as `GET` and answered `404` from both panels, while `Release`
820
+ * (which sends a session id) worked.
821
+ *
822
+ * @param path - route action under `ROUTE_PREFIX`.
823
+ * @param body - JSON body; an action without one sends `{}` rather than nothing.
824
+ * @returns the init to hand to `fetch`.
825
+ */
826
+ export function routeInit(path: string, body?: unknown): RequestInit {
827
+ // `logs` is read out of the registry rather than repeated as a literal: the
828
+ // contract gives the route one owner, and this stays correct once it lands.
829
+ const logs = (ROUTE_ACTIONS as Record<string, string | undefined>).logs
830
+ const reads = [ROUTE_ACTIONS.snapshot, ROUTE_ACTIONS.events, ...(logs === undefined ? [] : [logs])]
831
+ if (reads.includes(path)) return {}
832
+ return {
833
+ method: 'POST',
834
+ headers: { 'content-type': 'application/json' },
835
+ body: JSON.stringify(body ?? {}),
836
+ }
837
+ }
838
+
839
+ interface SnapshotState {
840
+ snapshot: McpSnapshot | undefined
841
+ error: string | undefined
842
+ busy: boolean
843
+ }
844
+
845
+ /**
846
+ * Poll the host snapshot while the panel is visible; the Settings page polls it
847
+ * unconditionally. Exported so both surfaces share one fetch/unwrap/poll path.
848
+ *
849
+ * The poll is the **fallback**: the host pushes every change over the status
850
+ * channel (`GET /project-mcp/events`, see `createEventStream` in `src/ui.ts`),
851
+ * and a panel whose stream is open polls nothing. A host half older than the
852
+ * route, a browser without `EventSource`, or a dropped connection all land in the
853
+ * same place — the poll keeps the picture fresh, and `EventSource` reconnects on
854
+ * its own until the stream is back.
855
+ * @param visible - false suspends polling (the sidebar tab does this while hidden).
856
+ * @param refreshMs - poll interval while the status channel is not connected.
857
+ * @param path - route action to poll; the snapshot unless a surface asks for another.
858
+ * @returns the latest snapshot, the last error, the in-flight flag and `run`.
859
+ */
860
+ export function useSnapshot(visible: boolean, refreshMs: number, path: string = 'snapshot') {
861
+ const [state, setState] = useState<SnapshotState>({ snapshot: undefined, error: undefined, busy: false })
862
+ const [pushed, setPushed] = useState(false)
863
+ const load = useCallback(async () => {
864
+ try {
865
+ const snapshot = await request(path)
866
+ setState((previous) => ({ ...previous, snapshot, error: undefined }))
867
+ } catch (error) {
868
+ setState((previous) => ({ ...previous, error: messageOf(error) }))
869
+ }
870
+ }, [path])
871
+ /**
872
+ * Apply one pushed frame. Every frame carries the whole picture, so one that
873
+ * arrived after a gap is still a complete answer — nothing to refetch.
874
+ */
875
+ const apply = useCallback((change: SnapshotChange) => {
876
+ setState((previous) => ({ snapshot: change.snapshot, error: undefined, busy: previous.busy }))
877
+ }, [])
878
+ useEffect(() => {
879
+ if (!visible || typeof EventSource === 'undefined') return
880
+ const source = new EventSource(`${ROUTE_PREFIX}/${ROUTE_ACTIONS.events}`)
881
+ const onFrame = (event: Event): void => {
882
+ try {
883
+ apply(JSON.parse(String((event as MessageEvent).data)) as SnapshotChange)
884
+ } catch {
885
+ // A frame the panel cannot read is one poll away; the connection stays.
886
+ }
887
+ }
888
+ source.addEventListener('hello', onFrame)
889
+ source.addEventListener('change', onFrame)
890
+ source.addEventListener('open', () => setPushed(true))
891
+ source.addEventListener('error', () => setPushed(false))
892
+ return () => {
893
+ source.close()
894
+ setPushed(false)
895
+ }
896
+ }, [visible, apply])
897
+ useEffect(() => {
898
+ if (!visible || pushed) return
899
+ void load()
900
+ const timer = setInterval(() => void load(), Math.max(1_000, refreshMs))
901
+ return () => clearInterval(timer)
902
+ }, [visible, pushed, refreshMs, load])
903
+ /**
904
+ * Run one action. The method comes from {@link routeInit}, so an action with
905
+ * no payload is still a `POST`.
906
+ * @param path - route action under `ROUTE_PREFIX`.
907
+ * @param body - JSON body, when the action takes one.
908
+ */
909
+ const run = useCallback(async (path: string, body?: unknown) => {
910
+ setState((previous) => ({ ...previous, busy: true }))
911
+ try {
912
+ setState({ snapshot: await request(path, body), error: undefined, busy: false })
913
+ } catch (error) {
914
+ setState((previous) => ({ ...previous, busy: false, error: messageOf(error) }))
915
+ }
916
+ }, [])
917
+ /**
918
+ * Run one action once per body, and set the picture once.
919
+ *
920
+ * The pin route writes exactly one name per call (`PinRequest`), so a server's
921
+ * worth of names is a fan-out rather than one request — and a server-level
922
+ * press is one intent, so it deserves one repaint: the requests go out
923
+ * together and the last body's answer becomes the picture, instead of the
924
+ * panel painting itself once per name and racing its own writes.
925
+ *
926
+ * That answer is the state *after* the last write of the batch, not
927
+ * necessarily after the last one to settle: the host answers every call with
928
+ * the whole picture, so a straggler's effect arrives with the next pushed
929
+ * frame or poll, and the panel's own error line reports a refusal either way.
930
+ * @param path - route action under `ROUTE_PREFIX`.
931
+ * @param bodies - one body per write; nothing is sent for an empty batch.
932
+ */
933
+ const runAll = useCallback(async (path: string, bodies: readonly unknown[]) => {
934
+ if (bodies.length === 0) return
935
+ setState((previous) => ({ ...previous, busy: true }))
936
+ try {
937
+ const answers = await Promise.all(bodies.map((body) => request(path, body)))
938
+ const fresh = answers[answers.length - 1]
939
+ setState((previous) =>
940
+ fresh === undefined
941
+ ? { ...previous, busy: false }
942
+ : { snapshot: fresh, error: undefined, busy: false },
943
+ )
944
+ } catch (error) {
945
+ setState((previous) => ({ ...previous, busy: false, error: messageOf(error) }))
946
+ }
947
+ }, [])
948
+ return { ...state, run, runAll, reload: load }
949
+ }
950
+
951
+ /**
952
+ * Just enough of `Storage` for the log-filter and Clear-mark helpers, so tests
953
+ * need no DOM. The tab has no mode to remember since F-26: one surface means one
954
+ * screen, and browser-local storage only carries the ring's own filters.
955
+ */
956
+ export interface PanelStorage {
957
+ getItem(key: string): string | null
958
+ setItem(key: string, value: string): void
959
+ }
960
+
961
+ /** The browser's storage, or undefined when this half runs without one. */
962
+ export function browserStorage(): PanelStorage | undefined {
963
+ try {
964
+ return (globalThis as { localStorage?: PanelStorage }).localStorage
965
+ } catch {
966
+ // Reading the property itself throws when a policy blocks storage.
967
+ return undefined
968
+ }
969
+ }
970
+
971
+ /**
972
+ * Read one preference out of browser-local storage.
973
+ *
974
+ * Both the tab and the Settings page persist a single small choice; every
975
+ * storage access is guarded, so a policy that blocks storage (or a browser
976
+ * without one) only costs the choice at the next reload.
977
+ * @param key - storage key.
978
+ * @param storage - storage to read; defaults to the browser's own.
979
+ * @returns the stored string, or undefined when absent or unavailable.
980
+ */
981
+ export function storedString(
982
+ key: string,
983
+ storage: PanelStorage | undefined = browserStorage(),
984
+ ): string | undefined {
985
+ try {
986
+ return storage?.getItem(key) ?? undefined
987
+ } catch {
988
+ // Reading the property itself throws when a policy blocks storage.
989
+ return undefined
990
+ }
991
+ }
992
+
993
+ /**
994
+ * Persist one preference; a storage that refuses the write only costs the
995
+ * choice at the next reload.
996
+ * @param key - storage key.
997
+ * @param value - value to store.
998
+ * @param storage - storage to write; defaults to the browser's own.
999
+ */
1000
+ export function storeString(
1001
+ key: string,
1002
+ value: string,
1003
+ storage: PanelStorage | undefined = browserStorage(),
1004
+ ): void {
1005
+ try {
1006
+ storage?.setItem(key, value)
1007
+ } catch {
1008
+ // Storage disabled: the value still applies until the page is reloaded.
1009
+ }
1010
+ }
1011
+
1012
+ /**
1013
+ * Which sessions the Logs tab reads: the tab's own session, or every session of
1014
+ * the project. The mockup offers exactly these two.
1015
+ */
1016
+ export type LogScope = 'session' | 'all'
1017
+
1018
+ /** Which levels the Logs tab reads: everything, or the failures only. */
1019
+ export type LogLevelFilter = 'all' | 'error'
1020
+
1021
+ /** `localStorage` key of the Logs tab's session-scope filter. */
1022
+ export const LOG_SCOPE_KEY = `${TAB_ID}:logsScope`
1023
+
1024
+ /** `localStorage` key of the Logs tab's level filter. */
1025
+ export const LOG_LEVEL_KEY = `${TAB_ID}:logsLevel`
1026
+
1027
+ /**
1028
+ * `localStorage` key of the Logs tab's **client-side** Clear mark.
1029
+ *
1030
+ * `Clear` has no route (see the frozen contract, C1): the tab remembers the
1031
+ * moment and stops drawing events at or before it. The host's ring is untouched,
1032
+ * so a later `Sync` still answers with the whole buffer.
1033
+ */
1034
+ export const LOGS_CLEARED_KEY = `${TAB_ID}:logsClearedAt`
1035
+
1036
+ /** Scope read when nothing valid is persisted: this tab's own session. */
1037
+ export const DEFAULT_LOG_SCOPE: LogScope = 'session'
1038
+
1039
+ /**
1040
+ * Level read when nothing valid is persisted: errors only.
1041
+ *
1042
+ * The ring records the whole lifecycle, and at a project's first step that is a
1043
+ * wall of `mounting`/`is up` lines; the owner asked for the tab to answer "did
1044
+ * anything break" before it answers anything else. Every level is one click
1045
+ * away, and a level the user chose is persisted and wins over this default.
1046
+ */
1047
+ export const DEFAULT_LOG_LEVEL: LogLevelFilter = 'error'
1048
+
1049
+ /**
1050
+ * Events one snapshot carries and one `GET logs` page answers with.
1051
+ *
1052
+ * A mirror of the host's `LOG_PAGE_SIZE` (`src/logs.ts`), not a second owner of
1053
+ * the rule: the client asks for a page and reads what it is handed.
1054
+ */
1055
+ export const LOG_PAGE_SIZE = 50
1056
+
1057
+ /**
1058
+ * Read the persisted session-scope filter.
1059
+ * @param storage - storage to read; defaults to the browser's own.
1060
+ * @returns the stored scope, or {@link DEFAULT_LOG_SCOPE}.
1061
+ */
1062
+ export function logScopeOf(storage: PanelStorage | undefined = browserStorage()): LogScope {
1063
+ return storedString(LOG_SCOPE_KEY, storage) === 'all' ? 'all' : DEFAULT_LOG_SCOPE
1064
+ }
1065
+
1066
+ /**
1067
+ * Read the persisted level filter.
1068
+ *
1069
+ * Both stored values are answered as themselves; only an unknown or absent
1070
+ * entry falls back to {@link DEFAULT_LOG_LEVEL}. Testing against the default
1071
+ * instead would silently swallow the other valid value whenever the default
1072
+ * changes — the filter has two states, so both are named here.
1073
+ * @param storage - storage to read; defaults to the browser's own.
1074
+ * @returns the stored filter, or {@link DEFAULT_LOG_LEVEL}.
1075
+ */
1076
+ export function logLevelOf(storage: PanelStorage | undefined = browserStorage()): LogLevelFilter {
1077
+ const stored = storedString(LOG_LEVEL_KEY, storage)
1078
+ return stored === 'all' || stored === 'error' ? stored : DEFAULT_LOG_LEVEL
1079
+ }
1080
+
1081
+ /**
1082
+ * Read the Clear mark.
1083
+ * @param storage - storage to read; defaults to the browser's own.
1084
+ * @returns the epoch ms of the last Clear, or undefined when none was pressed.
1085
+ */
1086
+ export function logsClearedAt(storage: PanelStorage | undefined = browserStorage()): number | undefined {
1087
+ const stored = storedString(LOGS_CLEARED_KEY, storage)
1088
+ if (stored === undefined) return undefined
1089
+ const at = Number(stored)
1090
+ return Number.isFinite(at) ? at : undefined
1091
+ }
1092
+
1093
+ /**
1094
+ * Persist one of the Logs tab's own choices.
1095
+ * @param key - {@link LOG_SCOPE_KEY} or {@link LOG_LEVEL_KEY}.
1096
+ * @param value - the choice to store.
1097
+ * @param storage - storage to write; defaults to the browser's own.
1098
+ */
1099
+ export function persistLogFilter(
1100
+ key: string,
1101
+ value: string,
1102
+ storage: PanelStorage | undefined = browserStorage(),
1103
+ ): void {
1104
+ storeString(key, value, storage)
1105
+ }
1106
+
1107
+ /**
1108
+ * Record a Clear: events at or before `at` stop being drawn from now on.
1109
+ * @param at - the moment Clear was pressed, in epoch ms.
1110
+ * @param storage - storage to write; defaults to the browser's own.
1111
+ */
1112
+ export function persistLogsClearedAt(
1113
+ at: number,
1114
+ storage: PanelStorage | undefined = browserStorage(),
1115
+ ): void {
1116
+ storeString(LOGS_CLEARED_KEY, String(at), storage)
1117
+ }
1118
+
1119
+ /** One page of events as `GET logs` answers it (contract C1). */
1120
+ export interface LogPage {
1121
+ /** Events, oldest first. */
1122
+ readonly events: readonly LogEvent[]
1123
+ /** How many events the project's ring holds in total. */
1124
+ readonly total: number
1125
+ /** Whether the ring holds events older than the last one on this page. */
1126
+ readonly more: boolean
1127
+ }
1128
+
1129
+ /** Build the `GET logs` query for one page request. */
1130
+ function logsQuery(projectRoot: string, before: number | undefined, limit: number): URLSearchParams {
1131
+ const query = new URLSearchParams({ projectRoot, limit: String(limit) })
1132
+ if (before !== undefined) query.set('before', String(before))
1133
+ return query
1134
+ }
1135
+
1136
+ /**
1137
+ * Read one page of older events over the contract's `GET logs` route.
1138
+ *
1139
+ * The snapshot carries the newest {@link LOG_PAGE_SIZE} events; "show older"
1140
+ * asks the route for the page before the oldest one on screen. `before` is the
1141
+ * exclusive cursor the host pages on (`at < before`).
1142
+ * @param projectRoot - project the page belongs to.
1143
+ * @param before - epoch ms to page before; the snapshot page is requested without one.
1144
+ * @param limit - page size; {@link LOG_PAGE_SIZE} unless a test asks otherwise.
1145
+ * @param fetchImpl - `fetch` to use; defaults to the browser's.
1146
+ * @returns the page, or `undefined` when the host refused or the answer was unreadable.
1147
+ */
1148
+ export async function fetchLogs(
1149
+ projectRoot: string,
1150
+ before?: number,
1151
+ limit: number = LOG_PAGE_SIZE,
1152
+ fetchImpl: typeof fetch | undefined = (globalThis as { fetch?: typeof fetch }).fetch,
1153
+ ): Promise<LogPage | undefined> {
1154
+ if (fetchImpl === undefined) return undefined
1155
+ // The action is read out of the shared registry, so this route has one owner:
1156
+ // adding it there (contract C1) is what makes this line compile.
1157
+ const action = (ROUTE_ACTIONS as Record<string, string | undefined>).logs
1158
+ if (action === undefined) return undefined
1159
+ try {
1160
+ const query = logsQuery(projectRoot, before, limit)
1161
+ const response = await fetchImpl(`${ROUTE_PREFIX}/${action}?${query.toString()}`)
1162
+ const payload = (await response.json()) as Envelope<LogPage>
1163
+ if (payload.ok !== true || payload.value === undefined) return undefined
1164
+ return payload.value
1165
+ } catch {
1166
+ return undefined
1167
+ }
1168
+ }
1169
+
1170
+ /**
1171
+ * The events one session's ring holds, as the logs disclosure's badge counts them.
1172
+ *
1173
+ * The snapshot field is the **session's** own count (contract C1) — not the
1174
+ * project's — so the badge answers "how much happened here" rather than "how
1175
+ * busy is this folder".
1176
+ * @param session - the session, or undefined when the tab has none.
1177
+ * @returns the session's event count, `0` when the field is absent.
1178
+ */
1179
+ export function sessionLogCount(session: { readonly logCount?: number } | undefined): number {
1180
+ return session?.logCount ?? 0
1181
+ }
1182
+
1183
+ /**
1184
+ * Keep the newest `at`-time first, and drop the duplicates a page overlap can
1185
+ * produce, so "show older" appends rather than repeats.
1186
+ * @param older - the page just read.
1187
+ * @param shown - what is already on screen.
1188
+ * @returns the merged list, newest first.
1189
+ */
1190
+ export function mergeLogs(older: readonly LogEvent[], shown: readonly LogEvent[]): LogEvent[] {
1191
+ const seen = new Set(shown.map((event) => `${event.at}:${event.level}:${event.message}`))
1192
+ const fresh = older.filter((event) => !seen.has(`${event.at}:${event.level}:${event.message}`))
1193
+ return [...shown, ...fresh]
1194
+ }
1195
+
1196
+ /**
1197
+ * Whether the ring holds events older than the ones on screen, and where the
1198
+ * next page starts.
1199
+ *
1200
+ * The exclusive cursor is the oldest event drawn, which is what the host pages
1201
+ * on. A cursor already asked for is spent: a page that added nothing the filters
1202
+ * let through must not ask for itself again, or a short session inside a busy
1203
+ * project would loop. Absent a project total the client trusts the snapshot's
1204
+ * own length, so a host half that predates `logCount` simply draws no button.
1205
+ * @param props - the visible events, the project's total, and the cursors already asked for.
1206
+ * @returns `more` and the `cursor` the next page starts at.
1207
+ */
1208
+ export function logsPaging(props: {
1209
+ visible: readonly LogEvent[]
1210
+ total: number
1211
+ attempted: readonly number[]
1212
+ }): { more: boolean; cursor: number | undefined } {
1213
+ const cursor = props.visible.at(-1)?.at
1214
+ return {
1215
+ more: props.visible.length < props.total && cursor !== undefined && !props.attempted.includes(cursor),
1216
+ cursor,
1217
+ }
1218
+ }
1219
+
1220
+ /**
1221
+ * The empty state of the Logs tab: nothing recorded yet, and where to look.
1222
+ * @param t - translate seat.
1223
+ * @returns the element, so the copy can be asserted without a DOM.
1224
+ */
1225
+ export function logsEmptyState(t: Translate): ReactNode {
1226
+ return emptyState(t('logsEmptyTitle'), t('logsEmptyHint'), 'logs-empty')
1227
+ }
1228
+
1229
+ /**
1230
+ * The empty state of the level filter, not of the ring.
1231
+ *
1232
+ * The tab opens on `errors`; a project whose ring holds only `mounting`/`is up`
1233
+ * lines would otherwise read "no events yet" while the counter beside the
1234
+ * disclosure's badge says it holds several. Saying so is the difference between a quiet
1235
+ * project and a hidden list.
1236
+ * @param t - translate seat.
1237
+ * @returns the element, keyed for the array {@link logList} returns.
1238
+ */
1239
+ export function logsNoErrorsState(t: Translate): ReactNode {
1240
+ return emptyState(t('logsNoErrorsTitle'), t('logsNoErrorsHint'), 'logs-empty')
1241
+ }
1242
+
1243
+ /**
1244
+ * The one project this tab belongs to: the project whose live sessions include
1245
+ * the tab's session. A tab never shows another project — the settings popup and
1246
+ * the native settings page are the surfaces with the whole picture.
1247
+ * @param snapshot - host snapshot, or undefined before the first poll lands.
1248
+ * @param sessionId - the session this tab is open in.
1249
+ * @returns the matching project, or undefined when there is none (yet).
1250
+ */
1251
+ export function currentProject(
1252
+ snapshot: McpSnapshot | undefined,
1253
+ sessionId: string | undefined,
1254
+ ): ProjectSnapshot | undefined {
1255
+ if (snapshot === undefined || sessionId === undefined) return undefined
1256
+ return snapshot.projects.find(
1257
+ (project) =>
1258
+ project.sessionIds.includes(sessionId) ||
1259
+ (project.sessions ?? []).some((session) => session.id === sessionId),
1260
+ )
1261
+ }
1262
+
1263
+ /**
1264
+ * Statuses the "Problems" view lists, most actionable first. The quiet states —
1265
+ * `active`, `idle`, `disabled` — are answers, not problems.
1266
+ */
1267
+ export const PROBLEM_STATUSES = ['error', 'conflict', 'connecting'] as const
1268
+
1269
+ /** One status and the rows currently in it. */
1270
+ export interface StatusGroup {
1271
+ status: ServerStatus
1272
+ rows: ServerRow[]
1273
+ }
1274
+
1275
+ /**
1276
+ * Split merged rows into the groups the "Problems" view shows.
1277
+ * @param rows - merged project rows, in document order.
1278
+ * @returns one entry per non-empty group, in {@link PROBLEM_STATUSES} order.
1279
+ */
1280
+ export function statusGroups(rows: readonly ServerRow[]): StatusGroup[] {
1281
+ const groups: StatusGroup[] = []
1282
+ for (const status of PROBLEM_STATUSES) {
1283
+ const matching = rows.filter((row) => row.status === status)
1284
+ if (matching.length > 0) groups.push({ status, rows: matching })
1285
+ }
1286
+ return groups
1287
+ }
1288
+
1289
+ /**
1290
+ * Tab body: the project this session works in, and nothing else.
1291
+ *
1292
+ * The whole picture — every project with a live session — lives in the side card
1293
+ * settings popup, not in a tab that belongs to one conversation.
1294
+ */
1295
+ export function ProjectMcpPanel(props: {
1296
+ visible: boolean
1297
+ sessionId: string | undefined
1298
+ refreshMs: number
1299
+ /**
1300
+ * The shell's translate seat for this namespace. Required on purpose: the
1301
+ * panel is one of the surfaces whose copy must follow the language
1302
+ * preference, so `./index.ts` composes it with the seat from `./tab-locale.ts`
1303
+ * rather than letting a missing prop silently fall back to English.
1304
+ */
1305
+ t: Translate
1306
+ /**
1307
+ * Host-namespace seat for the Logs tab's coded events (F-48); without one
1308
+ * the events render their payload's English, byte-identical to before codes.
1309
+ */
1310
+ hostT?: Translate | undefined
1311
+ }): ReactNode {
1312
+ const t = props.t
1313
+ const { snapshot, error, busy, run, runAll } = useSnapshot(props.visible, props.refreshMs)
1314
+ const project = currentProject(snapshot, props.sessionId)
1315
+ const groups = project === undefined ? [] : statusGroups(project.rows)
1316
+ const policy = project === undefined ? undefined : policyOf(project)
1317
+ // The Logs disclosure counts this session's own events, not the project's: the
1318
+ // number the contract puts on `SessionSnapshot.logCount` (C1). A host half
1319
+ // without the field reports `0`, which the block prints as a real `0`.
1320
+ const session = (project?.sessions ?? []).find((entry) => entry.id === props.sessionId)
1321
+ const logsSession = sessionLogCount(session)
1322
+ // The pin keeps its own route and answers with the fresh snapshot, so the
1323
+ // panel's own `run` carries it: a refusal lands in the same line as every
1324
+ // other host refusal instead of being swallowed by a silent refresh.
1325
+ const onPin = useCallback(
1326
+ (tool: string, pinned: boolean): void => {
1327
+ if (project === undefined) return
1328
+ void run(ROUTE_ACTIONS.pin, pinBody(project.projectRoot, tool, pinned))
1329
+ },
1330
+ [project, run],
1331
+ )
1332
+ // A server's worth of names is one intent and one press (F-44): the names come
1333
+ // from the surface that showed them, the direction from what the project
1334
+ // already pins, and the writes go out as one batch.
1335
+ const onPinServer = useCallback(
1336
+ (server: string, names: readonly string[]): void => {
1337
+ if (project === undefined) return
1338
+ const press = serverPinPress(names, policy?.pins ?? [])
1339
+ void runAll(
1340
+ ROUTE_ACTIONS.pin,
1341
+ press.names.map((name) => pinBody(project.projectRoot, name, press.pinned)),
1342
+ )
1343
+ },
1344
+ [project, policy, runAll],
1345
+ )
1346
+ // Both operator actions are scoped to the project this tab shows: the panel
1347
+ // answers with that project's slice, and the host never starts a server for
1348
+ // another project because a row here was retried. Without a project there is
1349
+ // nothing to scope, so the request stays the global one it always was.
1350
+ const retry = useCallback(
1351
+ (): void => void run(ROUTE_ACTIONS.retry, operatorBody(project?.projectRoot)),
1352
+ [project, run],
1353
+ )
1354
+ const sync = useCallback(
1355
+ (): void => void run(ROUTE_ACTIONS.sync, operatorBody(project?.projectRoot)),
1356
+ [project, run],
1357
+ )
1358
+ const release = useCallback(
1359
+ (sessionId: string): void => void run(ROUTE_ACTIONS.release, { sessionId }),
1360
+ [run],
1361
+ )
1362
+ return h(
1363
+ 'div',
1364
+ { style: STYLE.root },
1365
+ h(PanelHeader, {
1366
+ project,
1367
+ sessions: project?.sessionIds.length ?? 0,
1368
+ busy,
1369
+ onSync: sync,
1370
+ t,
1371
+ }),
1372
+ h(
1373
+ 'div',
1374
+ { style: STYLE.body },
1375
+ // The host's refusal is the body's first line, so the toolbar is the
1376
+ // body's immediate sibling in the panel (the contract's own gate anchor)
1377
+ // whatever the read did.
1378
+ error === undefined ? null : h('div', { style: STYLE.error }, error),
1379
+ tabBody({
1380
+ project,
1381
+ sessionId: props.sessionId,
1382
+ groups,
1383
+ busy,
1384
+ policy,
1385
+ onPin,
1386
+ onPinServer,
1387
+ onRelease: release,
1388
+ onRetry: retry,
1389
+ sessionLogCount: logsSession,
1390
+ t,
1391
+ hostT: props.hostT,
1392
+ }),
1393
+ ),
1394
+ )
1395
+ }
1396
+
1397
+ /**
1398
+ * The one-phrase reading of the toolbar's right edge.
1399
+ *
1400
+ * F-26 left the surface with one screen and no mode to branch on, so the phrase
1401
+ * answers the one question no block above it answers on its own: how many
1402
+ * sessions the project has. The problems block badges its own groups, the logs
1403
+ * block its own events, and the tools block its own counters, so nothing here
1404
+ * repeats them.
1405
+ * @param props - the project's session count.
1406
+ * @param t - translate seat.
1407
+ * @returns the phrase the toolbar's right edge prints.
1408
+ */
1409
+ export function panelSummary(props: { sessions: number }, t: Translate): string {
1410
+ return sessionCount(props.sessions, t)
1411
+ }
1412
+
1413
+ /** Everything the tab's toolbar reads. */
1414
+ export interface PanelHeaderProps {
1415
+ /** The tab's own project, or undefined when its session has none. */
1416
+ project: ProjectSnapshot | undefined
1417
+ /** Sessions attached to the project; what the right edge counts. */
1418
+ sessions: number
1419
+ busy: boolean
1420
+ onSync: () => void
1421
+ t: Translate
1422
+ }
1423
+
1424
+ /**
1425
+ * The tab's one toolbar row.
1426
+ *
1427
+ * The project's own header — the folder, the `this session` chip that says whose
1428
+ * tab this is, the summary phrase and the action at the right edge. The segment
1429
+ * bar that used to be the second row is gone (F-26): there is one screen, so
1430
+ * there is nothing to switch. Pure and exported: the panel around it owns the
1431
+ * poll and the state.
1432
+ * @param props - see {@link PanelHeaderProps}.
1433
+ * @returns the toolbar row.
1434
+ */
1435
+ export function PanelHeader(props: PanelHeaderProps): ReactNode {
1436
+ const { t, project } = props
1437
+ return h(
1438
+ 'div',
1439
+ { style: STYLE.bar },
1440
+ project === undefined
1441
+ ? h('span', { style: STYLE.muted }, t('noProjectLabel'))
1442
+ : h(
1443
+ 'span',
1444
+ { style: STYLE.name, title: project.projectRoot },
1445
+ basename(project.projectRoot),
1446
+ ),
1447
+ project === undefined ? null : h('span', { style: STYLE.tag }, t('thisSession')),
1448
+ h('span', { style: { flex: 1 } }),
1449
+ h('button', { style: STYLE.button, disabled: props.busy, onClick: props.onSync }, t('sync')),
1450
+ // The toolbar's right edge is the mockup's `.dim`
1451
+ // (`docs/design/mockups/harness.html`, `.dim` — the tertiary tone):
1452
+ // one phrase, at the tertiary tone, and the only summary reading in the bar.
1453
+ h('span', { style: STYLE.dim }, panelSummary({ sessions: props.sessions }, t)),
1454
+ )
1455
+ }
1456
+
1457
+ /** Everything the tab renders under its toolbar. */
1458
+ export interface TabBodyProps {
1459
+ /** The tab's own project, or undefined when this session has none. */
1460
+ project: ProjectSnapshot | undefined
1461
+ /** Session this tab is open in. */
1462
+ sessionId: string | undefined
1463
+ /** Problem groups of {@link project}, precomputed by the panel. */
1464
+ groups: StatusGroup[]
1465
+ busy: boolean
1466
+ /** The project's policy, precomputed by the panel; read from the project when absent. */
1467
+ policy?: ToolPolicy | undefined
1468
+ /** Pin or unpin one tool of {@link project}; absent while nothing can be written. */
1469
+ onPin?: ((tool: string, pinned: boolean) => void) | undefined
1470
+ /**
1471
+ * Pin every name of one server in one press (F-44); absent while nothing can
1472
+ * be written. The names are the ones the surface that called it lists — the
1473
+ * hidden tier's own names — and the expansion into names is the whole
1474
+ * meaning: the host stores no server pin (`docs/design/contracts/policy.md`).
1475
+ */
1476
+ onPinServer?: ((server: string, names: readonly string[]) => void) | undefined
1477
+ /**
1478
+ * Retry every failed mount of {@link project}; absent while nothing can be
1479
+ * written. The host route is project-scoped, so a row's own `Retry` sends the
1480
+ * request the errors block's button sends.
1481
+ */
1482
+ onRetry?: (() => void) | undefined
1483
+ onRelease: (sessionId: string) => void
1484
+ /** Events of this tab's own session, at the moment the snapshot was taken. */
1485
+ sessionLogCount?: number
1486
+ /** Storage the Logs block persists its filters and Clear mark in. */
1487
+ storage?: PanelStorage | undefined
1488
+ /** Translate seat; falls back to this module's English copy without one. */
1489
+ t?: Translate
1490
+ /** Host-namespace seat for the Logs block's coded events (F-48). */
1491
+ hostT?: Translate | undefined
1492
+ }
1493
+
1494
+ /**
1495
+ * What to add where, said from the host's own document list.
1496
+ *
1497
+ * The files a project is read from are a config fact — `ProjectSnapshot.files`,
1498
+ * published in read order — so the empty state names the project's own documents
1499
+ * instead of a path baked into this bundle, and says plainly when the deployment
1500
+ * reads none at all. A host older than the field reports nothing, and then no
1501
+ * file name is promised: the hint speaks about declaring one, not about a path
1502
+ * that host may never read.
1503
+ */
1504
+ function declaredHint(project: ProjectSnapshot, t: Translate): string {
1505
+ const files = project.files
1506
+ // No list at all is a host older than the field, and then no file name is
1507
+ // promised: the hint asks for a document without naming a path that host may
1508
+ // never read.
1509
+ if (files === undefined) return t('noServersDeclaredUnknown')
1510
+ const documents = files.filter((file) => file.scope === 'project').map((file) => file.path)
1511
+ if (documents.length === 0) return t('noServersDeclaredNowhere')
1512
+ return t('noServersDeclaredHint', { documents: documents.join(' · ') })
1513
+ }
1514
+
1515
+ /**
1516
+ * The tab body: one screen, its blocks in the contract's order.
1517
+ *
1518
+ * F-26 folded the four modes into one surface, so the body is a list of blocks
1519
+ * rather than a branch: the session's declared servers, the sessions that
1520
+ * disagree with the project (F-24's section, still only while some do), the tool
1521
+ * offer, and the two disclosures — the problems, only while there are any, and
1522
+ * the event ring, always. Every situation where a surface has nothing to list
1523
+ * still answers for itself above the blocks.
1524
+ * @param props - see {@link TabBodyProps}.
1525
+ * @returns the blocks below the toolbar, in order.
1526
+ */
1527
+ export function tabBody(props: TabBodyProps): ReactNode {
1528
+ const t = translateOf(props.t)
1529
+ if (props.sessionId === undefined) {
1530
+ return emptyState(t('noSession'), t('noSessionHint'))
1531
+ }
1532
+ const { project } = props
1533
+ if (project === undefined) {
1534
+ return emptyState(t('noProject'), t('noProjectHint'))
1535
+ }
1536
+ // This session's own rows, not the merged project view: what this conversation
1537
+ // resolves is the first thing the screen answers (`sessionRowsOf`).
1538
+ const rows = sessionRowsOf(project, props.sessionId)
1539
+ const sessions = sessionBreakdown(project, props.sessionId, t)
1540
+ const disagreeing = sessions.filter((session) => session.deviates)
1541
+ return [
1542
+ rows.length === 0
1543
+ ? emptyState(t('noServersDeclared'), declaredHint(project, t), 'servers')
1544
+ : h(ServersBlock, { key: 'servers', rows, usage: project.usage, t, hostT: props.hostT }),
1545
+ // The F-24 disagreement view. The merged project rows are no longer drawn
1546
+ // here — the block above is this session's own reading — but `Release` for a
1547
+ // single session still lives only in this section.
1548
+ h(SessionList, {
1549
+ key: 'sessions',
1550
+ sessions: disagreeing,
1551
+ busy: props.busy,
1552
+ onRelease: props.onRelease,
1553
+ merged: sessions.length > 1,
1554
+ t: props.t,
1555
+ hostT: props.hostT,
1556
+ }),
1557
+ h(ToolsSection, {
1558
+ key: 'tools',
1559
+ project,
1560
+ sessionId: props.sessionId,
1561
+ policy: props.policy,
1562
+ onPin: props.onPin,
1563
+ onPinServer: props.onPinServer,
1564
+ pending: props.busy,
1565
+ t,
1566
+ hostT: props.hostT,
1567
+ }),
1568
+ // The errors disclosure exists only while there are problem groups; there is
1569
+ // no "all quiet" copy to draw, because an absent block is the quiet answer.
1570
+ props.groups.length === 0
1571
+ ? null
1572
+ : h(
1573
+ Disclosure,
1574
+ {
1575
+ key: 'errors',
1576
+ label: t('errorsSection'),
1577
+ count: props.groups.length,
1578
+ showHint: t('showErrors'),
1579
+ hideHint: t('hideErrors'),
1580
+ body: [
1581
+ h(IssueView, {
1582
+ key: 'issues',
1583
+ project,
1584
+ groups: props.groups,
1585
+ onRetry: props.onRetry,
1586
+ busy: props.busy,
1587
+ t,
1588
+ hostT: props.hostT,
1589
+ }),
1590
+ // `Retry failed` used to sit on the mode bar; the errors block is
1591
+ // where the action belongs now that the bar is gone.
1592
+ props.onRetry === undefined
1593
+ ? null
1594
+ : h(
1595
+ 'button',
1596
+ {
1597
+ key: 'retry',
1598
+ style: STYLE.button,
1599
+ title: t('retryHint'),
1600
+ disabled: props.busy,
1601
+ onClick: props.onRetry,
1602
+ },
1603
+ t('retryFailed'),
1604
+ ),
1605
+ ],
1606
+ t,
1607
+ },
1608
+ ),
1609
+ h(Disclosure, {
1610
+ key: 'logs',
1611
+ label: t('logsSection'),
1612
+ count: props.sessionLogCount ?? 0,
1613
+ showHint: t('showLogs'),
1614
+ hideHint: t('hideLogs'),
1615
+ body: h(LogsView, {
1616
+ project,
1617
+ sessionId: props.sessionId,
1618
+ t,
1619
+ hostT: props.hostT,
1620
+ storage: props.storage,
1621
+ }),
1622
+ t,
1623
+ }),
1624
+ ]
1625
+ }
1626
+
1627
+ /**
1628
+ * The tools block of the one surface.
1629
+ *
1630
+ * {@link ToolsView} stays pure — the pure specs resolve it directly — so the
1631
+ * row whose detail block is open lives here, one state for the section, the way
1632
+ * {@link SessionList} keeps one session open at a time. Exported like the other
1633
+ * stateful block so {@link tabBody}'s block order can be asserted by type.
1634
+ *
1635
+ * The filter panel's query and pressed tiers (F-43) live here for the same
1636
+ * reason and outlive a snapshot
1637
+ * refresh: a poll repaints the block, and a filter that reset itself every five
1638
+ * seconds would be unusable.
1639
+ *
1640
+ * The filter is this component's own state and is not persisted anywhere: a
1641
+ * query is a reading aid for the minute, and the two filters the panel does
1642
+ * store — the log ring's — are stored because a page of that ring costs a
1643
+ * request. Nothing here does.
1644
+ * @param props - what {@link ToolsView} takes.
1645
+ * @returns the session's tool offer, with one row open at most.
1646
+ */
1647
+ export function ToolsSection(props: {
1648
+ project: ProjectSnapshot
1649
+ sessionId: string
1650
+ policy?: ToolPolicy | undefined
1651
+ onPin?: ((tool: string, pinned: boolean) => void) | undefined
1652
+ /** Pin every hidden name of one server in one press (F-44). */
1653
+ onPinServer?: ((server: string, names: readonly string[]) => void) | undefined
1654
+ pending?: boolean
1655
+ t: Translate
1656
+ /** Host-namespace seat for the presentation owner's coded note (F-48). */
1657
+ hostT?: Translate | undefined
1658
+ }): ReactNode {
1659
+ const [openTool, setOpenTool] = useState<string | undefined>(undefined)
1660
+ // Three states, not two: `undefined` is "nobody has pressed the head", and it
1661
+ // is what lets the filter open the hidden tier on its own without stealing the
1662
+ // press that follows (see {@link ToolsView}'s own `openHidden`).
1663
+ const [openHidden, setOpenHidden] = useState<boolean | undefined>(undefined)
1664
+ const [query, setQuery] = useState('')
1665
+ const [tiers, setTiers] = useState<readonly ToolTier[]>([])
1666
+ // The filter this section hands to the block, built once here because the
1667
+ // hidden head's own toggle has to know it: the press inverts the state the
1668
+ // user is *looking at*, and while a filter is live that state may be the one
1669
+ // the filter opened the tier in (`undefined`), not `false`.
1670
+ const filter: ToolFilter = { query, tiers }
1671
+ const filterActive = toolFilterActive(filter)
1672
+ const onToggleTool = useCallback((name: string): void => {
1673
+ setOpenTool((current) => (current === name ? undefined : name))
1674
+ }, [])
1675
+ const onToggleHidden = useCallback((): void => {
1676
+ setOpenHidden((value) => !(value ?? filterActive))
1677
+ }, [filterActive])
1678
+ const onQuery = useCallback((value: string): void => setQuery(value), [])
1679
+ const onTier = useCallback((tier: ToolTier): void => {
1680
+ setTiers((held) => toggledTier(held, tier))
1681
+ }, [])
1682
+ const onClearFilter = useCallback((): void => {
1683
+ setQuery('')
1684
+ setTiers([])
1685
+ }, [])
1686
+ return h(ToolsView, {
1687
+ ...props,
1688
+ openTool,
1689
+ onToggleTool,
1690
+ openHidden,
1691
+ onToggleHidden,
1692
+ filter,
1693
+ onQuery,
1694
+ onTier,
1695
+ onClearFilter,
1696
+ })
1697
+ }
1698
+
1699
+ /**
1700
+ * One disclosure of the single surface: a head button and, while it is open, its
1701
+ * body.
1702
+ *
1703
+ * The `div`/`button[aria-expanded]` pair is the shape the parity gate reads a
1704
+ * disclosure by, which is why the head is a button of its own and the body is
1705
+ * the only thing that appears when it opens. The state is local on purpose: what
1706
+ * is folded away is this block's, not the panel's, so the panel keeps rendering
1707
+ * one pure tree per snapshot.
1708
+ */
1709
+ /**
1710
+ * The head one disclosure draws: toggled marker, label and the count badge.
1711
+ *
1712
+ * A pure function of its props on purpose. {@link Disclosure} is a component
1713
+ * with state, and the tools block is a pure tree of elements resolved by tests
1714
+ * without a React runtime — a stateful child in that tree would be invoked
1715
+ * outside a component and break the walk. The tiers that must be pure (the
1716
+ * hidden list) draw this head themselves and keep their open state one level up,
1717
+ * which is why the head exists apart from the wrapper that usually wears it.
1718
+ * @param props - label, count, open state and the head's tooltip.
1719
+ * @returns the `button[aria-expanded]` the parity gate reads a disclosure by.
1720
+ */
1721
+ export function disclosureHead(props: {
1722
+ label: string
1723
+ count?: number | undefined
1724
+ open: boolean
1725
+ hint?: string | undefined
1726
+ onToggle: () => void
1727
+ }): ReactNode {
1728
+ return h(
1729
+ 'button',
1730
+ {
1731
+ style: STYLE.disclosureHead,
1732
+ 'aria-expanded': props.open,
1733
+ title: props.hint,
1734
+ onClick: props.onToggle,
1735
+ },
1736
+ `${props.open ? '▾' : '▸'} ${props.label}`,
1737
+ props.count === undefined ? null : h('span', { style: STYLE.tag }, String(props.count)),
1738
+ )
1739
+ }
1740
+
1741
+ export function Disclosure(props: {
1742
+ /** The head's word-label; the marker is drawn beside it, not stored. */
1743
+ label: string
1744
+ /** The number the head's badge prints, when it has one. */
1745
+ count?: number | undefined
1746
+ /** The head's tooltip while the block is open. */
1747
+ showHint?: string | undefined
1748
+ /** The head's tooltip while the block is closed. */
1749
+ hideHint?: string | undefined
1750
+ /** What the head reveals; rendered only while the disclosure is open. */
1751
+ body: ReactNode
1752
+ /** Translate seat; falls back to this module's English copy without one. */
1753
+ t?: Translate | undefined
1754
+ }): ReactNode {
1755
+ const [open, setOpen] = useState(false)
1756
+ return h(
1757
+ 'div',
1758
+ { style: STYLE.disclosure },
1759
+ disclosureHead({
1760
+ label: props.label,
1761
+ count: props.count,
1762
+ open,
1763
+ hint: open ? props.hideHint : props.showHint,
1764
+ onToggle: (): void => setOpen((value) => !value),
1765
+ }),
1766
+ open ? h('div', { style: STYLE.disclosureBody }, props.body) : null,
1767
+ )
1768
+ }
1769
+
1770
+ /**
1771
+ * The session's own tool offer, when the host half published one.
1772
+ * @param project - the project this tab belongs to.
1773
+ * @param sessionId - the tab's session.
1774
+ * @returns the per-session `tools`, or undefined when the host has none yet.
1775
+ */
1776
+ export function sessionToolsOf(
1777
+ project: ProjectSnapshot,
1778
+ sessionId: string | undefined,
1779
+ ): SessionTools | undefined {
1780
+ if (sessionId === undefined) return undefined
1781
+ const sessions = (project.sessions ?? []) as readonly { id: string; tools?: SessionTools }[]
1782
+ return sessions.find((session) => session.id === sessionId)?.tools
1783
+ }
1784
+
1785
+ /**
1786
+ * The declared servers of the session this tab belongs to: the session's own
1787
+ * rows when the host published that session, the project's merged rows
1788
+ * otherwise.
1789
+ *
1790
+ * Per-session rows, not the merged project view: with the own-scope fallback a
1791
+ * session can run its own instance of a declaration, so its state — running,
1792
+ * stalled or released — is what this conversation actually has, and another
1793
+ * session of the same project may be in a different one.
1794
+ * @param project - the project snapshot the tab read.
1795
+ * @param sessionId - the conversation the tab is open in.
1796
+ * @returns the declared servers this session resolves.
1797
+ */
1798
+ export function sessionRowsOf(
1799
+ project: ProjectSnapshot,
1800
+ sessionId: string | undefined,
1801
+ ): readonly ServerRow[] {
1802
+ if (sessionId === undefined) return []
1803
+ const sessions = (project.sessions ?? []) as readonly { id: string; rows?: ServerRow[] }[]
1804
+ const session = sessions.find((entry) => entry.id === sessionId)
1805
+ return session === undefined ? project.rows : (session.rows ?? [])
1806
+ }
1807
+
1808
+ /** The three counts the tools block answers for. */
1809
+ export interface ToolCounts {
1810
+ /** Offered because the durable counters proved them hot. */
1811
+ pinned: number
1812
+ /** Offered because this session disclosed them, from either on-demand tier. */
1813
+ disclosed: number
1814
+ /** Mounted for the project but not offered in the request. */
1815
+ hidden: number
1816
+ /** Every tool the model would see: pins plus disclosures. */
1817
+ offering: number
1818
+ }
1819
+
1820
+ /**
1821
+ * Count one session's offer into the three tiers the mockup names.
1822
+ *
1823
+ * Real data throughout — it reads only {@link SessionTools} — so every figure it
1824
+ * returns is a fact, not an invention.
1825
+ * @param tools - one session's tool offer.
1826
+ * @returns the pinned, disclosed and hidden counts.
1827
+ */
1828
+ export function toolCounts(tools: SessionTools): ToolCounts {
1829
+ const pinned = tools.baseline.length
1830
+ const disclosed = tools.activated.length + tools.context.length
1831
+ return {
1832
+ pinned,
1833
+ disclosed,
1834
+ hidden: tools.deferred.length,
1835
+ offering: pinned + disclosed,
1836
+ }
1837
+ }
1838
+
1839
+ /** One server's share of one list of registry names. */
1840
+ export interface ServerNames {
1841
+ /** Registry names one list holds for this server, in that list's own order. */
1842
+ readonly names: readonly string[]
1843
+ /** Server the tools belong to, or `unknown` when the name is not prefixed. */
1844
+ server: string
1845
+ /** How many names of that list are this server's. */
1846
+ count: number
1847
+ }
1848
+
1849
+ /**
1850
+ * The hidden tier's reading of {@link ServerNames}, under the name its callers
1851
+ * know it by: the grouping is the same one, only the list differs.
1852
+ */
1853
+ export type HiddenServer = ServerNames
1854
+
1855
+ /**
1856
+ * Split hidden tool names by the server they were mounted from.
1857
+ *
1858
+ * The registry's own naming is `mcp__<server>__<tool>` (a project-level prefix
1859
+ * is added by `mcp-client` only on a collision), so the server is the second
1860
+ * `__`-separated segment. A name that does not follow that shape is counted
1861
+ * under `unknown` rather than dropped: the hidden count must stay exact.
1862
+ * @param deferred - names the session mounted but did not offer.
1863
+ * @returns one entry per server, by descending count, then by name.
1864
+ */
1865
+ export function hiddenByServer(deferred: readonly string[]): HiddenServer[] {
1866
+ return byServer(deferred)
1867
+ }
1868
+
1869
+ /**
1870
+ * Split the pinned names by the server each one came from (F-44).
1871
+ *
1872
+ * The pinned tier reads its names per server for the same reason the hidden tier
1873
+ * does: a server is the unit a user thinks in when the list gets long, and it is
1874
+ * what the one press that releases a whole server acts on. The grouping is
1875
+ * {@link hiddenByServer}'s own, so the two tiers of one block order their groups
1876
+ * alike — biggest first, then by name — while each keeps its own list's order
1877
+ * inside a group.
1878
+ * @param pins - the project's pin list, as the host published it.
1879
+ * @returns one entry per server, each holding the names it contributed.
1880
+ */
1881
+ export function pinnedByServer(pins: readonly string[]): ServerNames[] {
1882
+ return byServer(pins)
1883
+ }
1884
+
1885
+ /**
1886
+ * One list of registry names, grouped by the server each name carries.
1887
+ *
1888
+ * A name without the registry's prefix belongs to no server and is filed under
1889
+ * `unknown` rather than dropped or attributed to a made-up one: the group is
1890
+ * real even when the name cannot be traced, and a row that vanished would hide a
1891
+ * pin the user wrote.
1892
+ * @param list - the names to group, in the order they are read in.
1893
+ * @returns one entry per server, biggest group first, then by server name.
1894
+ */
1895
+ function byServer(list: readonly string[]): ServerNames[] {
1896
+ const names = new Map<string, string[]>()
1897
+ for (const name of list) {
1898
+ const server = serverOfToolName(name) ?? 'unknown'
1899
+ const held = names.get(server)
1900
+ if (held === undefined) names.set(server, [name])
1901
+ else held.push(name)
1902
+ }
1903
+ return [...names.entries()]
1904
+ .map(([server, held]) => ({ server, count: held.length, names: held }))
1905
+ .sort((left, right) => right.count - left.count || left.server.localeCompare(right.server))
1906
+ }
1907
+
1908
+ /**
1909
+ * The prefix the registry publishes project MCP tools under, and the server part
1910
+ * of one such name — defined in `./usage-view.ts` and re-exported at the top of
1911
+ * this module, where the panel's callers have always found them.
1912
+ */
1913
+
1914
+ /** How much of the disclosure budget the session has spent. */
1915
+ export interface BudgetSplit {
1916
+ /** Tools the model sees. */
1917
+ used: number
1918
+ /** Tools mounted for the project. */
1919
+ total: number
1920
+ /** `used / total` as a whole percentage, `0` when nothing is mounted. */
1921
+ percent: number
1922
+ /** `true` while the surface is over its configured budget. */
1923
+ exhausted: boolean
1924
+ }
1925
+
1926
+ /**
1927
+ * Split the session's tool offer against the mounted surface: the bar and the
1928
+ * tooltip of the budget line. Both numbers are real counts the host published.
1929
+ * @param tools - one session's tool offer.
1930
+ * @returns the offering against the mounted total.
1931
+ */
1932
+ export function budgetSplit(tools: SessionTools): BudgetSplit {
1933
+ const used = toolCounts(tools).offering
1934
+ const total = tools.mounted
1935
+ return {
1936
+ used,
1937
+ total,
1938
+ percent: total === 0 ? 0 : Math.min(100, Math.round((used / total) * 100)),
1939
+ exhausted: tools.deferring,
1940
+ }
1941
+ }
1942
+
1943
+ /**
1944
+ * One tier of the tools block: the four parts its counter chips count, and the
1945
+ * four the filter panel switches between (F-43).
1946
+ */
1947
+ export type ToolTier = 'pinned' | 'counters' | 'disclosed' | 'hidden'
1948
+
1949
+ /**
1950
+ * The tools block's filter: one query over the registry names, and the tiers the
1951
+ * user narrowed the list to.
1952
+ *
1953
+ * The two halves answer different questions and are kept apart because of it: a
1954
+ * query asks "where is this name", a tier asks "show me this rung alone", and
1955
+ * the block draws the names that pass both. The filter is the tools block's own
1956
+ * state rather than a persisted one — unlike the log ring's filters, which are
1957
+ * stored because a page of the ring costs a request — because a query is a
1958
+ * reading aid for the minute, and a panel that reopened onto a stale one would
1959
+ * read as an empty catalogue.
1960
+ */
1961
+ export interface ToolFilter {
1962
+ /** Free text, matched against the registry name; empty passes every name. */
1963
+ query: string
1964
+ /** Tiers to draw; empty — every tier — is the state the block opens in. */
1965
+ tiers: readonly ToolTier[]
1966
+ }
1967
+
1968
+ /** The filter of a block nobody has narrowed, where everything passes. */
1969
+ export const NO_TOOL_FILTER: ToolFilter = { query: '', tiers: [] }
1970
+
1971
+ /**
1972
+ * `true` when `name` passes the query.
1973
+ *
1974
+ * A case-insensitive substring, so `grafana` finds `mcp__grafana-local__query`:
1975
+ * the registry name carries its server as its own prefix, and one field answers
1976
+ * both readings. The query is trimmed first, because a search field with a
1977
+ * trailing space would otherwise match nothing and look broken.
1978
+ * @param name - the registry name of the row.
1979
+ * @param query - what the user typed.
1980
+ * @returns whether the name passes.
1981
+ */
1982
+ export function matchesToolQuery(name: string, query: string): boolean {
1983
+ const needle = query.trim().toLowerCase()
1984
+ return needle === '' || name.toLowerCase().includes(needle)
1985
+ }
1986
+
1987
+ /**
1988
+ * `true` while the filter narrows anything at all — a query, a tier, or both.
1989
+ *
1990
+ * The block asks this to decide whether it is showing a filtered list: the
1991
+ * counts line, the empty state and the hidden tier's own opening all turn on it.
1992
+ * @param filter - the block's filter.
1993
+ * @returns whether the filter is doing something.
1994
+ */
1995
+ export function toolFilterActive(filter: ToolFilter): boolean {
1996
+ return filter.query.trim() !== '' || filter.tiers.length > 0
1997
+ }
1998
+
1999
+ /**
2000
+ * `true` when the filter lets this tier through: no tier pressed means every
2001
+ * tier, which is the reading the block opens in.
2002
+ * @param filter - the block's filter.
2003
+ * @param tier - the tier being drawn.
2004
+ * @returns whether the tier is drawn.
2005
+ */
2006
+ export function tierVisible(filter: ToolFilter, tier: ToolTier): boolean {
2007
+ return filter.tiers.length === 0 || filter.tiers.includes(tier)
2008
+ }
2009
+
2010
+ /**
2011
+ * The rows of one tier that pass the query, in the order they were given.
2012
+ * @param rows - the tier's rows, already in the block's own order.
2013
+ * @param query - what the user typed.
2014
+ * @returns the rows to draw.
2015
+ */
2016
+ export function filterToolRows<T extends { name: string }>(rows: readonly T[], query: string): T[] {
2017
+ return rows.filter((row) => matchesToolQuery(row.name, query))
2018
+ }
2019
+
2020
+ /**
2021
+ * The hidden names that pass the query, grouped by server as they were.
2022
+ *
2023
+ * A server whose every hidden name is filtered out goes with its count: the
2024
+ * group head prints `{server} · {count}` of what is drawn under it, and a head
2025
+ * over an empty list would be a number the user cannot spend.
2026
+ * @param servers - the hidden names, grouped by server ({@link hiddenByServer}).
2027
+ * @param query - what the user typed.
2028
+ * @returns the groups that kept at least one name, their counts renumbered.
2029
+ */
2030
+ export function filterHiddenServers(
2031
+ servers: readonly HiddenServer[],
2032
+ query: string,
2033
+ ): HiddenServer[] {
2034
+ const kept: HiddenServer[] = []
2035
+ for (const entry of servers) {
2036
+ const names = entry.names.filter((name) => matchesToolQuery(name, query))
2037
+ if (names.length > 0) kept.push({ server: entry.server, names, count: names.length })
2038
+ }
2039
+ return kept
2040
+ }
2041
+
2042
+ /**
2043
+ * The tier list with one tier toggled: a press adds it, a second press releases
2044
+ * it. An empty list means every tier, so releasing the last one hands the block
2045
+ * its full list back.
2046
+ * @param tiers - the tiers currently pressed.
2047
+ * @param tier - the tier the user pressed.
2048
+ * @returns the new tier list, in the order the presses happened.
2049
+ */
2050
+ export function toggledTier(tiers: readonly ToolTier[], tier: ToolTier): ToolTier[] {
2051
+ return tiers.includes(tier) ? tiers.filter((held) => held !== tier) : [...tiers, tier]
2052
+ }
2053
+
2054
+ /** How much of one server's tool set a project already pins. */
2055
+ export type ServerPinState = 'all' | 'some' | 'none'
2056
+
2057
+ /**
2058
+ * How much of one server's names the project already pins (F-44).
2059
+ *
2060
+ * The question a server-level control answers is about a *set* of names — the
2061
+ * ones its own surface lists — so the reading is a proportion and not a flag:
2062
+ * `all`, a part, or none. Both surfaces ask it before they draw their switch and
2063
+ * again before they write.
2064
+ * @param names - the names this control speaks for, as its surface lists them.
2065
+ * @param pins - the project's own pin list.
2066
+ * @returns the proportion of `names` the pin list holds.
2067
+ */
2068
+ export function serverPinState(
2069
+ names: readonly string[],
2070
+ pins: readonly string[],
2071
+ ): ServerPinState {
2072
+ const held = new Set(pins)
2073
+ const pinned = names.filter((name) => held.has(name)).length
2074
+ if (pinned === 0) return 'none'
2075
+ return pinned === names.length ? 'all' : 'some'
2076
+ }
2077
+
2078
+ /**
2079
+ * What one press of a server-level control writes (F-44).
2080
+ *
2081
+ * A server pin is the names themselves — the same list, the same route — and not
2082
+ * a rule of its own: this unit expands a server into its names, so a tool the
2083
+ * server mounts later is covered by no earlier press (the limits are in
2084
+ * `docs/design/contracts/policy.md`).
2085
+ *
2086
+ * The direction is the reading's own: a set that is wholly pinned is released,
2087
+ * and any other set is completed. A half-pinned server therefore *adds* the
2088
+ * names it is missing rather than throwing the pinned ones away, so one press
2089
+ * ever moves the set towards a state the user asked for and never loses a pin
2090
+ * nobody touched.
2091
+ * @param names - the names this control speaks for.
2092
+ * @param pins - the project's own pin list.
2093
+ * @returns the names to write and the state to write them in. The names are
2094
+ * empty only when the set is empty: a set that is wholly pinned is released
2095
+ * whole, and any other set has at least one name missing.
2096
+ */
2097
+ export function serverPinPress(
2098
+ names: readonly string[],
2099
+ pins: readonly string[],
2100
+ ): { pinned: boolean; names: string[] } {
2101
+ const held = new Set(pins)
2102
+ if (serverPinState(names, pins) === 'all') {
2103
+ return { pinned: false, names: names.filter((name) => held.has(name)) }
2104
+ }
2105
+ return { pinned: true, names: names.filter((name) => !held.has(name)) }
2106
+ }
2107
+
2108
+ /** One counter of the tools vocabulary: which tier, its label, and the count. */
2109
+ export interface CounterPart {
2110
+ /** Tier the counter answers for. */
2111
+ key: ToolTier
2112
+ /** Locale label of the tier, already translated. */
2113
+ label: string
2114
+ count: number
2115
+ }
2116
+
2117
+ /**
2118
+ * The four counters, one part each.
2119
+ *
2120
+ * Two of them are tiers of one list and have to be told apart: `pinned` is the
2121
+ * user's own pin list, `counters` is the rest of the baseline — the names the
2122
+ * durable usage counters proved hot. As one number they could say "2 pinned"
2123
+ * over a pin list of one, which is exactly what the block drew before: the
2124
+ * sentence promised an action on rows that carried none. The budget still counts
2125
+ * both, because both are offered in every request ({@link toolCounts}).
2126
+ *
2127
+ * One source for every reading of these numbers: the tools block draws one chip
2128
+ * per part, and the settings page's Tools rows read the same parts, so the two
2129
+ * surfaces can never disagree. A part whose count is zero is not a chip — the
2130
+ * block prints numbers, not the absence of them.
2131
+ * @param tools - one session's tool offer.
2132
+ * @param policy - the project's tool policy, which owns the pin list.
2133
+ * @param t - translate seat.
2134
+ * @returns pinned, counters, disclosed and hidden, in that order.
2135
+ */
2136
+ export function counterParts(
2137
+ tools: SessionTools,
2138
+ policy: ToolPolicy,
2139
+ t: Translate,
2140
+ ): CounterPart[] {
2141
+ const counts = toolCounts(tools)
2142
+ const byCounters = tools.baseline.filter((name) => !policy.pins.includes(name)).length
2143
+ return [
2144
+ { key: 'pinned', label: t('toolsPinned'), count: policy.pins.length },
2145
+ { key: 'counters', label: t('toolsByCounters'), count: byCounters },
2146
+ { key: 'disclosed', label: t('toolsDisclosed'), count: counts.disclosed },
2147
+ { key: 'hidden', label: t('toolsHidden'), count: counts.hidden },
2148
+ ]
2149
+ }
2150
+
2151
+ /** A tool row the tools block draws, with the action it offers. */
2152
+ export interface ToolRow {
2153
+ /** Registry name. */
2154
+ name: string
2155
+ /** `true` when the project's own pin list holds this name, not the counters. */
2156
+ pinned?: boolean
2157
+ /** Clock time of the last offer or call, as `HH:MM`, when the host published one. */
2158
+ time?: string | undefined
2159
+ /** Short label shown on the row, when there is one. */
2160
+ note?: string | undefined
2161
+ /**
2162
+ * Both of the host's readings for this row: the project's counter and this
2163
+ * session's, and whether the host recorded the row's server at all.
2164
+ *
2165
+ * The property is absent where the host published nothing for the project,
2166
+ * which is what keeps a row the counters never saw from reading as a row of
2167
+ * zeroes.
2168
+ */
2169
+ calls?: ToolCalls | undefined
2170
+ }
2171
+
2172
+ /**
2173
+ * The pinned rows to draw: the user's own pin list, then the counter-seeded
2174
+ * remainder of the baseline tier.
2175
+ *
2176
+ * The pin list is the only durable user choice here, so it comes first and is
2177
+ * the only part with an `Unpin` action. The rest of `baseline` is offered for
2178
+ * the same reason the counters say "pinned": the durable usage counters proved
2179
+ * those names hot, and a name that disappeared from the list would make the
2180
+ * toolbar's own badge disagree with what is under it. Those rows carry no
2181
+ * action — unpinning a name the user never pinned is not a thing this panel
2182
+ * offers — and get {@link ToolRow.pinned} `false`.
2183
+ * @param tools - one session's tool offer.
2184
+ * @param policy - the project's policy, whose `pins` are the user's own list.
2185
+ * @returns one row per offered name, user-pinned first, in list order.
2186
+ */
2187
+ export function pinnedRows(tools: SessionTools, policy: ToolPolicy): ToolRow[] {
2188
+ const pinned = policy.pins.map((name) => ({ name, pinned: true }))
2189
+ const pinnedNames = new Set(policy.pins)
2190
+ const counted = tools.baseline
2191
+ .filter((name) => !pinnedNames.has(name))
2192
+ .map((name) => ({ name, pinned: false }))
2193
+ return [...pinned, ...counted]
2194
+ }
2195
+
2196
+ /**
2197
+ * The clock time of one offer, as a disclosed row shows it.
2198
+ *
2199
+ * Only the `session` tier carries `at`; the `context` tier records a step, not a
2200
+ * time, so a row without one renders no clock at all.
2201
+ * @param at - epoch milliseconds of the last offer or call.
2202
+ * @returns `HH:MM` in the viewer's own zone.
2203
+ */
2204
+ export function toolTime(at: number): string {
2205
+ const date = new Date(at)
2206
+ const pad = (value: number): string => String(value).padStart(2, '0')
2207
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}`
2208
+ }
2209
+
2210
+ /**
2211
+ * Surface A's budget line, one branch per state the host can publish.
2212
+ *
2213
+ * `deferring` decides first, because it is the same flag that fills `deferred`:
2214
+ * a line that claimed the gate was off while the list below it showed hidden
2215
+ * tools would contradict itself. With nothing deferred, `budgetChars: 0` means
2216
+ * the gate is switched off in this deployment — the contract's own reading of a
2217
+ * zero budget — and any other budget means the surface simply fits, which is
2218
+ * not a state: a fitting surface gets no line at all, because the chips above
2219
+ * already carry `0 hidden` and a sentence repeating that is the empty row the
2220
+ * block stopped drawing.
2221
+ *
2222
+ * The figure is the host's own measurement in **characters** (`surfaceChars` /
2223
+ * `budgetChars`, contract C7), with the token count derived from it at the
2224
+ * contract's own rate of four characters per token. There are no slots here:
2225
+ * the host has never modelled them, so the line no longer invents them.
2226
+ * @param tools - one session's tool offer.
2227
+ * @param t - translate seat.
2228
+ * @returns the budget row, `null` when there is nothing to say, without the
2229
+ * exhausted note above it.
2230
+ */
2231
+ export function budgetLine(tools: SessionTools, t: Translate): ReactNode {
2232
+ if (tools.deferring) {
2233
+ const split = budgetSplit(tools)
2234
+ const tokens = Math.round(tools.surfaceChars / 4)
2235
+ return h(
2236
+ 'div',
2237
+ null,
2238
+ h(
2239
+ 'div',
2240
+ {
2241
+ style: STYLE.budget,
2242
+ title: t('toolsBudgetBreakdown', {
2243
+ used: split.used,
2244
+ total: split.total,
2245
+ percent: split.percent,
2246
+ }),
2247
+ },
2248
+ h('span', { style: { ...STYLE.budgetUsed, width: `${split.percent}%` } }),
2249
+ ),
2250
+ h(
2251
+ 'div',
2252
+ { style: STYLE.muted },
2253
+ t('toolsBudget', {
2254
+ used: tools.surfaceChars,
2255
+ total: tools.budgetChars,
2256
+ tokens,
2257
+ }),
2258
+ ),
2259
+ )
2260
+ }
2261
+ if (tools.budgetChars === 0) return h('div', { style: STYLE.muted }, t('toolsBudgetGateOff'))
2262
+ return null
2263
+ }
2264
+
2265
+ /**
2266
+ * What one tool row's detail block is opened with (F-26).
2267
+ *
2268
+ * The block prints only what the host published about this one name. `SessionTools`
2269
+ * measures the whole set (`surfaceChars` / `visibleChars` / `deferredChars`), not
2270
+ * a single tool, so there is no per-tool size here to print and none is derived:
2271
+ * the group's own budget line is where an estimate is real.
2272
+ */
2273
+ export interface ToolDetail {
2274
+ /** Tier that offered the name: the pin list, this session, or context ranking. */
2275
+ via: 'pin' | 'session' | 'context'
2276
+ /** The host's own step counter, when it published one (contract C2). */
2277
+ step?: number | undefined
2278
+ /** Epoch milliseconds of the last offer or call, when the host published one. */
2279
+ at?: number | undefined
2280
+ /** `true` while this row's detail block is open. */
2281
+ open: boolean
2282
+ /** Toggle this row's detail block. */
2283
+ onToggle: () => void
2284
+ }
2285
+
2286
+ /**
2287
+ * The fact line of one tool's detail block.
2288
+ *
2289
+ * The server comes out of the registry name the host publishes, and the step and
2290
+ * the time appear only while the host published them: no number, no line —
2291
+ * an invented `step 4` is exactly what contract C2 exists to prevent. A name
2292
+ * that does not carry the `mcp__` prefix has no server to name, and then no
2293
+ * server is printed rather than a guessed one.
2294
+ * @param name - the registry name on the row.
2295
+ * @param detail - the tier and the host's own step and time, when it gave them.
2296
+ * @param t - translate seat.
2297
+ * @returns the facts to join into one line, in the contract's order.
2298
+ */
2299
+ export function toolDetailFacts(name: string, detail: ToolDetail, t: Translate): string[] {
2300
+ const server = serverOfToolName(name)
2301
+ const tier =
2302
+ detail.via === 'pin'
2303
+ ? t('toolTierPinned')
2304
+ : detail.via === 'session'
2305
+ ? t('toolTierSession')
2306
+ : t('toolTierContext')
2307
+ return [
2308
+ server === undefined ? undefined : t('toolServer', { server }),
2309
+ tier,
2310
+ detail.step === undefined ? undefined : t('toolsStep', { step: detail.step }),
2311
+ detail.at === undefined ? undefined : toolTime(detail.at),
2312
+ ].filter((fact): fact is string => fact !== undefined)
2313
+ }
2314
+
2315
+ /**
2316
+ * One row of the one surface's tools block: a header button that opens the
2317
+ * registry name and how the tool was offered, and the row's one action beside it.
2318
+ *
2319
+ * F-26 turned the row into a disclosure. The header keeps what it always showed
2320
+ * — the tier dot, the name, the time and the step the host gave, and the pin
2321
+ * action — and lives in a `button[aria-expanded]` so the row itself is the parity
2322
+ * gate's tool line. The action stays a sibling: a button inside a button is not a
2323
+ * thing HTML has.
2324
+ * @param row - the name, its time and its note.
2325
+ * @param action - the row's one action, when it has one.
2326
+ * @param tier - which tier offered the row; `pinned` when not given.
2327
+ * @param detail - the disclosure state and the facts it opens.
2328
+ * @param t - translate seat; falls back to this module's English copy.
2329
+ * @returns the row element.
2330
+ */
2331
+ export function toolRow(
2332
+ row: ToolRow,
2333
+ action: { label: string; hint: string; onClick: () => void; disabled?: boolean } | undefined,
2334
+ tier: 'pinned' | 'disclosed' | 'hidden',
2335
+ detail: ToolDetail,
2336
+ t: Translate = translateOf(),
2337
+ ): ReactNode {
2338
+ const open = detail.open
2339
+ const calls = callsLabel(row.calls, t)
2340
+ return h(
2341
+ 'div',
2342
+ { key: row.name, style: STYLE.tool },
2343
+ h(
2344
+ 'button',
2345
+ {
2346
+ style: STYLE.toolLine,
2347
+ 'aria-expanded': open,
2348
+ title: open ? t('hideTool') : t('showTool'),
2349
+ onClick: detail.onToggle,
2350
+ },
2351
+ h('span', {
2352
+ style: { ...STYLE.dot, background: STATUS_COLOR[tier === 'pinned' ? 'active' : 'idle'] },
2353
+ }),
2354
+ h('span', { style: STYLE.name }, row.name),
2355
+ // The host's own counter, immediately after the name it counts: the one
2356
+ // reading on the row that is about how the tool has been used rather than
2357
+ // about what it is.
2358
+ calls === undefined ? null : h('span', { style: STYLE.dim }, calls),
2359
+ row.time === undefined ? null : h('span', { style: STYLE.muted }, row.time),
2360
+ row.note === undefined ? null : h('span', { style: STYLE.muted }, row.note),
2361
+ ),
2362
+ action === undefined
2363
+ ? null
2364
+ : h(
2365
+ 'button',
2366
+ { style: STYLE.button, title: action.hint, disabled: action.disabled === true, onClick: action.onClick },
2367
+ action.label,
2368
+ ),
2369
+ open
2370
+ ? h(
2371
+ 'div',
2372
+ { style: STYLE.toolDetail },
2373
+ // The full public name the host published, in mono — the same string the
2374
+ // header shows, spelled out where there is room for it.
2375
+ h('div', { style: STYLE.name }, row.name),
2376
+ h('div', { style: STYLE.detail }, toolDetailFacts(row.name, detail, t).join(' · ')),
2377
+ )
2378
+ : null,
2379
+ )
2380
+ }
2381
+
2382
+ /**
2383
+ * The declared servers of this session, in document order, with the state each
2384
+ * one is in.
2385
+ *
2386
+ * The first block of the one surface answers "what is declared, and what is it
2387
+ * doing right now", and a server that is declared but not serving is exactly why
2388
+ * an apparently empty catalog is empty: without this list `Nothing to hide yet`
2389
+ * reads as "nothing is wrong" while a stalled process quietly withholds all of
2390
+ * its tools.
2391
+ *
2392
+ * The row is the status and nothing else — the dot, the name, the status word
2393
+ * and the transport chip. Its `title` still carries the host's own multi-line
2394
+ * diagnostic, so hovering answers "why" without a click, but the diagnostic is
2395
+ * not drawn under the rows: F-26 hid it behind the errors disclosure, which
2396
+ * prints the same host text through {@link IssueView}'s rows. Drawing it in both
2397
+ * places put an amber wall between the model's tools and the reader.
2398
+ * @param props - the rows to list and the translate seat.
2399
+ * @returns the section, or `null` when the session declares nothing.
2400
+ */
2401
+ export function ServersBlock(props: {
2402
+ rows: readonly ServerRow[]
2403
+ /** The project's usage counters, when the host published any (`idle {n}d`). */
2404
+ usage?: ProjectUsage
2405
+ t: Translate
2406
+ /** Host-namespace seat for the rows' coded details (F-48). */
2407
+ hostT?: Translate | undefined
2408
+ }): ReactNode {
2409
+ const { rows, t } = props
2410
+ if (rows.length === 0) return null
2411
+ const up = rows.filter((row) => row.status === 'active').length
2412
+ const failed = rows.filter((row) => row.status === 'error').length
2413
+ return h(
2414
+ 'div',
2415
+ { style: STYLE.serversBlock },
2416
+ h(
2417
+ 'div',
2418
+ { style: STYLE.row },
2419
+ h('span', { style: STYLE.groupInline }, t('toolsServers')),
2420
+ h('span', { style: { flex: 1 } }),
2421
+ h(
2422
+ 'span',
2423
+ {
2424
+ style: failed === 0 ? STYLE.tag : { ...STYLE.tag, ...STYLE.tagWarn },
2425
+ title: rows.map((row) => `${row.name}: ${t(STATUS_KEYS[row.status])}`).join('\n'),
2426
+ },
2427
+ t('toolsServersUp', { up, total: rows.length }),
2428
+ ),
2429
+ ),
2430
+ ...rows.map((row) => {
2431
+ // The host's own record of this server; a row the counters never saw has
2432
+ // no `lastUsedAt` to read and the quiet word is simply not drawn.
2433
+ const idle = idleNote(row.status, props.usage?.[row.name]?.lastUsedAt, t)
2434
+ return h(
2435
+ 'div',
2436
+ {
2437
+ style: STYLE.row,
2438
+ key: `tools#server#${row.name}`,
2439
+ title: rowDetail(row, props.hostT) ?? t(STATUS_HINT[row.status]),
2440
+ },
2441
+ h('span', {
2442
+ style: { ...STYLE.dot, background: STATUS_COLOR[row.status] },
2443
+ 'aria-hidden': true,
2444
+ }),
2445
+ h('span', { style: STYLE.name }, row.name),
2446
+ // The status as a word, not only as the dot's colour: the question this
2447
+ // block answers is asked by someone who may not know the palette.
2448
+ h('span', { style: { ...STYLE.muted, color: STATUS_COLOR[row.status] } }, t(STATUS_KEYS[row.status])),
2449
+ idle === undefined ? null : h('span', { style: STYLE.dim }, idle),
2450
+ row.transport === undefined
2451
+ ? null
2452
+ : h('span', { style: STYLE.tag }, shortTransport(row.transport)),
2453
+ )
2454
+ }),
2455
+ )
2456
+ }
2457
+
2458
+ /**
2459
+ * The hidden tier of the tools block: the names the model does not see, in a
2460
+ * list the user can open and act on.
2461
+ *
2462
+ * Hidden is the one tier whose contents are a list rather than a reading. The
2463
+ * counters already say how many names are left out, so this block adds the two
2464
+ * things they cannot: the names themselves, grouped by the server they were
2465
+ * mounted from, and the `Pin` that pulls one back into every request. The open
2466
+ * state arrives from the parent, so the tier is a pure function of its props —
2467
+ * the same reason the head is drawn by {@link disclosureHead} rather than by
2468
+ * {@link Disclosure}.
2469
+ * @param props - the hidden names, the requested `Pin` write and the open state.
2470
+ * @returns the head and, while open, one row per server and name.
2471
+ */
2472
+ export function HiddenTier(props: {
2473
+ /** How many names the head's badge prints, the counters' own hidden figure. */
2474
+ count: number
2475
+ /** The hidden names, grouped by server, in the host's order. */
2476
+ servers: readonly HiddenServer[]
2477
+ /** `true` while the list is open. */
2478
+ open: boolean
2479
+ /** Toggle the list. */
2480
+ onToggle: () => void
2481
+ /** Pin one name, or absent while there is nothing to write to. */
2482
+ onChange?: ((tool: string, pinned: boolean) => void) | undefined
2483
+ /**
2484
+ * Pin every name of one server in one press (F-44), or absent while there is
2485
+ * nothing to write to. The names are this group's own: the list is what the
2486
+ * user is reading, and a server action that wrote names the tier does not show
2487
+ * would be a press with a hidden meaning.
2488
+ */
2489
+ onPinServer?: ((server: string, names: readonly string[]) => void) | undefined
2490
+ /**
2491
+ * The project's own pin list, read for one thing only: whether a server's group
2492
+ * is already wholly pinned, which decides whether the line says `Pin all` or
2493
+ * `Unpin all`. A tier's names are usually unpinned, but nothing in the snapshot
2494
+ * forbids a pinned name to sit in `deferred` — a pin written between two
2495
+ * assemblies, or one the host itself still defers — and the label may not
2496
+ * promise the opposite of what the press does.
2497
+ */
2498
+ pins?: readonly string[] | undefined
2499
+ /** `true` while a pin write is in flight, so the buttons stay still. */
2500
+ pending: boolean
2501
+ t: Translate
2502
+ }): ReactNode {
2503
+ const { t } = props
2504
+ /**
2505
+ * One server line's own press.
2506
+ *
2507
+ * The words follow the reading both surfaces share ({@link serverPinState}): a
2508
+ * group that is wholly pinned says `Unpin all`, anything else says `Pin all` —
2509
+ * and the direction the parent writes is {@link serverPinPress}'s, which is the
2510
+ * same rule. In the ordinary case a group's names are unpinned and the second
2511
+ * word never appears: it exists for the snapshot where a name is pinned and
2512
+ * still deferred — a pin written between two assemblies, or a hidden name the
2513
+ * user pinned from this very list — because there the first word would be the
2514
+ * opposite of what the press does.
2515
+ * @param entry - one server's hidden names.
2516
+ * @returns the press of that line.
2517
+ */
2518
+ const serverPress = (entry: HiddenServer): ReactNode => {
2519
+ const all = serverPinState(entry.names, props.pins ?? []) === 'all'
2520
+ return h(
2521
+ 'button',
2522
+ {
2523
+ type: 'button',
2524
+ style: STYLE.button,
2525
+ title: all ? t('toolsUnpinAllHint') : t('toolsPinAllHint'),
2526
+ disabled: props.pending,
2527
+ onClick: () => props.onPinServer?.(entry.server, entry.names),
2528
+ },
2529
+ all ? t('toolsUnpinAll') : t('toolsPinAll'),
2530
+ )
2531
+ }
2532
+ return h(
2533
+ 'div',
2534
+ { style: STYLE.disclosure },
2535
+ disclosureHead({
2536
+ label: t('toolsGroupHidden'),
2537
+ count: props.count,
2538
+ open: props.open,
2539
+ hint: t('toolsHiddenVia'),
2540
+ onToggle: props.onToggle,
2541
+ }),
2542
+ props.open
2543
+ ? h(
2544
+ 'div',
2545
+ { style: STYLE.disclosureBody },
2546
+ ...props.servers.flatMap((entry) => [
2547
+ // The server's own line, with the one press that takes all of it
2548
+ // (F-44): the label stays the reading it was, and the action sits at
2549
+ // the right edge the way every other action in the block does.
2550
+ h(
2551
+ 'div',
2552
+ { key: `${entry.server}-group`, style: STYLE.row },
2553
+ h('span', { style: STYLE.group }, `${entry.server} · ${entry.count}`),
2554
+ h('span', { style: { flex: 1 } }),
2555
+ props.onPinServer === undefined ? null : serverPress(entry),
2556
+ ),
2557
+ // One row per name, the full `mcp__<server>__<tool>` the registry
2558
+ // carries, with the pin that moves it into the always-offered list.
2559
+ // The row is not a disclosure of its own: a list read to be chosen
2560
+ // needs no second level under each name.
2561
+ ...entry.names.map((name) =>
2562
+ toolRow(
2563
+ { name },
2564
+ {
2565
+ label: t('toolsPin'),
2566
+ hint: t('toolsPinHint'),
2567
+ onClick: () => props.onChange?.(name, true),
2568
+ disabled: props.pending,
2569
+ },
2570
+ 'hidden',
2571
+ { via: 'pin', open: false, onToggle: () => undefined },
2572
+ t,
2573
+ ),
2574
+ ),
2575
+ ]),
2576
+ )
2577
+ : null,
2578
+ )
2579
+ }
2580
+
2581
+ /**
2582
+ * The tools block's filter row (F-43): one query over the registry names, the
2583
+ * count of what is left on screen, and the `Clear` that hands the whole list
2584
+ * back.
2585
+ *
2586
+ * The tier half of the filter is not here but in the counter chips of the row
2587
+ * above, which stop being a reading and become the switch. The block prints one
2588
+ * number per tier (F-28) and says it once (F-37), so a second row of the same
2589
+ * four words without their counts would be a copy of a figure the chips already
2590
+ * carry.
2591
+ *
2592
+ * Nothing is drawn while the caller hands in no writer: a pure tree composed by
2593
+ * a spec keeps the block it had — an input whose value could never change is the
2594
+ * worse half of a control. The design-only render mode is not that caller: it
2595
+ * composes {@link tabBody}, so its panel is the product's own. The caption is
2596
+ * the exception: a filter the block was handed still hides rows, and hiding them
2597
+ * without saying so is the one thing the row exists to prevent.
2598
+ * @param props - the filter, what it kept, and the writers behind it.
2599
+ * @returns the panel's row with its own caption; the caption alone without a
2600
+ * writer, and `null` when a filter nobody applied has no writer either.
2601
+ */
2602
+ export function ToolsFilter(props: {
2603
+ filter: ToolFilter
2604
+ /** Names passing the filter, and every name the block holds before it. */
2605
+ shown: number
2606
+ total: number
2607
+ /** Replace the query; absent leaves the field out of the tree. */
2608
+ onQuery?: ((query: string) => void) | undefined
2609
+ /** Drop the query and every pressed tier. */
2610
+ onClear?: (() => void) | undefined
2611
+ t: Translate
2612
+ }): ReactNode {
2613
+ const { t } = props
2614
+ const active = toolFilterActive(props.filter)
2615
+ // The caption is the only place the filter's own effect is readable: the chips
2616
+ // above it count the tiers, not what the query left of them.
2617
+ const caption = active
2618
+ ? h(
2619
+ 'div',
2620
+ { style: STYLE.dim },
2621
+ props.shown === 0
2622
+ ? t('toolsFilterNone')
2623
+ : t('toolsFilterShown', { shown: props.shown, total: props.total }),
2624
+ )
2625
+ : null
2626
+ if (props.onQuery === undefined) return caption
2627
+ return h(
2628
+ 'div',
2629
+ null,
2630
+ h(
2631
+ 'div',
2632
+ { style: STYLE.row },
2633
+ h('input', {
2634
+ type: 'search',
2635
+ style: STYLE.filterInput,
2636
+ value: props.filter.query,
2637
+ placeholder: t('toolsFilterPlaceholder'),
2638
+ 'aria-label': t('toolsFilterLabel'),
2639
+ onChange: (event: { target: { value: string } }) => props.onQuery?.(event.target.value),
2640
+ }),
2641
+ active && props.onClear !== undefined
2642
+ ? h(
2643
+ 'button',
2644
+ {
2645
+ type: 'button',
2646
+ style: STYLE.button,
2647
+ title: t('toolsFilterClearHint'),
2648
+ onClick: () => props.onClear?.(),
2649
+ },
2650
+ t('toolsFilterClear'),
2651
+ )
2652
+ : null,
2653
+ ),
2654
+ caption,
2655
+ )
2656
+ }
2657
+
2658
+ /**
2659
+ * The tools block of the single surface: what this session's model sees now.
2660
+ *
2661
+ * Answers with the three counters, the pinned list, the tools the session
2662
+ * disclosed, and the hidden remainder grouped by the server it was mounted from.
2663
+ * Every reading is the host's own: `policy.pins` for the list a user wrote by
2664
+ * hand, `SessionTools` for the offer counters, `OfferedTool.step` for the
2665
+ * disclosure step (contract C2), and `ProjectSnapshot.presentation` for a second
2666
+ * owner of the request (contract C3). Pure and without state: the row whose
2667
+ * detail block is open is handed in by {@link ToolsSection}, which keeps one
2668
+ * open at a time.
2669
+ *
2670
+ * The filter (F-43) arrives the same way, from {@link ToolsSection}: the query,
2671
+ * the pressed tiers and the three writers. Without them the block draws every
2672
+ * tier and every name, exactly as it did before the panel existed.
2673
+ */
2674
+ export function ToolsView(props: {
2675
+ project: ProjectSnapshot
2676
+ sessionId: string
2677
+ /** Policy to read the pin list from; the project's own when omitted. */
2678
+ policy?: ToolPolicy | undefined
2679
+ /** Pin or unpin one name; absent while there is nothing to write to. */
2680
+ onPin?: ((tool: string, pinned: boolean) => void) | undefined
2681
+ /**
2682
+ * Pin every hidden name of one server in one press (F-44). The names travel
2683
+ * with the call because this block is what grouped them; the writer above
2684
+ * expands them into the pin list the host stores.
2685
+ */
2686
+ onPinServer?: ((server: string, names: readonly string[]) => void) | undefined
2687
+ /** `true` while a pin request is in flight, so the buttons stay still. */
2688
+ pending?: boolean
2689
+ /** The one row whose detail block is open, when a row is open. */
2690
+ openTool?: string | undefined
2691
+ /** Toggle one row's detail block. */
2692
+ onToggleTool?: ((name: string) => void) | undefined
2693
+ /**
2694
+ * The hidden list's own state: `true` / `false` once the user has pressed its
2695
+ * head, `undefined` while nobody has — which is the state the filter is
2696
+ * allowed to open the tier in. Held by {@link ToolsSection} and not by the
2697
+ * tier itself, so this block stays a pure tree of elements: its tests resolve
2698
+ * it without a React runtime.
2699
+ */
2700
+ openHidden?: boolean | undefined
2701
+ /** Toggle the hidden list. */
2702
+ onToggleHidden?: (() => void) | undefined
2703
+ /** The filter the panel shows; absent means every tier, every name. */
2704
+ filter?: ToolFilter | undefined
2705
+ /** Replace the query. */
2706
+ onQuery?: ((query: string) => void) | undefined
2707
+ /** Fold one tier in or out of the filter. */
2708
+ onTier?: ((tier: ToolTier) => void) | undefined
2709
+ /** Drop the query and every pressed tier. */
2710
+ onClearFilter?: (() => void) | undefined
2711
+ t: Translate
2712
+ /** Host-namespace seat for the presentation owner's coded note (F-48). */
2713
+ hostT?: Translate | undefined
2714
+ }): ReactNode {
2715
+ const { t } = props
2716
+ const tools = sessionToolsOf(props.project, props.sessionId)
2717
+ /** One row's disclosure state, with the tier and the host's own step and time. */
2718
+ const detailOf = (
2719
+ name: string,
2720
+ via: ToolDetail['via'],
2721
+ step?: number | undefined,
2722
+ at?: number | undefined,
2723
+ ): ToolDetail => ({
2724
+ via,
2725
+ step,
2726
+ at,
2727
+ open: props.openTool === name,
2728
+ onToggle: () => props.onToggleTool?.(name),
2729
+ })
2730
+ // `tools` absent is the host's only "not mounted yet" signal: a session with a
2731
+ // published offer that happens to be empty has real zeroes to print, and the
2732
+ // two states must not be conflated. The declared servers of the session are not
2733
+ // part of this block any more — the one surface draws them above it (F-26).
2734
+ if (tools === undefined) {
2735
+ return h(
2736
+ 'div',
2737
+ { style: STYLE.project },
2738
+ emptyState(t('toolsNotMounted'), t('toolsNotMountedHint')),
2739
+ h('div', { style: STYLE.codeLine }, t('toolsNotMountedCode')),
2740
+ )
2741
+ }
2742
+ const counts = toolCounts(tools)
2743
+ const split = budgetSplit(tools)
2744
+ const policy = props.policy ?? policyOf(props.project)
2745
+ // A mode the owner chose is not this plugin hiding tools, and the counters
2746
+ // cannot say which it is: `deferred` is the whole surface under `off` and empty
2747
+ // under `direct`, so printing them raw would report a switched-off project as
2748
+ // `0 pinned` and `N hidden` — the plugin taking credit for a decision it did not
2749
+ // make, and inviting the user to free slots that would change nothing.
2750
+ if (policy.mode === 'off') {
2751
+ return h(
2752
+ 'div',
2753
+ { style: STYLE.project },
2754
+ h(
2755
+ 'div',
2756
+ { style: STYLE.row },
2757
+ h('span', { style: STYLE.muted }, t('toolsSeeModel')),
2758
+ h('span', { style: { flex: 1 } }),
2759
+ h('span', null, t('toolsModeOffCounters', { mounted: tools.mounted })),
2760
+ ),
2761
+ h('div', { style: STYLE.warnNote }, t('toolsModeOff')),
2762
+ h('div', { style: STYLE.muted }, t('toolsModeOffHint')),
2763
+ )
2764
+ }
2765
+ // The host's own counters for this project and for the session the block is
2766
+ // open in: one row reads its server's record by registry name, and a row whose
2767
+ // server the host never recorded carries a value that draws nothing (no data,
2768
+ // no label) rather than a zero.
2769
+ const usage = props.project.usage
2770
+ const withCalls = (row: ToolRow): ToolRow => ({
2771
+ ...row,
2772
+ calls: toolCalls(row.name, usage, props.sessionId),
2773
+ })
2774
+ const rows = pinnedRows(tools, policy).map(withCalls)
2775
+ // The filter arrives from {@link ToolsSection}; a block nobody can write a
2776
+ // filter to draws the unfiltered tree it always did.
2777
+ const filter = props.filter ?? NO_TOOL_FILTER
2778
+ const active = toolFilterActive(filter)
2779
+ const everyPinned = rows.filter((row) => row.pinned)
2780
+ const everyCounted = rows.filter((row) => !row.pinned)
2781
+ const everyHidden = hiddenByServer(tools.deferred)
2782
+ // Only the `session` tier carries `at`; the `context` tier has no timestamp to
2783
+ // render, and the step tag both tiers show comes from the host's counter
2784
+ // (contract C2). The detail block prints the step and the time only while the
2785
+ // host published them, so each raw value is kept beside the row it belongs to;
2786
+ // the header keeps the note and the clock it always had.
2787
+ const everyDisclosed: { row: ToolRow; detail: ToolDetail }[] = [
2788
+ ...tools.activated.map((tool) => ({
2789
+ row: withCalls({
2790
+ name: tool.name,
2791
+ time: tool.at === undefined ? undefined : toolTime(tool.at),
2792
+ // The step is real once the host stamps it (contract C2). Absent, the row
2793
+ // shows no tag at all — no invented `step 4`.
2794
+ note: tool.step === undefined ? undefined : t('toolsStep', { step: tool.step }),
2795
+ }),
2796
+ detail: detailOf(tool.name, 'session', tool.step, tool.at),
2797
+ })),
2798
+ ...tools.context.map((tool) => ({
2799
+ row: withCalls({
2800
+ name: tool.name,
2801
+ note: tool.step === undefined ? undefined : t('toolsStep', { step: tool.step }),
2802
+ }),
2803
+ detail: detailOf(tool.name, 'context', tool.step),
2804
+ })),
2805
+ ]
2806
+ // What each tier draws once the filter has had its say: a tier the filter left
2807
+ // out draws nothing at all, a tier it kept draws the rows the query kept, and
2808
+ // the two figures below answer for exactly those rows. `total` is every row the
2809
+ // block holds before the filter — the denominator counts rows, not distinct
2810
+ // names, because rows are what the block draws: a name the session both pinned
2811
+ // and disclosed is two lines, and the caption answers for the lines.
2812
+ const pinned = tierVisible(filter, 'pinned') ? filterToolRows(everyPinned, filter.query) : []
2813
+ const counted = tierVisible(filter, 'counters') ? filterToolRows(everyCounted, filter.query) : []
2814
+ const disclosed = tierVisible(filter, 'disclosed')
2815
+ ? everyDisclosed.filter(({ row }) => matchesToolQuery(row.name, filter.query))
2816
+ : []
2817
+ const hidden = tierVisible(filter, 'hidden') ? filterHiddenServers(everyHidden, filter.query) : []
2818
+ const hiddenShown = hidden.reduce((sum, entry) => sum + entry.count, 0)
2819
+ const shown = pinned.length + counted.length + disclosed.length + hiddenShown
2820
+ const total =
2821
+ everyPinned.length +
2822
+ everyCounted.length +
2823
+ everyDisclosed.length +
2824
+ everyHidden.reduce((sum, entry) => sum + entry.names.length, 0)
2825
+ const onChange = props.onPin
2826
+ // The counters as chips, and only the ones that carry a number: `0 pinned` is
2827
+ // the empty row this block no longer draws, one chip at a time. With all four
2828
+ // at zero the row keeps its label and stops there, rather than printing four
2829
+ // zeroes at a panel that has nothing to count.
2830
+ //
2831
+ // One exception, and it is the price of the chip having become a control: a
2832
+ // tier the user pressed keeps its chip even after a host refresh drove its
2833
+ // count to zero, because a filter whose switch vanished would leave an empty
2834
+ // list nobody can explain — `Clear` is reachable, the chip that caused it is
2835
+ // not. It prints `0 {label}` while it is pressed, and the moment it is
2836
+ // released the zero is not drawn again.
2837
+ const chips = counterParts(tools, policy, t).filter(
2838
+ (part) => part.count > 0 || filter.tiers.includes(part.key),
2839
+ )
2840
+ // One pinned row per name, so a server's group can draw the row it stands for
2841
+ // without searching the list again.
2842
+ const pinnedByName = new Map(pinned.map((row) => [row.name, row]))
2843
+ // The chips are the filter's tier half (F-43): the same plate, the same
2844
+ // `{count} {label}` words, a button instead of a span while the block can write
2845
+ // the filter to something. A pressed chip means "this tier alone", and pressing
2846
+ // it again hands every tier back — an empty tier list is what "every tier"
2847
+ // means, so there is no fifth `all` chip to press and no state where none of
2848
+ // the four reads as applied.
2849
+ const tierChip = (part: CounterPart): ReactNode => {
2850
+ const on = filter.tiers.includes(part.key)
2851
+ const label = `${part.count} ${part.label}`
2852
+ if (props.onTier === undefined) return h('span', { key: part.key, style: STYLE.tag }, label)
2853
+ return h(
2854
+ 'button',
2855
+ {
2856
+ key: part.key,
2857
+ type: 'button',
2858
+ style: on ? { ...STYLE.filterChip, ...STYLE.filterChipOn } : STYLE.filterChip,
2859
+ 'aria-pressed': on,
2860
+ title: t('toolsFilterTier'),
2861
+ onClick: () => props.onTier?.(part.key),
2862
+ },
2863
+ label,
2864
+ )
2865
+ }
2866
+ return h(
2867
+ 'div',
2868
+ { style: STYLE.project },
2869
+ h(
2870
+ 'div',
2871
+ { style: STYLE.row },
2872
+ h('span', { style: STYLE.muted }, t('toolsSeeModel')),
2873
+ h('span', { style: { flex: 1 } }),
2874
+ chips.length === 0 ? null : h('span', { style: STYLE.chips }, chips.map(tierChip)),
2875
+ ),
2876
+ policy.mode === 'direct'
2877
+ ? h('div', { style: STYLE.muted }, t('toolsModeDirect'))
2878
+ : budgetLine(tools, t),
2879
+ split.exhausted
2880
+ ? h('div', { style: STYLE.warnNote }, `${t('toolsBudgetExhausted')} — ${t('toolsBudgetFree')}`)
2881
+ : null,
2882
+ // The filter sits between the head's readings and the list it narrows: the
2883
+ // counters above it say what the session offers, this row says what is left
2884
+ // of it on screen. Without a writer it draws nothing at all.
2885
+ h(ToolsFilter, {
2886
+ key: 'filter',
2887
+ filter,
2888
+ shown,
2889
+ total,
2890
+ onQuery: props.onQuery,
2891
+ onClear: props.onClearFilter,
2892
+ t,
2893
+ }),
2894
+ // A tier with nothing in it is not a heading over an apology, it is nothing:
2895
+ // each group below is drawn only while it has rows, and the zero it would
2896
+ // have printed lives in the chips above. One number per block (F-28), said
2897
+ // once (F-37). A tier the filter left out is nothing too — the chip that
2898
+ // pressed it is what says so.
2899
+ pinned.length === 0
2900
+ ? null
2901
+ : [
2902
+ h('div', { key: 'pinned', style: STYLE.group }, t('toolsGroupPinned')),
2903
+ // Since F-44 the pinned list is grouped by the server each name came
2904
+ // from, and each group carries the press that releases that whole
2905
+ // server — the counterpart of pinning one from the hidden tier or from
2906
+ // the settings page. The rows keep their own order inside a group: the
2907
+ // order the user pinned them in.
2908
+ ...pinnedByServer(pinned.map((row) => row.name)).flatMap((group) => [
2909
+ h(
2910
+ 'div',
2911
+ { key: `${group.server}-pinned`, style: STYLE.row },
2912
+ h('span', { style: STYLE.group }, `${group.server} · ${group.count}`),
2913
+ h('span', { style: { flex: 1 } }),
2914
+ props.onPinServer === undefined
2915
+ ? null
2916
+ : h(
2917
+ 'button',
2918
+ {
2919
+ type: 'button',
2920
+ style: STYLE.button,
2921
+ title: t('toolsUnpinServerHint'),
2922
+ disabled: props.pending === true,
2923
+ onClick: () => props.onPinServer?.(group.server, group.names),
2924
+ },
2925
+ t('toolsUnpinAll'),
2926
+ ),
2927
+ ),
2928
+ // The only real user choice on this surface: it is the host's pin list
2929
+ // that decides the row, so the action writes it back.
2930
+ ...group.names.map((name) => {
2931
+ const row = pinnedByName.get(name)
2932
+ return row === undefined
2933
+ ? null
2934
+ : toolRow(
2935
+ row,
2936
+ {
2937
+ label: t('toolsUnpin'),
2938
+ hint: t('toolsUnpinHint'),
2939
+ onClick: () => onChange?.(row.name, false),
2940
+ disabled: props.pending === true,
2941
+ },
2942
+ 'pinned',
2943
+ detailOf(row.name, 'pin'),
2944
+ t,
2945
+ )
2946
+ }),
2947
+ ]),
2948
+ ],
2949
+ counted.length === 0
2950
+ ? null
2951
+ : [
2952
+ h('div', { key: 'counters', style: STYLE.group }, t('toolsGroupCounters')),
2953
+ // Offered by the counters rather than chosen by the user, which is why
2954
+ // the action here is the pin that turns one into a user pin: the host's
2955
+ // own `POST pin` writes the very list the pinned group above reads.
2956
+ ...counted.map((row) =>
2957
+ toolRow(
2958
+ row,
2959
+ {
2960
+ label: t('toolsPin'),
2961
+ hint: t('toolsPinHint'),
2962
+ onClick: () => onChange?.(row.name, true),
2963
+ disabled: props.pending === true,
2964
+ },
2965
+ 'pinned',
2966
+ detailOf(row.name, 'pin'),
2967
+ t,
2968
+ ),
2969
+ ),
2970
+ ],
2971
+ disclosed.length === 0
2972
+ ? null
2973
+ : [
2974
+ h('div', { key: 'disclosed', style: STYLE.group }, t('toolsGroupDisclosed')),
2975
+ ...disclosed.map(({ row, detail }) =>
2976
+ toolRow(
2977
+ row,
2978
+ { label: t('toolsHide'), hint: t('toolsHideHint'), onClick: () => undefined },
2979
+ 'disclosed',
2980
+ detail,
2981
+ t,
2982
+ ),
2983
+ ),
2984
+ ],
2985
+ hidden.length === 0
2986
+ ? null
2987
+ : [
2988
+ // The one tier whose contents are a list rather than a reading: the
2989
+ // counters can say how many names are hidden, but only the names
2990
+ // themselves let a user pull one back. So the head opens, and the
2991
+ // sentence that used to sit under it as a caption became the head's own
2992
+ // tooltip — nothing hidden draws no head at all.
2993
+ h(HiddenTier, {
2994
+ key: 'hidden',
2995
+ // While the filter is on, the head counts what is under it, so the
2996
+ // number and the list agree: the chip above keeps the tier's own
2997
+ // total, which is why the two read differently and neither lies.
2998
+ count: active ? hiddenShown : counts.hidden,
2999
+ servers: hidden,
3000
+ // A query that found hidden names is a question about them: the tier
3001
+ // opens itself rather than leaving the matches behind a fold the user
3002
+ // has to guess at. The user's own press outranks that, which is why
3003
+ // `openHidden` has three states and not two: `undefined` — nobody has
3004
+ // pressed the head — is where the filter may open the tier, and the
3005
+ // first press replaces it with a choice that stands, filter or not.
3006
+ open: props.openHidden ?? active,
3007
+ onToggle: () => props.onToggleHidden?.(),
3008
+ onChange,
3009
+ onPinServer: props.onPinServer,
3010
+ pins: policy.pins,
3011
+ pending: props.pending === true,
3012
+ t,
3013
+ }),
3014
+ ],
3015
+ // Another plugin owning `assembly.tools` is the host's finding, not the
3016
+ // mockup's (contract C3). No field, no banner; the banner is a fact the host
3017
+ // reported.
3018
+ props.project.presentation === undefined
3019
+ ? null
3020
+ : h(
3021
+ 'div',
3022
+ { style: STYLE.warnNote },
3023
+ `${t('toolsPresentationOwner')}: ${props.project.presentation.name}. ${resolveHost(props.hostT ?? hostTranslate(undefined), props.project.presentation.noteCode, undefined, props.project.presentation.note)}`,
3024
+ ),
3025
+ )
3026
+ }
3027
+
3028
+ /**
3029
+ * "Problems" body: the rows that need a look, grouped by status.
3030
+ *
3031
+ * This is the body of the errors disclosure (F-26), so nothing above it repeats
3032
+ * the groups: the block starts at the first group — `error`, then `conflict`,
3033
+ * then `connecting`, in the order {@link statusGroups} triage puts them in —
3034
+ * and the disclosure's own badge is what says how many groups there are.
3035
+ * @param props - the project, its problem groups and the row action.
3036
+ * @returns the grouped rows.
3037
+ */
3038
+ export function IssueView(props: {
3039
+ project: ProjectSnapshot
3040
+ groups: StatusGroup[]
3041
+ /** Retry the project's failed mounts; absent while nothing can be written. */
3042
+ onRetry?: (() => void) | undefined
3043
+ /** `true` while a host action is in flight, so the row buttons stay still. */
3044
+ busy?: boolean | undefined
3045
+ /** Translate seat; falls back to this module's English copy without one. */
3046
+ t?: Translate | undefined
3047
+ /** Host-namespace seat for the rows' coded details (F-48). */
3048
+ hostT?: Translate | undefined
3049
+ }): ReactNode {
3050
+ const t = translateOf(props.t)
3051
+ return h(
3052
+ 'div',
3053
+ { style: STYLE.project },
3054
+ props.groups.map((group) =>
3055
+ h(
3056
+ 'div',
3057
+ { key: group.status },
3058
+ h('div', { style: STYLE.group }, `${t(STATUS_KEYS[group.status])} · ${group.rows.length}`),
3059
+ group.rows.flatMap((row) =>
3060
+ serverRow(row, `problem-${group.status}`, {
3061
+ onRetry: props.onRetry,
3062
+ busy: props.busy,
3063
+ t: props.t,
3064
+ hostT: props.hostT,
3065
+ }),
3066
+ ),
3067
+ ),
3068
+ ),
3069
+ )
3070
+ }
3071
+
3072
+ /**
3073
+ * Centred message for a state that has nothing to list.
3074
+ * @param title - the headline.
3075
+ * @param hint - the line under it.
3076
+ * @param key - React key, for the callers that place the result inside an array
3077
+ * (React requires one there); variadic callers leave it out.
3078
+ */
3079
+ export function emptyState(title: string, hint: string, key?: string): ReactNode {
3080
+ return h(
3081
+ 'div',
3082
+ key === undefined ? { style: STYLE.empty } : { key, style: STYLE.empty },
3083
+ h('div', { style: STYLE.emptyTitle }, title),
3084
+ h('div', { style: STYLE.hint }, hint),
3085
+ )
3086
+ }
3087
+
3088
+ /** `info` and `up` are the quiet half of the level vocabulary. */
3089
+ const LOG_CHIP: Record<LogEvent['level'], CSSProperties> = {
3090
+ info: {},
3091
+ up: { color: STATUS_COLOR.active },
3092
+ warn: { color: STATUS_COLOR.connecting },
3093
+ error: { color: STATUS_COLOR.error },
3094
+ }
3095
+
3096
+ /** `12:41:31` — the clock the mockup's log rows carry, seconds included. */
3097
+ function logTime(at: number): string {
3098
+ const date = new Date(at)
3099
+ const pad = (value: number): string => String(value).padStart(2, '0')
3100
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
3101
+ }
3102
+
3103
+ /**
3104
+ * The three facts of a failure, one per line.
3105
+ *
3106
+ * The host hands the facts over as separate lines — the endpoint, the document
3107
+ * that declared the server, and what did not appear — so they are relayed as
3108
+ * they are: split, trimmed, and with anything labelled as advice dropped. The
3109
+ * hint and the reminder about `Retry` are not facts, and `Retry` is already a
3110
+ * button on the server's own row.
3111
+ * @param detail - the event's `detail`, when it has one.
3112
+ * @returns the lines to draw under the event, empty when there is nothing to say.
3113
+ */
3114
+ export function logFacts(detail: string | undefined): string[] {
3115
+ if (detail === undefined) return []
3116
+ return detail
3117
+ .split('\n')
3118
+ .map((line) => line.trim())
3119
+ // The host's own advice is not a fact: the row above already carries the
3120
+ // reason, and `Retry` is a button on the server's row, not a sentence here.
3121
+ .filter((line) => !/^(hint|note|next step)\s*:/i.test(line))
3122
+ .filter((line) => line.length > 0)
3123
+ }
3124
+
3125
+ /**
3126
+ * One line of the event list.
3127
+ *
3128
+ * The message takes its own width (see {@link STYLE.logRow}) rather than a right
3129
+ * column, which is what keeps the row readable in a sidebar. A coded event is
3130
+ * resolved through the host seat (F-48): the translated template wins, and a
3131
+ * code the namespace does not know — or an event that carries none — renders
3132
+ * the payload's English exactly as before.
3133
+ * @param event - the event to draw.
3134
+ * @param key - React key for the row.
3135
+ * @param t - translate seat.
3136
+ * @param hostT - host-namespace seat; without one the payload's English shows.
3137
+ * @returns the row, plus the failure's fact lines under it.
3138
+ */
3139
+ export function logRow(event: LogEvent, key: string, t: Translate, hostT?: Translate | undefined): ReactNode {
3140
+ const host = hostT ?? hostTranslate(undefined)
3141
+ const detail = resolveHost(host, event.detailCode, event.detailParams, event.detail)
3142
+ const facts = logFacts(detail === '' ? undefined : detail)
3143
+ return h(
3144
+ 'div',
3145
+ { key },
3146
+ h(
3147
+ 'div',
3148
+ { style: STYLE.logRow },
3149
+ h('span', { style: STYLE.logTime }, logTime(event.at)),
3150
+ h(
3151
+ 'span',
3152
+ { style: { ...STYLE.tag, ...STYLE.logLevel, ...LOG_CHIP[event.level] ?? {} } },
3153
+ t(`logsLevel${event.level.charAt(0).toUpperCase()}${event.level.slice(1)}`),
3154
+ ),
3155
+ event.server === undefined ? null : h('span', { style: STYLE.logName }, event.server),
3156
+ h('span', { style: STYLE.logMessage }, resolveHost(host, event.code, event.params, event.message)),
3157
+ ),
3158
+ facts.map((fact, index) => h('div', { key: `${key}#fact${index}`, style: STYLE.logDetail }, fact)),
3159
+ )
3160
+ }
3161
+
3162
+ /**
3163
+ * The events the toolbar's two filters let through, newest first.
3164
+ *
3165
+ * Scope and level first, then the Clear mark: a cleared event is one the user
3166
+ * has said they are done with, whatever the filters say. The ring holds oldest
3167
+ * first, so the result is reversed to read newest first, like every log view.
3168
+ * @param props - the events and the three filters.
3169
+ * @returns the visible events, newest first.
3170
+ */
3171
+ export function logVisible(props: {
3172
+ logs: readonly LogEvent[]
3173
+ scope: LogScope
3174
+ level: LogLevelFilter
3175
+ sessionId: string | undefined
3176
+ clearedAt: number | undefined
3177
+ }): LogEvent[] {
3178
+ return props.logs
3179
+ .filter(
3180
+ (event) =>
3181
+ (props.level === 'all' || event.level === 'error') &&
3182
+ (props.scope === 'all' || event.sessionId === props.sessionId) &&
3183
+ (props.clearedAt === undefined || event.at > props.clearedAt),
3184
+ )
3185
+ .sort((left, right) => right.at - left.at)
3186
+ }
3187
+
3188
+ /**
3189
+ * The event ring, as the logs block reads it.
3190
+ *
3191
+ * The snapshot carries the newest page (contract C1); everything older is one
3192
+ * route call behind "Show older". The two filters and the Clear mark are the
3193
+ * tab's own, stored locally — Clear has no route, by contract, so it only
3194
+ * remembers a moment and stops drawing events at or before it.
3195
+ * Exported and pure (no hooks) so a test can drive the toolbar and the list
3196
+ * directly; {@link LogsView} is the stateful wrapper around it.
3197
+ * @param project - the project whose ring is shown.
3198
+ * @param logs - events to draw, newest first.
3199
+ * @param props - the filters, the paging state and the callbacks behind them.
3200
+ * @returns the toolbar and the list.
3201
+ */
3202
+ export function logList(
3203
+ project: ProjectSnapshot,
3204
+ logs: readonly LogEvent[],
3205
+ props: {
3206
+ scope: LogScope
3207
+ level: LogLevelFilter
3208
+ total: number
3209
+ loading: boolean
3210
+ failed: boolean
3211
+ t: Translate
3212
+ /** Host-namespace seat for the coded events (F-48); the payload's English shows without one. */
3213
+ hostT?: Translate | undefined
3214
+ onScope: (scope: LogScope) => void
3215
+ onLevel: (level: LogLevelFilter) => void
3216
+ onClear: () => void
3217
+ onOlder: () => void
3218
+ more: boolean
3219
+ },
3220
+ ): ReactNode {
3221
+ const { t } = props
3222
+ const chip = (
3223
+ filter: { label: string; on: boolean; onClick: () => void },
3224
+ ): ReactNode =>
3225
+ h(
3226
+ 'button',
3227
+ {
3228
+ key: filter.label,
3229
+ style: filter.on ? { ...STYLE.logFilter, ...STYLE.logFilterOn } : STYLE.logFilter,
3230
+ // The applied chip of each pair is the pressed one. The mode switch is
3231
+ // what F-26 took away, and with it every `[aria-pressed]` outside a
3232
+ // disclosure; these two pairs live inside the logs body, where the gate
3233
+ // reads them as such.
3234
+ 'aria-pressed': filter.on,
3235
+ onClick: filter.on ? undefined : filter.onClick,
3236
+ },
3237
+ filter.label,
3238
+ )
3239
+ return [
3240
+ h(
3241
+ 'div',
3242
+ { style: STYLE.bar, key: 'logs-toolbar' },
3243
+ chip({
3244
+ label: t('logsThisSession'),
3245
+ on: props.scope === 'session',
3246
+ onClick: () => props.onScope('session'),
3247
+ }),
3248
+ chip({
3249
+ label: t('logsAllSessions'),
3250
+ on: props.scope === 'all',
3251
+ onClick: () => props.onScope('all'),
3252
+ }),
3253
+ h('span', { style: { flex: 1 } }),
3254
+ chip({
3255
+ label: t('logsAllLevels'),
3256
+ on: props.level === 'all',
3257
+ onClick: () => props.onLevel('all'),
3258
+ }),
3259
+ chip({
3260
+ label: t('logsErrorsOnly'),
3261
+ on: props.level === 'error',
3262
+ onClick: () => props.onLevel('error'),
3263
+ }),
3264
+ h(
3265
+ 'button',
3266
+ { style: STYLE.button, title: t('logsClearHint'), onClick: props.onClear },
3267
+ t('logsClear'),
3268
+ ),
3269
+ ),
3270
+ logs.length === 0
3271
+ ? props.level === 'error' && props.total > 0
3272
+ ? logsNoErrorsState(t)
3273
+ : logsEmptyState(t)
3274
+ : h(
3275
+ 'div',
3276
+ { key: 'logs-events' },
3277
+ h('div', { style: STYLE.group }, t('logsProjectCount', { count: props.total })),
3278
+ logs.map((event, index) => logRow(event, `${event.at}-${index}`, t, props.hostT)),
3279
+ ),
3280
+ props.failed ? h('div', { style: STYLE.muted, key: 'logs-failed' }, t('logsLoadFailed')) : null,
3281
+ props.loading
3282
+ ? h('div', { style: STYLE.muted, key: 'logs-loading' }, t('logsLoading'))
3283
+ : props.more
3284
+ ? h(
3285
+ 'div',
3286
+ { key: 'logs-more' },
3287
+ h(
3288
+ 'button',
3289
+ { style: STYLE.button, title: t('logsMoreHint'), onClick: props.onOlder },
3290
+ t('logsMore'),
3291
+ ),
3292
+ h(
3293
+ 'span',
3294
+ { style: STYLE.muted },
3295
+ t('logsShown', { shown: logs.length, total: props.total }),
3296
+ ),
3297
+ )
3298
+ : null,
3299
+ ]
3300
+ }
3301
+
3302
+ /**
3303
+ * The logs block of the tab: this plugin's own event ring, one project's
3304
+ * worth of it, with the two filters the mockup shows.
3305
+ * @param props - the project, the tab's session, that session's event count and
3306
+ * the storage the filters live in.
3307
+ * @returns the toolbar plus the newest events.
3308
+ */
3309
+ export function LogsView(props: {
3310
+ project: ProjectSnapshot
3311
+ sessionId: string | undefined
3312
+ /** Storage seam for tests; defaults to the browser's own. */
3313
+ storage?: PanelStorage | undefined
3314
+ t: Translate
3315
+ /** Host-namespace seat for the coded events (F-48). */
3316
+ hostT?: Translate | undefined
3317
+ }): ReactNode {
3318
+ const { t, project } = props
3319
+ const [scope, setScope] = useState<LogScope>(() => logScopeOf(props.storage))
3320
+ const [level, setLevel] = useState<LogLevelFilter>(() => logLevelOf(props.storage))
3321
+ const [clearedAt, setClearedAt] = useState<number | undefined>(() => logsClearedAt(props.storage))
3322
+ const [older, setOlder] = useState<readonly LogEvent[]>([])
3323
+ const [request, setRequest] = useState<number | undefined>(undefined)
3324
+ const [failed, setFailed] = useState(false)
3325
+ // Cursors already paged for. A page whose events the filters hide still
3326
+ // advances the buffer, so this only ever stops a genuinely spent cursor.
3327
+ const [attempted, setAttempted] = useState<readonly number[]>([])
3328
+ const projectRoot = project.projectRoot
3329
+ const snapshot = project.logs ?? []
3330
+ // The page buffer is unfiltered on purpose: the filters decide what is drawn,
3331
+ // not what is buffered, so a page whose events the filters hide still moves
3332
+ // the cursor past itself instead of being asked for again.
3333
+ const buffered = [...older, ...snapshot]
3334
+ const visible = logVisible({ logs: buffered, scope, level, sessionId: props.sessionId, clearedAt })
3335
+ const total = project.logCount ?? snapshot.length
3336
+ const { more, cursor } = logsPaging({ visible, total, attempted })
3337
+ useEffect(() => {
3338
+ if (request === undefined) return
3339
+ let live = true
3340
+ setAttempted((seen) => (seen.includes(request) ? seen : [...seen, request]))
3341
+ setFailed(false)
3342
+ void fetchLogs(projectRoot, request).then((page) => {
3343
+ if (!live) return
3344
+ if (page === undefined) setFailed(true)
3345
+ else setOlder((shown) => mergeLogs(page.events, shown))
3346
+ setRequest(undefined)
3347
+ })
3348
+ return () => {
3349
+ live = false
3350
+ }
3351
+ }, [request, projectRoot])
3352
+ const changeScope = (next: LogScope): void => {
3353
+ setScope(next)
3354
+ persistLogFilter(LOG_SCOPE_KEY, next, props.storage)
3355
+ }
3356
+ const changeLevel = (next: LogLevelFilter): void => {
3357
+ setLevel(next)
3358
+ persistLogFilter(LOG_LEVEL_KEY, next, props.storage)
3359
+ }
3360
+ const clear = (): void => {
3361
+ // One millisecond back, so the next event landing in the same millisecond as
3362
+ // the click is not swallowed with the ones the user cleared.
3363
+ const at = Date.now() - 1
3364
+ setClearedAt(at)
3365
+ persistLogsClearedAt(at, props.storage)
3366
+ }
3367
+ return h(
3368
+ 'div',
3369
+ { style: STYLE.project },
3370
+ logList(project, visible, {
3371
+ scope,
3372
+ level,
3373
+ total,
3374
+ loading: request !== undefined,
3375
+ failed,
3376
+ t,
3377
+ hostT: props.hostT,
3378
+ onScope: changeScope,
3379
+ onLevel: changeLevel,
3380
+ onClear: clear,
3381
+ onOlder: () => setRequest(cursor),
3382
+ more,
3383
+ }),
3384
+ )
3385
+ }
3386
+
3387
+ /** Side card settings panel: the declaration detail plus per-project release. */
3388
+ export function ProjectMcpSettings(props: {
3389
+ pluginSettings: Record<string, unknown>
3390
+ updatePluginSetting: (key: string, value: unknown) => void
3391
+ onClose?: (() => void) | undefined
3392
+ /** Translate seat; the popup follows the shell's language when it is given one. */
3393
+ t?: Translate | undefined
3394
+ /** Host-namespace seat for the wire-coded payload fields (F-48). */
3395
+ hostT?: Translate | undefined
3396
+ }): ReactNode {
3397
+ const t = translateOf(props.t)
3398
+ const { snapshot, error, busy, run } = useSnapshot(true, refreshMsOf(props.pluginSettings))
3399
+ const projects = snapshot?.projects ?? []
3400
+ return h(
3401
+ 'div',
3402
+ { style: STYLE.root },
3403
+ h(
3404
+ 'div',
3405
+ { style: STYLE.bar },
3406
+ h('span', { style: STYLE.name }, t('mountedPerProject')),
3407
+ h('span', { style: STYLE.muted }, t('projectsCount', { count: projects.length })),
3408
+ h('span', { style: { flex: 1 } }),
3409
+ h(
3410
+ 'button',
3411
+ { style: STYLE.button, disabled: busy, onClick: () => void run(ROUTE_ACTIONS.sync) },
3412
+ t('sync'),
3413
+ ),
3414
+ props.onClose === undefined
3415
+ ? null
3416
+ : h('button', { style: STYLE.button, onClick: () => props.onClose?.() }, t('close')),
3417
+ ),
3418
+ error === undefined ? null : h('div', { style: STYLE.error }, error),
3419
+ h(
3420
+ 'div',
3421
+ { style: STYLE.body },
3422
+ projects.length === 0
3423
+ ? h('div', { style: { ...STYLE.muted, padding: 8 } }, t('nothingMounted'))
3424
+ : projects.map((project) =>
3425
+ h(ProjectBlock, {
3426
+ key: project.projectRoot,
3427
+ project,
3428
+ busy,
3429
+ onRelease: (sessionId) => void run('release', { sessionId }),
3430
+ hostT: props.hostT,
3431
+ }),
3432
+ ),
3433
+ ),
3434
+ )
3435
+ }
3436
+
3437
+ /**
3438
+ * One project block: the merged rows (what the project as a whole reports) plus
3439
+ * the per-session breakdown underneath — but only for the sessions whose own
3440
+ * reading differs from the merge.
3441
+ *
3442
+ * The project is the subject now that one project-level mount serves every
3443
+ * session: a session that reads exactly like the merged rows adds no answer, so
3444
+ * the section is left out entirely and the block is just the project. A session
3445
+ * that mounts something else, or has not turned yet, is the only reason to show
3446
+ * the breakdown under it.
3447
+ */
3448
+ export function ProjectBlock(props: {
3449
+ project: ProjectSnapshot
3450
+ /** Session this tab belongs to; missing in the settings popup. */
3451
+ currentSessionId?: string | undefined
3452
+ /** True while a host action is in flight. */
3453
+ busy: boolean
3454
+ /** Called with the id of the session whose servers should be released. */
3455
+ onRelease: (sessionId: string) => void
3456
+ /** Retry the project's failed mounts; absent while nothing can be written. */
3457
+ onRetry?: (() => void) | undefined
3458
+ /**
3459
+ * `false` when the surface above already names the project and carries its
3460
+ * `this session` chip — the sidebar tab's own header does. Defaults to `true`.
3461
+ */
3462
+ showName?: boolean | undefined
3463
+ /** Translate seat; falls back to this module's English copy without one. */
3464
+ t?: Translate | undefined
3465
+ /**
3466
+ * Host-namespace seat for the wire-coded payload fields (F-48); without one
3467
+ * the echo seat applies and every coded field shows its payload's English.
3468
+ */
3469
+ hostT?: Translate | undefined
3470
+ }): ReactNode {
3471
+ const t = translateOf(props.t)
3472
+ const hostT = props.hostT ?? hostTranslate(undefined)
3473
+ const { project } = props
3474
+ const totals = countStatuses(project.rows)
3475
+ const sessions = sessionBreakdown(project, props.currentSessionId, t)
3476
+ const current = sessions.some((session) => session.current)
3477
+ // Project-first: the section is the disagreement view, so it is handed only
3478
+ // the sessions that read differently. An empty list makes it render nothing at
3479
+ // all — the header included — which is the quiet case this exists for.
3480
+ const deviating = sessions.filter((session) => session.deviates)
3481
+ return h(
3482
+ 'div',
3483
+ { style: STYLE.project, key: project.projectRoot },
3484
+ props.showName === false
3485
+ ? null
3486
+ : h(
3487
+ 'div',
3488
+ { style: STYLE.projectHead },
3489
+ h(
3490
+ 'span',
3491
+ { style: STYLE.name, title: project.projectRoot },
3492
+ basename(project.projectRoot),
3493
+ ),
3494
+ current ? h('span', { style: STYLE.tag }, t('thisSession')) : null,
3495
+ h('span', { style: { flex: 1 } }),
3496
+ h('span', { style: STYLE.muted }, summarize(totals, t)),
3497
+ ),
3498
+ h(
3499
+ 'div',
3500
+ // Rung 0: the project's merged rows are the ladder's baseline.
3501
+ { style: STYLE.indent(0) },
3502
+ project.rows.flatMap((row) =>
3503
+ serverRow(row, 'merged', { onRetry: props.onRetry, busy: props.busy, t: props.t, hostT: props.hostT }),
3504
+ ),
3505
+ ),
3506
+ projectIssueLines(project).map((issue, index) =>
3507
+ h(
3508
+ 'div',
3509
+ { style: STYLE.detail, key: `${issue.source}#${index}` },
3510
+ `${issue.level}: ${resolveHost(hostT, issue.code, issue.params, issue.message)}`,
3511
+ ),
3512
+ ),
3513
+ h(SessionList, {
3514
+ key: `${project.projectRoot}#sessions`,
3515
+ sessions: deviating,
3516
+ busy: props.busy,
3517
+ onRelease: props.onRelease,
3518
+ // The note is about the rows above, which stay the merge of *all* the
3519
+ // project's sessions even when only one of them is out of step.
3520
+ merged: sessions.length > 1,
3521
+ t: props.t,
3522
+ hostT: props.hostT,
3523
+ }),
3524
+ )
3525
+ }
3526
+
3527
+ /**
3528
+ * The issues the rows below do not already carry.
3529
+ *
3530
+ * A failing mount is reported twice by the host: once as the row's own `detail`,
3531
+ * which the row renders in its banner, and once as a snapshot issue naming the
3532
+ * same server. Only the issues that no banner repeats belong under the rows —
3533
+ * the document-level ones.
3534
+ * @param project - one project from the host snapshot.
3535
+ * @returns the issues left to print, in host order.
3536
+ */
3537
+ export function projectIssueLines(project: ProjectSnapshot): ProjectSnapshot['issues'] {
3538
+ return project.issues.filter(
3539
+ (issue) =>
3540
+ issue.server === undefined ||
3541
+ !project.rows.some((row) => row.name === issue.server && row.detail !== undefined),
3542
+ )
3543
+ }
3544
+
3545
+ /** Per-session view model the panel renders under one project. */
3546
+ export interface SessionBreakdown {
3547
+ /** Agent (session) id; shown truncated, in full in the tooltip. */
3548
+ id: string
3549
+ /** True when this is the session the tab is open in. */
3550
+ current: boolean
3551
+ /** This session's own rows, in document order. */
3552
+ rows: ServerRow[]
3553
+ /** One-line status summary. */
3554
+ summary: string
3555
+ /**
3556
+ * True when this session's own reading disagrees with the project's merged
3557
+ * rows. The `sessions` section exists only for these sessions: the project's
3558
+ * rows come first, and a session that reads exactly like them says nothing.
3559
+ */
3560
+ deviates: boolean
3561
+ }
3562
+
3563
+ /**
3564
+ * Whether one session's own rows disagree with the project's merged rows.
3565
+ *
3566
+ * The project's `rows` are the merge of every session, so one that mounts a
3567
+ * different set, or that has not turned yet, reads differently from them. The
3568
+ * comparison is per server and order-insensitive: each side is read as a
3569
+ * `name → set of statuses` map, so the same rows in another order are not a
3570
+ * disagreement. A name declared twice counts only for what it says — the same
3571
+ * status twice collapses into one, while two different statuses are a
3572
+ * disagreement whichever order the two sides list them in. A session whose own
3573
+ * `rows` are empty claims nothing and therefore never disagrees — a host half
3574
+ * older than the per-session field must not make the section appear.
3575
+ * @param merged - the project's merged rows.
3576
+ * @param own - one session's own rows.
3577
+ * @returns `true` when the two readings differ.
3578
+ */
3579
+ export function sessionDeviates(merged: readonly ServerRow[], own: readonly ServerRow[]): boolean {
3580
+ if (own.length === 0) return false
3581
+ const projectStatus = statusesByName(merged)
3582
+ const sessionStatus = statusesByName(own)
3583
+ if (projectStatus.size !== sessionStatus.size) return true
3584
+ for (const [name, statuses] of projectStatus) {
3585
+ const ownStatuses = sessionStatus.get(name)
3586
+ if (ownStatuses === undefined || ownStatuses.size !== statuses.size) return true
3587
+ for (const status of statuses) {
3588
+ if (!ownStatuses.has(status)) return true
3589
+ }
3590
+ }
3591
+ return false
3592
+ }
3593
+
3594
+ /** One side's rows as `name → the statuses that name was declared with`. */
3595
+ function statusesByName(rows: readonly ServerRow[]): Map<string, Set<ServerRow['status']>> {
3596
+ const byName = new Map<string, Set<ServerRow['status']>>()
3597
+ for (const row of rows) {
3598
+ const statuses = byName.get(row.name)
3599
+ if (statuses === undefined) byName.set(row.name, new Set([row.status]))
3600
+ else statuses.add(row.status)
3601
+ }
3602
+ return byName
3603
+ }
3604
+
3605
+ /**
3606
+ * Split a project's snapshot into its per-session view.
3607
+ *
3608
+ * Sessions of one project mount independently, so the merged `rows` cannot say
3609
+ * which session holds a server. Each entry also carries whether that session's
3610
+ * own reading {@link sessionDeviates} from the merge: the panel prints the
3611
+ * project's rows first and the section only for the sessions that differ, so the
3612
+ * answer to "is anything not as the project says" is computed once, here.
3613
+ * `sessions`, and each entry's `rows` with it, are read defensively: the browser
3614
+ * half hot-reloads while the host half only picks up a new build at restart, so
3615
+ * a newer panel can meet a host that predates either field.
3616
+ * @param project - one project from the host snapshot.
3617
+ * @param currentSessionId - the session this tab belongs to, if known.
3618
+ * @param t - translate seat for the summary line; English without one.
3619
+ * @returns one entry per session, in host order.
3620
+ */
3621
+ export function sessionBreakdown(
3622
+ project: ProjectSnapshot,
3623
+ currentSessionId: string | undefined,
3624
+ t?: Translate,
3625
+ ): SessionBreakdown[] {
3626
+ return (project.sessions ?? []).map((session) => {
3627
+ const rows = session.rows ?? []
3628
+ return {
3629
+ id: session.id,
3630
+ current: currentSessionId !== undefined && session.id === currentSessionId,
3631
+ rows,
3632
+ summary: summarize(countStatuses(rows), translateOf(t)),
3633
+ deviates: sessionDeviates(project.rows, rows),
3634
+ }
3635
+ })
3636
+ }
3637
+
3638
+ /**
3639
+ * The deviating sessions' own rows, read as one summary line.
3640
+ *
3641
+ * The collapsed `sessions` section answers "who is not holding this project the
3642
+ * way the rows above say", so its header counts the statuses across the sessions
3643
+ * it lists — the deviating ones — not across the whole project.
3644
+ * @param sessions - the deviating part of the project's per-session breakdown.
3645
+ * @param t - translate seat; falls back to this module's English copy.
3646
+ * @returns the merged status summary, e.g. `2 active, 1 idle`.
3647
+ */
3648
+ export function sessionsSummary(sessions: readonly SessionBreakdown[], t?: Translate): string {
3649
+ return summarize(countStatuses(sessions.flatMap((session) => session.rows)), translateOf(t))
3650
+ }
3651
+
3652
+ /**
3653
+ * The header row of the collapsed sessions section.
3654
+ *
3655
+ * Collapsed is the default: the section is a disclosure, so the header has to
3656
+ * carry the whole answer on its own — the label, how many sessions are out of
3657
+ * step, and their merged status. The list handed to it is already the deviating
3658
+ * one, so the count chip counts those, never how many sessions the project has
3659
+ * (the toolbar's right edge is where that count lives). Exported and pure so
3660
+ * the shape is asserted without a renderer; {@link SessionList} owns the open
3661
+ * state and the rows below it.
3662
+ * @param props - the deviating sessions, the open flag and the toggle.
3663
+ * @returns the header row.
3664
+ */
3665
+ export function sessionsHeader(props: {
3666
+ sessions: readonly SessionBreakdown[]
3667
+ open: boolean
3668
+ onToggle: () => void
3669
+ /** `true` when the rows above are a merge of these sessions, not one session's own. */
3670
+ merged?: boolean | undefined
3671
+ t?: Translate | undefined
3672
+ }): ReactNode {
3673
+ const t = translateOf(props.t)
3674
+ return h(
3675
+ 'div',
3676
+ // Rung 1: the `sessions` section sits one step right of the project rows.
3677
+ { style: { ...STYLE.sessionHead, ...STYLE.indent(1) } },
3678
+ h(
3679
+ 'button',
3680
+ {
3681
+ // The mockup draws the section label in the tertiary tone
3682
+ // (`docs/design/mockups/harness.html`) — it names the seam, it is not the content.
3683
+ style: { ...STYLE.sessionToggle, ...STYLE.dim },
3684
+ 'aria-expanded': props.open,
3685
+ title: props.open ? t('hideSessions') : t('showSessions'),
3686
+ onClick: props.onToggle,
3687
+ },
3688
+ `${props.open ? '▾' : '▸'} ${t('sessionsSection')}`,
3689
+ ),
3690
+ h('span', { style: STYLE.tag }, deviationCount(props.sessions.length, t)),
3691
+ h('span', { style: STYLE.muted }, sessionsSummary(props.sessions, t)),
3692
+ h('span', { style: { flex: 1 } }),
3693
+ props.merged === true ? h('span', { style: STYLE.muted }, t('mergedAcrossSessions')) : null,
3694
+ )
3695
+ }
3696
+
3697
+ /**
3698
+ * The list of the sessions that read differently from the project.
3699
+ *
3700
+ * Project-first: the rows above are the project's own reading, and a session
3701
+ * that reads exactly like them adds nothing, so the panel hands this component
3702
+ * only the sessions whose own rows disagree. An empty list therefore means the
3703
+ * whole project agrees with itself — the quiet case — and the section renders
3704
+ * nothing at all: no header, no rows. When there is something to explain, the
3705
+ * section still starts collapsed so a single out-of-step session does not push
3706
+ * the project's rows out of the way; opening it lists one row per deviating
3707
+ * session, and each of those opens its own rows.
3708
+ */
3709
+ export function SessionList(props: {
3710
+ sessions: SessionBreakdown[]
3711
+ busy: boolean
3712
+ onRelease: (sessionId: string) => void
3713
+ /** `true` when the rows above are a merge of the project's sessions, not one session's own. */
3714
+ merged?: boolean | undefined
3715
+ /** Translate seat; falls back to this module's English copy without one. */
3716
+ t?: Translate | undefined
3717
+ /** Host-namespace seat for the rows' coded details (F-48). */
3718
+ hostT?: Translate | undefined
3719
+ }): ReactNode {
3720
+ const [section, setSection] = useState(false)
3721
+ const [open, setOpen] = useState<string | undefined>(undefined)
3722
+ // Nothing to explain: the section is the whole disagreement view, header
3723
+ // included, and a project that reads like every one of its sessions gets none.
3724
+ if (props.sessions.length === 0) return null
3725
+ return h(
3726
+ 'div',
3727
+ { style: STYLE.sessions },
3728
+ sessionsHeader({
3729
+ sessions: props.sessions,
3730
+ open: section,
3731
+ merged: props.merged,
3732
+ onToggle: () => setSection((value) => !value),
3733
+ t: props.t,
3734
+ }),
3735
+ section
3736
+ ? props.sessions.map((session) =>
3737
+ h(sessionEntry, {
3738
+ key: session.id,
3739
+ session,
3740
+ expanded: open === session.id,
3741
+ onToggle: () => setOpen((value) => (value === session.id ? undefined : session.id)),
3742
+ busy: props.busy,
3743
+ onRelease: props.onRelease,
3744
+ t: props.t,
3745
+ hostT: props.hostT,
3746
+ }),
3747
+ )
3748
+ : null,
3749
+ )
3750
+ }
3751
+
3752
+ /**
3753
+ * One session's block inside the expanded `sessions` section: its own header row
3754
+ * (the short id, `this session` when it is, the summary, `Release`) and, when it
3755
+ * is open, the servers that session holds.
3756
+ *
3757
+ * Pure, with the disclosure state given to it rather than owned, so the ladder it
3758
+ * draws — rung `2` for the header, rung `3` for the rows under it — is asserted
3759
+ * without rendering {@link SessionList}.
3760
+ * @param props - the session, its open state and the row action.
3761
+ * @returns the session's block.
3762
+ */
3763
+ export function sessionEntry(props: {
3764
+ session: SessionBreakdown
3765
+ expanded: boolean
3766
+ onToggle: () => void
3767
+ busy: boolean
3768
+ onRelease: (sessionId: string) => void
3769
+ t?: Translate | undefined
3770
+ /** Host-namespace seat for the rows' coded details (F-48). */
3771
+ hostT?: Translate | undefined
3772
+ }): ReactNode {
3773
+ const t = translateOf(props.t)
3774
+ const { session } = props
3775
+ return h(
3776
+ 'div',
3777
+ // Rung 2: one session of the section, one step right of its header.
3778
+ { style: { ...STYLE.session, ...STYLE.indent(2) } },
3779
+ h(
3780
+ 'div',
3781
+ { style: STYLE.sessionHead },
3782
+ h(
3783
+ // The marker belongs to a **collapsed** row only (mockup `:323`): an
3784
+ // expanded session already shows its servers, so a turned-down triangle
3785
+ // beside them would be a second, redundant marker. The button stays
3786
+ // either way, so the row is still the control that folds it back up.
3787
+ 'button',
3788
+ {
3789
+ // A collapsed session's id is the mock's `.dim` (`docs/design/mockups/harness.html`):
3790
+ // once open, the id is content and reads in the primary tone.
3791
+ style: props.expanded ? STYLE.sessionToggle : { ...STYLE.sessionToggle, ...STYLE.dim },
3792
+ title: props.expanded ? t('hideSession') : t('showSession'),
3793
+ 'aria-expanded': props.expanded,
3794
+ onClick: props.onToggle,
3795
+ },
3796
+ props.expanded ? shortSessionId(session.id) : `▸ ${shortSessionId(session.id)}`,
3797
+ ),
3798
+ session.current ? h('span', { style: STYLE.tag }, t('thisSession')) : null,
3799
+ h('span', { style: STYLE.muted }, session.summary),
3800
+ h('span', { style: { flex: 1 } }),
3801
+ h(
3802
+ 'button',
3803
+ {
3804
+ style: STYLE.button,
3805
+ disabled: props.busy,
3806
+ title: session.id,
3807
+ onClick: () => props.onRelease(session.id),
3808
+ },
3809
+ t('release'),
3810
+ ),
3811
+ ),
3812
+ props.expanded ? sessionRows(session, props.t, props.hostT) : null,
3813
+ )
3814
+ }
3815
+
3816
+ /**
3817
+ * One session's own server rows, or the placeholder when that session declared
3818
+ * nothing, at rung `3` — the deepest level of the surface's indentation ladder.
3819
+ * Exported so the panel tests can assert what a session block shows without a
3820
+ * DOM.
3821
+ * @param session - one entry of {@link sessionBreakdown}.
3822
+ * @param t - translate seat; falls back to this module's English copy.
3823
+ * @param hostT - host-namespace seat for the rows' coded details (F-48).
3824
+ * @returns the rows element tree for that session.
3825
+ */
3826
+ export function sessionRows(session: SessionBreakdown, t?: Translate, hostT?: Translate): ReactNode {
3827
+ return h(
3828
+ 'div',
3829
+ // Rung 3: the servers a session holds, one step right of the session row.
3830
+ { style: STYLE.indent(3) },
3831
+ session.rows.length === 0
3832
+ ? h('div', { style: STYLE.muted }, translateOf(t)('nothingDeclared'))
3833
+ : session.rows.map((row) => serverRow(row, session.id, { t, hostT })),
3834
+ )
3835
+ }
3836
+
3837
+ /** `session-8fce1c` reads better as `8fce1c` in a narrow sidebar. */
3838
+ function shortSessionId(id: string): string {
3839
+ const trimmed = id.replace(/^session-/, '')
3840
+ return trimmed.length > 8 ? `${trimmed.slice(0, 8)}…` : trimmed
3841
+ }
3842
+
3843
+ /**
3844
+ * `1 session` / `3 sessions`, through the locale table.
3845
+ *
3846
+ * The toolbar's right edge answers how many sessions the project has; the
3847
+ * `sessions` section counts something else and uses
3848
+ * {@link deviationCount} instead.
3849
+ */
3850
+ export function sessionCount(count: number, t: Translate): string {
3851
+ return count === 1 ? t('sessionsOne') : t('sessionsMany', { count })
3852
+ }
3853
+
3854
+ /**
3855
+ * `1 differs` / `3 differ` — how many sessions are out of step with the project.
3856
+ *
3857
+ * A chip of its own phrase rather than `{count} sessions`: the section lists the
3858
+ * deviating sessions only, and "1 session" beside one row would read as the
3859
+ * project having a single session, which the toolbar already says.
3860
+ */
3861
+ export function deviationCount(count: number, t: Translate): string {
3862
+ return count === 1 ? t('differsOne') : t('differsMany', { count })
3863
+ }
3864
+
3865
+ /** `1 server` / `3 servers`, through the locale table. */
3866
+ export function serverCount(count: number, t: Translate): string {
3867
+ return count === 1 ? t('serversOne') : t('serversMany', { count })
3868
+ }
3869
+
3870
+ /**
3871
+ * The short form of a transport: the mockup's rows carry `http` / `stdio`.
3872
+ * @param transport - the transport the host reported.
3873
+ * @returns the chip's label.
3874
+ */
3875
+ export function shortTransport(transport: string): string {
3876
+ return transport === 'streamable-http' ? 'http' : transport
3877
+ }
3878
+
3879
+ /** Everything one server row needs beyond the row itself. */
3880
+ export interface ServerRowOptions {
3881
+ /** Retry the project's failed mounts; absent while nothing can be written. */
3882
+ onRetry?: (() => void) | undefined
3883
+ /** `true` while a host action is in flight, so the row's button stays still. */
3884
+ busy?: boolean | undefined
3885
+ /**
3886
+ * The host's own `lastUsedAt` for this server, when it published a record for
3887
+ * it: the quiet row then reads `idle 3d` beside its status word
3888
+ * ({@link idleNote}).
3889
+ */
3890
+ lastUsedAt?: string | undefined
3891
+ /** Translate seat; falls back to this module's English copy without one. */
3892
+ t?: Translate | undefined
3893
+ /**
3894
+ * Host-namespace seat for the row's coded detail (F-48); without one the
3895
+ * payload's English shows, byte-identical to before codes existed.
3896
+ */
3897
+ hostT?: Translate | undefined
3898
+ }
3899
+
3900
+ /**
3901
+ * A row's detail line as the screen shows it (F-48): the coded companions
3902
+ * resolved through the host seat, and the payload's English prose when they
3903
+ * are absent (an old host) or the seat does not know the code (a client older
3904
+ * than the host). `undefined` stays `undefined`, so a detail-less row keeps
3905
+ * its status hint as the tooltip.
3906
+ * @param row - the server row.
3907
+ * @param hostT - the host-namespace seat, when the surface has one.
3908
+ * @returns the sentence to render, or `undefined` for a row with no detail.
3909
+ */
3910
+ export function rowDetail(row: ServerRow, hostT?: Translate | undefined): string | undefined {
3911
+ if (row.detail === undefined) return undefined
3912
+ return resolveHost(hostT ?? hostTranslate(undefined), row.detailCode, row.detailParams, row.detail)
3913
+ }
3914
+
3915
+ /**
3916
+ * The quiet `idle {n}d` word a server row shows beside its status word.
3917
+ *
3918
+ * Only the two quiet statuses get one: `active`, `connecting`, `error` and
3919
+ * `conflict` already say what the server is doing, and a figure of inactivity
3920
+ * beside them would be a second answer to a question nobody asked. The word is
3921
+ * the span since the host's own `lastUsedAt` (`ProjectSnapshot.usage`), and it
3922
+ * is drawn only while that record exists and parses: no data, no word — never a
3923
+ * `0`.
3924
+ * @param status - the row's status.
3925
+ * @param lastUsedAt - ISO timestamp of the server's most recent call.
3926
+ * @param t - translate seat; falls back to this module's English copy.
3927
+ * @param now - epoch milliseconds to measure against; `Date.now()` by default.
3928
+ * @returns the label, or undefined when this row shows none.
3929
+ */
3930
+ export function idleNote(
3931
+ status: ServerStatus,
3932
+ lastUsedAt: string | undefined,
3933
+ t: Translate = translateOf(),
3934
+ now: number = Date.now(),
3935
+ ): string | undefined {
3936
+ if (status !== 'idle' && status !== 'disabled') return undefined
3937
+ const span = idleOf(lastUsedAt, now)
3938
+ if (span === undefined) return undefined
3939
+ const key = span.unit === 'day' ? 'idleDay' : span.unit === 'hour' ? 'idleHour' : 'idleMinute'
3940
+ return t(key, { count: span.count })
3941
+ }
3942
+
3943
+ /**
3944
+ * How often one tool was called, as its row writes it.
3945
+ *
3946
+ * The counters belong to the host's record of the tool's server, and there are
3947
+ * two of them: the project's, which is what proved the tool hot, and the reading
3948
+ * session's own share of it (F-34). The row leads with the session's figure —
3949
+ * the question a reader at one session asks — and names the project's when the
3950
+ * two disagree, because that disagreement is the whole point: tools are mounted
3951
+ * for the project and used inside a session. Three states are told apart: a
3952
+ * figure to print, a server the host recorded whose counter for this tool is
3953
+ * absent (`never called`), and no record at all, which draws nothing.
3954
+ * @param calls - the two readings, absent when the host published no record.
3955
+ * @param t - translate seat; falls back to this module's English copy.
3956
+ * @returns the label, or undefined when the row shows none.
3957
+ */
3958
+ export function callsLabel(calls: ToolCalls | undefined, t: Translate = translateOf()): string | undefined {
3959
+ if (calls === undefined || !calls.recorded) return undefined
3960
+ // The session's own reading leads whenever the host splits its counters by
3961
+ // session; without a split the project total is the only figure there is.
3962
+ const lead = calls.split ? calls.session : calls.project
3963
+ const figure =
3964
+ lead === undefined ? t('callsNone') : lead === 1 ? t('callsOne') : t('callsMany', { count: lead })
3965
+ const project = calls.project
3966
+ // The project's figure rides along exactly while it adds something: it is
3967
+ // published, and the session's own reading does not already say it. Two numbers
3968
+ // that agree are one number, and `never called · 182 in the project` says what
3969
+ // "never called" alone would leave unsaid.
3970
+ const adds = project !== undefined && project !== lead
3971
+ return adds ? `${figure} · ${t('callsProject', { count: project })}` : figure
3972
+ }
3973
+
3974
+ /**
3975
+ * One server, as the tab draws it.
3976
+ *
3977
+ * The status is the dot, not a word: its colour comes from the shared
3978
+ * {@link STATUS_COLOR} table and its tooltip through {@link STATUS_HINT}, so the
3979
+ * row reads at a glance and still explains itself on hover. The transport and
3980
+ * the quiet states (`idle`, `disabled`) are chips, and the quiet rows are dimmed
3981
+ * rather than recoloured. A row the host reported a failure for carries its own
3982
+ * `Retry` — the host route is project-scoped, so it sends exactly the request
3983
+ * the toolbar's button sends — and its detail in a banner underneath, with the
3984
+ * coloured left rule the mockup uses for a failure.
3985
+ * @param row - the server row.
3986
+ * @param keyPrefix - prefix for the two element keys of this row.
3987
+ * @param options - the row action and the translate seat.
3988
+ * @returns the row and, when it has one, its detail banner.
3989
+ */
3990
+ export function serverRow(
3991
+ row: ServerRow,
3992
+ keyPrefix: string,
3993
+ options: ServerRowOptions = {},
3994
+ ): ReactNode[] {
3995
+ const t = translateOf(options.t)
3996
+ const quiet = row.status === 'idle' || row.status === 'disabled'
3997
+ // The host's detail line, translated when the row carries its wire code.
3998
+ const detail = rowDetail(row, options.hostT)
3999
+ // The span since the host's own `lastUsedAt`, drawn beside the quiet status
4000
+ // word and only there: `idle 3d` says how long a quiet server has been quiet,
4001
+ // which is a fact the status word alone cannot carry.
4002
+ const idle = idleNote(row.status, options.lastUsedAt, t)
4003
+ return [
4004
+ h(
4005
+ 'div',
4006
+ {
4007
+ style: quiet ? { ...STYLE.row, ...STYLE.rowQuiet } : STYLE.row,
4008
+ key: `${keyPrefix}#${row.name}`,
4009
+ title: detail ?? t(STATUS_HINT[row.status]),
4010
+ },
4011
+ h('span', {
4012
+ style: { ...STYLE.dot, background: STATUS_COLOR[row.status] },
4013
+ 'aria-hidden': true,
4014
+ }),
4015
+ h('span', { style: STYLE.name }, row.name),
4016
+ row.transport === undefined
4017
+ ? null
4018
+ : h('span', { style: STYLE.tag }, shortTransport(row.transport)),
4019
+ // The quiet chip takes the mock's `.dim` tone (`docs/design/mockups/harness.html`),
4020
+ // one step below the transport chip beside it.
4021
+ quiet ? h('span', { style: { ...STYLE.tag, ...STYLE.tagQuiet } }, t(STATUS_KEYS[row.status])) : null,
4022
+ idle === undefined ? null : h('span', { style: STYLE.dim }, idle),
4023
+ h('span', { style: { flex: 1 } }),
4024
+ row.status === 'error' && options.onRetry !== undefined
4025
+ ? h(
4026
+ 'button',
4027
+ {
4028
+ style: STYLE.button,
4029
+ title: t('retryHint'),
4030
+ disabled: options.busy === true,
4031
+ onClick: options.onRetry,
4032
+ },
4033
+ t('retry'),
4034
+ )
4035
+ : null,
4036
+ ),
4037
+ // A quiet row's detail ("not mounted yet — this session has not started a
4038
+ // turn") is a fact about a *normal* state, and the mockup draws `idle` as a
4039
+ // chip with no note under it (`docs/design/mockups/harness.html`): a warning banner per
4040
+ // idle server turns a calm list into a wall of amber. The reason stays on
4041
+ // the row's own `title`, and the errors disclosure (error / conflict /
4042
+ // connecting only) is where the host's text is read out in full.
4043
+ row.detail === undefined || quiet
4044
+ ? null
4045
+ : h(
4046
+ 'div',
4047
+ {
4048
+ style:
4049
+ row.status === 'error'
4050
+ ? STYLE.banner
4051
+ : { ...STYLE.banner, ...STYLE.bannerWarn },
4052
+ key: `${keyPrefix}#${row.name}#detail`,
4053
+ },
4054
+ detail,
4055
+ ),
4056
+ ]
4057
+ }
4058
+
4059
+ function countStatuses(rows: readonly ServerRow[]): Partial<Record<ServerStatus, number>> {
4060
+ const totals: Partial<Record<ServerStatus, number>> = {}
4061
+ for (const row of rows) totals[row.status] = (totals[row.status] ?? 0) + 1
4062
+ return totals
4063
+ }
4064
+
4065
+ /** The statuses a summary line names, in the order it names them. */
4066
+ const SUMMARY_ORDER = ['active', 'connecting', 'idle', 'error', 'conflict'] as const
4067
+
4068
+ /**
4069
+ * The `{count}` template key of every status — a full `ServerStatus` record,
4070
+ * so a status the order above ever names without a template is a compile
4071
+ * error, not a raw token in the summary line.
4072
+ */
4073
+ const SUMMARY_KEYS: Record<ServerStatus, LocaleKey> = {
4074
+ active: 'summaryActive',
4075
+ connecting: 'summaryConnecting',
4076
+ idle: 'summaryIdle',
4077
+ disabled: 'summaryDisabled',
4078
+ error: 'summaryError',
4079
+ conflict: 'summaryConflict',
4080
+ }
4081
+
4082
+ /**
4083
+ * One line of status counts (`2 active, 1 idle`), every count a `{count}`
4084
+ * placeholder of its status's template so no language reads a concatenation.
4085
+ * @param totals - the counted rows.
4086
+ * @param t - translate seat; falls back to this module's English copy.
4087
+ * @returns the summary, or the `summaryNone` answer when nothing was counted.
4088
+ */
4089
+ function summarize(
4090
+ totals: Partial<Record<ServerStatus, number>>,
4091
+ t: Translate = fallbackTranslate,
4092
+ ): string {
4093
+ const parts: string[] = []
4094
+ for (const status of SUMMARY_ORDER) {
4095
+ const count = totals[status]
4096
+ if (count !== undefined && count > 0) parts.push(t(SUMMARY_KEYS[status], { count }))
4097
+ }
4098
+ return parts.length === 0 ? t('summaryNone') : parts.join(', ')
4099
+ }
4100
+
4101
+ /** Last path segment; used for every project and document label. */
4102
+ export function basename(path: string): string {
4103
+ const parts = path.split('/').filter((part) => part !== '')
4104
+ return parts[parts.length - 1] ?? path
4105
+ }
4106
+
4107
+ function messageOf(error: unknown): string {
4108
+ return error instanceof Error ? error.message : String(error)
4109
+ }
4110
+
4111
+ /** Read the persisted poll interval out of a plugin settings blob. */
4112
+ export function refreshMsOf(settings: Record<string, unknown>): number {
4113
+ const value = settings[REFRESH_KEY]
4114
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : DEFAULT_REFRESH_MS
4115
+ }
4116
+
4117
+ /** Read the settings blob of this descriptor from the sidebar snapshot. */
4118
+ export function pluginSettingsOf(snapshot: { prefs: { pluginSettings?: Record<string, Record<string, unknown>> } }): Record<string, unknown> {
4119
+ return snapshot.prefs.pluginSettings?.[TAB_ID] ?? {}
4120
+ }