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,1136 @@
1
+ /**
2
+ * The tools side of the plugin's page in DSH's native Settings.
3
+ *
4
+ * The page has two pages of its own, because one plugin is one row of the
5
+ * settings navigation: `Servers` is the declaration view this module never
6
+ * touches, and `Tools` is the per-project policy the disclosure half of the
7
+ * mockup lays out. Both live in the same `settings.section` registration — this
8
+ * module adds the tab, it does not register a second navigation item.
9
+ *
10
+ * Tools answers a different question than the live surfaces: not "what does the
11
+ * model see right now", but "what will this project offer, and what is pinned".
12
+ * Everything on it is measured rather than invented: the server and tool counts
13
+ * come from the host snapshot's rows and each session's `tools`, the pinned list
14
+ * and the mode are the project's own `policy`, the per-server counters are
15
+ * counted from the session's own offer by the registry's `mcp__<server>__`
16
+ * prefix, the conflicts are the host's report, and the request preview lists the
17
+ * names the session really offers with the token estimate the contract derives
18
+ * from the serialized sizes. Nothing here reads `./demo.ts`, and no row invents
19
+ * a value the host does not publish.
20
+ *
21
+ * @module dsh-project-mcp/client/settings-tools
22
+ */
23
+
24
+ import { createElement as h } from 'react'
25
+ import type { ReactNode } from 'react'
26
+ import type {
27
+ ConflictChoice,
28
+ ProjectSnapshot,
29
+ ServerConflict,
30
+ SessionTools,
31
+ ToolMode,
32
+ ToolPolicy,
33
+ } from '../types.ts'
34
+ import { policyOf } from './policy.ts'
35
+ import { STYLE } from './settings.ts'
36
+ import type { LocaleKey, Translate } from './settings.ts'
37
+ import {
38
+ basename,
39
+ callsLabel,
40
+ serverOfToolName,
41
+ serverPinPress,
42
+ serverPinState,
43
+ toolCounts,
44
+ toolCalls,
45
+ } from './view.ts'
46
+ import type { ToolCalls } from './view.ts'
47
+ import { byCalls } from './usage-view.ts'
48
+ import { hostTranslate, resolveHost } from './locales/host.ts'
49
+
50
+ /**
51
+ * A serialized size in tokens, by the contract's own reading: `chars / 4`.
52
+ *
53
+ * The estimate is printed only where a size is known: a session the host
54
+ * published without `deferredChars` gets the hidden count and no estimate,
55
+ * rather than an invented one.
56
+ * @param chars - serialized size in characters.
57
+ * @returns the estimate, rounded to a whole token.
58
+ */
59
+ export function tokenEstimate(chars: number): number {
60
+ return Math.round(chars / 4)
61
+ }
62
+
63
+ /**
64
+ * The three values the mode switch offers, in the order the contract lists them.
65
+ *
66
+ * Straight from the frozen `ToolMode`, so the form cannot drift into the
67
+ * mockup's `all-direct` spelling of the same state.
68
+ */
69
+ export const TOOL_MODES: readonly ToolMode[] = ['disclosure', 'direct', 'off']
70
+
71
+ /** Which of the plugin page's own pages is open. */
72
+ export type SettingsPageKey = 'servers' | 'tools'
73
+
74
+ /** Page shown when nothing else was chosen, so the page never opens blank. */
75
+ export const DEFAULT_SETTINGS_PAGE: SettingsPageKey = 'servers'
76
+
77
+ /** One page of the plugin's own settings page, in the switch's order. */
78
+ export interface SettingsPageTab {
79
+ key: SettingsPageKey
80
+ /** Dictionary key of the label; the switch resolves it through `t`. */
81
+ labelKey: LocaleKey
82
+ }
83
+
84
+ /**
85
+ * The two pages of our own settings page.
86
+ *
87
+ * `Servers` is what the plugin has shipped since the write path landed; `Tools`
88
+ * is the disclosure policy, added next to it rather than as a second row of the
89
+ * settings navigation.
90
+ */
91
+ export const SETTINGS_PAGES: readonly SettingsPageTab[] = [
92
+ { key: 'servers', labelKey: 'tabServers' },
93
+ { key: 'tools', labelKey: 'tabTools' },
94
+ ]
95
+
96
+ /** The `Servers` / `Tools` switch inside our own settings page. */
97
+ export function SettingsPageSwitch(props: {
98
+ page: SettingsPageKey
99
+ onChange: (page: SettingsPageKey) => void
100
+ t: Translate
101
+ }): ReactNode {
102
+ const item = (tab: SettingsPageTab): ReactNode =>
103
+ h(
104
+ 'button',
105
+ {
106
+ key: tab.key,
107
+ style:
108
+ tab.key === props.page
109
+ ? { ...STYLE.segmentItem, ...STYLE.segmentItemActive }
110
+ : STYLE.segmentItem,
111
+ 'aria-pressed': tab.key === props.page,
112
+ onClick: () => props.onChange(tab.key),
113
+ },
114
+ props.t(tab.labelKey),
115
+ )
116
+ return h('div', { style: STYLE.segment }, SETTINGS_PAGES.map(item))
117
+ }
118
+
119
+ // ── the project table ─────────────────────────────────────────────────────────
120
+
121
+ /** How many live sessions one project has; the table's "seen" column. */
122
+ export function liveSessions(project: ProjectSnapshot): number {
123
+ return project.sessionIds.length
124
+ }
125
+
126
+ /**
127
+ * The live snapshot of one project's first session, when the host published one.
128
+ * @param project - project row of the settings page.
129
+ * @returns that session's snapshot, or undefined when nothing is live.
130
+ */
131
+ export function firstSession(project: ProjectSnapshot): ProjectSnapshot['sessions'][number] | undefined {
132
+ return (project.sessions ?? [])[0]
133
+ }
134
+
135
+ /** The tools one project shows in the table, with their provenance. */
136
+ export interface ProjectToolCounts {
137
+ /** Servers the project declares. */
138
+ servers: number
139
+ /** Tools mounted for the project, when the session published them. */
140
+ tools: number | undefined
141
+ /** Tools the session activated on demand. */
142
+ disclosed: number
143
+ }
144
+
145
+ /**
146
+ * Count one project's servers and tools.
147
+ *
148
+ * Both numbers are real: servers are `project.rows`, tools are the mounted total
149
+ * of the first live session's `SessionTools`. A project whose sessions published
150
+ * no offer has no tool count at all — the row shows a dash — because the count of
151
+ * its *servers* is not the count of its tools.
152
+ * @param project - project row of the settings page.
153
+ * @returns the counts; `tools` is undefined when no session published an offer.
154
+ */
155
+ export function projectToolCounts(project: ProjectSnapshot): ProjectToolCounts {
156
+ const live = firstSession(project)?.tools
157
+ return {
158
+ servers: project.rows.length,
159
+ tools: live?.mounted,
160
+ disclosed: live === undefined ? 0 : toolCounts(live).disclosed,
161
+ }
162
+ }
163
+
164
+ /** The policy row of one project: the host's own counts and the policy in force. */
165
+ export interface ProjectPolicyRow {
166
+ /** Project root. */
167
+ projectRoot: string
168
+ /** Short label the table shows. */
169
+ label: string
170
+ /** Declared servers and mounted tools. */
171
+ counts: ProjectToolCounts
172
+ /** The policy in force, as the host published it. */
173
+ policy: ToolPolicy
174
+ }
175
+
176
+ /**
177
+ * One table row per project with a live session, in snapshot order.
178
+ * @param projects - projects the host snapshot carries.
179
+ * @returns the rows the table renders.
180
+ */
181
+ export function projectPolicyRows(projects: readonly ProjectSnapshot[]): ProjectPolicyRow[] {
182
+ return projects.map((project) => ({
183
+ projectRoot: project.projectRoot,
184
+ label: basename(project.projectRoot),
185
+ counts: projectToolCounts(project),
186
+ policy: policyOf(project),
187
+ }))
188
+ }
189
+
190
+ /** What one mode value is called in the UI. */
191
+ const MODE_KEYS: Record<ToolMode, LocaleKey> = {
192
+ disclosure: 'modeDisclosure',
193
+ direct: 'modeDirect',
194
+ off: 'modeOff',
195
+ }
196
+
197
+ /** The label of one mode value. */
198
+ export function modeLabel(mode: ToolMode, t: Translate): string {
199
+ return t(MODE_KEYS[mode])
200
+ }
201
+
202
+ /**
203
+ * The dense per-project overview: one row per project with a live session.
204
+ *
205
+ * The mode cell is the one interactive column: a mode is a value the host
206
+ * stores, so it is written as soon as it is clicked (the page says so under the
207
+ * form) and the button goes quiet while the answer is in flight.
208
+ *
209
+ * Seven columns did not fit the settings panel's content column on every window;
210
+ * the five the host answers for do, and the table is still a scroll region
211
+ * rather than a block that runs under the panel edge. Its headers stay on one
212
+ * line, and the project name — the only free-form text in it — wraps inside its
213
+ * cell instead of widening the table.
214
+ */
215
+ export function ToolsProjectTable(props: {
216
+ rows: readonly ProjectPolicyRow[]
217
+ /** Roots the host is currently writing a mode or a pin for. */
218
+ pending: ReadonlySet<string>
219
+ onMode: (projectRoot: string, mode: ToolMode) => void
220
+ t: Translate
221
+ }): ReactNode {
222
+ const { t } = props
223
+ const th = { ...STYLE.th, whiteSpace: 'nowrap' as const }
224
+ return h(
225
+ 'div',
226
+ { style: STYLE.tableScroll },
227
+ h(
228
+ 'table',
229
+ { style: STYLE.table },
230
+ h(
231
+ 'thead',
232
+ null,
233
+ h(
234
+ 'tr',
235
+ null,
236
+ h('th', { style: th }, t('project')),
237
+ h('th', { style: th }, t('servers')),
238
+ h('th', { style: th }, t('toolsCount')),
239
+ h('th', { style: th }, t('pinned')),
240
+ h('th', { style: th }, t('mode')),
241
+ ),
242
+ ),
243
+ h(
244
+ 'tbody',
245
+ null,
246
+ props.rows.map((row) =>
247
+ h(
248
+ 'tr',
249
+ { key: row.projectRoot },
250
+ h('td', { style: { ...STYLE.td, overflowWrap: 'anywhere' as const } }, row.label),
251
+ h('td', { style: STYLE.td }, String(row.counts.servers)),
252
+ h(
253
+ 'td',
254
+ { style: STYLE.td },
255
+ row.counts.tools === undefined ? '—' : String(row.counts.tools),
256
+ ),
257
+ h('td', { style: STYLE.td }, String(row.policy.pins.length)),
258
+ h(
259
+ 'td',
260
+ { style: STYLE.td },
261
+ ModeSwitchRow({
262
+ mode: row.policy.mode,
263
+ busy: props.pending.has(row.projectRoot),
264
+ onMode: (mode) => props.onMode(row.projectRoot, mode),
265
+ t,
266
+ }),
267
+ ),
268
+ ),
269
+ ),
270
+ ),
271
+ ),
272
+ )
273
+ }
274
+
275
+ // ── the tools tab ─────────────────────────────────────────────────────────────
276
+
277
+ /** Props of the `Tools` page: the selected project and its host policy. */
278
+ export interface ToolsPageProps {
279
+ /** The project the page shows; selected by the shared project picker. */
280
+ project: ProjectSnapshot
281
+ /** Every project with a live session, for the overview table above the form. */
282
+ rows: readonly ProjectPolicyRow[]
283
+ /** Switch one project's mode; the host stores it, so it is written at once. */
284
+ onMode: (projectRoot: string, mode: ToolMode) => void
285
+ /** Roots with a policy write in flight. */
286
+ pending: ReadonlySet<string>
287
+ /** Last refusal from a policy write, when the host did not take it. */
288
+ modeError: string | undefined
289
+ /** Wire companions of `modeError`, when the host coded the refusal (F-48). */
290
+ modeErrorCode?: string | undefined
291
+ /** Flat params of `modeErrorCode`. */
292
+ modeErrorParams?: Record<string, string> | undefined
293
+ /** Re-read the host snapshot now; the conflict report's own action. */
294
+ onSync: () => void
295
+ /** Pin or unpin one tool of one project; the host stores it at once. */
296
+ onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined
297
+ /** Tool names with a pin write in flight, per `projectRoot` + `tool`. */
298
+ pinPending?: ReadonlySet<string> | undefined
299
+ /** Last refusal from a pin write, when the host did not take it. */
300
+ pinError?: string | undefined
301
+ /** Wire companions of `pinError`, when the host coded the refusal (F-48). */
302
+ pinErrorCode?: string | undefined
303
+ /** Flat params of `pinErrorCode`. */
304
+ pinErrorParams?: Record<string, string> | undefined
305
+ /**
306
+ * Choose which declaration of one contested name the project shows. The host
307
+ * stores the answer and answers with the snapshot that already reflects it,
308
+ * so this page draws the new state instead of guessing it.
309
+ */
310
+ onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined
311
+ /** Contested names with a choice write in flight, per `projectRoot` + name. */
312
+ choicePending?: ReadonlySet<string> | undefined
313
+ /** Last refusal from a choice write, when the host did not take it. */
314
+ choiceError?: string | undefined
315
+ /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */
316
+ choiceErrorCode?: string | undefined
317
+ /** Flat params of `choiceErrorCode`. */
318
+ choiceErrorParams?: Record<string, string> | undefined
319
+ t: Translate
320
+ /** Host-namespace seat for the conflicts' coded messages (F-48). */
321
+ hostT?: Translate | undefined
322
+ }
323
+
324
+ /**
325
+ * The `Tools` page: the project table, then the form of the selected project.
326
+ *
327
+ * The page is a vertical list of setting rows rather than the mockup's split:
328
+ * a policy form is a list of settings, which is what DSH's own settings pages
329
+ * are, and the split's panes are too narrow for the sentences they had to hold.
330
+ */
331
+ export function ToolsPage(props: ToolsPageProps): ReactNode {
332
+ const { t } = props
333
+ const policy = policyOf(props.project)
334
+ return h(
335
+ 'div',
336
+ null,
337
+ h(ToolsProjectTable, {
338
+ rows: props.rows,
339
+ pending: props.pending,
340
+ onMode: props.onMode,
341
+ t,
342
+ }),
343
+ props.modeError === undefined
344
+ ? null
345
+ : h(
346
+ 'div',
347
+ { style: STYLE.noteError },
348
+ // A coded refusal translates through the host seat; prose alone
349
+ // renders exactly as it did before codes existed.
350
+ `${t('modeRefused')} ${resolveHost(props.hostT ?? hostTranslate(undefined), props.modeErrorCode, props.modeErrorParams, props.modeError)}`,
351
+ ),
352
+ h(ProjectForm, {
353
+ project: props.project,
354
+ policy,
355
+ onMode: props.onMode,
356
+ pending: props.pending.has(props.project.projectRoot),
357
+ onSync: props.onSync,
358
+ onPin: props.onPin,
359
+ pinPending: props.pinPending,
360
+ pinError: props.pinError,
361
+ pinErrorCode: props.pinErrorCode,
362
+ pinErrorParams: props.pinErrorParams,
363
+ onChoice: props.onChoice,
364
+ choicePending: props.choicePending,
365
+ choiceError: props.choiceError,
366
+ choiceErrorCode: props.choiceErrorCode,
367
+ choiceErrorParams: props.choiceErrorParams,
368
+ t,
369
+ hostT: props.hostT,
370
+ }),
371
+ )
372
+ }
373
+
374
+ /**
375
+ * The switch that stands for a whole server (F-44).
376
+ *
377
+ * It wears the control every per-name row below wears, and its reading is
378
+ * {@link serverPinState}'s proportion: on while the project pins **every** name
379
+ * this page lists for that server, off otherwise. A half-pinned server
380
+ * therefore reads off, and that is the honest reading of the only store there
381
+ * is — the pin list holds names, no rule about servers, and this page has no
382
+ * third visual for "some". What the press does is said by the tooltip and is
383
+ * never a loss: the set is completed when it is not complete and released only
384
+ * when it is ({@link serverPinPress}).
385
+ *
386
+ * The names are **every** name the host published for that server: the offered
387
+ * ones this page lists below, and the ones it kept hidden. A pin is what pulls a
388
+ * hidden name into the request (that is what the tab's hidden tier does with its
389
+ * own `Pin`), so a switch that stood for the server while skipping them would
390
+ * leave the server half-pinned — and the row's own description already counts
391
+ * them (`1 of 3 tools offered directly`).
392
+ * @param props - the project, the server, the names that stand for it and the writer.
393
+ * @returns the switch, inert while there is nothing to write to.
394
+ */
395
+ function serverPinSwitch(props: {
396
+ projectRoot: string
397
+ server: string
398
+ /** Every name the host published for this server, hidden ones included. */
399
+ names: readonly string[]
400
+ /** The project's own pin list. */
401
+ pins: readonly string[]
402
+ /** `true` while a pin write of this server is in flight. */
403
+ pending: boolean
404
+ onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined
405
+ t: Translate
406
+ }): ReactNode {
407
+ const { t } = props
408
+ const all = serverPinState(props.names, props.pins) === 'all'
409
+ const press = serverPinPress(props.names, props.pins)
410
+ // `names` is never empty for a row that is drawn: the rows come from
411
+ // `serverToolCounts`, and a server is in that list because it contributed at
412
+ // least one name. A switch over nothing would not exist to be disabled.
413
+ const disabled = props.onPin === undefined || props.pending
414
+ return h(
415
+ 'button',
416
+ {
417
+ type: 'button',
418
+ style: all ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },
419
+ 'aria-checked': all,
420
+ 'aria-label': `${props.server} — ${all ? t('serverUnpin') : t('serverPin')}`,
421
+ title: all ? t('serverUnpinHint') : t('serverPinHint'),
422
+ disabled,
423
+ onClick: () => {
424
+ for (const name of press.names) props.onPin?.(props.projectRoot, name, press.pinned)
425
+ },
426
+ },
427
+ h('span', { style: all ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob }),
428
+ )
429
+ }
430
+
431
+ /**
432
+ * The form of one project's policy: the setting rows — the mode, then one row
433
+ * per server of the session — under the page's own note, then the pinned group
434
+ * with the conflict report, the mounted tool list and the request preview as
435
+ * full-width blocks.
436
+ *
437
+ * The server rows are the mockup's "not to be touched" field, made real: each
438
+ * one names a server this session mounts and says, from the session's own offer,
439
+ * how many of its tools the model is offered directly. A row that used to
440
+ * promise a locked example service now counts the project's own servers.
441
+ */
442
+ export function ProjectForm(props: {
443
+ project: ProjectSnapshot
444
+ /** The host's policy for that project: the mode and the pin list. */
445
+ policy: ToolPolicy
446
+ onMode: (projectRoot: string, mode: ToolMode) => void
447
+ /** `true` while this project's mode is being written. */
448
+ pending: boolean
449
+ /** Re-read the host snapshot now; the conflict report's own action. */
450
+ onSync: () => void
451
+ /** Pin or unpin one tool of this project; the host stores it at once. */
452
+ onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined
453
+ /** Tool names with a pin write in flight. */
454
+ pinPending?: ReadonlySet<string> | undefined
455
+ /** Last refusal from a pin write, when the host did not take it. */
456
+ pinError?: string | undefined
457
+ /** Wire companions of `pinError`, when the host coded the refusal (F-48). */
458
+ pinErrorCode?: string | undefined
459
+ /** Flat params of `pinErrorCode`. */
460
+ pinErrorParams?: Record<string, string> | undefined
461
+ /** Choose which declaration of one contested name this project shows. */
462
+ onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined
463
+ /** Contested names with a choice write in flight. */
464
+ choicePending?: ReadonlySet<string> | undefined
465
+ /** Last refusal from a choice write, when the host did not take it. */
466
+ choiceError?: string | undefined
467
+ /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */
468
+ choiceErrorCode?: string | undefined
469
+ /** Flat params of `choiceErrorCode`. */
470
+ choiceErrorParams?: Record<string, string> | undefined
471
+ t: Translate
472
+ /** Host-namespace seat for the conflicts' coded messages (F-48). */
473
+ hostT?: Translate | undefined
474
+ }): ReactNode {
475
+ const { t, policy } = props
476
+ const tools = firstSession(props.project)?.tools
477
+ const servers = tools === undefined ? [] : serverToolCounts(tools)
478
+ // The names this page lists, read once: the per-name list below works from
479
+ // this set.
480
+ const offered = offeredNames(tools)
481
+ /**
482
+ * Every name the host published for one server, offered and hidden alike.
483
+ *
484
+ * The per-name list below shows the offered half only, but a server's switch
485
+ * speaks for the server: the hidden names are exactly the ones a pin pulls
486
+ * into the request, and the row's own description counts them, so leaving them
487
+ * out would make the switch quieter than the sentence beside it.
488
+ * @param server - the `serverName` as the registry spells it in the prefix.
489
+ * @returns the names, offered first, each once.
490
+ */
491
+ const mountedOf = (server: string): string[] => [
492
+ ...new Set([
493
+ ...offered.filter((name) => serverOfToolName(name) === server),
494
+ ...(tools?.deferred ?? []).filter((name) => serverOfToolName(name) === server),
495
+ ]),
496
+ ]
497
+ return h(
498
+ 'div',
499
+ null,
500
+ // The mode is the host's own value: the write goes out on the click, so
501
+ // the row carries the hint about that instead of a Save of its own. The
502
+ // longer explanation rides the row's tooltip rather than a paragraph above
503
+ // it — the mockup spends its lines on controls, not on prose.
504
+ SettingRow({
505
+ label: t('mode'),
506
+ description: t('modeHint'),
507
+ title: t('policyNote'),
508
+ control: ModeSwitchRow({
509
+ mode: policy.mode,
510
+ busy: props.pending,
511
+ onMode: (mode) => props.onMode(props.project.projectRoot, mode),
512
+ t,
513
+ }),
514
+ last: servers.length === 0,
515
+ }),
516
+ // One row per server, and since F-44 the row is also where a whole server
517
+ // gets pinned: the name keeps its place at the right edge and the switch
518
+ // stands beside it, so the reading and the action share one line.
519
+ ...servers.map((count, index) => {
520
+ const names = mountedOf(count.server)
521
+ return SettingRow({
522
+ label: t('server'),
523
+ description: serverOfferLabel(count, t),
524
+ control: h(
525
+ 'span',
526
+ { style: STYLE.settingRowControl },
527
+ h('span', { style: STYLE.muted }, count.server),
528
+ serverPinSwitch({
529
+ projectRoot: props.project.projectRoot,
530
+ server: count.server,
531
+ names,
532
+ pins: policy.pins,
533
+ pending: names.some((name) => props.pinPending?.has(name) === true),
534
+ onPin: props.onPin,
535
+ t,
536
+ }),
537
+ ),
538
+ last: index === servers.length - 1,
539
+ })
540
+ }),
541
+ h(
542
+ 'div',
543
+ { style: STYLE.settingGroup },
544
+ h('div', { style: STYLE.settingGroupHead }, t('pinned')),
545
+ // The pin list is the host's: names the user pinned by hand, in the order
546
+ // they pinned them. No badge, because nothing here is invented — and the
547
+ // list gets the whole width, so a long name cannot be clipped.
548
+ h(
549
+ 'div',
550
+ { style: STYLE.tagList },
551
+ policy.pins.length === 0
552
+ ? h('span', { style: STYLE.hint }, t('pinListEmpty'))
553
+ : policy.pins.map((name) => h('span', { key: name, style: STYLE.tag }, name)),
554
+ ),
555
+ // The conflict check is real: the report is the host's own
556
+ // `ProjectSnapshot.conflicts`, drawn under the row, and the button asks
557
+ // the host for a fresh snapshot rather than standing in for one. Both the
558
+ // hint and the button carry the label "Check conflicts": the head is the
559
+ // block's own title, and the button repeats it as the action.
560
+ SettingRow({
561
+ label: t('checkConflicts'),
562
+ description: t('pinList'),
563
+ title: t('checkConflictsHint'),
564
+ control: h(
565
+ 'button',
566
+ { style: STYLE.button, title: t('checkConflictsHint'), onClick: props.onSync },
567
+ t('checkConflicts'),
568
+ ),
569
+ last: true,
570
+ }),
571
+ ConflictReport({
572
+ projectRoot: props.project.projectRoot,
573
+ conflicts: props.project.conflicts ?? [],
574
+ onChoice: props.onChoice,
575
+ choicePending: props.choicePending,
576
+ choiceError: props.choiceError,
577
+ choiceErrorCode: props.choiceErrorCode,
578
+ choiceErrorParams: props.choiceErrorParams,
579
+ t,
580
+ hostT: props.hostT,
581
+ }),
582
+ ),
583
+ h(ToolList, {
584
+ project: props.project,
585
+ policy,
586
+ onPin: props.onPin,
587
+ pinPending: props.pinPending,
588
+ pinError: props.pinError,
589
+ pinErrorCode: props.pinErrorCode,
590
+ pinErrorParams: props.pinErrorParams,
591
+ t,
592
+ hostT: props.hostT,
593
+ }),
594
+ h(RequestPreview, { project: props.project, policy, t }),
595
+ )
596
+ }
597
+
598
+ /**
599
+ * The host's conflict report for one project, always drawn.
600
+ *
601
+ * The report needs no click to appear: the host counts the conflicts when it
602
+ * builds the snapshot, so hiding them behind a button would hide an answer the
603
+ * page already holds. The empty state is a real answer too — "no conflicts" is
604
+ * the good case, and the row above it says so instead of showing nothing.
605
+ * @param props - the conflicts, in the host's order.
606
+ * @returns one row per conflict, or the empty state.
607
+ */
608
+ export function ConflictReport(props: {
609
+ /** Project the names belong to; the choice is stored per project. */
610
+ projectRoot: string
611
+ conflicts: readonly ServerConflict[]
612
+ /** Choose a declaration; absent leaves the cards read-only. */
613
+ onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined
614
+ /** Contested names with a write in flight. */
615
+ choicePending?: ReadonlySet<string> | undefined
616
+ /** Last refusal from a choice write, when the host did not take it. */
617
+ choiceError?: string | undefined
618
+ /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */
619
+ choiceErrorCode?: string | undefined
620
+ /** Flat params of `choiceErrorCode`. */
621
+ choiceErrorParams?: Record<string, string> | undefined
622
+ t: Translate
623
+ /**
624
+ * Host-namespace seat for the conflicts' coded messages (F-48); without one
625
+ * each card renders its payload's English, byte-identical to before codes.
626
+ */
627
+ hostT?: Translate | undefined
628
+ }): ReactNode {
629
+ const { t } = props
630
+ if (props.conflicts.length === 0) {
631
+ return h('div', { style: { ...STYLE.hint, padding: '8px 0' } }, t('conflictsNone'))
632
+ }
633
+ return h(
634
+ 'div',
635
+ null,
636
+ props.conflicts.map((conflict) =>
637
+ // One conflict is one card, in the alarm tone: the mockups draw a conflict
638
+ // as a note that reads as a warning, not as another table row.
639
+ h(
640
+ 'div',
641
+ { key: conflict.server, style: STYLE.noteError },
642
+ h('strong', null, conflict.server),
643
+ ' ',
644
+ h('span', { style: conflictTone(conflict.kind) }, conflictKindLabel(conflict.kind, t)),
645
+ h(
646
+ 'div',
647
+ { style: STYLE.muted },
648
+ resolveHost(props.hostT ?? hostTranslate(undefined), conflict.code, conflict.params, conflict.message),
649
+ ),
650
+ conflict.sources.length === 0
651
+ ? null
652
+ : h(
653
+ 'div',
654
+ { style: STYLE.hint },
655
+ t('conflictSources', { sources: conflict.sources.join(' · ') }),
656
+ ),
657
+ ConflictChoiceRow({
658
+ projectRoot: props.projectRoot,
659
+ conflict,
660
+ onChoice: props.onChoice,
661
+ pending: props.choicePending?.has(choiceKey(props.projectRoot, conflict.server)) ?? false,
662
+ t,
663
+ }),
664
+ ),
665
+ ),
666
+ props.choiceError === undefined
667
+ ? null
668
+ : h(
669
+ 'div',
670
+ { style: STYLE.noteError },
671
+ `${t('choiceRefused')} ${resolveHost(props.hostT ?? hostTranslate(undefined), props.choiceErrorCode, props.choiceErrorParams, props.choiceError)}`,
672
+ ),
673
+ )
674
+ }
675
+
676
+ /**
677
+ * The choice control of one conflict card: which of the declarations this
678
+ * project shows.
679
+ *
680
+ * Drawn wherever a profile-level reservation meets a surface that can write the
681
+ * answer. A duplicate declaration has no toggle on purpose: both copies live in
682
+ * this project's own documents, and no rename of the winner brings the loser
683
+ * back.
684
+ *
685
+ * The three answers are the host's own `ConflictChoice`, in its order. `profile`
686
+ * and `native` need nothing but the name the conflict already carries; `local`
687
+ * is the one that cannot be drawn without a worked-out alias, so a host that
688
+ * published none loses that button alone — an alias-less project can still keep
689
+ * the profile instance or mount its own declaration under the declared name.
690
+ * @param props - the conflict, its project and the write surface.
691
+ * @returns the row, or `null` when the conflict carries no choice.
692
+ */
693
+ function ConflictChoiceRow(props: {
694
+ projectRoot: string
695
+ conflict: ServerConflict
696
+ onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined
697
+ pending: boolean
698
+ t: Translate
699
+ }): ReactNode {
700
+ const { conflict, t } = props
701
+ const write = props.onChoice
702
+ if (conflict.kind !== 'profile' || write === undefined) return null
703
+ const choice = conflict.choice ?? 'profile'
704
+ const button = (next: ConflictChoice, title: string, label: string): ReactNode =>
705
+ h(
706
+ 'button',
707
+ {
708
+ type: 'button',
709
+ style: choice === next ? STYLE.choiceOn : STYLE.choiceOff,
710
+ disabled: props.pending,
711
+ 'aria-pressed': choice === next,
712
+ title,
713
+ onClick: () => write(props.projectRoot, conflict.server, next),
714
+ },
715
+ label,
716
+ )
717
+ const alias = conflict.alias
718
+ return h(
719
+ 'div',
720
+ { style: STYLE.choiceRow },
721
+ h('span', { style: STYLE.hint }, t('choiceLabel')),
722
+ button('profile', t('choiceProfileHint'), t('conflictProfile')),
723
+ // Only a `local` answer names the alias it would mount under, so the button
724
+ // exists exactly where the host published one.
725
+ alias === undefined
726
+ ? null
727
+ : button('local', t('choiceLocalHint', { alias }), t('choiceLocal', { alias })),
728
+ button('native', t('choiceNativeHint'), t('choiceNative')),
729
+ )
730
+ }
731
+
732
+ /** The key one contested name's write is tracked under: project + name. */
733
+ export function choiceKey(projectRoot: string, server: string): string {
734
+ return `${projectRoot}\u0000${server}`
735
+ }
736
+
737
+ /**
738
+ * The chip rule an alarm about this kind of conflict wears.
739
+ *
740
+ * A profile-level reservation is the warning tone — the name is taken, nothing
741
+ * is broken. A duplicate declaration inside one project is the error tone: only
742
+ * one of the two can win, so a declaration the file states is being dropped.
743
+ * @param kind - the host's own conflict kind.
744
+ * @returns the chip style for that kind.
745
+ */
746
+ function conflictTone(kind: ServerConflict['kind']): Record<string, unknown> {
747
+ return kind === 'profile' ? STYLE.tagWarn : STYLE.tagError
748
+ }
749
+
750
+ /** What one conflict kind is called in the UI. */
751
+ const CONFLICT_KEYS: Record<ServerConflict['kind'], LocaleKey> = {
752
+ profile: 'conflictProfile',
753
+ duplicate: 'conflictDuplicate',
754
+ }
755
+
756
+ /** The label of one conflict kind. */
757
+ export function conflictKindLabel(kind: ServerConflict['kind'], t: Translate): string {
758
+ return t(CONFLICT_KEYS[kind])
759
+ }
760
+
761
+ /**
762
+ * One setting row of the `Tools` page: the label and its description in the
763
+ * text column, the control in the column on the right.
764
+ *
765
+ * The text column is the wide one and the one that wraps — `flex: 1` takes the
766
+ * leftover width and `minWidth: 0` lets it shrink below its content instead of
767
+ * pushing the control out of the panel. The control column is `flex: none`, so
768
+ * it measures to its own content and never wraps. That is exactly the shape the
769
+ * old three-pane grid got wrong: it put sentences in panes narrower than one of
770
+ * their words, so they rendered as one-word-wide slivers.
771
+ * @param props - label, optional description and the row's own control.
772
+ * @returns the row element.
773
+ */
774
+ export function SettingRow(props: {
775
+ /** Bold text of the text column. */
776
+ label: string
777
+ /** Muted one-line description under the label, when the row has one. */
778
+ description?: string
779
+ /**
780
+ * The longer explanation of the row, as a tooltip rather than a paragraph.
781
+ *
782
+ * The mockups keep a settings line to a label and a control; anything that
783
+ * needs a sentence hangs it off the label it explains.
784
+ */
785
+ title?: string
786
+ /** The control, sized to its content in the column on the right. */
787
+ control: ReactNode
788
+ /** `true` on the last row of a group, whose trailing separator is dropped. */
789
+ last?: boolean
790
+ }): ReactNode {
791
+ return h(
792
+ 'div',
793
+ { style: props.last === true ? { ...STYLE.settingRow, ...STYLE.lastRow } : STYLE.settingRow },
794
+ h(
795
+ 'div',
796
+ {
797
+ style: STYLE.settingRowText,
798
+ ...(props.title === undefined ? null : { title: props.title }),
799
+ },
800
+ h('div', { style: STYLE.settingRowLabel }, props.label),
801
+ props.description === undefined
802
+ ? null
803
+ : h('div', { style: STYLE.settingRowDesc }, props.description),
804
+ ),
805
+ h('div', { style: STYLE.settingRowControl }, props.control),
806
+ )
807
+ }
808
+
809
+ /**
810
+ * The mode switch: `disclosure / direct / off`, the host's own three values.
811
+ *
812
+ * Unlike the mockup's segmented controls below it, this one writes through to
813
+ * the host the moment it is clicked (the caller owns the request), so each
814
+ * button stays disabled until the answer lands and the row re-reads the mode the
815
+ * host actually stored.
816
+ */
817
+ export function ModeSwitchRow(props: {
818
+ mode: ToolMode
819
+ busy: boolean
820
+ onMode: (mode: ToolMode) => void
821
+ t: Translate
822
+ }): ReactNode {
823
+ return h(
824
+ 'span',
825
+ { style: STYLE.segment },
826
+ TOOL_MODES.map((mode) =>
827
+ h(
828
+ 'button',
829
+ {
830
+ key: mode,
831
+ style:
832
+ mode === props.mode
833
+ ? { ...STYLE.segmentItem, ...STYLE.segmentItemActive }
834
+ : STYLE.segmentItem,
835
+ 'aria-pressed': mode === props.mode,
836
+ disabled: props.busy,
837
+ onClick: () => props.onMode(mode),
838
+ },
839
+ modeLabel(mode, props.t),
840
+ ),
841
+ ),
842
+ )
843
+ }
844
+
845
+ // ── the session's own offer, counted per server ───────────────────────────────
846
+
847
+ /** One server's share of a session's offer. */
848
+ export interface ServerToolCount {
849
+ /** Server name, without the registry's `mcp__` prefix. */
850
+ server: string
851
+ /** Its tools the session offers the model right now. */
852
+ offered: number
853
+ /** Its tools mounted for the project but held back from this offer. */
854
+ hidden: number
855
+ /** `offered + hidden`. */
856
+ total: number
857
+ }
858
+
859
+ /**
860
+ * The names one session offers, in offer order: the durable baseline, then the
861
+ * two on-demand tiers.
862
+ *
863
+ * Each name once: the tiers are not disjoint — a pinned or hot name can be
864
+ * activated too — and both readers of this list count, so a repeat would be
865
+ * counted twice (the per-server rows) or printed twice (the picker below).
866
+ * @param tools - one session's offer, when the host published one.
867
+ * @returns the public names, each once; empty without an offer.
868
+ */
869
+ export function offeredNames(tools: SessionTools | undefined): string[] {
870
+ if (tools === undefined) return []
871
+ return [
872
+ ...new Set([
873
+ ...tools.baseline,
874
+ ...tools.activated.map((tool) => tool.name),
875
+ ...tools.context.map((tool) => tool.name),
876
+ ]),
877
+ ]
878
+ }
879
+
880
+ /**
881
+ * The names this project's request would carry, in offer order: the host's pin
882
+ * list first, then the session's own offer, each name once.
883
+ *
884
+ * Pins lead because that is where the request builder starts: a pinned name is
885
+ * offered from the first step whatever the counters say. A pin the project no
886
+ * longer mounts is kept — the declaration may come back — which is why the list
887
+ * follows `policy.pins` rather than filtering it first.
888
+ * @param tools - one session's tool offer.
889
+ * @param policy - the project's policy, whose `pins` lead the list.
890
+ * @returns the visible names, in request order.
891
+ */
892
+ export function visibleToolNames(tools: SessionTools, policy: ToolPolicy): string[] {
893
+ const seen = new Set<string>()
894
+ const names: string[] = []
895
+ for (const name of [...policy.pins, ...offeredNames(tools)]) {
896
+ if (seen.has(name)) continue
897
+ seen.add(name)
898
+ names.push(name)
899
+ }
900
+ return names
901
+ }
902
+
903
+ /**
904
+ * Count the session's offer per server, by the registry's `mcp__<server>__`
905
+ * prefix (contract C6).
906
+ *
907
+ * `offered` and `hidden` are the session's own lists, so a name without the
908
+ * prefix — a built-in, or one another owner contributes — belongs to no server
909
+ * and is left out rather than filed under a made-up one. The sum of `total` is
910
+ * therefore a lower bound on `SessionTools.mounted`, which stays the control.
911
+ * @param tools - one session's tool offer.
912
+ * @returns one entry per server, ordered by name.
913
+ */
914
+ export function serverToolCounts(tools: SessionTools): ServerToolCount[] {
915
+ const counts = new Map<string, ServerToolCount>()
916
+ const bump = (name: string, tier: 'offered' | 'hidden'): void => {
917
+ const server = serverOfToolName(name)
918
+ if (server === undefined) return
919
+ const entry = counts.get(server) ?? { server, offered: 0, hidden: 0, total: 0 }
920
+ if (tier === 'offered') entry.offered += 1
921
+ else entry.hidden += 1
922
+ entry.total = entry.offered + entry.hidden
923
+ counts.set(server, entry)
924
+ }
925
+ for (const name of offeredNames(tools)) bump(name, 'offered')
926
+ for (const name of tools.deferred) bump(name, 'hidden')
927
+ return [...counts.values()].sort((left, right) => left.server.localeCompare(right.server))
928
+ }
929
+
930
+ /**
931
+ * What one server's counters mean in words: everything it mounts is offered
932
+ * directly, or only part of it is.
933
+ * @param count - one server's counters.
934
+ * @param t - translate seat.
935
+ * @returns the sentence the filter row carries.
936
+ */
937
+ export function serverOfferLabel(count: ServerToolCount, t: Translate): string {
938
+ return count.hidden === 0
939
+ ? t('serverAllOffered', { count: count.offered })
940
+ : t('serverPartlyOffered', { offered: count.offered, total: count.total })
941
+ }
942
+
943
+ /** One name and its switch: the picker's row. */
944
+ function pinRow(
945
+ name: string,
946
+ pinned: boolean,
947
+ pending: boolean,
948
+ calls: ToolCalls | undefined,
949
+ props: {
950
+ onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined
951
+ project: ProjectSnapshot
952
+ t: Translate
953
+ },
954
+ ): ReactNode {
955
+ const { t } = props
956
+ const disabled = props.onPin === undefined || pending
957
+ const figure = callsLabel(calls, t)
958
+ return h(
959
+ 'div',
960
+ { key: name, style: STYLE.listItem },
961
+ h('span', { style: STYLE.muted }, name),
962
+ figure === undefined ? null : h('span', { style: STYLE.hint }, figure),
963
+ h('span', { style: { flex: 1 } }),
964
+ h(
965
+ 'button',
966
+ {
967
+ type: 'button',
968
+ style: pinned ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },
969
+ 'aria-checked': pinned,
970
+ 'aria-label': name,
971
+ title: pinned ? t('toolsUnpinHint') : t('toolsPinHint'),
972
+ disabled,
973
+ onClick: () => props.onPin?.(props.project.projectRoot, name, !pinned),
974
+ },
975
+ h('span', { style: pinned ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob }),
976
+ ),
977
+ )
978
+ }
979
+
980
+ /**
981
+ * The project's mounted tools as a full-width block, with the pinned ones
982
+ * marked.
983
+ *
984
+ * It lists the names the host actually offers — the pinned list first, then
985
+ * whatever this session's own `tools` published — so a name on screen is a name
986
+ * the project really mounts. The total in the head is the host's count of
987
+ * mounted tools; a project whose session has published no offer yet shows a
988
+ * dash and no rows rather than a number nobody measured.
989
+ *
990
+ * The block used to be the split's left pane, which is why it carried a
991
+ * fixed-width rail and a right border; it is a card between two other blocks
992
+ * now, so its rows are separated by the card's own rules instead.
993
+ *
994
+ * Since F-32 the rows are ordered by the host's own call counters and carry
995
+ * that count, so the name worth pinning is the name at the top rather than the
996
+ * one the session happened to list first.
997
+ */
998
+ export function ToolList(props: {
999
+ project: ProjectSnapshot
1000
+ policy: ToolPolicy
1001
+ /** Pin or unpin one tool of this project; absent leaves the switches inert. */
1002
+ onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined
1003
+ /** Tool names with a pin write in flight. */
1004
+ pinPending?: ReadonlySet<string> | undefined
1005
+ /** Last refusal from a pin write, when the host did not take it. */
1006
+ pinError?: string | undefined
1007
+ /** Wire companions of `pinError`, when the host coded the refusal (F-48). */
1008
+ pinErrorCode?: string | undefined
1009
+ /** Flat params of `pinErrorCode`. */
1010
+ pinErrorParams?: Record<string, string> | undefined
1011
+ t: Translate
1012
+ /** Host-namespace seat for the refusal's coded message (F-48). */
1013
+ hostT?: Translate | undefined
1014
+ }): ReactNode {
1015
+ const { t } = props
1016
+ const counts = projectToolCounts(props.project)
1017
+ const live = firstSession(props.project)
1018
+ const tools = live?.tools
1019
+ const offered = offeredNames(tools)
1020
+ const pinnedNames = new Set(props.policy.pins)
1021
+ const pending = props.pinPending ?? new Set<string>()
1022
+ const rest = counts.tools === undefined ? 0 : Math.max(0, counts.tools - offered.length)
1023
+ return h(
1024
+ 'div',
1025
+ { style: STYLE.card },
1026
+ h('div', { style: STYLE.cardHead }, `${t('tabTools')} · ${counts.tools ?? '—'}`),
1027
+ offered.length === 0
1028
+ ? h(
1029
+ 'div',
1030
+ { style: STYLE.listItem },
1031
+ h('span', { style: STYLE.hint }, t('requestPreviewNoOffer')),
1032
+ )
1033
+ : [...offered]
1034
+ .sort(byCalls(props.project.usage, live?.id))
1035
+ .map((name) =>
1036
+ pinRow(
1037
+ name,
1038
+ pinnedNames.has(name),
1039
+ pending.has(name),
1040
+ toolCalls(name, props.project.usage, live?.id),
1041
+ props,
1042
+ ),
1043
+ ),
1044
+ rest > 0
1045
+ ? h(
1046
+ 'div',
1047
+ { style: { ...STYLE.listItem, ...STYLE.muted } },
1048
+ h('span', { style: STYLE.hint }, t('moreTools', { count: rest })),
1049
+ )
1050
+ : null,
1051
+ // The prefix is a fact of the registry, not a setting of this page: it is
1052
+ // stated once, under the names it explains, and is not a control.
1053
+ h(
1054
+ 'div',
1055
+ { style: { ...STYLE.listItem, ...STYLE.lastRow } },
1056
+ h('span', { style: STYLE.hint }, t('prefixFact')),
1057
+ ),
1058
+ props.pinError === undefined
1059
+ ? null
1060
+ : h(
1061
+ 'div',
1062
+ { style: STYLE.noteError },
1063
+ `${t('pinRefused')} ${resolveHost(props.hostT ?? hostTranslate(undefined), props.pinErrorCode, props.pinErrorParams, props.pinError)}`,
1064
+ ),
1065
+ )
1066
+ }
1067
+
1068
+ /**
1069
+ * The request the policy would build, as far as the host publishes it: the names
1070
+ * this session offers, in request order, with the pinned ones marked.
1071
+ *
1072
+ * The names are real — the session's own `tools` plus the policy's pin list —
1073
+ * and the sizes are the contract's own (`visibleChars` / `deferredChars`), so
1074
+ * the token estimate is `Math.round(chars / 4)` and is printed only where a size
1075
+ * is known: a snapshot without `deferredChars` shows the hidden count and no
1076
+ * estimate at all, rather than an invented one. The mockup's `tools[] = 6` with
1077
+ * its five made-up lines and its invented savings went with the other
1078
+ * placeholders.
1079
+ *
1080
+ * It used to be the split's third column, where the widest line of the preview
1081
+ * was wider than the pane and collided with the form beside it.
1082
+ */
1083
+ export function RequestPreview(props: {
1084
+ project: ProjectSnapshot
1085
+ policy: ToolPolicy
1086
+ t: Translate
1087
+ }): ReactNode {
1088
+ const { t } = props
1089
+ const tools = firstSession(props.project)?.tools
1090
+ if (tools === undefined) {
1091
+ return h(
1092
+ 'div',
1093
+ { style: STYLE.card },
1094
+ h('div', { style: STYLE.cardHead }, t('requestPreview')),
1095
+ h(
1096
+ 'div',
1097
+ { style: { ...STYLE.listItem, ...STYLE.lastRow } },
1098
+ h('span', { style: STYLE.hint }, t('requestPreviewNoOffer')),
1099
+ ),
1100
+ )
1101
+ }
1102
+ const names = visibleToolNames(tools, props.policy)
1103
+ const pinned = new Set(props.policy.pins)
1104
+ const footer =
1105
+ tools.deferredChars === undefined
1106
+ ? t('requestPreviewHidden', { count: tools.deferred.length })
1107
+ : t('requestPreviewSaved', {
1108
+ count: tools.deferred.length,
1109
+ tokens: tokenEstimate(tools.deferredChars),
1110
+ })
1111
+ return h(
1112
+ 'div',
1113
+ { style: STYLE.card },
1114
+ h(
1115
+ 'div',
1116
+ { style: STYLE.cardHead },
1117
+ t('requestPreview'),
1118
+ h('span', { style: STYLE.tag }, t('requestPreviewTools', { count: names.length })),
1119
+ tools.visibleChars === undefined
1120
+ ? null
1121
+ : h(
1122
+ 'span',
1123
+ { style: STYLE.tag },
1124
+ t('requestPreviewTokens', { tokens: tokenEstimate(tools.visibleChars) }),
1125
+ ),
1126
+ ),
1127
+ h(
1128
+ 'pre',
1129
+ { style: STYLE.json },
1130
+ names.map((name) =>
1131
+ h('div', { key: name }, pinned.has(name) ? `${name} ${t('pinTag')}` : name),
1132
+ ),
1133
+ h('div', { style: STYLE.muted }, footer),
1134
+ ),
1135
+ )
1136
+ }